text stringlengths 7 3.69M |
|---|
variable = "varIabLe";
console.log(`This is one way to pass a ${variable}`);
console.log('This is another way to pass a ' + variable);
console.log('Let\'s check types:\n');
var number = 5.1234098098098345098153451;
console.log(`${number} is a type of ` + typeof number);
var string = "Stringy" + "cheese";
var num2str = 1 + "cat";
var array = [];
console.log(`${string} is a ` + typeof string);
console.log(`${num2str} is a ` + typeof num2str + ` where we concatenate a number and a string`);
console.log(`${array} is an empty ` + typeof array);
var rando = Math.random();
console.log('Generate a random number: ' + rando);
var rando1 = rando * 10;
console.log('Make it between 1 and 10:' + rando1);
console.log(Object.getOwnPropertyNames(Math));
console.log("\n\nNow we want to practice arrow functions.\n");
function fn1(params) {
return params * 2;
};
var fn2 = (params) => params * 2;
console.log("For fn1, we use return. For fn2, we use the arrow function");
console.log(`fn1 returns ${fn1(4)}`);
console.log(`fn2 returns ${fn2(4)}`);
|
(function() {
'use strict';
var app = angular.module("githubViewer");
var GithubOneRepoController = function($scope, $routeParams) {
//$scope.repoName = $routeParams.repoName;
$scope.repoNameTest = "Test REPO NAME";
$scope.repoName = $routeParams.repoName;
//$scope.contributors; // make a service that gets these contributors
};
app.controller("GithubOneRepoController", GithubOneRepoController);
}()); |
let first = document.body.firstChild;
first.innerHTML = "I am the first child!";
// first.parentNode.innerHTML = 'I am the parent and my inner HTML has been replaced!';
|
function spawnCommentBox(){
document.getElementById('commenting-box').style.display = 'block';
}
function postComment(){
console.log('Posting Comment...');
let commentValue = document.getElementById('comment-input').value;
let currentUserPk = currentDetailUserPk;
$.ajax({
type: "POST",
url: `/dashboard/findOther/detail/${currentUserPk}/comment/`,
data: {
'comment-value':commentValue,
'csrfmiddlewaretoken': document.getElementsByName('csrfmiddlewaretoken')[0].value
},
success: function(json) {
console.log('Success!');
let newCommentObj = {};
newCommentObj['commentText'] = commentValue;
newCommentObj['owner'] = currentLoggedUserName;
ownerComments.push(newCommentObj);
updateCommentList();
},
error: function(json){
console.log(json);
}
});
}
function updateCommentList(){
// 'comment-show-space'
let tempView = ``;
if (ownerComments.length > 0){
for (let i = 0; i < ownerComments.length; i++){
tempView += `
<p>${ownerComments[i]['commentText']} by ${ownerComments[i]['owner']}</p>
`;
};
}else{
tempView = '<p>No Comments to show Yet!</p>'
}
document.getElementById('comment-show-space').innerHTML = tempView;
};
updateCommentList(); |
import React from "react";
import { connect } from "react-redux";
import { getFastSearch } from "./redux/actions.js";
import { getHash } from "../util/getHash.js";
import "./css/hot_search.css";
const fastSearchOptions =
[
{
className: "hot-search__image-new-building",
elements:
[
{
title: "Каталог новостроек",
selected: true,
searchConditions:
{
searchType:75,
completion_of_construction: [1,3],
operationType:[-1],
view_type:5
}
},
{
title: "Строящиеся дома",
searchConditions:
{
searchType:75,
completion_of_construction: [3],
operationType:[-1],
view_type:5
}
},
{
title: "Новостройки",
searchConditions:
{
searchType:75,
completion_of_construction: [1],
operationType:[-1],
view_type:5
}
},
{
title: "Жилые комплексы новые",
searchConditions:
{
searchType:59,
asset_group_kind:[1],
completion_of_construction: [1,3],
operationType:[-1],
view_type:5
}
},
{
title: "Долгострои",
selected: true,
searchConditions:
{
searchType:9,
completion_of_construction: [4],
operationType:[-1],
view_type:5
}
}
]
},
{
className: "hot-search__image-mstorey-residential-buildings",
elements:
[
{
title: "Многоквартирные дома",
selected: true,
searchConditions:
{
searchType:9,
operationType:[-1],
view_type:5
}
},
{
title: "Элита",
searchConditions:
{
searchType:9,
building_class:[1],
operationType:[-1],
view_type:5
}
},
{
title: "Бизнес класс",
searchConditions:
{
searchType:9,
building_class:[2],
operationType:[-1],
view_type:5
}
},
{
title: "Жилые комплексы",
searchConditions:
{
searchType:59,
asset_group_kind:[1],
operationType:[-1],
view_type:5
}
},
{
title: "Аварийные дома",
selected: true,
searchConditions:
{
searchType:9,
completion_of_construction: [5],
operationType:[-1],
view_type:5
}
}
]
},
{
className: "hot-search__image-building",
elements:
[
{
title: "Жилые дома",
selected: true,
searchConditions:
{
searchType:57,
operationType:[1],
interval:4,
building_kind:[2],
view_type:5
}
},
{
title: "Коттеджи",
searchConditions:
{
searchType:11,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Таунхаусы",
searchConditions:
{
searchType:12,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Дачи",
searchConditions:
{
searchType:13,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Участки",
searchConditions:
{
searchType:37,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Коттеджные поселки",
searchConditions:
{
searchType:59,
operationType:[1],
interval:4,
asset_group_kind:[2],
asset_group_type:[2],
view_type:5
}
},
{
title: "Недострои",
selected: true,
searchConditions:
{
searchType:37,
operationType:[1],
interval:4,
land_improvement:[6,9,15,21,22,23,24,28,29,30],
view_type:5
}
}
]
},
{
className: "hot-search__image-land",
elements:
[
{
title: "Земля",
selected: true,
searchConditions:
{
searchType:36,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Торгово-офисная",
searchConditions:
{
searchType:39,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Производственная",
searchConditions:
{
searchType:40,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Сельхоз угодья",
searchConditions:
{
searchType:41,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "База 2014 г.",
selected: true,
searchConditions:
{
searchType:36,
operationType:[1],
economic_operations_date_from: "01.01.2013",
economic_operations_date_to: "31.12.2013",
view_type:5
}
}
]
},
{
className: "hot-search__image-building5000",
elements:
[
{
title: "Каталог бизнес-центров",
selected: true,
searchConditions:
{
searchType:57,
building_kind:[8],
building_type:[22],
operationType:[-1],
view_type:5
}
},
{
title: "Офисы",
searchConditions:
{
searchType:27,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Торговое",
searchConditions:
{
searchType:57,
building_kind:[5],
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "Street-retail",
searchConditions:
{
searchType:21,
operationType:[1],
interval:4,
view_type:5
}
},
{
title: "База 2018 г.",
selected: true,
searchConditions:
{
searchType:61,
operationType:[1],
economic_operations_date_from: "01.01.2017",
economic_operations_date_to: "31.12.2018",
view_type:5
}
},
{
title: "Объекты более 5000 кв.м",
selected: true,
searchConditions:
{
searchType:62,
operationType:[-1],
view_type:5
}
}
]
},
{
className: "hot-search__image-property-complex",
elements:
[
{
title: "Индустриальные комплексы",
selected: true,
searchConditions:
{
searchType:63,
operationType:[-1],
view_type:5
}
},
{
title: "Склады",
searchConditions:
{
searchType:33,
operationType:[-1],
view_type:5
}
},
{
title: "Технопарки",
searchConditions:
{
searchType:65,
operationType:[-1],
view_type:5
}
},
{
title: "Промзоны",
searchConditions:
{
searchType:66,
operationType:[-1],
view_type:5
}
}
]
},
{
className: "hot-search__image-period",
elements:
[
]
},
{
className: "hot-search__image-office",
elements:
[
{
title: "Аренда квартир",
searchConditions:
{
searchType:1,
operationType:[2],
interval:3,
view_type:5
}
},
{
title: "Аренда офисов",
searchConditions:
{
searchType:27,
operationType:[2],
interval:4,
view_type:5
}
},
{
title: "Аренда торговых",
searchConditions:
{
searchType:19,
operationType:[2],
interval:4,
view_type:5
}
},
{
title: "Аренда ТЦ",
searchConditions:
{
searchType:23,
operationType:[2],
interval:4,
view_type:5
}
},
{
title: "Аренда складов",
searchConditions:
{
searchType:33,
operationType:[2],
interval:4,
view_type:5
}
},
{
title: "Аренда хостелов",
searchConditions:
{
searchType:73,
operationType:[2],
interval:4,
view_type:5
}
},
{
title: "Аренда гостиниц",
searchConditions:
{
searchType:56,
operationType:[2],
interval:4,
view_type:5
}
}
]
},
{
className: "hot-search__image-ready-business",
elements:
[
{
title: "Готовый бизнес",
selected: true,
searchConditions:
{
searchType:48,
operationType:[1],
interval:5,
view_type:5
}
},
{
title: "Общепит",
searchConditions:
{
searchType:49,
operationType:[1],
interval:5,
view_type:5
}
},
{
title: "Обслуживание",
searchConditions:
{
searchType:74,
operationType:[1],
interval:5,
view_type:5
}
},
{
title: "Производство",
searchConditions:
{
searchType:52,
operationType:[1],
interval:5,
view_type:5
}
},
{
title: "Автосервис",
searchConditions:
{
searchType:53,
operationType:[1],
interval:5,
view_type:5
}
},
{
title: "АЗС",
searchConditions:
{
searchType:54,
operationType:[1],
interval:5,
view_type:5
}
}
]
}
];
function List( props )
{
const className = "grid-cols-8 hot-search__wrapper " + props.className;
return (
<ul className={ className }>
{
props.elements.map( ( element ) => <Element key={ element.title } setFormValues={ props.setFormValues } { ...element } /> )
}
</ul>
);
}
const ElementConnected = ( props ) => <li className={ props.selected && "hot-search__text-title" } onClick={ () => props.getFastSearch( props.searchConditions ) }>{ props.title }</li>;
const mapDispatchToProps = ( dispatch, ownProps ) => (
{
getFastSearch: ( searchConditions ) =>
{
ownProps.setFormValues( searchConditions );
dispatch( getFastSearch( searchConditions ) );
}
} );
const Element = connect( null, mapDispatchToProps )( ElementConnected );
export default class FastSearch extends React.Component
{
// Never update this component
shouldComponentUpdate( nextProps, nextState )
{
return false;
}
render()
{
return (
<div className="grid-row hot-search__grid-row-margin">
{
fastSearchOptions.map( ( list ) => <List key={ getHash( list ) } setFormValues={ this.props.setFormValues } { ...list } /> )
}
</div>
);
}
} |
const express = require("express");
const router = express.Router();
const insertExperiment = require("../library/insertExperiment");
/**
* Express.js router for /newExperiment
*
* Create a new experiment under specific project with given experiment information
*/
const newExperiment = router.post('/newExperiment', function (req,res) {
console.log("Hello, newProject!");
const uid = req.session.passport.user.profile.id;
const ename = req.query.ename;
const pid = req.query.pid;
const description = req.query.description;
const public = req.query.public;
insertExperiment(ename, pid, description,public);
res.end();
});
module.exports = newExperiment; |
'use strict';
const express = require('express');
const app = express();
let count = 42; // this should update based on sensor reading
app.use('/static', express.static(__dirname + '/src/public/'));
app.set('view engine', 'pug');
app.set('views', __dirname + '/src/templates/');
app.use('/static', express.static(__dirname + '/src/public/'));
app.get('/', function(req, res){
res.render('index', {
count: count // this is defined on line 6
});
});
app.listen(3000, function() {
console.log("The frontend server is running on port 3000")
});
|
"use strict";
class listTableOptions {
constructor(options) {
if (options.withColumns === undefined) {
this.withColumns = false;
}
if (options.withPrimaryKey === undefined) {
this.withPrimaryKey = true;
}
}
}
module.exports = listTableOptions;
|
// JS Partials - Used in concat & uglify tasks
var jssrc = [
// NO CONFLICT
'source/js/cagov/noconflict.js',
// BOOTSTRAP
'source/js/bootstrap/alert.js',
'source/js/bootstrap/button.js',
'source/js/bootstrap/collapse.js',
'source/js/bootstrap/dropdown.js',
'source/js/bootstrap/modal.js',
'source/js/bootstrap/tab.js',
'source/js/bootstrap/transition.js',
'source/js/bootstrap/tooltip.js',
// TBOOTSTRAP ACCESSIBILITY PLUGIN
'source/js/bootstrap-accessibility-plugin/functions.js',
'source/js/bootstrap-accessibility-plugin/dropdown.js',
'source/js/bootstrap-accessibility-plugin/tab.js',
// THIRD PARTY LIBS
'source/js/libs/responsive-tabs.js',
'source/js/libs/owl.carousel.js',
'source/js/libs/jquery.fancybox.js',
'source/js/libs/jquery.eqheight.js',
'source/js/libs/countUp.js',
'source/js/libs/jquery.waypoints.js',
'source/js/libs/Vague.js',
'source/js/libs/require.js',
// CAGOV CORE
'source/js/cagov/helpers.js',
'source/js/cagov/gatag.js',
'source/js/cagov/navigation.js',
'source/js/cagov/accordion.js',
'source/js/cagov/panel.js',
'source/js/cagov/search.js',
'source/js/cagov/plugins.js',
'source/js/cagov/gallery.js',
'source/js/cagov/profile-banners.js',
'source/js/cagov/carousel.js',
'source/js/cagov/jobs.js',
'source/js/cagov/locations.js',
'source/js/cagov/socialsharer.js',
'source/js/cagov/breadcrumb.js',
'source/js/cagov/service-tiles.js',
'source/js/cagov/number-counter.js',
'source/js/cagov/header.js',
'source/js/cagov/fixed-header.js',
'source/js/cagov/charts.js',
'source/js/cagov/parallax.js',
'source/js/cagov/animations.js',
'source/js/cagov/more.js',
'source/js/cagov/high-contrast.js',
'source/js/cagov/geo.js',
'source/js/cagov/ask-group.js'
];
var csssrc = {
"css/cagov.core.css": "source/less/cagov.core.less",
"css/cagov.font-only.css": "source/less/cagov.font-only.less",
"css/colorscheme-oceanside.css": "source/less/colorscheme/colorscheme-master.less"
}
// Avoid having to use ASP classic mode for server side includes in IIS using browsersync-ssi
var ssi = require('browsersync-ssi');
module.exports = function (grunt) {
require('time-grunt')(grunt);
grunt.initConfig({
/* Load the package.json so we can use pkg variables */
pkg: grunt.file
.readJSON('package.json'), concat: {
options: {
banner: '<%= banner %><%= jqueryCheck %>',
stripBanners: false
},
javascripts: {
src: jssrc,
dest: 'js/cagov.core.js'
}
},
uglify: {
my_target: {
files: {
'js/cagov.core.js': jssrc
}
},
options: {
// the banner is inserted at the top of the output
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("mmm-dd-yyyy' +
'") %> */\n/* JS COMPILED FROM SOURCE DO NOT MODIFY */\n'
}
},
less: {
development: {
options: {
paths: ["css"],
compress: false,
ieCompat: true,
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("mmm-dd-yyyy' +
'") %> */\n/* STYLES COMPILED FROM SOURCE (LESS) DO NOT MODIFY */\n\n'
},
files: csssrc
},
production: {
options: {
paths: ["css"],
compress: true,
ieCompat: true,
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("mmm-dd-yyyy' +
'") %> */\n/* STYLES COMPILED FROM SOURCE (LESS) DO NOT MODIFY */\n\n'
},
files: csssrc
}
},
htmllint: {
// Run on small directories at a time when possible
all: ["*.html"]
},
browserSync: {
dev: {
bsFiles: {
src: [
'css/*.css', 'js/*.js', '**/*.html',
]
},
options: {
watchTask: true,
startPath: "index.html",
server: {
baseDir: "./",
middleware: ssi({
baseDir: './',
ext: '.html'
})
}
}
}
},
autoprefixer: {
development: {
browsers: [
'Android 2.3', 'Android >= 4', 'Chrome >= 20', 'Firefox >= 24', // Firefox 24 is the latest ESR
'Explorer >= 8', 'iOS >= 6', 'Opera >= 12', 'Safari >= 6'
],
expand: true,
flatten: true,
src: ['css/cagov.core.css', 'css/colorscheme-oceanside'],
dest: 'css'
}
},
watch: {
/* watch for less changes */
less: {
files: ['source/**/*.less'],
tasks: [
'autoprefixer', 'less:development'
]
},
/* watch and see if our javascript files change, or new packages are installed */
js: {
files: ['source/**/*.js'],
tasks: ['concat']
},
/* watch our files for change, reload */
livereload: {
files: [
'ssi/*.html', 'sample/**/*', './*.html', 'css/*.css', 'images/*'
],
options: {
livereload: true
}
},
/* Reload gruntfile if it changes */
grunt: {
files: ['Gruntfile.js']
}
/* Add new module here. Mind the comma's :) */
}
});
// LOAD TASKS
// Use grunt to execute compass
grunt.loadNpmTasks('grunt-contrib-less');
// Use grunt to watch file changes.
grunt.loadNpmTasks('grunt-contrib-watch');
// Use uglify for js minification
grunt.loadNpmTasks('grunt-contrib-uglify');
// Concatenate js files
grunt.loadNpmTasks('grunt-contrib-concat');
// Automatic vendor prefixing
grunt.loadNpmTasks('grunt-autoprefixer');
// Open Source browser testing server
grunt.loadNpmTasks('grunt-browser-sync');
// HTML Linting
grunt.loadNpmTasks('grunt-html');
// REGISTER TASKS
// Default task to watch and output uncompresses
grunt.registerTask('default', [
'concat', 'less:development', 'autoprefixer', 'browserSync', 'watch'
]);
// Build task to minify css and js
grunt.registerTask('build', [
'uglify', 'less:production', 'autoprefixer'
]);
// Development task to concat and unminify
grunt.registerTask('dev', [
'concat', 'less:development', 'autoprefixer'
]);
// HTML linting
grunt.registerTask('lint', [
'concat', 'less:development', 'htmllint'
]);
};
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsRepositories = {
name: 'repositories',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8 23.01l2.5-1.5 2.5 1.5V19H8v4.01zM8 5h2v2H8zM8 10h2v2H8zM8 15.01h2v2H8z"/><path d="M18.36 1.05A1.47 1.47 0 0018 1H6a2 2 0 00-2 2v16a2 2 0 002 2V3h12v16h-3v2h3a2 2 0 002-2V3a2 2 0 00-1.64-1.95z"/></svg>`
};
|
QUnit.module( "Test call count - second case" );
QUnit[ window.sessionStorage ? "test" : "skip" ](
"does not skip tests after reordering",
function( assert ) {
assert.equal( window.totalCount, 2 );
}
);
|
import React, {Component} from 'react';
import ListGroup from'react-bootstrap/ListGroup'
class Category extends Component {
render() {
let {category} = this.props;
return (
<ListGroup.Item variant="info" href="/category/:name">{category.name}</ListGroup.Item>
)
}
}
export default Category; |
/*
* ProGade API
* Copyright 2012, Hans-Peter Wandura (ProGade)
* Last changes of this file: Aug 21 2012
*/
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_Nodes()
{
// Declarations...
// Construct...
// Methods...
/*
@start method
@return axInfos [type]mixed[][/type]
[en]...[/en]
*/
this.getInfos = function(_xElement)
{
var _oElement = this.getNode(_xElement);
return oPGObjects.getStructureString({'oObject':_oElement, 'bUseHtml': false});
}
/* @end method */
/*
@start method
@group Properties
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sProperty [needed][type]string[/type]
[en]...[/en]
@param xValue [type]mixed[/type]
[en]...[/en]
*/
this.set = function(_xElement, _sProperty, _xValue)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
if (typeof(_xValue) == 'undefined') {var _xValue = null;}
_xValue = this.getRealParameter({'oParameters': _xElement, 'sName': 'xValue', 'xParameter': _xValue});
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getNode(_xElement);
if (_oElement)
{
if (_xValue === null) {_oElement.removeAttribute(_sProperty, 0);}
else {_oElement.setAttribute(_sProperty, _xValue, 0);}
}
}
/* @end method */
/*
@start method
@group Properties
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sProperty [needed][type]string[/type]
[en]...[/en]
*/
this.unset = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
this.set({'xElement': _xElement, 'sProperty': _sProperty, 'xValue': null});
}
/* @end method */
/*
@start method
@group Properties
@return xValue [type]mixed[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sProperty [needed][type]string[/type]
[en]...[/en]
*/
this.get = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getNode({'xElement': _xElement});
if (_oElement) {return _oElement.getAttribute(_sProperty, 0);}
return null;
}
/* @end method */
/*
@start method
@group CSS
@return sStyle [type]string[/type]
[en]...[/en]
@param sStyle [needed][type]string[/type]
[en]...[/en]
*/
this.formatStyle = function(_sStyle)
{
if (typeof(_sStyle) == 'undefined') {var _sStyle = null;}
_sStyle = this.getRealParameter({'oParameters': _sStyle, 'sName': 'sStyle', 'xParameter': _sStyle});
return _sStyle.replace(/-([a-z])/, RegExp.$1.toUpperCase());
}
/* @end method */
/*
@start method
@group CSS
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sProperty [needed][type]string[/type]
[en]...[/en]
@param xValue [type]mixed[/type]
[en]...[/en]
*/
this.setStyle = function(_xElement, _sProperty, _xValue)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
if (typeof(_xValue) == 'undefined') {var _xValue = null;}
_xValue = this.getRealParameter({'oParameters': _xElement, 'sName': 'xValue', 'xParameter': _xValue});
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getNode({'xElement': _xElement});
if (_oElement)
{
if (_xValue === null)
{
if (typeof(_oElement.style.removeAttribute) != 'undefined') {_oElement.style.removeAttribute(this.formatStyle({'sStyle': _sProperty}));}
else if (typeof(_oElement.style.removeProperty) != 'undefined') {_oElement.style.removeProperty(_sProperty);}
else if (typeof(oPGCss) != 'undefined') {oPGCss.unsetStyle(_oElement, _sProperty);}
}
else
{
if (typeof(_oElement.style.setAttribute) != 'undefined') {_oElement.style.setAttribute(this.formatStyle({'sStyle': _sProperty}), _xValue, 0);}
else if (typeof(_oElement.style.setProperty) != 'undefined') {_oElement.style.setProperty(_sProperty, _xValue, null);}
else if (typeof(oPGCss) != 'undefined') {oPGCss.setStyle({'oElement': _oElement, 'sStyle': _sProperty+':'+_xValue+';'});}
}
}
}
/* @end method */
/*
@start method
@group CSS
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param axStyle [needed][type]mixed[][/type]
[en]...[/en]
*/
this.setStyles = function(_xElement, _axStyle)
{
if (typeof(_axStyle) == 'undefined') {var _axStyle = null;}
_axStyle = this.getRealParameter({'oParameters': _xElement, 'sName': 'axStyle', 'xParameter': _axStyle});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
for (var _sProperty in _axStyle)
{
this.setStyle({'xElement': _xElement, 'sProperty': _sProperty, 'xValue': _axStyle[_sProperty]});
}
}
/* @end method */
/*
@start method
@group CSS
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sProperty [needed][type]string[/type]
[en]...[/en]
*/
this.unsetStyle = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
this.setStyle({'xElement': _xElement, 'sProperty': _sProperty});
}
/* @end method */
/*
@start method
@group CSS
@return xValue [type]mixed[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sProperty [needed][type]string[/type]
[en]...[/en]
*/
this.getStyle = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getNode({'xElement': _xElement});
if (_oElement)
{
if (typeof(_oElement.style.getAttribute) != 'undefined') {return _oElement.style.getAttribute(this.formatStyle({'sStyle': _sProperty}), 0);}
else if (typeof(_oElement.style.getPropertyValue) != 'undefined') {return _oElement.style.getPropertyValue(_sProperty);}
}
return null;
}
/* @end method */
/*
@start method
@group Get
@return oNode [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
if (typeof(_xElement) == 'string') {return this.oDocument.getElementById(_xElement);}
else if (typeof(_xElement) == 'object') {return _xElement;}
return null;
}
/* @end method */
/*
@start method
@group Manipulation
@return oNodeCopy [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param bWithContent [type]bool[/type]
[en]...[/en]
*/
this.copy = function(_xElement, _bWithContent)
{
if (typeof(_bWithContent) == 'undefined') {var _bWithContent = null;}
_bWithContent = this.getRealParameter({'oParameters': _xElement, 'sName': 'bWithContent', 'xParameter': _bWithContent});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement});
if (_bWithContent == null) {_bWithContent = true;}
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {return _oNode.cloneNode(true);}
return null;
}
/* @end method */
this.clone = this.copy;
/*
@start method
@group Manipulation
@return oReplacedElement [type]object[/type]
[en]...[/en]
@param xElementToReplace [needed][type]mixed[/type]
[en]...[/en]
@param xElementReplaceWith [needed][type]mixed[/type]
[en]...[/en]
*/
this.replace = function(_xElementToReplace, _xElementReplaceWith)
{
if (typeof(_xElementReplaceWith) == 'undefined') {var _xElementReplaceWith = null;}
_xElementReplaceWith = this.getRealParameter({'oParameters': _xElementToReplace, 'sName': 'xElementReplaceWith', 'xParameter': _xElementReplaceWith});
_xElementToReplace = this.getRealParameter({'oParameters': _xElementToReplace, 'sName': 'xElementToReplace', 'xParameter': _xElementToReplace, 'bNotNull': true});
var _oNodeToReplace = this.getNode({'xElement': _xElementToReplace});
var _oNodeToReplaceWith = this.getNode({'xElement': _xElementReplaceWith});
var _oParentNode = this.getParentNode({'xElement': _xElement});
if ((_oNodeToReplace) && (_oNodeToReplaceWith) && (_oParentNode))
{
return _oParentNode.replaceChild(_oNodeToReplaceWith, _oNodeToReplace);
}
return null;
}
/* @end method */
/*
@start method
@group Manipulation
@return oRemovedElement [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.remove = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement});
var _oNode = this.getNode({'xElement': _xElement});
var _oParentNode = this.getParentNode({'xElement': _xElement});
if ((_oNode) && (_oParentNode))
{
return _oParentNode.removeChild(_oNode);
}
return null;
}
/* @end method */
this.kill = this.remove;
/*
@start method
@group Manipulation
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sHtml [needed][type]string[/type]
[en]...[/en]
*/
this.insertHtml = function(_xElement, _sHtml)
{
if (typeof(_sHtml) == 'undefined') {var _sHtml = null;}
_sHtml = this.getRealParameter({'oParameters': _xElement, 'sName': 'sHtml', 'xParameter': _sHtml});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {_oNode.innerHTML = _sHtml;}
}
/* @end method */
this.addHtml = this.insertHtml;
/*
@start method
@group Manipulation
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sText [needed][type]string[/type]
[en]...[/en]
*/
this.insertText = function(_xElement, _sText)
{
if (typeof(_sText) == 'undefined') {var _sText = null;}
_sText = this.getRealParameter({'oParameters': _xElement, 'sName': 'sText', 'xParameter': _sText});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {_oNode.innerText = _sText;}
}
/* @end method */
this.addText = this.insertText;
/*
@start method
@group Manipulation
@return oInsertedNode [type]object[/type]
[en]...[/en]
@param xIntoParent [needed][type]mixed[/type]
[en]...[/en]
@param xInsertElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.insertInto = function(_xIntoParent, _xInsertElement)
{
if (typeof(_xInsertElement) == 'undefined') {var _xInsertElement = null;}
_xInsertElement = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xInsertElement', 'xParameter': _xInsertElement});
_xIntoParent = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xIntoParent', 'xParameter': _xIntoParent, 'bNotNull': true});
var _oIntoParentNode = this.getNode({'xElement': _xIntoParent});
var _oInsertElement = this.getNode({'xElement': _xInsertElement});
if ((_oInsertElement) && (_oIntoParentNode))
{
return _oIntoParentNode.appendChild(_oInsertElement);
}
return false;
}
/* @end method */
/*
@start method
@group Manipulation
@return oInsertedNode [type]object[/type]
[en]...[/en]
@param xBeforeChild [needed][type]mixed[/type]
[en]...[/en]
@param xInsertElement [needed][type]mixed[/type]
[en]...[/en]
@param xIntoParent [type]mixed[/type]
[en]...[/en]
*/
this.insertBefore = function(_xBeforeChild, _xInsertElement, _xIntoParent)
{
if (typeof(_xBeforeChild) == 'undefined') {var _xBeforeChild = null;}
if (typeof(_xInsertElement) == 'undefined') {var _xInsertElement = null;}
_xBeforeChild = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xBeforeChild', 'xParameter': _xBeforeChild});
_xInsertElement = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xInsertElement', 'xParameter': _xInsertElement});
_xIntoParent = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xIntoParent', 'xParameter': _xIntoParent, 'bNotNull': true});
if (_xIntoParent == null) {_xIntoParent = this.getParentNode({'xElement': _oBeforeChildNode});}
var _oIntoParentNode = this.getNode({'xElement': _xIntoParent});
var _oBeforeChildNode = this.getNode({'xElement': _xBeforeChild});
var _oInsertElement = this.getNode({'xElement': _xInsertElement});
if ((_oInsertElement) && (_oBeforeChildNode) && (_oIntoParentNode))
{
return _oIntoParentNode.insertBefore(_oInsertElement, _oBeforeChildNode);
}
return false;
}
/* @end method */
/*
@start method
@group Manipulation
@return oInsertedNode [type]object[/type]
[en]...[/en]
@param xAfterChild [needed][type]mixed[/type]
[en]...[/en]
@param xInsertElement [needed][type]mixed[/type]
[en]...[/en]
@param xIntoParent [type]mixed[/type]
[en]...[/en]
*/
this.insertAfter = function(_xAfterChild, _xInsertElement, _xIntoParent)
{
if (typeof(_xAfterChild) == 'undefined') {var _xAfterChild = null;}
if (typeof(_xInsertElement) == 'undefined') {var _xInsertElement = null;}
_xAfterChild = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xAfterChild', 'xParameter': _xAfterChild});
_xInsertElement = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xInsertElement', 'xParameter': _xInsertElement});
_xIntoParent = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xIntoParent', 'xParameter': _xIntoParent, 'bNotNull': true});
if (_xIntoParent == null) {_xIntoParent = this.getParentNode({'xElement': _oBeforeChildNode});}
var _oIntoParentNode = this.getNode({'xElement': _xIntoParent});
var _oAfterChildNode = this.getNode({'xElement': _xAfterChild});
var _oInsertElement = this.getNode({'xElement': _xInsertElement});
if ((_oInsertElement) && (_oAfterChildNode) && (_oIntoParentNode))
{
var _oNextChildNode = null;
if (_oAfterChildNode.nextSibling)
{
_oNextChildNode = _oAfterChildNode.nextSibling;
return _oIntoParentNode.insertBefore(_oInsertElement, _oNextChildNode);
}
else
{
return _oIntoParentNode.appendChild(_oInsertElement);
}
}
return false;
}
/* @end method */
/*
@start method
@group Get
@return oNode [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getNextNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {return _oNode.nextSibling;}
return false;
}
/* @end method */
/*
@start method
@group Get
@return oNode [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getPreviousNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {return _oNode.previousSibling;}
return false;
}
/* @end method */
/*
@start method
@group Get
@return oNode [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getParentNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {return _oNode.parentNode;}
return false;
}
/* @end method */
/*
@start method
@group Get
@return aoNodes [type]object[][/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
/*this.getParentNodes = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode)
{
var _aoNodes = [];
if ((!_oNode) || (_oNode.tagName == 'body')) {return null;}
while ((_oNode) && (_oNode.tagName != 'body'))
{
_aoNodes.push(_oNode);
_oNode.parentNode;
}
return _aoNodes;
}
return null;
}*/
/* @end method */
/*
@start method
@group Get
@return oNode [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getFirstChildNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {return _oNode.firstChild;}
return false;
}
/* @end method */
/*
@start method
@group Get
@return oNode [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getLastChildNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oNode = this.getNode({'xElement': _xElement});
if (_oNode) {return _oNode.lastChild;}
return false;
}
/* @end method */
/*
@start method
@group Get
@return aoNodes [type]object[][/type]
[en]...[/en]
@param bIncludeCurrent [type]bool[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param xMaxElement [type]mixed[/type]
[en]...[/en]
*/
this.getParentNodes = function(_bIncludeCurrent, _xElement, _xMaxElement)
{
if (typeof(_bIncludeCurrent) == 'undefined') {var _bIncludeCurrent = null;}
if (typeof(_xElement) == 'undefined') {var _xElement = null;}
if (typeof(_xMaxElement) == 'undefined') {var _xMaxElement = null;}
_xElement = this.getRealParameter({'oParameters': _bIncludeCurrent, 'sName': 'xElement', 'xParameter': _xElement});
_xMaxElement = this.getRealParameter({'oParameters': _bIncludeCurrent, 'sName': 'xMaxElement', 'xParameter': _xMaxElement});
_bIncludeCurrent = this.getRealParameter({'oParameters': _bIncludeCurrent, 'sName': 'bIncludeCurrent', 'xParameter': _bIncludeCurrent});
if (_bIncludeCurrent == null) {_bIncludeCurrent = false;}
var _sNodeName = '';
var _sMaxElementName = '';
var _oNode = this.getNode({'xElement': _xElement});
if (_xMaxElement != null)
{
var _oMaxNode = null;
if (typeof(_xMaxElement) == 'string')
{
if (_xMaxElement[0] == '#') {_oMaxNode = this.getNode({'xElement': _xMaxElement});}
else {_sMaxElementName = _xMaxElement.toLowerCase();}
}
else if (typeof(_xMaxElement) == 'object') {_oMaxNode = _xMaxElement;}
if (_oMaxNode) {_sMaxElementName = _oMaxNode.nodeName.toLowerCase();}
}
if (_oNode)
{
var _aoNodes = new Array();
if ((_sNodeName == 'body') || (_sNodeName == '#document')) {return _aoNodes;}
_sNodeName = _oNode.nodeName.toLowerCase();
if (_bIncludeCurrent == true) {_aoNodes.push(_oNode);}
if (_sNodeName == _sMaxElementName) {return _aoNodes;}
_oNode = _oNode.parentNode;
if (_oNode)
{
_sNodeName = '';
if (_oNode.nodeName) {_sNodeName = _oNode.nodeName.toLowerCase();}
while ((_oNode) && (_sNodeName != 'body'))
{
if ((_sNodeName == 'body') || (_sNodeName == '#document')) {return _aoNodes;}
_aoNodes.push(_oNode);
if (_sNodeName == _sMaxElementName) {return _aoNodes;}
_oNode = _oNode.parentNode;
if (_oNode.nodeName) {_sNodeName = _oNode.nodeName.toLowerCase();}
}
}
return _aoNodes;
}
return false;
}
/* @end method */
/*
@start method
@group Other
@return oNode [type]object[/type]
[en]...[/en]
[de]...[/de]
@param sTag [needed][type]string[/type]
[en]...[/en]
[de]...[/de]
@param axAttributes [type]mixed[][/type]
[en]...[/en]
@param axStyles [type]mixed[][/type]
[en]...[/en]
*/
this.build = function(_sTag, _axAttributes, _axStyles)
{
if (typeof(_axAttributes) == 'undefined') {var _axAttributes = null;}
if (typeof(_axStyles) == 'undefined') {var _axStyles = null;}
_axAttributes = this.getRealParameter({'oParameters': _sTag, 'sName': 'axAttributes', 'xParameter': _axAttributes});
_axStyles = this.getRealParameter({'oParameters': _sTag, 'sName': 'axStyles', 'xParameter': _axStyles});
_sTag = this.getRealParameter({'oParameters': _sTag, 'sName': 'sTag', 'xParameter': _sTag});
if (_sTag != null)
{
var _oNode = this.oDocument.createElement(_sTag);
if (_oNode)
{
var _sProperty = '';
for (_sProperty in _axAttributes)
{
this.set({'xElement': _oNode, 'sProperty': _sProperty, 'xValue': _axAttributes[_sProperty]});
}
for (_sProperty in _axStyles)
{
this.setStyle({'xElement': _oNode, 'sProperty': _sProperty, 'xValue': _axStyles[_sProperty]});
}
}
return _oNode;
}
return null;
}
/* @end method */
/*
@start method
@group Other
@return oNode [type]object[/type]
[en]...[/en]
[de]...[/de]
@param sTag [needed][type]string[/type]
[en]...[/en]
[de]...[/de]
@param axAttributes [type]mixed[][/type]
[en]...[/en]
@param axStyles [type]mixed[][/type]
[en]...[/en]
*/
this.buildInto = function(_xIntoParent, _sTag, _axAttributes, _axStyles)
{
if (typeof(_axAttributes) == 'undefined') {var _axAttributes = null;}
if (typeof(_axStyles) == 'undefined') {var _axStyles = null;}
_sTag = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'sTag', 'xParameter': _sTag});
_axAttributes = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'axAttributes', 'xParameter': _axAttributes});
_axStyles = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'axStyles', 'xParameter': _axStyles});
_xIntoParent = this.getRealParameter({'oParameters': _xIntoParent, 'sName': 'xIntoParent', 'xParameter': _xIntoParent});
if (_xIntoParent)
{
var _oNode = this.build({'sTag': _sTag, 'axAttributes': _axAttributes, 'axStyles': _axStyles});
if (_oNode) {return this.insertInto({'xIntoParent': _xIntoParent, 'xInsertElement': _oNode});}
}
return null;
}
/* @end method */
}
/* @end class */
classPG_Nodes.prototype = new classPG_ClassBasics();
var oPGNodes = new classPG_Nodes();
function classPG_NodesHtmlSingleTagBasics()
{
// Declarations...
// Construct...
// Methods...
this.set = function(_xElement, _sProperty, _xValue)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
if (typeof(_xValue) == 'undefined') {var _xValue = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xValue = this.getRealParameter({'oParameters': _xElement, 'sName': 'xValue', 'xParameter': _xValue});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.set({'xElement': _xElement, 'sProperty': _sProperty, 'xValue': _xValue});
}
this.unset = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.unset({'xElement': _xElement, 'sProperty': _sProperty});
}
this.get = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
return oPGNodes.get({'xElement': _xElement, 'sProperty': _sProperty});
}
this.getNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
return oPGNodes.getNode({'xElement': _xElement});
}
this.getObject = this.getNode;
this.copy = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
return oPGNodes.copy({'xElement': _xElement});
}
this.clone = this.copy;
this.remove = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.remove({'xElement': _xElement});
}
this.kill = this.remove;
}
function classPG_NodesHtmlDoubleTagBasics()
{
// Declarations...
// Construct...
// Methods...
this.set = function(_xElement, _sProperty, _xValue)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
if (typeof(_xValue) == 'undefined') {var _xValue = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xValue = this.getRealParameter({'oParameters': _xElement, 'sName': 'xValue', 'xParameter': _xValue});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.set({'xElement': _xElement, 'sProperty': _sProperty, 'xValue': _xValue});
}
this.unset = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.unset({'xElement': _xElement, 'sProperty': _sProperty});
}
this.get = function(_xElement, _sProperty)
{
if (typeof(_sProperty) == 'undefined') {var _sProperty = null;}
_sProperty = this.getRealParameter({'oParameters': _xElement, 'sName': 'sProperty', 'xParameter': _sProperty});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
return oPGNodes.get({'xElement': _xElement, 'sProperty': _sProperty});
}
this.getNode = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
return oPGNodes.getNode({'xElement': _xElement});
}
this.getObject = this.getNode;
this.copy = function(_xElement, _bWithContent)
{
if (typeof(_bWithContent) == 'undefined') {var _bWithContent = null;}
_bWithContent = this.getRealParameter({'oParameters': _xElement, 'sName': 'bWithContent', 'xParameter': _bWithContent});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
return oPGNodes.copy({'xElement': _xElement, 'bWithContent': _bWithContent});
}
this.clone = this.copy;
this.remove = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.remove({'xElement': _xElement});
}
this.kill = this.remove;
this.insertHtml = function(_xElement, _sHtml)
{
if (typeof(_sHtml) == 'undefined') {var _sHtml = null;}
_sHtml = this.getRealParameter({'oParameters': _xElement, 'sName': 'sHtml', 'xParameter': _sHtml});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.insertHtml({'xElement': _xElement, 'sHtml': _sHtml});
}
this.addHtml = this.insertHtml;
this.insertText = function(_xElement, _sText)
{
if (typeof(_sText) == 'undefined') {var _sText = null;}
_sText = this.getRealParameter({'oParameters': _xElement, 'sName': 'sText', 'xParameter': _sText});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
oPGNodes.insertText({'xElement': _xElement, 'sText': _sText});
}
this.addText = this.insertText;
}
|
var story = {
"title": "Booking-flight",
"pages": [{
"title": "Booking-flight",
"height": 805,
"width": 1001,
"image": "Booking-flight.png",
"links": [],
"image2x": "Booking-flight@2x.png"
}],
"highlightLinks": true,
"resolutions": [2]
} |
import React from 'react';
import { Scene, Router, Actions } from 'react-native-router-flux';
import LoginForm from './components/LoginForm';
import PetList from './components/PetList';
import PetCreate from './components/PetCreate';
import PetProfile from './components/PetProfile';
import PetEdit from './components/PetEdit';
const RouterComponent = () => {
return (
<Router>
<Scene key="root" hideNavBar>
<Scene key="auth">
<Scene key="login" component={LoginForm} title="Feast" initial />
</Scene>
<Scene key="main">
<Scene
rightTitle="Add"
onRight={() => Actions.petCreate()}
key="petList"
component={PetList}
title="Pets"
initial
/>
<Scene
key="petCreate"
component={PetCreate}
title="Add Pet"
/>
<Scene
key="petProfile"
component={PetProfile}
// title="Pet" // Dynamically change title to pet's name
/>
<Scene
key="petEdit"
component={PetEdit}
title="Edit Pet"
/>
</Scene>
</Scene>
</Router>
);
};
export default RouterComponent;
|
import styled from 'styled-components';
const IconButton = styled.button`
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 42px;
width: 42px;
height: 42px;
border: 0;
border-radius: 50%;
cursor: pointer;
outline: 0;
transition: all 0.2s;
background-color: transparent;
svg {
fill: ${({ fill }) => fill};
}
&:hover {
background-color: ${({ theme }) => theme.action};
}
`;
export default IconButton; |
const { rem, hsla } = require('csx/lib')
const { padding, scroll } = require('csstips')
module.exports = ({
} = {}) => {
return [
scroll,
padding(rem(.8)),
{
$debugName: 'Debug',
fontSize: rem(.96),
backgroundColor: hsla(0, 0, 0, 1).lighten(0.2).toString(),
color: hsla(0, 0, 1, 1).darken(0.2).toString(),
fontFamily: '"Source Sans Pro"',
}
]
}
|
import axios from 'axios';
import qs from 'qs';
function feedback(category, text)
{
const url ="https://script.google.com/macros/s/AKfycbwaeyBnsnO-zOXopeVfEF5r3cszfs6xOo_2WRb_vMduIY5Xy2c/exec";
return axios.post(url, qs.stringify({
category: category,
text: text
}));
};
export default feedback; |
import React, { Component } from 'react';
import "./containerone.css";
import ceepc from "../Assets/Pics/ceepc.png";
import logoc1 from "../Assets/Pics/LOGO_c_1.png"
class ContainerOne extends Component {
render() {
return (
<div className="cards">
<article className="card">
<img src={ceepc} alt="ceepc" />
<div className="text">
<p>Dobrodošli na Facultas English</p>
<p>Želite učiti jezik od najboljih?</p>
<p>Želite steći svjetski priznatu diplomu?</p>
<p>Želite da Vaše dijete uči engleski jezik po Cambridge English programu?</p>
<p>Želite učiti jezik od najboljih?</p>
</div>
</article>
<article className="card">
<img src={logoc1} alt="ceepc" />
<div className="text">
<p>CAMBRIDGE CENTAR FACULTAS je jedinstveni ispitni i pripremni jezički centar u Sarajevu.</p>
<p>Želite učiti jezik od najboljih?</p>
<p>Želite steći svjetski priznatu diplomu?</p>
<p>Želite da Vaše dijete uči engleski jezik po Cambridge English programu?</p>
</div>
</article>
</div>
);
}
}
export default ContainerOne; |
// initialization
// condition
// final statement
// let i = 0;
// for (; i < 5; ) {
// // console.log(i);
// // i++;
// }
// console.log(i);
// let arr = [1, 2, 3, 4, 5];
// for (let i = 0; i < arr.length; i++) {
// console.log(arr[i]);
// }
for (let i = 1; i <= 1000; i++) {
if (i % 3 === 0 && i % 25 === 0) {
console.log(i);
}
}
|
const passportHttp = require('passport-http');
const users = require('./../secure/users') || [];
module.exports = new passportHttp.BasicStrategy({}, (username, password, done) => {
const targetUser = users.find(user => user.username === username && user.password === password);
if (targetUser) {
return done(null, targetUser);
} else {
return done(null, false, {message: 'Such user doesn\'t exist'});
}
});
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "4f50f770b9c62ef204a5afc0cfb99bd5",
"url": "/index.html"
},
{
"revision": "86c5fca0da678fa72dc0",
"url": "/static/css/main.aa177f17.chunk.css"
},
{
"revision": "72729f8c5b9726d368f5",
"url": "/static/js/2.2701b9d6.chunk.js"
},
{
"revision": "570d362d673dab785e62d2b8563e1118",
"url": "/static/js/2.2701b9d6.chunk.js.LICENSE.txt"
},
{
"revision": "86c5fca0da678fa72dc0",
"url": "/static/js/main.8d49ba83.chunk.js"
},
{
"revision": "f0be2d6b237b3fb64219",
"url": "/static/js/runtime-main.24b8e7b7.js"
}
]); |
/**
* Created by hui.sun on 15/12/10.
*/
/**
* 4pl Grid thead配置
* check:true //使用checkbox 注(选中后对象中增加pl4GridCheckbox.checked:true)
* checkAll:true //使用全选功能
* field:’id’ //字段名(用于绑定)
* name:’序号’ //表头标题名
* link:{
* url:’/aaa/{id}’ //a标签跳转 {id}为参数 (与click只存在一个)
* click:’test’ //点击事件方法 参数test(index(当前索引),item(当前对象))
* }
* input:true //使用input 注(不设置默认普通文本)
* type:text //与input一起使用 注(type:operate为操作项将不绑定field,与按钮配合使用)
* buttons:[{
* text:’收货’, //显示文本
* call:’tackGoods’, //点击事件 参数tackGoods(index(当前索引),item(当前对象))
* type:’link button’ //类型 link:a标签 button:按钮
* state:'checkstorage', //跳转路由 注(只有当后台传回按钮数据op.butType=link 才会跳转)
* style:’’ //设置样式
* }] //启用按钮 与type:operate配合使用 可多个按钮
* style:’width:10px’ //设置样式
*
*/
'use strict';
define(['../../../app'], function(app) {
app.factory('packBusiness', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) {
return {
getThead: function() {
return [{
name:'序号',
type:'pl4GridCount'
}, {
field: 'taskId',
name: '业务单号'
}, {
field: 'pickTime',
name: '拣货日期'
}, {
field: 'customerID',
name: '客户'
},{
field: 'goodsCount',
name: '拣货数量'
}, {
field: 'op',
name: '操作',
type: 'operate',
buttons: [{
text: '包装',
btnType: 'link',
state: 'orderPack',
isBtnShow:'1'
}]
}]
},
getTheadChange: function() {
return [{
name:'序号',
type:'pl4GridCount'
}, {
field: 'taskId',
name: '业务单号'
}, {
field: 'packTime',
name: '包装日期'
}, {
field: 'customerID',
name: '客户'
}, {
field: 'userName',
name: '操作人'
},{
field: 'goodsCount',
name: '拣货数量 '
}, {
field: 'op',
name: '操作',
type: 'operate',
buttons: [{
text: '查看',
btnType: 'link',
state: 'orderPack'
},{
text: '打印清单',
btnType: 'btn',
call:'print',
style: 'font-size:10px;'
}]
}]
},
getSearch: function(data) {
data.param = $filter('json')(data.param);
//console.log()
var deferred = $q.defer();
$http.post(HOST + '/orderBox/getDicLists',data)
.success(function(data) {
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e);
});
return deferred.promise;
},
getDataTable: function(data) {
//将param转换成json字符串
data.param = $filter('json')(data.param);
var deferred = $q.defer();
$http.post(HOST + '/orderBox/queryOrderBoxList', data)
.success(function(data) {
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e);
});
return deferred.promise;
}
}
}]);
}); |
import * as home from './action-type'
export const saveBanner = ( data ) => {
return {
type : home.saveBanner ,
data
}
} |
var request = require('request');
const common = require('./common');
//const { response } = require('express');
//need to handle for all the metricanmes
exports.metricAlert = async(req,res) =>{
try {
Promise.all(req.query.metricnames.map(async function (eachMetricName){
url = `https://management.azure.com/${req.query.scope}/providers/Microsoft.Insights/metrics?api-version=2018-01-01&aggregation=${req.query.aggregation}&metricnames=${eachMetricName}&interval=${req.query.interval}×pan=${req.query.timespan}`
response = await common.getCommon(url,req.header('Authorization'))
if(response.value.length !== 0){
var data = response.value[0].timeseries[0].data
var aggr = (req.query.aggregation).toLowerCase()
data.forEach(element => {
if(!element[aggr]){
element[aggr] = null }
});
return response
}else{
return response
}
})).then((results)=>{
res.send(results)
}).catch(err=>{
res.status(400).send(err)
})
} catch(error) {
console.log(error)
res.status(404).send({"Error":"Error in getting response"})
}
}
|
import React from 'react';
import logo from './logo.svg';
import './App.css';
import App1 from './App1';
import { useTranslation } from 'react-i18next';
import Particles from 'react-particles-js';
const App = () => {
const { t, i18n } = useTranslation();
const changeLang = lang => {
i18n.changeLanguage(lang)
}
const style = {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
overflow: "hidden"
};
return (
<div className="App">
<header className="App-header">
<div style={style}>
<Particles
params={{
"particles": {
"number": {
"value": 50
},
"size": {
"value": 3
}
},
"interactivity": {
"events": {
"onhover": {
"enable": true,
"mode": "repulse"
}
}
}
}} />
</div>
<div style={{ zIndex: 2 }}>
<button className="button" onClick={() => changeLang('en')} > English </button>
<button className="button" onClick={() => changeLang('hi')} > Hindi </button>
<button className="button" onClick={() => changeLang('de')} > Germany </button>
</div>
<img src={logo} className="App-logo" alt="logo" />
<App1 />
<h4>{t('title')}</h4>
<h3>{t('description')}</h3>
</header>
</div>
);
}
export default App;
|
// Constant
export const acrossBackFactor = 0.97
export const frontOverlap = 0.01
export const frontArmholeDeeper = 0.005
// Fit
export const armholeDepthFactor = { pct: 70, min: 60, max: 80, menu: 'fit' }
export const backScyeDart = { deg: 2, min: 0, max: 6, menu: 'fit' }
export const centerBackDart = { pct: 2, min: 0, max: 5, menu: 'fit' }
export const chestEase = { pct: 2, min: 1, max: 10, menu: 'fit' }
export const frontScyeDart = { deg: 6, min: 0, max: 12, menu: 'fit' }
export const hipsEase = { pct: 8, min: 2, max: 15, menu: 'fit' }
export const lengthBonus = { pct: 1, min: 0, max: 8, menu: 'fit' }
export const waistEase = { pct: 8, min: 2, max: 15, menu: 'fit' }
// Style
export const buttons = { count: 6, min: 4, max: 12, menu: 'style' }
export const frontStyle = { dflt: 'classic', list: ['classic', 'rounded'], menu: 'style' }
export const hemRadius = { pct: 6, min: 2, max: 12, menu: 'style' }
export const hemStyle = { dflt: 'classic', list: ['classic', 'rounded', 'square'], menu: 'style' }
export const necklineDrop = { pct: 50, min: 35, max: 85, menu: 'style' }
export const pocketLocation = { pct: 35, min: 25, max: 55, menu: 'style' }
export const pocketWidth = { pct: 10, max: 15, min: 8, menu: 'style' }
export const weltHeight = { pct: 12.5, max: 20, min: 10, menu: 'style' }
// Advanced
export const backInset = { pct: 15, min: 10, max: 20, menu: 'advanced' }
export const frontInset = { pct: 15, min: 10, max: 20, menu: 'advanced' }
export const shoulderInset = { pct: 10, min: 0, max: 20, menu: 'advanced' }
export const neckInset = { pct: 5, min: 0, max: 10, menu: 'advanced' }
export const pocketAngle = { deg: 5, min: 0, max: 5, menu: 'advanced' }
|
import Link from 'next/link';
import React from 'react';
import useSticky from '../../hooks/use-sticky';
import MobileMenu from './mobile-menu';
import NavMenus from './nav-menus';
const HeaderTwo = () => {
const { headerSticky } = useSticky();
return (
<React.Fragment>
<header className="d-none d-lg-block">
<div id="header-sticky" className={`tp-header-area-two header-transparent header-space-three pl-115 pr-115
${headerSticky ? 'header-sticky' : ''}`}>
<div className="container-fluid">
<div className="row align-items-center header-space-two">
<div className="col-xxl-3 col-xl-3 col-lg-3">
<div className="tp-logo text-start">
<Link href="/">
<a>
<img src="/assets/img/logo/logo-blue.png" alt="" />
</a>
</Link>
</div>
</div>
<div className="col-xxl-6 col-xl-6 col-lg-6">
<div className="tp-main-menu text-center">
<nav id="mobile-menu">
{/* nav menus start */}
<NavMenus />
{/* nav menus end */}
</nav>
</div>
</div>
<div className="col-xxl-3 col-xl-3 col-lg-3">
<div className="tp-header-button text-end">
<Link href="/contact">
<a className="tp-btn">Let’s Talk 👋</a>
</Link>
</div>
</div>
</div>
</div>
</div>
</header>
{/* <!-- mobile-menu-area --> */}
<MobileMenu logo={"logo-blue.png"} />
{/* <!-- mobile-menu-area-end --> */}
</React.Fragment>
);
};
export default HeaderTwo; |
var Dom = require('xmldom').DOMParser;
var fs = require('fs');
var FileKeyInfo = require('xml-crypto').FileKeyInfo;
var select = require('xml-crypto').xpath.SelectNodes;
var SignedXml = require('xml-crypto').SignedXml;
/**
* this piece of middleware verifies a digital signature from a soap web service
**/
module.exports = function (req, res, next) {
var app = req.app, logger = app.logger, soap = app.body.raw;
if (validateXml(logger, soap, app.getPublicKey()) === false) {
logger.log('info', 'itkevents', {message: 'The digital signature failed verification'});
var err = new Error("The digital signature failed verification");
return next(err);
}
logger.log('info', 'itkevents', {message: 'The digital signature was successfully validated'});
return next();
};
/**
* need to rewrite this function to be defensive
*/
function validateXml(logger, xml, key) {
try {
var doc = new Dom().parseFromString(xml);
var signature = select(doc, "/*/*[local-name(.)='Header']/*[local-name(.)='Security']/*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']");
var sig = new SignedXml();
sig.keyInfoProvider = new FileKeyInfo(key);
sig.loadSignature(signature.toString());
var res = sig.checkSignature(xml);
if (!res) {
logger.log('info', 'itkevents', {message: 'Signature Errors : ' + sig.validationErrors});
}
return res;
}
catch (err) {
logger.log('info', 'itkevents', {message: 'Error validating XML '+ err});
return false;
}
}
|
import Codeck from '../src/Codeck'
const smallDeck = ['AS', 'KS', 'QS', 'JS']
const smallCharset = [' ', 'X']
describe('Codeck', () => {
test('Can be instantiated with or without `new`', () => {
expect(new Codeck()).toBeInstanceOf(Codeck)
expect(Codeck()).toBeInstanceOf(Codeck)
})
test('Can be given a custom deck and charset', () => {
const codeck = new Codeck(smallDeck, smallCharset)
expect(codeck.deck).toBe(smallDeck)
expect(codeck.charset).toBe(smallCharset)
})
test('computes a sensible max length', () => {
const codec = new Codeck(smallDeck, smallCharset)
expect(codec.maxLength).toBe(4)
})
test('encodes', () => {
const codec = new Codeck(smallDeck, smallCharset)
expect(codec.encode(' X')).toEqual(['AS', 'KS', 'JS', 'QS'])
})
test('decodes', () => {
const codec = new Codeck(smallDeck, smallCharset)
expect(codec.decode(['AS', 'KS', 'JS', 'QS'])).toBe(' X')
})
test('runs symetrically on larger datasets', () => {
const codec = new Codeck()
const message = 'hello there'
expect(codec.decode(codec.encode(message)).trim()).toBe(message)
})
})
|
const mongoose = require("mongoose");
const userModel= require("./createTask");
// to read task by id
module.exports = readTask =async (id,owner)=>{
try{
const task = await userModel.findOne({ _id:id, createdBy: owner })
if(!task){
throw "Task not found";
}
return task;
} catch(e){
throw e;
}
}
|
'use strict';
/**
* @ngdoc overview
* @name cookieApp
* @description
* # cookieApp
*
* Main module of the application.
*/
/*angular
.module('cookieApp', [
'ngCookies'
]);*/
angular
.module('cookieApp', ["ui.router","ngCookies"]).controller('zd',['$scope','$http','$cookieStore',function ($scope,$http,$cookieStore) {
var username=$cookieStore.get("username");
var password=$cookieStore.get("password");
$scope.updata={
username:uesrname,
password:password
}
}]).config(['$stateProvider','$urlRouterProvider',function ($stateProvider,$urlRouterProvider){
$stateProvider.state('denglu',{
url:'/denglu',
templateUrl:'views/denglu.html',
controller:'denglu'
}).state('zhuce',{
url:'/zhuce',
templateUrl:'views/zhuce.html',
controller:'zhuce'
}).state('riji',{
url:'/riji',
templateUrl:'views/riji.html',
controller:'riji'
}).state('zx',{
url:'/zx?id&title&content',
templateUrl:'views/zx.html',
controller:'zx'
}).state('add',{
url:'/add',
templateUrl:'views/add.html',
controller:'add'
})
$urlRouterProvider.when('','/denglu')
}])
|
const inquirer = require('inquirer')
const clear = require('clear')
const edit = (next, task) => inquirer
.prompt([
{
type: 'input',
name: 'update',
message: `Update`,
default: () => `${task.name}`,
validate: function (value) {
return value !== ''
}
}
]).then(answers => {
console.log('answers ->', answers['update'])
task.update(answers['update'])
next()
})
module.exports = edit |
'use strict';
const { expect } = require('chai');
const { createStubInstance } = require('sinon');
const {
CollectionReference,
DocumentReference,
Firestore
} = require('@google-cloud/firestore');
const StaffMembershipRequestRepository = require('../../../src/lib/repository/staff-membership-request-repository');
const request = {
providerId: 'TEST-PROVIDER',
businessName: 'TEST-BUSINESS-NAME',
requestorUid: 'TEST-REQUESTOR',
requestedStaffMemberEmail: 'test@test.com'
};
describe('staff-membership-request-repository unit tests', () => {
let repo, firestore;
let collectionReference, documentReference;
before(() => {
firestore = createStubInstance(Firestore);
collectionReference = createStubInstance(CollectionReference);
documentReference = createStubInstance(DocumentReference);
collectionReference.doc.returns(documentReference);
collectionReference.where.returns(documentReference);
documentReference.collection.returns(collectionReference);
firestore.collection.returns(collectionReference);
repo = new StaffMembershipRequestRepository(firestore);
});
afterEach(() => {
documentReference.get.resetHistory();
documentReference.set.resetHistory();
documentReference.delete.resetHistory();
documentReference.create.resetHistory();
collectionReference.doc.resetHistory();
collectionReference.where.resetHistory();
documentReference.collection.resetHistory();
documentReference.create.resetHistory();
collectionReference.add.resetHistory();
firestore.runTransaction.resetHistory();
documentReference.delete.resetHistory();
});
context('create', () => {
it('should save the document', () => {
collectionReference.add.resolves({ id: 'TEST' });
expect(repo.create(request)).to.be.fulfilled.then(documentId => {
expect(
collectionReference.add.calledWith({
providerId: 'TEST-PROVIDER',
businessName: 'TEST-BUSINESS-NAME',
requestorUid: 'TEST-REQUESTOR',
requestedStaffMemberEmail: 'test@test.com',
status: 'NEW'
})
).to.be.true;
expect(documentId).to.equal('TEST');
});
});
});
context('findById', () => {
it('should return request when found', () => {
documentReference.get.resolves({
id: 'TEST-ID',
data: () => request,
exists: true
});
expect(repo.findById('TEST-ID')).to.be.fulfilled.then(response => {
expect(response).to.deep.equal({
id: 'TEST-ID',
providerId: 'TEST-PROVIDER',
businessName: 'TEST-BUSINESS-NAME',
requestorUid: 'TEST-REQUESTOR',
requestedStaffMemberEmail: 'test@test.com'
});
});
});
it('should return empty object when nothing is found', () => {
documentReference.get.resolves({
exists: false
});
expect(repo.findById('TEST-ID')).to.be.fulfilled.then(response => {
expect(response).to.deep.equal({});
});
});
it('should return empty object when doc reference is undefined', () => {
documentReference.get.resolves(undefined);
expect(repo.findById('TEST-ID')).to.be.fulfilled.then(response => {
expect(response).to.deep.equal({});
});
});
});
context('findByRequestedEmail', () => {
it('should return found documents', () => {
documentReference.get.resolves({
forEach: func =>
func({
id: 'TEST-ID',
data: () => request
}),
empty: false
});
expect(repo.findByRequestedEmail('TEST-EMAIL')).to.be.fulfilled.then(
result => {
expect(result).to.deep.equal([
{
id: 'TEST-ID',
providerId: 'TEST-PROVIDER',
businessName: 'TEST-BUSINESS-NAME',
requestorUid: 'TEST-REQUESTOR',
requestedStaffMemberEmail: 'test@test.com'
}
]);
}
);
});
it('should return nothing if no documents are found', () => {
documentReference.get.resolves({
empty: true
});
expect(repo.findByRequestedEmail('TEST-EMAIL')).to.be.fulfilled.then(
result => {
expect(result).to.deep.equal([]);
}
);
});
});
context('update', () => {
it('should resolve if request exists', () => {
firestore.runTransaction.callsFake(
async func => await func(documentReference)
);
documentReference.get.resolves({
data: () => request,
exists: true
});
documentReference.set.resolves();
expect(
repo.update('TEST-ID', {
status: 'APPROVED',
staffMemberUid: 'TEST'
})
).to.be.fulfilled.then(() => {
expect(collectionReference.doc.calledWith('TEST-ID')).to.be.true;
expect(documentReference.set.called).to.be.true;
});
});
it('should reject if provider does not exists', () => {
firestore.runTransaction.callsFake(
async func => await func(documentReference)
);
documentReference.get.resolves({
exists: false
});
documentReference.set.resolves();
expect(
repo.update('TEST-ID', {
status: 'APPROVED',
staffMemberUid: 'TEST'
})
).to.be.rejected.then(err => {
expect(collectionReference.doc.calledWith('TEST-ID')).to.be.true;
expect(documentReference.set.called).to.be.false;
expect(err.code).to.equal('REQUEST_NOT_EXISTING');
});
});
});
});
|
import {LOAD_PRODUCTS_BY_CATEGORY, LOAD_PRODUCTS_BY_CATEGORY_ERROR} from "../constants/productConstant";
const DEFAULT_STATE = {
products: [],
loading: true
};
export default function(state = DEFAULT_STATE, action) {
switch (action.type) {
case LOAD_PRODUCTS_BY_CATEGORY:
return { ...state, products: action.payload, loading:false }
case LOAD_PRODUCTS_BY_CATEGORY_ERROR:
return {loading: false, error:action.payload}
default:
return state;
}
};
|
// ==UserScript==
// @name Assignments UC Paste Comments
// @namespace https://jorgecardoso.eu
// @version 0.1
// @license MIT
// @description Allows pasting Comments directly on the Assignments page of the InforDocente system of the University of Coimbra. Just copy (Ctrl-C) a table from a spreadsheet file making sure that there is a column with the student number and a column with the comments (the comments column should be the last column). Then open the assignment page and press Ctrl-V; a button will appear: click on it and wait for all comments to be inserted.
// @author jorgecardoso
// @copyright 2020, Jorge C. S. Cardoso (https://jorgecardoso.eu)
// @match https://infordocente.uc.pt/nonio/ensino/detalhesSubmissaoTrabalhos.do*
// @match https://infordocente.uc.pt/nonio/ensino/detalhesSubmissaoAluno.do*
// @match https://infordocente.uc.pt/nonio/ensino/adicionarAlterarApreciacao.do*
// @grant none
// @updateURL https://openuserjs.org/meta/jorgecardoso/Assignments_UC_Paste_Comments.meta.js
// ==/UserScript==
(function() {
'use strict';
if ( window.location.href.indexOf("detalhesSubmissaoTrabalhos.do") >= 0) {
console.log("Entregas Trabalhos UC");
document.querySelector("body").addEventListener("paste", function(evt){
var data = evt.clipboardData.getData("text/plain");
console.log("Pasted data: ");
var newData = "";
var insideQuote = false;
for (var i = 0; i < data.length; i++) {
if (data[i] === "\"" ) {
insideQuote = !insideQuote;
console.log("quote");
}
if (data[i] === "\n" && insideQuote) {
newData += "####";
} else {
newData += data[i];
}
}
//console.log(data);
console.log(newData);
var rawTable = newData.split("\n");
var dataTable = [];
rawTable.forEach(function(row) {
var r = row.split("\t").map(function(s) {return s.trim();});
dataTable.push(r);
});
console.log(dataTable);
localStorage.setItem("dataTable", JSON.stringify(dataTable));
var automateButton = document.createElement('button');
automateButton.innerText = "Go";
automateButton.style.cssText = "position: fixed; right:0; top:50%";
document.body.appendChild(automateButton);
automateButton.addEventListener("click", function() {
console.log("Automating");
var linksToProcess = [];
// get all links for student numbers present in our data table
var rows = document.querySelectorAll("table td:nth-last-child(6),table td:nth-last-child(7)");
rows.forEach(function(row){
console.log(row);
if (existsInTable(dataTable, row.innerText.trim())) {
console.log("exists");
linksToProcess.push(row.parentElement.querySelector("[href^=\"detalhesSubmissaoAluno.do\"]"));
}
});
console.log(linksToProcess);
// var allLinks = document.querySelectorAll("[href^=\"detalhesSubmissaoAluno.do\"]");
var currentLink = 0;
window.addEventListener("message", function(event) {
console.log("received", event);
setTimeout(function() {
processNextStudent();
}, 1000);
}, false);
//console.log(allLinks);
var processNextStudent = function() {
currentLink++;
console.log("Current Link", currentLink);
if (currentLink < linksToProcess.length) {
win.location= linksToProcess[currentLink].href+"&automate=true";
console.log("Opened URL", linksToProcess[currentLink].href+"&automate=true");
//setTimeout( returnCloseWindow(window), 5000);
}
};
var win = window.open(linksToProcess[currentLink].href+"&automate=true");
});
});
} else if ( window.location.href.indexOf("detalhesSubmissaoAluno.do") >= 0 && window.location.href.indexOf("automate=true") >= 0) {
console.log("Entregas Trabalhos UC Aluno");
var adicionar = document.querySelector("[href^=\"adicionarAlterarApreciacao.do\"]");
if (adicionar !== null) {
window.location = adicionar.href+"&automate=true";
}
} else if ( window.location.href.indexOf("adicionarAlterarApreciacao.do") >= 0 && window.location.href.indexOf("automate=true") >= 0 ) {
window.onload = function() {
console.log("Entregas Trabalhos UC Aluno: Apreciacao");
var dataTable = JSON.parse(localStorage.getItem("dataTable"));
console.log(dataTable);
if (dataTable) {
var editor = document.querySelector("#htmlhelper_ifr");
console.log(editor);
// setTimeout(function() {
var autores = document.querySelector("#adicionarAlterarApreciacaoFormBean table tr:nth-child(3) td:nth-child(2)");
var studentNumbers = Array.from(new Set(autores.innerText.match(/\d\d\d\d\d\d\d\d\d\d/gi)));
console.log(studentNumbers);
var first = true;
var innerDoc = editor.contentDocument || editor.contentWindow.document;
var textField = innerDoc.getElementById("tinymce");
for (var i = 0; i < studentNumbers.length; i++ ) {
console.log(studentNumbers[i]);
for ( var j = 0; j < dataTable.length; j++) {
for ( var k = 0; k < dataTable[j].length; k++) {
//console.log(dataTable[j][k]);
if (studentNumbers[i] === dataTable[j][k] ) {
if (first) {
textField.innerText = "";
first = false;
}
console.log(dataTable[j][dataTable[j].length-1]);
textField.innerText += dataTable[j][dataTable[j].length-1].replace(/####/g, '\n').replace(/"/g, '');
}
}
}
}
if (!first) {
var visible = document.querySelector("input[name=\"visivelAlunos\"]");
visible.checked = true;
var gravar = document.querySelector("input[type=\"submit\"][value=\"Gravar\"]");
window.opener.postMessage("ok", "*");
gravar.click();
}
// }, 3000);
}
};
}
function existsInTable(dataTable, value) {
for ( var j = 0; j < dataTable.length; j++) {
for ( var k = 0; k < dataTable[j].length; k++) {
//console.log(dataTable[j][k]);
if (value === dataTable[j][k] ) {
return true;
}
}
}
return false;
}
})(); |
import angular from 'angular'
(function() {
'use strict'
angular.module('tc.account').config(routes)
routes.$inject = ['$stateProvider']
function routes($stateProvider) {
var states = {
'auth': {
parent: 'root',
abstract: true,
data: {
authRequired: false
}
},
logout: {
url: '/logout/',
views: {
'header@': {},
'container@': {
controller: 'LogoutController'
},
'footer@': {}
},
data: {
authRequired: false
}
}
}
angular.forEach(states, function(state, name) {
$stateProvider.state(name, state)
})
}
})()
|
$(document).ready(function(){
(function(){
$("input:password").bind("copy cut paste",function(e){
return false;
});
$("#reg").validate({
rules:{
userName:{
required: true,
rangelength:[5,10],
remote : {
url:'is_user.php',
type : 'POST',
}
},
email:{
required: true,
email: true,
},
password:{
required: true,
rangelength:[5,10],
},
repeat_password:{
required: true,
equalTo: "#password"
},
},
messages: {
userName: {
required:"请输入用户名",
rangelength: jQuery.validator.format("请输入一个长度介于 {0} 和 {1} 之间用户名"),
remote:"用户名已经被占用",
},
email: {
required: "请输入Email地址",
email: "请输入正确的email地址"
},
password: {
required: "请输入密码",
rangelength: jQuery.validator.format("请输入一个长度介于 {0} 和 {1} 之间的密码"),
},
repeat_password: {
required: "请输入确认密码",
minlength: "确认密码不能小于5个字符",
equalTo: "两次输入密码不一致"
}
},
errorPlacement: function(error, element) {
$(element).parent().parent().children(".my_error").append(error);
//alert($(element).parent().parent().children(".my_error").html());
},
submitHandler: function(form)
{
$.post("add-user.php",
$('#reg').serialize()
,function(data,status){
$.cookie('user',$('#userName').val());
$(".user_member,.login_out").show();
$(".user_login,.user_reg").hide();
$(".user_member").html($('#userName').val());
$('#myModal').modal('hide');
});
}
});
$(".user_member,.login_out").hide();
if( $.cookie('user')){
$(".user_member,.login_out").show();
$(".user_login,.user_reg").hide();
$(".user_member").html($.cookie('user'));
}else{
$(".user_member,.login_out").hide();
$(".user_login,.user_reg").show();
}
$('.login_out').click(function () {
$.removeCookie('user');
window.location.Reload();
});
})();
(function(){
$("#login_form").validate({
submitHandler: function(form)
{
$.post("login.php",
$('#login_form').serialize()
,function(data,status){
$.cookie('user',$('#login_user').val());
$(".user_member,.login_out").show();
$(".user_login,.user_reg").hide();
$(".user_member").html($.cookie('user'));
$('#myModal2').modal('hide');
});
//$(form).ajaxSubmit({
// url : 'login.php',
// type : 'POST',
// success : function (responseText, statusText) {
//
// }
//});
},
rules:{
login_user:{
required: true,
rangelength:[5,10],
},
login_pass:{
required: true,
rangelength:[5,10],
remote : {
url : 'login.php',
type : 'POST',
data : {
login_user : function () {
return $('#login_user').val();
},
},
},
}
},
messages:{
login_user:{
required:"请输入用户名",
rangelength: jQuery.validator.format("请输入长度介于 {0} 和 {1} 之间用户名"),
},
login_pass:{
required: "请输入密码",
rangelength: jQuery.validator.format("请输入长度介于 {0} 和 {1} 之间的密码"),
remote : '帐号或密码不正确!',
}
},
errorLabelContainer : 'ol.my_error',
wrapper : 'li',
//onsubmit:false,
//onfocusout:false,
//onkeyup:false,
//onclick:false,
});
})();
}); |
import NodeSelector from "./NodeSelector"
export default NodeSelector
|
/* See license.txt for terms of usage */
define([
"firebug/lib/trace",
],
function(FBTrace) {
// xxxHonza: FBTrace isn't available when loading from within bootstrap.js
// The default FBTrace implementation should buffer all logs that are fired
// before the tracing console is opened.
// ********************************************************************************************* //
// Constants
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
// ********************************************************************************************* //
// Module
var Server =
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Initialization
initialize: function()
{
try
{
Cu.import("resource:///modules/devtools/dbg-server.jsm");
DebuggerServer.init(function() { return true; });
// Add built-in actors (like e.g. debugger actors)
DebuggerServer.addBrowserActors();
// devtools.debugger.remote-enabled pref must be true
// Set devtools.debugger.force-local pref to false in order to
// allow remote cross-machine connections.
// xxxHonza: get the port number from preferences
DebuggerServer.closeListener();
DebuggerServer.openListener(5999, false);
this.hookPackets();
}
catch (ex)
{
Cu.reportError(ex);
}
},
shutdown: function()
{
FBTrace.sysout("Server; shutdown");
// xxxHonza: what if there are other tools sharing the connection?
DebuggerServer.closeListener();
},
/**
* Just for debugging purposes only. Hook server side packet communication
* and log it into the tracing console.
*/
hookPackets: function()
{
var onSocketAccepted = DebuggerServer.onSocketAccepted;
DebuggerServer.onSocketAccepted = function(aSocket, aTransport)
{
onSocketAccepted.apply(this, arguments);
var conn;
for (var p in this._connections)
{
conn = this._connections[p];
break;
}
if (!conn)
return;
var onPacket = conn.onPacket;
conn.onPacket = function(packet)
{
FBTrace.sysout("PACKET RECEIVED " + JSON.stringify(packet), packet);
onPacket.apply(this, arguments);
}
var send = conn._transport.send;
conn._transport.send = function(packet)
{
send.apply(this, arguments);
FBTrace.sysout("PACKET SEND " + JSON.stringify(packet), packet);
}
}
}
}
// ********************************************************************************************* //
// Registration
return Server;
// ********************************************************************************************* //
});
|
// Show the table with the robot
/**
* Draw the table with the robot on screen.
*
* @param {object} state Simulation state.
*/
export function draw(state) {
// Set the CSS variables for the number of rows and columns
document.documentElement.style.setProperty("--colNum", state.xMax + 1);
document.documentElement.style.setProperty("--rowNum", state.yMax + 1);
let tableElement = document.querySelector(".ToyRobot-table");
let totalCells = (state.xMax + 1) * (state.yMax + 1);
let cellHtml = "<div class='ToyRobot-tableCell'></div>";
if (state.x === null) {
// No robot -> show empty table
tableElement.innerHTML = cellHtml.repeat(totalCells);
} else {
// Robot: exists
// Show it on the board
// Number of cells before and after robot
let cellsAfter = state.y * (state.xMax + 1) + state.xMax - state.x;
let cellsBefore = totalCells - cellsAfter - 1;
tableElement.innerHTML = '';
// Show empty cells before robot
tableElement.innerHTML = cellHtml.repeat(cellsBefore);
let direction = `ToyRobot-robotFace-${state.direction}`;
// Cell with the robot
tableElement.innerHTML += `<div class='ToyRobot-tableCell'>
<img class='ToyRobot-robot ${direction}' src='./images/robot.svg' />
</div>`;
// Empty cells after robot
tableElement.innerHTML += cellHtml.repeat(cellsAfter);
}
}
|
var person = readline("Please enter your name", "Harry Potter");
console.log('hello'+ person) |
module.exports = require('./filter.js')
|
'use strict'
let lolConfig = require('./lolConfig')
module.exports = {
lolConfig
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import Index from './pages/index';
import Vendor from './pages/Vendor';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import './assets/styles/app.css';
const theme = createMuiTheme({
palette: {
type: 'dark',
background: {
main: 'red',
},
primary: {
main: '#ffd000',
light: '#00c853',
},
secondary: {
main: '#311b92'
},
//text: {
// primary: 'rgba(0, 0, 0, 0.75)'
//},
// These properties below do nothing:
primary1Color: "rgba(0, 200, 83, 0.85)",
primary2Color: "#00c853",
primary3Color: "#9e9e9e",
accent1Color: "#311b92",
//textColor: "rgba(0, 0, 0, 0.75)",
shadowColor: "rgba(0, 0, 0, 0.4)"
}
});
ReactDOM.render(<MuiThemeProvider theme={theme}><Index /></MuiThemeProvider>, document.getElementById('root'));
|
import Mock from 'mockjs';
import $store from '../../../store/index.js'
const login_adminUrl = $store.state.mock.url.loginAdminUrl;
const login_admin = {
'success': true,
'flag':'login_success',
'user|1': [
{
"data": {
"grade": 0,
"account": /^[a-zA-Z]{1,3}[a-zA-Z0-9]{5,7}$/,
"name": '西兰花的春天', //随机产生一个中文的姓名
"pass": /^[a-zA-Z0-9]{6,10}$/,
"jobNum": '@guid',
'token': /^Gcx_broccoliSpring_[a-zA-Z0-9]{10,12}_HelloNicetoMeetyou_myWechat_lensgcx$/,
'email': "@EMAIL",
"sex|1": [ //性别
'male', 'female', 'secrecy',
'male', 'female', 'male', 'female'
],
"birthday": '@date("yyyy-MM-dd")', //出生日期
"WeChat": /^[a-zA-Z]{1,3}[a-zA-Z0-9]{5,7}$/, //微信号
"mobile": /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}|14[7]\d{8}|15[89]\d{8}|18[0-9]\d{8}$/, //手机号
"roles|1": ['总监', '设计师', '运营经理', '制版师', '行政财务'],//角色
"remarks|1": ["优秀员工","骨干员工"], //备注
"status": 'admin',
"sign":'前端建筑设计师,灵魂画师,生活艺术家,价值观导师',
'random|1-100': 1, //1-100随机数
"avatar": function () {
return 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';
},
/* ===================== 入职日期(YY-MM-DD HH:mm:ss) ===================== */
'year|2005-2017': 0,
'm|0-12': 0,
'd|0-30': 0,
"month": function (n) {
const m = parseInt(n.context.currentContext.m);
if (m < 10) {
return '0' + m;
}
else {
return m;
}
},
"day": function (n) {
const d = parseInt(n.context.currentContext.d);
if (d < 10) {
return '0' + d;
}
else {
return d;
}
},
't': '@time("HH:mm:ss")',
"entry_date": function (n) {
const date1 = parseInt(n.context.currentContext.year) + "-" + n.context.currentContext.month + "-" + n.context.currentContext.day;
return date1 + " " + n.context.currentContext.t;
},
}
}
]
};
/**
* mockTest_login_admin
* @param url
* @param tem
*/
const mockTest_login_admin = function (url, tem) {
Mock.mock(url, tem);
};
export {login_adminUrl, login_admin, mockTest_login_admin}
|
const youreSuperSpecial = false;
const doYouLikeCarrotCake = "yes I do";
console.log({ youreSuperSpecial, doYouLikeCarrotCake });
|
/**
* Created by ssanchez on 28/12/15.
*/
/**
* Home controller
*
* @param $rootScope
* @param $scope
* @constructor
*/
function HomeCtrl ($rootScope, $scope, $window) {
$scope.scrollerNavVisible = true;
}
/**
* Se añadio la funcionalidad
* al buscador de la home
*
* @param $rootScope
* @param $window
* @param $document
* @returns {{restrict: string, link: Function}}
*/
function scrollernav ($rootScope, $window, $document) {
return {
'restrict': 'C',
'link': function ($scope, $element, $attrs) {
var window = angular.element($window),
body = angular.element($document[0].body),
element = angular.element($element);
window.on('scroll', function () {
if (window.scrollTop() > 360) {
body.removeClass('specialheader');
element.removeClass('specialSearch');
}
else {
body.addClass('specialheader');
element.addClass('specialSearch');
}
});
}
}
}
app
.controller('HomeCtrl', [
'$rootScope',
'$scope',
'$window',
HomeCtrl
])
.directive('scrollernav', [
'$rootScope',
'$window',
'$document',
scrollernav
]);
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
describe('App tests', () => {
it('App renders without a problem', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
it('Snapshot matches', () => {
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
it('h1 exists', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('h1').exists()).toBe(true);
expect(wrapper.find('h1').text()).toBe('Show text app');
});
it('button exists', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('button').exists()).toBe(true);
});
it('button changes text according to state', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('button').text()).toBe('Hide');
wrapper.setState({
isTextShown: false
})
expect(wrapper.find('button').text()).toBe('Show');
});
it('handleClick', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('button').text()).toBe('Hide');
expect(wrapper.find('p').exists()).toBe(true);
wrapper.find('button').simulate('click');
expect(wrapper.find('button').text()).toBe('Show');
expect(wrapper.find('p').exists()).toBe(false);
});
it('p exists', () => {
const wrapper = shallow(<App />);
wrapper.setState({
isTextShown: true
})
expect(wrapper.find('p').exists()).toBe(true);
wrapper.setState({
isTextShown: false
})
expect(wrapper.find('p').exists()).toBe(false);
});
}); |
import React from "react"
import rp from "request-promise"
import mathjs from "mathjs"
import katex from "katex"
import Sherlock from "sherlockjs" // time parsing library
const {clipboard} = window.require("electron")
const wolframtoken = require("./secret.js").wolframToken
const dataURI = require("./dataURIs.js")
const electron = window.require("electron") // little trick to import electron in react
const remote = electron.remote
const Store = remote.require("electron-store")
const factStore = new Store({name: "fact"})
export default [
{
keys: ["remember"],
enterHandler: query => {
const sherlocked = Sherlock.parse(query)
const start = new Date()
const interval = setInterval(() => {
const now = new Date()
if (now >= sherlocked.startDate) {
alert(sherlocked.eventTitle)
clearInterval(interval)
}
}, (start - sherlocked.startDate) / 10)
},
preview: query => (
<div style={{height: "100%"}}>
<img
alt="clock"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.wr}
/> remember {query}
</div>
),
},
{
keys: ["fact", "fc"],
enterHandler: query => alert(factStore.get(query)),
preview: query => (
<div style={{height: "100%"}}>
<img
alt="logo wr"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.wr}
/>
{factStore.get(query.trim())}
</div>
),
},
{
keys: ["factAdd", "fcAdd"],
enterHandler: query => {
try {
factStore.set(
query.split("=")[0].trim(),
query.split("=")[1].trim()
)
} catch (e) {
alert("wrong formatting, use = to create a new fact")
}
},
preview: query => (
<div style={{height: "100%"}}>
<img
alt="logo wr"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.wr}
/> add fact {query}
</div>
),
},
{
keys: ["wr"],
enterHandler: query =>
window.open(
"http://www.wordreference.com/definition/" +
encodeURIComponent(query)
),
preview: query => (
<div style={{height: "100%"}}>
<img
alt="logo wr"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.wr}
/>
{query}
</div>
),
},
{
keys: ["wrenit"],
enterHandler: query =>
window.open(
"http://www.wordreference.com/enit/" + encodeURIComponent(query)
),
preview: query => (
<div style={{height: "100%", lineHeight: "44px"}}>
<img
alt="logo wrenit"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.en_it}
/>
{query}
</div>
),
},
{
keys: ["writen"],
enterHandler: query =>
window.open(
"http://www.wordreference.com/iten/" + encodeURIComponent(query)
),
preview: query => (
<div style={{height: "100%", lineHeight: "44px"}}>
<img
alt="logo writen"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.it_en}
/>
{query}
</div>
),
},
{
keys: ["goo.gl", "shorten"],
enterHandler: query => {
var options = {
method: "POST",
uri:
"https://www.googleapis.com/urlshortener/v1/url/?key=" +
require("./secret.js").googlToken,
body: {
longUrl: query,
},
json: true, // Automatically stringifies the body to JSON
}
rp(options).then(res => clipboard.writeText(res.id))
},
preview: query => "Shorten " + query,
},
{
keys: ["wolfram", "wm"],
enterHandler: query =>
window.open(
"https://www.wolframalpha.com/input/?i=" +
encodeURIComponent(query)
),
asyncPreview: query =>
rp(
"https://api.wolframalpha.com/v1/result?i=" +
encodeURIComponent(query) +
"&appid=" +
wolframtoken
)
.then(function(result) {
try {
const node = mathjs.parse(result)
const tex = node.toTex()
const html = katex.renderToString(tex)
return (
<div style={{height: "100%"}}>
<img
alt="logo wolfram"
style={{verticalAlign: "middle"}}
width="50px"
src={dataURI.wolfram}
/>
<span
dangerouslySetInnerHTML={{__html: html}}
/>
</div>
)
} catch (e) {
console.log(e)
return (
<div>
<img alt="logo wolfram" src={dataURI.wolfram} />
{result}
</div>
)
}
})
.catch(() => {
return "no short answer available"
}),
},
{
keys: ["word"],
enterHandler: query => rp("http://setgetgo.com/randomword/get.php"),
asyncPreview: query => rp("http://setgetgo.com/randomword/get.php"),
},
// {
// keys: ["mw"],
// enterHandler: query =>
// window.open(
// "https://www.merriam-webster.com/thesaurus/" +
// encodeURIComponent(query)
// ),
// asyncPreview: query =>
// rp(
// "http://www.dictionaryapi.com/api/v1/references/thesaurus/xml/" +
// encodeURIComponent(query) +
// "?key=05935704-c40b-4514-a43a-913757cebf5c"
// )
// .then(function(xml){
// return <div><image src="https://assets2.merriam-webster.com/mw/static/app-standalone-images/MW_logo.png" />BOH</div>
// })
// .catch(function(e){
// return "not found"
// }),
// },
]
|
import React from 'react';
import ReactDOM from 'react-dom';
// import createReactClass from 'create-react-class';
const Welcome = ((props) => {
return (
<div>
<h4>Welcome to my site, {props.firstName}!</h4>
<h4>{props.lastName}</h4>
</div>
)
});
class App extends React.Component {
nameMapper(nameArray) {
return nameArray.map((name, i) =>
<li key={i}>{name}</li>
);
}
render() {
const nameArray = ['Chris', 'Jane', 'BillyBob', 'JoeyJoeJoe', 'Mary'];
return (
<div>
<Welcome firstName="Marcin" lastName="Kopanski"/>
<ul>
{this.nameMapper(nameArray)}
</ul>
<Welcome firstName="Jane" lastName="Doe" />
</div>
)
}
}
// const App = createReactClass({
//
// nameMapper: function() {
// const nameArray = ['Chris', 'Jane', 'BillyBob', 'JoeyJoeJoe', 'Mary'];
//
// return nameArray.map((name, i) =>
// <li key={i}>{name}</li>
// );
// },
//
// render: function() {
// return (
// <div>
// <Welcome firstName="Marcin" lastName="Kopanski"/>
// <ul>
// {this.nameMapper}
// </ul>
// <Welcome firstName="Jane" lastName="Doe" />
// </div>
// )
// }
// });
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
import React from 'react'
import Link from 'gatsby-link'
const IndexPage = () => (
<div>
<h1>Reformulação do site</h1>
<p>A versão atual do site do OpenStreetMap Brasil é feita em jekyll e hospedada via Github Pages. Este é o primeiro esboço do site no processo de migração para uma <a href="https://jamstack.org">jamstack</a>.</p>
</div>
)
export default IndexPage
|
/*
* ProGade API
* Copyright 2012, Hans-Peter Wandura (ProGade)
* Last changes of this file: Aug 22 2012
*/
var PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NAME = 0;
var PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_START = 1;
var PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_END = 2;
var PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NOSLASHES = 3;
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_CodeHighlighter()
{
// Declarations...
this.iMaxMappings = 10000;
this.bHighlightCommands = true;
this.bHighlightFunctions = true;
this.asCommands = new Array();
this.asFunctions = new Array();
this.asDelimiters = new Array();
this.asCodeMap = new Array();
// Construct...
// Methods...
this.init = function()
{
this.addDelimiter('DoubleQuotes', '"', '"', true);
this.addDelimiter('SingleQuotes', "'", "'", true);
this.addDelimiter('MultiLineComments', '/*', '*/', false);
this.addDelimiter('SingleLineComments', '//', '\n', false);
}
this.addDelimiter = function(_sName, _xStart, _xEnd, _bNoSlahes)
{
this.asDelimiters.push(new Array());
this.asDelimiters[this.asDelimiters.length-1][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NAME] = _sName;
this.asDelimiters[this.asDelimiters.length-1][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_START] = _xStart;
this.asDelimiters[this.asDelimiters.length-1][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_END] = _xEnd;
this.asDelimiters[this.asDelimiters.length-1][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NOSLASHES] = _bNoSlahes;
}
this.highlight = function(_sCode)
{
var _oRegExp;
var _sSearch = '';
var _asCommands = new Array('function', 'for', 'while', 'if', 'else', 'while', 'foreach', 'each', 'do', 'echo', 'true', 'false', 'null');
var _asFunctions = new Array('include', 'isset', 'define', 'defined', 'error_reporting', 'unset', 'date', 'mktime', 'time', 'explode', 'implode', 'str_replace', 'preg_match', 'preg_replace', 'replace', 'utf8_decode', 'utf8_encode');
var _asCode = this.parse(_sCode);
_sCode = '';
for (var i=0; i<_asCode.length; i++)
{
if (_asCode[i][0] != 'Code')
{
_sCode += '<span style="';
switch (_asCode[i][0])
{
case 'DoubleQuotes':
case 'SingleQuotes':
_sCode += 'color:#CC0000;';
break;
case 'MultiLineComments':
case 'SingleLineComments':
_sCode += 'color:#ff9900;';
break;
}
_sCode += '">';
}
else
{
// _asCode[i][1] = _asCode[i][1].replace(/(<\?php)/gi, '<span style="color:#ff0000;">$1</span>');
// _asCode[i][1] = _asCode[i][1].replace(/(\?>)/g, '<span style="color:#ff0000;">$1</span>');
_asCode[i][1] = _asCode[i][1].replace(/([\+\-\*\/=\?!]{1,3}|[\-\+\.]{1,2})/g, '<span style="color:#00AA00;">$1</span>');
_asCode[i][1] = _asCode[i][1].replace(/\b([0-9]+)\b/g, '<span style="color:#ff0000;">$1</span>');
_asCode[i][1] = _asCode[i][1].replace(/(\$_REQUEST|\$_POST|\$_GET|\$_SERVER)/g, '<span style="color:#5588ff;">$1</span>');
var t=0;
if (this.bHighlightCommands == true)
{
_sSearch = '(';
for (t=0; t<_asCommands.length; t++)
{
// _sSearch = '(^|\\\s|;|{|}|\\\))('+_asCommands[t]+')(\\\s|$|\\\(|{|})';
// _sSearch = '(\\b'+_asCommands[t]+'\\b)';
if (t > 0) {_sSearch += '|';}
_sSearch += '\\b'+_asCommands[t]+'\\b';
}
_sSearch += ')';
_oRegExp = new RegExp(_sSearch, 'gi');
_asCode[i][1] = _asCode[i][1].replace(_oRegExp, '<span style="color:#00AA00;">$1</span>');
}
if (this.bHighlightFunctions == true)
{
_sSearch = '(';
for (t=0; t<_asFunctions.length; t++)
{
// _sSearch = '(\\b'+_asFunctions[t]+'\\b)';
if (t > 0) {_sSearch += '|';}
_sSearch += '\\b'+_asFunctions[t]+'\\b';
}
_sSearch += ')';
_oRegExp = new RegExp(_sSearch, 'g');
_asCode[i][1] = _asCode[i][1].replace(_oRegExp, '<span style="color:#0000ff;">$1</span>');
}
}
_sCode += _asCode[i][1];
if (_asCode[i][0] != 'Code') {_sCode += '</span>';}
}
return _sCode;
}
this.isNoSlash = function(_sCode, _iPos)
{
if (_iPos < 0) {return false;}
if (_iPos-1 >= 0)
{
if (_sCode.charAt(_iPos-1) == '\\') {return false;}
}
return true;
}
this.indexOfDelimiterWithoutSlash = function(_sCode, _sDelimiterStart, _iPos)
{
var _iAbortCounter = 0;
var _iCurrentPos = _iPos;
_iPos = -1;
do
{
if (this.isNoSlash(_sCode, _iCurrentPos)) {_iPos = _iCurrentPos;}
else
{
_iCurrentPos = _sCode.indexOf(_sDelimiterStart, _iCurrentPos+1);
}
_iAbortCounter++;
if (_iAbortCounter > 50) {return _sCode.length-1;}
}
while ((_iPos === -1) && (_iCurrentPos !== -1))
return _iPos;
}
this.parse = function(_sCode, _iMaxMappings)
{
this.init(); // only for testing purpose
this.asCodeMap = new Array();
if (!_sCode)
{
this.asCodeMap.push(new Array('Code', _sCode));
return this.asCodeMap;
}
var _iIndex = 0;
var _sDelimiterName = '';
var _sDelimiterStart = '';
var _sDelimiterEnd = '';
var _iCurrentPos = 0;
var _iStartPos = 0;
var _iEndPos = 0;
if (typeof(_iMaxMappings) == 'undefined') {_iMaxMappings = this.iMaxMappings;}
var _iFoundIndex = 0;
while ((_iEndPos < _sCode.length) && (this.asCodeMap.length < _iMaxMappings))
{
_iStartPos = -1;
_iFoundDelimiter = 0;
// find next map delimiter...
for (_iIndex = 0; _iIndex < this.asDelimiters.length; _iIndex++)
{
_sDelimiterStart = this.asDelimiters[_iIndex][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_START];
_iCurrentPos = _sCode.indexOf(_sDelimiterStart, 0);
if (this.asDelimiters[_iIndex][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NOSLASHES] == true)
{
_iCurrentPos = this.indexOfDelimiterWithoutSlash(_sCode, _sDelimiterStart, _iCurrentPos);
}
if (((_iCurrentPos < _iStartPos) || (_iStartPos === -1)) && (_iCurrentPos !== -1))
{
_iFoundIndex = _iIndex;
_iStartPos = _iCurrentPos;
}
}
// Map code...
if (_iStartPos !== -1)
{
if (_iStartPos > 0)
{
this.asCodeMap.push(new Array('Code', _sCode.substr(0, _iStartPos)));
_sCode = _sCode.substr(_iStartPos, _sCode.length-_iStartPos);
}
_iStartPos = 0;
_sDelimiterName = this.asDelimiters[_iFoundIndex][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NAME];
_sDelimiterEnd = this.asDelimiters[_iFoundIndex][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_END];
_iEndPos = _sCode.indexOf(_sDelimiterEnd, 1);
if (this.asDelimiters[_iFoundIndex][PG_CODEHIGHLIGHTER_DELIMITERS_INDEX_NOSLASHES] == true)
{
_iEndPos = this.indexOfDelimiterWithoutSlash(_sCode, _sDelimiterEnd, _iEndPos);
}
if (_iEndPos !== -1)
{
this.asCodeMap.push(new Array(_sDelimiterName, _sCode.substr(_iStartPos, _iEndPos+1)));
_sCode = _sCode.substr(_iEndPos+1, _sCode.length-_iEndPos);
}
else {/* todo: no end delimiter found in code */}
}
else
{
_iEndPos = _sCode.length;
this.asCodeMap.push(new Array('Code', _sCode));
_sCode = '';
}
}
if (_sCode.length > 0) {this.asCodeMap.push(new Array('Code', _sCode));}
return this.asCodeMap;
}
}
/* @end class */
classPG_CodeHighlighter.prototype = new classPG_ClassBasics();
var oPGCodeHighlighter = new classPG_CodeHighlighter();
|
import React from 'react';
import { shallow } from 'enzyme';
import { Link } from 'react-router-dom';
import Welcome from './Welcome';
describe('Welcome', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Welcome />);
});
it('Should contain an h1 displaying the word "Stratagem"', () => {
expect(wrapper.containsMatchingElement(<h1>Stratagem</h1>)).toBe(true);
})
it('Should contain an h5 displaying the words "Online Diplomacy"', () => {
expect(wrapper.containsMatchingElement(
<h5>Online Diplomacy</h5>
)).toBe(true);
})
it('Should contain a button that links to the login page', () => {
expect(wrapper.containsMatchingElement(
<Link to="/login">Login</Link>
)).toBe(true);
})
it('Should contain a button that links to the signup page', () => {
expect(wrapper.containsMatchingElement(
<Link to="/signup">Signup</Link>
)).toBe(true);
})
}) |
"use strict";
class Utils {
/**
* Función getRandomIndexOfArray: Retorna una posición random desde un array.
* @param {Array} array
* @returns {Number} newRandomPosition
*/
static getRandomIndexOfArray(array) {
return Math.floor(Math.random() * Number(array.length));
}
/**
* Función getRandomPhrase: Retorna un string random desde un array.
* @param {Array} array
* @returns {String} newText
*/
static getRandomPhrase(array) {
var i = 0;
i = Math.floor(Math.random() * Number(array.length));
return (array[i]);
}
/**
* Función isUpperCharacter: Retorna True si el caracter es mayúscula, False si es minúscula y undefined si no cumple las condiciones anteriores.
* @param {String} character
* @returns {Boolean} bolean
*/
static isUpperCharacter(character) {
if (/[A-Z]/.test(character)) {
console.VIPLog("Is Upper Case: " + character);
return true;
} else if (/[a-z]/.test(character)) {
console.VIPLog("Is Lower Case: " + character);
return false;
} else {
console.VIPLog("Is A Number: " + character);
return undefined;
}
}
/**
* Función parserIntToAlphabetic: Retorna un string aleatorio del tamaño de la variable length
* @param {Number} length
* @returns {String} string
*/
static generateRandomString(length) {
let randomString = '';
const stringValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++)
randomString += stringValues.charAt(Math.floor(Math.random() * stringValues.length));
return randomString;
}
}
module.exports = Utils; |
(function (window) {
'use strict';
/*
* GAME CONFIGURATION
*/
var Game = {
init: function () {
this.canvas = document.getElementById("game");
this.canvas.width = this.canvas.width;
this.canvas.height = this.canvas.height;
this.ctx = this.canvas.getContext("2d");
this.colour = "rgba(20,20,20,.7)";
this.bullets = [];
this.enemyBullets = [];
this.enemies = [];
this.maxEnemies = Config.maxEnemies;
this.currentFrame = 0;
this.maxLives = Config.maxLives;
this.binding();
this.player = new Player();
//this.laser = new Audio('audio/laser.mp3');
this.score = 0;
this.shooting = false;
this.isGameOver = false;
this.isPaused = false;
this.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
// Spawn enemies at the begining of the game.
for (var i = 0; i < this.maxEnemies; i++) {
this.enemies.push(new Enemy(i));
}
// Begin game render loop.
this.loop();
},
// Setup listeners to control the game.
binding: function() {
window.addEventListener("keydown", this.buttonDown);
window.addEventListener("keyup", this.buttonUp);
window.addEventListener("keypress", this.keyPressed);
},
// When player press spacebar, check if player hasn't made a shot. If so fire a shot.
// Check if game is over ,if so restart the game. Also, prevent the default action of spacebar.
keyPressed: function(e) {
e.preventDefault();
if (e.keyCode === Config.keys.shoot) {
Game.player.shoot();
if (Game.isGameOver) {
Game.init();
}
} else if(e.keyCode === Config.keys.pause && !Game.isPaused) {
Game.isPaused = true;
} else if(e.keyCode === Config.keys.pause && Game.isPaused) {
Game.isPaused = false;
Game.currentFrame = Game.requestAnimationFrame.call(window, Game.loop);
}
},
// When player releases spacebar. Tell the game logic that the player had fired.
// If player release left or right keys, stop player from moving in that direction.
buttonUp: function(e) {
e.preventDefault();
if (e.keyCode === Config.keys.shoot) {
Game.shooting = false;
}
if (e.keyCode === Config.keys.left || e.keyCode === Config.keys.leftArrow) {
Game.player.movingLeft = false;
}
if (e.keyCode === Config.keys.right || e.keyCode === Config.keys.rightArrow) {
Game.player.movingRight = false;
}
},
// When player holds down spacebar, fire multiple shots. If player press left, move left indefinitely.
// If player press right, move right indefinitly.
buttonDown: function(e) {
if (e.keyCode === Config.keys.shoot) {
Game.shooting = true;
//Game.laser.play();
}
if (e.keyCode === Config.keys.left || e.keyCode === Config.keys.leftArrow) {
Game.player.movingLeft = true;
}
if (e.keyCode === Config.keys.right || e.keyCode === Config.keys.rightArrow) {
Game.player.movingRight = true;
}
},
// Random number generator.
random: function(min, max) {
return Math.floor(Math.random() * (max - min) + min);
},
// Check if two objects collided with each other. Using the x and y coordinates on the canvas.
collision: function(a, b) {
return !(
((a.y + a.height) < (b.y)) ||
(a.y > (b.y + b.height)) ||
((a.x + a.width) < b.x) ||
(a.x > (b.x + b.width))
)
},
// Clear the canvas by painting it white, up to the width and height specified in the configuration.
clear: function() {
this.ctx.fillStyle = Game.colour;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
},
// When the game is over. Clear the game canvas. Display game over message along with the high score.
gameOver: function() {
this.isGameOver = true;
this.clear();
var message = "Game Over";
var message2 = "Score: " + Game.score;
var message3 = "Click or press Spacebar to Play Again";
this.ctx.fillStyle = "white";
this.ctx.font = "bold 30px Lato, sans-serif";
this.ctx.fillText(message, this.canvas.width / 2 - this.ctx.measureText(message).width / 2, this.canvas.height / 2 - 50);
this.ctx.fillText(message2, this.canvas.width / 2 - this.ctx.measureText(message2).width / 2, this.canvas.height / 2 - 5);
this.ctx.font = "bold 16px Lato, sans-serif";
this.ctx.fillText(message3, this.canvas.width / 2 - this.ctx.measureText(message3).width / 2, this.canvas.height / 2 + 30);
},
pause: function() {
this.clear();
var message = "PAUSED";
var message2 = "Score: " + Game.score;
var message3 = "Click or press P to Unpause";
this.ctx.fillStyle = "white";
this.ctx.font = "bold 30px Lato, sans-serif";
this.ctx.fillText(message, this.canvas.width / 2 - this.ctx.measureText(message).width / 2, this.canvas.height / 2 - 50);
this.ctx.fillText(message2, this.canvas.width / 2 - this.ctx.measureText(message2).width / 2, this.canvas.height / 2 - 5);
this.ctx.font = "bold 16px Lato, sans-serif";
this.ctx.fillText(message3, this.canvas.width / 2 - this.ctx.measureText(message3).width / 2, this.canvas.height / 2 + 30);
},
// Every game frame redraw the game score and the player's life.
updateScore: function() {
this.ctx.fillStyle = "white";
this.ctx.font = "16px Lato, sans-serif";
this.ctx.fillText("Score: " + this.score, 8, 20);
this.ctx.fillText("Lives Left: " + (this.maxLives), 8, 40);
},
// Main game loop that draws multiple enemies, player and bullets on the canvas.
loop: function() {
if (Game.isGameOver) {
Game.gameOver();
} else if(Game.isPaused) {
Game.pause();
} else {
// Clear the canvas.
Game.clear();
// Draw & update enemies.
for (var i in Game.enemies) {
var currentEnemy = Game.enemies[i];
currentEnemy.draw();
currentEnemy.update();
// If the game frame number can be full divided by the shooting speed fire.
if (Game.currentFrame % currentEnemy.shootingSpeed === 0) {
currentEnemy.shoot();
}
}
// Draw and update enemy bullets.
for (var x in Game.enemyBullets) {
Game.enemyBullets[x].draw();
Game.enemyBullets[x].update();
}
// Draw and update the player's bullets.
for (var z in Game.bullets) {
Game.bullets[z].draw();
Game.bullets[z].update();
}
// Draw the player once
Game.player.draw();
// Every frame update the player's position, score and change to the next frame.
// At the end of the loop.
Game.player.update();
Game.updateScore();
Game.currentFrame = Game.requestAnimationFrame.call(window, Game.loop);
}
}
};
/*
* PLAYER CONFIGURATION
*/
var Player = function() {
this.width = Config.player.width;
this.height = Config.player.height;
this.x = Game.canvas.width / 2 - this.width / 2;
this.y = Game.canvas.height - this.height;
this.movingLeft = false;
this.movingRight = false;
this.shootSpeed = Config.player.shootSpeed;
this.speed = Config.player.speed;
this.colour = Config.player.colour;
};
// Player die event. If player was hit and reduce their remaining lives.
// Otherwise, the game is over.
Player.prototype.die = function() {
if (Game.maxLives > 1) {
Game.maxLives--;
} else {
Game.maxLives = 0;
Game.gameOver();
}
};
// Draws the player on the canvas by drawing and painting the player white.
Player.prototype.draw = function() {
Game.ctx.fillStyle = this.colour;
Game.ctx.fillRect(this.x, this.y, this.width, this.height);
};
// Updates the player location and check if the player was hit by enemy bullets.
Player.prototype.update = function() {
if (this.movingLeft && this.x > 0) {
this.x -= this.speed;
}
if (this.movingRight && this.x + this.width < Game.canvas.width) {
this.x += this.speed;
}
if (Game.shooting && Game.currentFrame % this.shootSpeed === 0) {
this.shoot();
}
for (var i in Game.enemyBullets) {
var currentBullet = Game.enemyBullets[i];
if (Game.collision(currentBullet, this)) {
this.die();
delete Game.enemyBullets[i];
}
}
};
// Player's shoot function.
Player.prototype.shoot = function() {
Game.bullets.push(new Bullet(this.x + this.width / 2, Game.canvas.height - Config.player.height, Config.bullet.colour, Game.bullets.length, this));
};
/*
* BULLET CONFIGURATION
*/
var Bullet = function(x, y, colour, index, source) {
this.width = Config.bullet.width;
this.height = Config.bullet.height;
this.x = x;
this.y = y;
this.index = index;
this.active = true;
this.colour = colour;
this.source = source;
};
// Draw bullets on the canvas.
Bullet.prototype.draw = function() {
Game.ctx.fillStyle = this.colour;
Game.ctx.fillRect(this.x, this.y, this.width, this.height);
};
// Update the bullet's location by updating the x and y coordinates.
// Once the bullet reaches the top of the canvas remove bullet from canvas.
Bullet.prototype.update = function() {
if(this.source instanceof Player) {
this.y -= Config.player.bulletSpeed;
if (this.y < 0) {
delete Game.bullets[this.index];
}
}else if(this.source instanceof Enemy){
this.y += Config.enemy.bulletSpeed;
if (this.y > Game.canvas.height) {
delete Game.enemyBullets[this.index];
}
}
};
/*
* ENEMY CONFIGURATION
*/
var Enemy = function(index) {
this.width = Config.enemy.width;
this.height = Config.enemy.height;
this.x = Game.random(0, (Game.canvas.width - this.width));
this.y = Game.random(10, 40);
this.vy = Game.random(1, 3) * .1;
this.index = index;
this.speed = Game.random(Config.enemy.speedLowerLimit, Config.enemy.speedLowerLimit);
this.shootingSpeed = Config.enemy.shootSpeed;
this.movingLeft = Math.random() < 0.5 ? true : false;
this.colour = "hsl(" + Game.random(0, 360) + ", 60%, 50%)";
};
// Draw the enemies on the canvas.
Enemy.prototype.draw = function() {
Game.ctx.fillStyle = this.colour;
Game.ctx.fillRect(this.x, this.y, this.width, this.height);
};
// Update the current enemy location on the canvas. Checks if it had collided with the player's bullet.
// If so remove current enemy and bullet from canvas.
Enemy.prototype.update = function() {
if (this.movingLeft) {
if (this.x > 0) {
this.x -= this.speed;
this.y += this.vy;
} else {
this.movingLeft = false;
}
} else {
if (this.x + this.width < Game.canvas.width) {
this.x += this.speed;
this.y += this.vy;
} else {
this.movingLeft = true;
}
}
for (var i in Game.bullets) {
var currentBullet = Game.bullets[i];
if (Game.collision(currentBullet, this)) {
this.die();
delete Game.bullets[i];
}
}
};
// When an enemy dies, update the score by the set amount and creates enemies
// and spawn them after n seconds have passed.
Enemy.prototype.die = function() {
Game.enemies.pop(this);
delete this;
Game.score += Config.score;
if (Game.enemies.length < Game.maxEnemies) {
setTimeout(function() {
Game.enemies.push(new Enemy(Game.enemies.length));
}, Config.enemy.spawnTimeout);
}
};
// When shooting, create a new bullet on the canvas.
Enemy.prototype.shoot = function() {
Game.enemyBullets.push(new Bullet(this.x + this.width / 2, this.y, this.colour, Game.enemyBullets.length, this));
};
// Begin the game.
Game.init();
}(window));
|
/**
*
* @license Andy Mercer, (c) Stack Exchange Inc
* licensed under CC BY-SA 3.0 - https://creativecommons.org/licenses/by-sa/3.0/
* source: https://stackoverflow.com/a/38225299/14570657
*
* Modified into ES6
*
* */
HTMLSelectElement.prototype.contains = function (value) {
for (let option of this.options) {
if (option.value === value) {
return true;
}
}
return false;
} |
module.exports = function (req, res) {
req.getCredentials(function (error, credentials) {
if (error) res.json({ authenticated: false });
else res.json({ authenticated: credentials });
});
}
|
import React, { useEffect, Fragment, useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getMyProfile, createProfile } from '../../actions/profile';
import { getJournals } from '../../actions/journal';
import { Form, Row, Col, ListGroup } from 'react-bootstrap';
import { Link, Redirect } from 'react-router-dom';
import { Button, Grid, Header, Icon } from 'semantic-ui-react';
export const EditProfile = ({
getMyProfile,
createProfile,
profile: { profile, loading },
getJournals,
journal: { journals },
history,
auth: { user },
}) => {
const [formData, setFormData] = useState({
bio: '',
status: '',
allPrivate: '',
});
useEffect(() => {
getMyProfile();
getJournals();
setFormData({
bio: loading || !profile.bio ? '' : profile.bio,
status: loading || !profile.status ? '' : profile.status,
allPrivate: loading || !profile.allPrivate ? '' : profile.allPrivate,
});
}, [loading, getMyProfile, getJournals, profile.allPrivate, profile.bio, profile.status]);
const { bio, status, allPrivate } = formData;
const onChange = (e) =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = (e) => {
e.preventDefault();
createProfile(formData, history, true);
};
if (createProfile.edit) {
return <Redirect to='/journals/mine' />;
}
return (
<Fragment>
<hr />
<Link to='/journals/mine'>
<Button inverted color='blue' animated>
<Button.Content visible>Back To Jounals</Button.Content>
<Button.Content hidden>
<Icon name='arrow left' />
</Button.Content>
</Button>
</Link>
<div className='login well well-lg'>
<Header as='h2' color='blue' textAlign='center'>
<Header.Content>Edit Your Profile</Header.Content>
</Header>
</div>
<hr />
<Grid container textAlign='justified' columns='equal' divided>
{/* curr user's journal List */}
<Grid.Column width={4}>
<ListGroup>
<ListGroup.Item variant='primary'>Journal List:</ListGroup.Item>
{journals.length > 0 ? (
journals.map((journal) => (
<Link key={journal._id} to={`/journals/journal/${journal._id}`}>
<ListGroup.Item action variant='light' key={journal._id}>
{journal.title}
</ListGroup.Item>
</Link>
))
) : (
<ListGroup>
<ListGroup.Item>No Journals Found</ListGroup.Item>
<Button inverted color='blue' className='m-2'>
<Link to='/create-journal'>Write a journal</Link>
</Button>
</ListGroup>
)}
</ListGroup>
</Grid.Column>
{/* User's profile details */}
<Grid.Column width={12}>
<Grid celled='internally'>
<Grid.Row>
<Grid.Column>
<Header as='h2' icon='user secret' content='Details:' />
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Form stacked='true' onSubmit={(e) => onSubmit(e)}>
<Form.Group as={Row}>
<Form.Label column sm={3}>
Username:
</Form.Label>
<Form.Label column sm={9}>
{user.username}
</Form.Label>
</Form.Group>
<Form.Group as={Row}>
<Form.Label column sm={3}>
Status:
</Form.Label>
<Col sm={9}>
<input
type='text'
className='formControl'
name='status'
value={status}
placeholder='Personal status'
onChange={(e) => onChange(e)}
/>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Form.Label column sm={3}>
Bio:
</Form.Label>
<Col sm={9} className='green-border-focus'>
<Form.Control
as='textarea'
className='formControl'
name='bio'
placeholder='About yourself...'
value={bio}
row='5'
onChange={(e) => onChange(e)}
></Form.Control>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Form.Label column sm={3}>
Set journals all private?
</Form.Label>
<Col sm={9}>
<Form.Control
as='select'
name='allPrivate'
value={allPrivate}
onChange={(e) => onChange(e)}
>
<option>true</option>
<option>false</option>
</Form.Control>
</Col>
</Form.Group>
<Row>
<Col md={{ span: 4, offset: 5 }}>
<Button.Group>
<Link to='/journals/mine'>
<Button>Cancel</Button>
</Link>
<Button.Or />
<Button
inverted
color='blue'
type='submit'
value='EditProfile'
>
Save
</Button>
</Button.Group>
</Col>
</Row>
</Form>
</Grid.Column>
</Grid.Row>
</Grid>
</Grid.Column>
</Grid>
<Button
className='back-to-top'
floated='right'
basic
color='blue'
as='a'
icon='arrow circle up'
href='#top'
content='Top'
/>
</Fragment>
);
};
EditProfile.propTypes = {
getMyProfile: PropTypes.func.isRequired,
profile: PropTypes.object.isRequired,
journal: PropTypes.object.isRequired,
createProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
profile: state.profile,
journal: state.journal,
auth: state.auth,
});
export default connect(mapStateToProps, {
createProfile,
getJournals,
getMyProfile,
})(EditProfile);
|
"use strict";
/***********************************************/
/* script to setup map and initialise plots */
/***********************************************/
const map = L.map('mapid', { renderer: L.canvas(), worldCopyJump: true }).setView([0, 0], 3);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=sk.eyJ1IjoibWF5b2UiLCJhIjoiY2s3Z2VxZXM1MDQwMTNnbnVyYTg0MTlleCJ9.bFoFArF7FLimIxUBMjYZkA', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
minZoom: 1,
maxZoom: 8,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'sk.eyJ1IjoibWF5b2UiLCJhIjoiY2s3Z2VxZXM1MDQwMTNnbnVyYTg0MTlleCJ9.bFoFArF7FLimIxUBMjYZkA',
}).addTo(map);
const ISSIcon = L.icon({
iconUrl: './img/ISSIcon.png',
iconSize: [50, 30],
iconAnchor: [25, 15],
popupAnchor: [50, 25],
});
const drawPolyLine = (prevLoc, newLoc) => {
const latlongs = [prevLoc, newLoc];
new L.Polyline(latlongs, {
color: '#000',
opacity: 1,
weight: 1,
clickable: false,
}).addTo(map);
};
const iss = L.marker([0, 0], { icon: ISSIcon }).addTo(map);
const isscirc = L.circle([0, 0], 2200e3, { color: "#c22", opacity: 0.3, weight: 1, fillColor: "#c22", fillOpacity: 0.1 }).addTo(map);
isscirc.setRadius(500000);
/******************************************************************/
/* perform HTTP GET requests via AJAX and update map plots */
/******************************************************************/
// API docs: https://wheretheiss.at/w/developer
const positionUrl = `https://api.wheretheiss.at/v1/satellites/25544`;
const updateMap = (resp) => {
const { latitude, longitude, altitude, velocity } = resp; // destructure JSON object
const { lat, lng } = iss.getLatLng();
if ((lat !== 0 && lng !== 0) && !(lng > 179 && longitude < -179)) {
drawPolyLine([lat, lng], [latitude, longitude]);
}
iss.setLatLng([latitude, longitude]);
isscirc.setLatLng([latitude, longitude]);
map.panTo([latitude, longitude], { animate: true });
document.getElementById('iss-info').innerHTML = `Latitude: ${latitude}</br>Longitude: ${longitude}</br>Altitude: ${altitude}km</br>Velocity: ${velocity}km/h`;
setTimeout(() => performHttpGet(positionUrl, updateMap, showError), 5000);
};
const showError = () => {
map.removeLayer(iss);
map.removeLayer(isscirc);
document.getElementById('iss-info').innerHTML = `Tracker details could not be fetched. Please try reloading the page.`;
};
performHttpGet(positionUrl, updateMap, showError);
|
/*
公共视图
*/
let View = require("../../frameworks/mvc/View");
cc.Class({
extends: View,
properties: {
WAITING_ZORDER: 10,
waiting: null,
},
//显示透明loading并屏蔽掉所有事件响应
showWaiting(param) {
if (!this.waiting) {
// this.waiting = new WaitingLayer();
// this.addChild(this.waiting, this.WAITING_ZORDER);
}
if (param && !param.isAutoDestroy) {
//强制设置非自动销毁
//this.waiting.setAutoDestroy(false);
} else {
//this.waiting.startAutoDestroy();
}
},
//移除透明loading
removeWaiting() {
// if (this.waiting)
// this.removeChild(this.waiting);
//
// this.waiting = null;
},
}); |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
class Dropdown extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
children: null,
};
}
render() {
return (
<div className="bui-dropdown-container">
<button
onBlur={() => {
this.setState({
boolShowContent: false,
});
}}
onFocus={() => {
this.setState({
boolShowContent: true,
});
}}
>
{this.props.text || '下拉菜单'}
<i
className={classnames(this.props.icon, {
active: this.boolShowContent,
hide: !this.props.icon,
})}
/>
</button>
<div
className={classnames('bui-dropdown-content', {
hide: !this.state.boolShowContent,
})}
>
{this.props.children}
</div>
</div>
);
}
}
Dropdown.propTypes = {
children: PropTypes.any,
text: PropTypes.string,
icon: PropTypes.string,
};
export default Dropdown;
|
function LikeButton(props){
return React.createElement('button', {}, props.titulo);
} |
// Controllers list
define([
'./generator',
'./mosaic'
], function(){}); |
'use strict';
module.exports = function(sequelize, DataTypes) {
var jobType = sequelize.define('jobType', {
typeName: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return jobType;
};
|
<%@ page import="org.opencms.jsp.*,
org.opencms.workplace.*,
org.opencms.main.*,
org.opencms.file.types.CmsResourceTypeBinary" %><%
%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%
CmsJspActionElement cms = new CmsJspActionElement(pageContext, request, response);
pageContext.setAttribute("cms", cms);
CmsDialog dialog = new CmsDialog(pageContext, request, response);
pageContext.setAttribute("locale", dialog.getLocale().toString());
String itemResType = CmsResourceTypeBinary.getStaticTypeName();
%><fmt:setLocale value="${locale}" />
<fmt:bundle basename="org.opencms.ade.galleries.messages">
// nesting a FCKDialogCommand to use dynamic the dialog URLs
/**
* The dialog command constructor.<p>
*/
var dialogCommand = function() {
this.Name = "OcmsDownloadGallery";
}
/**
* Returns the command state.<p>
*
* @return the state
*/
dialogCommand.prototype.GetState = function() {
return FCK_TRISTATE_OFF;
}
/**
* Executes the command.<p>
*
* @return void
*/
dialogCommand.prototype.Execute = function() {
var command=new FCKDialogCommand(
'OcmsDownloadGallery',
'<%= dialog.key("GUI_DOWNLOAD_GALLERY_TITLE_0") %>',
downloadGalleryDialogUrl(),
685,
577
);
command.Execute();
}
//register the related commands
FCKCommands.RegisterCommand(
"OcmsDownloadGallery",
new dialogCommand());
//create the "OcmsDownloadGallery" toolbar button
//syntax: FCKToolbarButton(commandName, label, tooltip, style, sourceView, contextSensitive)
var opencmsDownloadGalleryItem = new FCKToolbarButton('OcmsDownloadGallery', '<%= dialog.key("GUI_DOWNLOAD_GALLERY_TITLE_0") %>', '<%= dialog.key("GUI_DOWNLOAD_GALLERY_TITLE_0") %>', null, false, true);
opencmsDownloadGalleryItem.IconPath = FCKConfig.SkinPath + "toolbar/oc-downloadgallery.gif";
//"OcmsDownloadGallery" is the name that is used in the toolbar configuration
FCKToolbarItems.RegisterItem("OcmsDownloadGallery", opencmsDownloadGalleryItem);
/**
* Returns if there is text selected within the FCKEditor.<p>
*
* @return <code>boolean</code> <code>true</code> if text is selected
*/
function hasSelectedText() {
var sel;
if (FCKBrowserInfo.IsIE) {
sel = FCK.EditorWindow.selection;
} else {
sel = FCK.EditorWindow.getSelection();
}
if ((FCKSelection.GetType() == 'Text' || FCKSelection.GetType() == 'Control') && sel != '') {
return true;
}
return false;
}
/**
* Searches for a frame by the specified name. Will only return siblings or ancestors.<p>
*
* @return <code>Frame</code> the frame or <code>null</code> if no matching frame is found
*/
function findFrame(startFrame, frameName){
if (startFrame == top){
// there may be security restrictions prohibiting access to the frame name
try{
if (startFrame.name == frameName){
return startFrame;
}
}catch(err){}
return null;
}
for (var i=0; i<startFrame.parent.frames.length; i++){
// there may be security restrictions prohibiting access to the frame name
try{
if (startFrame.parent.frames[i].name == frameName) {
return startFrame.parent.frames[i];
}
}catch(err){}
}
return findFrame(startFrame.parent, frameName);
}
/**
* Returns the path to the download gallery dialog with some request parameters for the dialog.<p>
*
* @return <code>String</code> the dialog URL
*/
function downloadGalleryDialogUrl() {
var path=null;
if (hasSelectedText() == true) {
var a = FCK.Selection.MoveToAncestorNode('A') ;
if (a) {
// link present
FCK.Selection.SelectNode(a);
//path to resource
path = a.getAttribute("_fcksavedurl");
// in case of a newly created link, use the href attribute
if (path == null || path==""){
path=a.getAttribute("href");
}
}
}
var resParam = "";
var editFrame=findFrame(self, 'edit');
if (editFrame.editedResource != null) {
resParam = "&resource=" + editFrame.editedResource;
} else {
resParam = "&resource=" + editFrame.editform.editedResource;
}
// set the content locale
var elementLanguage="${locale}";
try{
elementLanguage=editFrame.editform.document.forms['EDITOR']['elementlanguage'].value;
}catch(err){
// nothing to do
}
var searchParam = "&types=<%=itemResType %>¤telement="+ ( path==null ? "" : path)+"&__locale="+elementLanguage;
return "<%= cms.link("/system/modules/org.opencms.ade.galleries/gallery.jsp") %>?dialogmode=editor" + searchParam + resParam;
}
</fmt:bundle> |
{
"version": 1603013902,
"fileList": [
"data.js",
"c2runtime.js",
"jquery-3.4.1.min.js",
"offlineClient.js",
"images/player-sheet0.png",
"images/laser-sheet0.png",
"images/bugenemy-sheet0.png",
"images/crescentenemy-sheet0.png",
"images/fighterenemy-sheet0.png",
"images/bladeenemy-sheet0.png",
"images/saucerenemy-sheet0.png",
"images/scytheenemy-sheet0.png",
"images/slicerenemy-sheet0.png",
"icon-16.png",
"icon-32.png",
"icon-114.png",
"icon-128.png",
"icon-256.png",
"loading-logo.png"
]
} |
const app = require('./app')
const mongodbConn = require('./db/mongodb/mongodbConn')
const { dbConfig } = require('./config')
const port = process.env.PORT || 3001
async function appInit( port, app, dbConfig ){
try {
await mongodbConn( dbConfig )
await app.listen(port, () => console.log(`listen: ${port}`))
}
catch ( e ){
console.error(`Error appInit: ${e.message}`)
}
}
appInit(port, app, dbConfig) |
angular
.module('altairApp')
.controller("orgPublicCtrl", ['$scope','lptypes','role_data',
function ($scope,lptypes,role_data) {
$scope.domain="com.peace.users.model.mram.SubLegalpersons.";
var tool=[];
var com=[];
if(role_data[0].create>0){
tool.push("create");
// tool.push("save");
// tool.push("cancel");
}
if(role_data[0].export>0){
// tool.push("excel");
// tool.push("pdf");
}
if(role_data[0].update>0){
com.push("edit");
}
if(role_data[0].delete>0){
com.push("destroy");
}
$scope.confirmed = [];
$scope.change = function(i){
alert($scope.confirmed[i]);
if($scope.confirmed[i]){ //If it is checked
// alert('test'+i);
}
}
$scope.isChecked=function(item){
if(item.confirmed){
var id=item.id
$scope.confirmed[id] = 'true';
}
else{
console.log("end");
var id=item.id
$scope.confirmed[id] = 'false';
}
}
$scope.pPublicGrid = {
dataSource: {
transport: {
read: {
url: "/user/angular/SubLegalpersonsPublic",
contentType:"application/json; charset=UTF-8",
type:"POST"
},
update: {
url: "/user/service/editing/update/"+$scope.domain+"",
contentType:"application/json; charset=UTF-8",
type:"POST"
},
destroy: {
url: "/user/service/editing/delete/"+$scope.domain+"",
contentType:"application/json; charset=UTF-8",
type:"POST"
},
create: {
url: "/user/service/editing/create/"+$scope.domain+"",
contentType:"application/json; charset=UTF-8",
type:"POST",
complete: function(e) {
$(".k-grid").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options) {
return JSON.stringify(options);
}
},
schema: {
data:"data",
total:"total",
model: {
id: "id",
fields: {
id: { editable: false,nullable: true},
lpReg: { type: "string", validation: { required: true } },
lpType: { type: "number", validation: { required: true } },
lpName: { type: "string", validation: { required: true} },
lpNameL1: { type: "string"},
phone: { type: "string", validation: { required: true } },
famName: { type: "string", validation: { required: true } },
famNameL1: { type: "string", validation: { required: true} },
givName: { type: "string"},
givNameL1: { type: "string", validation: { required: true } },
mobile: { type: "string", validation: { required: true } },
email: { type: "string", validation: { required: true} },
personId: { type: "number", defaultValue:0},
ispublic: { type: "number",defaultValue:1},
confirmed: { type: "boolean",defaultValue:true}
}
}
},
pageSize: 8,
serverPaging: true,
serverSorting: true
},
filterable: true,
sortable: true,
columnMenu:true,
resizable: true,
toolbar: tool,
groupable:true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{ field:"lpReg", title: "<span data-translate='Reg.number'></span>" , locked: true,lockable: false,width: 150 },
{ field: "lpName", title: "<span data-translate='Company name'></span>", locked: true,lockable: false,width: 150},
{ field: "famName", title: "<span data-translate='Lastname /Mon/'></span>",width: 150 },
{ field: "givName", title: "<span data-translate='Firstname /Mon/'></span>" ,width: 150},
{ field: "famNameL1", title: "<span data-translate='Lastname /Eng/'></span>" ,width: 150},
{ field: "givNameL1", title: "<span data-translate='Firstname /Mon/'></span>" ,width: 150},
{ field: "lpNameL1", title: "<span data-translate='Company name'></span>" ,width: 150},
{ field: "phone", title: "<span data-translate='Phone'></span>" ,width: 150},
{ field:"lpType", title: "<span data-translate='Legal type'></span>", values:lptypes,width:350},
{ field: "mobile", title: "<span data-translate='Mobile'></span>" ,width: 150},
{ field: "email", title: "<span data-translate='Email'></span>",width: 150 },
{ command:com, title: " ", width: "250px" }
/* {
template: kendo.template($("#update").html()), width: 150
}*/
],
editable: "popup"
}
}]
)
|
app.controller('indexController', function($scope, $location, friendsFactory){
$scope.friends = [];
friendsFactory.index(function(data){
$scope.friends = data;
});
//console.log($scope.friends);
$scope.show = function(id){
$location.url('/show/' + id);
}
$scope.delete = function(id){
console.log(id);
friendsFactory.delete(id, function(data){
if(data.status){
console.log('deleted friend');
friendsFactory.index(function(data){
$scope.friends = data;
});
$location.url('/');
}else{
$scope.errors = data.error;
$location.url('/');
}
})
}
}) |
const config = require('../config/baseConfig');
const jsonwebtoken = require('jsonwebtoken');
const logger = require('./logger').getLogger('err');
const checkToken = (req, callback) => {
const token = req.body.token || req.query.token;
if(!token) {
logger.error('verify should be have token');
callback({err:'verify should be have token'});
}
jsonwebtoken.verify(token,config.token_secret_key,(err, decode) => {
if( err ){
logger.error(err);
callback(err);
}else{
callback(null);
}
})
}
module.exports = checkToken; |
'use strict'
function Queue(){
var q = [];
this.enqueue = function(v){
//console.log("enqueue "+v);
q.push(v);
}
this.dequeue = function(){
var e = q.shift();
// console.log("dequeue "+e +"qu" +q);
return e;
}
this.isEmpty = function(){
return (q.length <= 0);
}
}
function Graph(n) {
this.noOfvertices = n;
this.adjList = new Map();
this.addvertex = function(v){
this.adjList.set(v,[]);
}
this.addEdge = function(v,w){
this.adjList.get(v).push(w);
this.adjList.get(w).push(v);
}
this.printg=function(){
var keys = this.adjList.keys();
console.log("keys " +keys);
for(var i of keys){
var values = this.adjList.get(i);
var c = "";
for(var j of values){
c+=" " +j;
}
console.log("Graph : " +i +"is connected to " +c);
}
}
this.bfs = function(v){
var keys = this.adjList.keys();
var visited = [];
var queue = new Queue();
for(var i of keys){
visited[i] = false;
}
visited[v] = true;
queue.enqueue(v);
while(!queue.isEmpty()){
var ele = queue.dequeue();
console.log("visited ele is" +ele );
var neighb = this.adjList.get(ele)
console.log("nei" +neighb );
for(var i of neighb){
if(!visited[i]){
visited[i] = true;
queue.enqueue(i);
}
}
}
}
}
var g = new Graph(5);
g.addvertex(1);
g.addvertex(2);
g.addvertex(3);
g.addvertex(4);
g.addvertex(5);
g.addEdge(1,2);
g.addEdge(1,3);
g.addEdge(1,5);
g.addEdge(2,5);
g.addEdge(2,4);
g.addEdge(3,5);
g.printg();
g.bfs(1); |
import baseBehavior from '../helpers/baseBehavior'
import { $wuxBackdrop } from '../dialog-util'
Component({
/**
* 组件的属性列表
*/
properties: {
},
behaviors: [baseBehavior],
externalClasses: ['wux-class'],
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
hide() {
this.$$setData({ in: false })
this.$wuxBackdrop.release()
},
show(callback) {
this.getPhoneNumberCallback = callback
this.$$setData({ in: true})
this.$wuxBackdrop.retain()
return this.hide.bind(this)
},
confirm() {
this.hide()
},
cancel() {
this.hide()
},
getPhoneNumber(res) {
var that = this
console.log(JSON.stringify(res))
if (that.getPhoneNumberCallback){
if (res.detail.iv && res.detail.encryptedData){
that.getPhoneNumberCallback.success(res.detail)
} else {
that.getPhoneNumberCallback.fail(res.detail.errMsg)
}
}
}
},
created() {
this.$wuxBackdrop = $wuxBackdrop('#wux-backdrop', this)
},
})
|
export default function Log (prefix, msg) {
let backPage = chrome.extension.getBackgroundPage()
backPage.console.log(prefix)
backPage.console.log(msg)
console.log(msg)
}
|
const express = require('express');
const { MongoClient } = require('mongodb');
var cors = require('cors');
// niddisto id onosare data delete korte hole ObjectId id import korte hobe - karon holo mongodb te _id ar por ObjectId onosare ase. such as , _id:ObjectId("032djos3993ndse09u3")
const ObjectId = require('mongodb').ObjectId;
const app = express();
const port = 5000;
// middle ware
app.use(cors());
app.use(express.json());
/*
userName: newUsers1
password: LEwaWkaFETrxqbWS
*/
// connect your application from mongo db atlas
const uri = "mongodb+srv://newUsers1:LEwaWkaFETrxqbWS@cluster0.y6afp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
/* client.connect(err => {
const collection = client.db("FoodMaster").collection("users");
// perform actions on the collection object
console.log('hitting the database');
// data insert
const user = {name: 'Rani', email: 'Rani@gmail.com', phone: '0199999999999'};
collection.insertOne(user)
.then(() => {
console.log('insert success');
})
// console.error(err);
// client.close();
});
*/
/*
// data insert using async await (await use korle obossoi async use korte hobe)
async function run() {
try {
await client.connect();
const database = client.db("FoodMaster");
const usersCollection = database.collection("users");
// create a document to insert
const doc = {
name: "special one",
email: "special@hotmail.com",
}
const result = await usersCollection.insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.dir);
*/
// Setup client side React App to send data to the server
async function run() {
try {
await client.connect();
const database = client.db("FoodMaster");
const usersCollection = database.collection("users");
// GET API
app.get('/users', async(req, res) => {
// Find Multiple Documents from mongodb
const cursor = usersCollection.find({});
const users = await cursor.toArray(); // jehuto data array hisebe dorkar tai forEach ar poriborte toArray use kora hoise.
res.send(users);
})
// get user by users id
app.get('/users/:id', async (req, res) => {
// id wise data access
const id = req.params.id;
const query = { _id: ObjectId(id) };
const user = await usersCollection.findOne(query);
console.log('load user with id:' , id);
res.send(user);
} )
// POST api method route
app.post('/users', async (req, res) => {
// insert mongodb
const newUser = req.body;
const result = await usersCollection.insertOne(newUser);
console.log('hitting the post', req.body);
console.log('added user', result);
// ata jehuto post tai json hisebe pura result ta k client side a pathai dewya jabe.
res.json(result);
// res.send('POST request to the userspage')
});
// UPDATE API (update k put bola hoy)
app.put('/users/:id', async(req, res) => {
const id = req.params.id;
const updatedUser = req.body;
// update user from mongobd
const filter = {_id: ObjectId(id)};
const options = {upsert: true};
// create a document that sets the plot
const updateDoc = {
$set: {
name: updatedUser.name,
email: updatedUser.email
},
};
const result = await usersCollection.updateOne(filter, updateDoc, options)
console.log( 'updating user' ,req)
// json hisebe client side a data pathano
res.json(result)
})
// DELETE API
app.delete('/users/:id', async(req, res) => {
const id = req.params.id;
const query = {_id: ObjectId(id)};
const result = await usersCollection.deleteOne(query);
console.log('deleting user with id', result);
res.json(result);
})
}
finally {
// -----client.close(); ---comment korar karon holo(error ti lekha holo)-- MongoNotConnectedError: MongoClient must be connected to perform this operation
// await client.close();
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Running My CURD Server!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
}) |
import React, {useRef, useState} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
Keyboard,
} from 'react-native';
import {Colors, Fonts} from '../../../Theme';
import {NrmIcon} from '../../../Components';
import {popup} from '../../../Common/Helpers';
const SearchBox = ({
goBack,
setIsSetsearchBarFocus,
searchText,
setSearchText,
}) => {
const [searchTextInput, setsearchTextInput] = useState('');
const inputRef = useRef();
return (
<View style={styles.container}>
<TouchableOpacity style={styles.buttonContainer} onPress={goBack}>
<NrmIcon
name="search1"
size={24}
color={Colors.ORANGE_LIGHT}
type="AntDesign"
/>
</TouchableOpacity>
<TextInput
onBlur={() => {
console.log('blur');
Keyboard.dismiss();
}}
onEndEditing={() => {
console.log('end');
Keyboard.dismiss();
}}
style={styles.input}
multiline={false}
value={searchTextInput}
onChangeText={val => {
setsearchTextInput(val);
}}
onSubmitEditing={event => {
setsearchTextInput(event);
if (event.length <= 2) {
popup.warning('En az 3 harf girmelisiniz.');
}
// generateLog.search(event.nativeEvent.text)
}}
placeholderTextColor={Colors.GREY + '99'}
placeholder="Deterjan (1623 sonuç)"
/>
</View>
);
};
export default SearchBox;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
position: 'relative',
marginHorizontal: 10,
backgroundColor: Colors.GREY_LIGHTER,
height: 40,
alignItems: 'center',
borderRadius: 16,
width: 340,
},
input: {
fontSize: 17,
fontFamily: Fonts.family.semiBold,
fontWeight: Platform.OS === 'android' ? 'normal' : undefined,
flex: 1,
height: '100%',
color: Colors.GREY,
},
buttonContainer: {
paddingHorizontal: 8,
justifyContent: 'center',
},
});
|
/**
* Module dependencies.
*/
const appConsts = require('./app/config/appConstants')
var express = require('express')
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors');
var morgan = require('morgan');
/********************* Routes********************************/
const optionsRoutes = require('./routes/optionsRoutes');
const dbConnector = require('./app/db/connection');
var urlProvider = require('./app/config/urlProvider');
// const errorHandler=require('./app/services/errorHandler')
var app = express();
app.use(cors())
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(urlProvider.VERSION, optionsRoutes);
// app.use(function (err, req, res, next) {
// let errorResponse=errorHandler.getResponse(err);
// res.status(errorResponse.statusCode).send(errorResponse.response);
// });
// app.use(function(req, res, next) { //allow cross origin requests
// res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// res.header("Access-Control-Allow-Credentials", true);
// next();
// });
app.listen(appConsts.PORT, () => {
console.log('app is running at ', appConsts.PORT)
dbConnector.createMongooseConnections('test');
}); |
/* global _babelPolyfill */
export default typeof _babelPolyfill !== "undefined" && _babelPolyfill === true
|
/**
* 保障房项目初始化
*/
var queryProject = {
id: "queryProjectTable", //表格id
seItem: null, //选中的条目
table: null,
layerIndex: -1,
url:"",
secondLayerIndex:-1
};
/**
* 初始化表格的列
*/
queryProject.initColumn = function () {
return [
{field: 'selectItem', radio: false},
{title: '登记编号', field: '登记编号', align: 'center', valign: 'middle'},
{title: '申请人', field: '申请人', align: 'center', valign: 'middle'},
{title: '身份证件号', field: '身份证件号', align: 'center', valign: 'middle'},
{title: '案卷状态', field: '案卷状态', align: 'center', valign: 'middle'},
{title: 'OPTYPENUM', field: 'OPTYPENUM', align: 'center', valign: 'middle',visible: false},
{title: 'RECYEAR', field: 'RECYEAR', align: 'center', valign: 'middle',visible: false},
{title: 'RECNUM', field: 'RECNUM', align: 'center', valign: 'middle',visible: false},
{title: '操作', align: 'center', valign: 'middle',
formatter:function(value,row,index){
return '<a onclick="queryProject.detail('+'\'' +row.登记编号+'\',\''+ row.OPTYPENUM + '\',\'' +row.RECYEAR + '\',\''+ row.RECNUM +'\')">详细</a>';
}
}
];
};
queryProject.query = function(){
//是否勾选本人经办
var IsOwner_handle = $("input[name=owner_handle]:checked");
var IsOwner_handleVal = "";
if(IsOwner_handle.get(0)){
IsOwner_handleVal = IsOwner_handle.get(0).value;
}
//是否勾选精确查找
var IsPrecise_query = $("input[name=precise_query]:checked");
var IsPrecise_queryVal = "";
if(IsPrecise_query.get(0)){//勾选了
IsPrecise_queryVal = IsPrecise_query.get(0).value;
}
var param = {
"first":"2",
"registerNum":$("#registerNum").val(),
"application":$("#application").val(),
"idCard":$("#idCard").val(),
"archivesNum":$("#archivesNum").val(),
"iIsSelfExec":IsOwner_handleVal,
"IsPrecise_queryVal":IsPrecise_queryVal
};
queryProject.table.refresh({query: param});
}
queryProject.initSecondType = function(pNum){
if(pNum == ''){
return;
}
var ajax = new $ax(Feng.ctxPath + "/support/second_type", function (data) {
$("#business_second").html('<option value="">请选择</option>');
$.each(data,function (i,item) {
$("#business_second").append('<option value="'+item.OPPARTNUM+'">'+item.OPPARTNAME+'</option>')
})
}, function (data) {
});
ajax.set({pNum:pNum});
ajax.start();
}
queryProject.detail = function (sRecNumGather,OPTYPENUM,RECYEAR,RECNUM) {
var data = {sRecNumGather:sRecNumGather,
iOpTypeNum:OPTYPENUM,
iRecYear:RECYEAR,
iRecNum:RECNUM
};
$.ajax({
url:Feng.ctxPath + '/info/get_page_info',
data:data,
type:"post",
success:function (result) {
if(result.code != '200'){
Feng.info(result.msg);
return;
}
if(result.data.sPage){
var index = layer.open({
type: 2,
title: '详细',
area: ['80%', '80%'], //宽高
fix: false, //不固定
maxmin: true,
content: Feng.ctxPath + '/support/detail?page='+result.data.sPage+'&OpTypeNum=' + result.data.iOpTypeNum +'&RecYear=' + result.data.iRecYear +'&RecNum=' + result.data.iRecNum + "&info=" + '1'
});
queryProject.layerIndex = index;
layer.full(index);
}
},
error:function (result) {
Feng.info("系统异常!");
}
})
}
/**
* 关闭此对话框
*/
queryProject.close = function () {
parent.layer.close(window.parent.queryProject.layerIndex);
}
/**
* 关闭二级对话框
*/
queryProject.closeSecond = function () {
parent.layer.close(window.parent.queryProject.secondLayerIndex);
}
$(function () {
//初始化表格
var data = {
"first":"1"
};
queryProject.url = "/info/list";
var defaultColunms = queryProject.initColumn();
var table = new BSTable(queryProject.id, queryProject.url, defaultColunms);
table.setQueryParams(data);
queryProject.table = table.init();
});
|
import React from 'react';
import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { setSidePanel } from '../layout/uilayout-actions';
class NetworkAudit extends React.Component{
static icon = "wrench";
static label = "Network Audit";
constructor(props){
super(props)
this.setSidePanel = this.setSidePanel.bind(this);
}
setSidePanel(){
this.props.dispatch(setSidePanel('AuditRuleTree'));
}
render(){
return (
<div>
<h3><FontAwesomeIcon icon={NetworkAudit.icon}/> Network Audit</h3>
<div className="card mb-2">
<div className="card-body p-3">
<a href="#" className="launch-network-tree" onClick={this.setSidePanel}><FontAwesomeIcon icon="arrow-right"/> View audit rules</a>
</div>
</div>
</div>
);
}
}
export default connect()(NetworkAudit); |
import React from 'react'
import { connect } from 'react-redux'
import { closeSnackbar } from '../actions/uiAction'
import { Snackbar as SnackbarMI } from 'material-ui'
const CLOSE_TIME_IN_MILLIS = 5000
const Snackbar = props => {
const { closeSnackbar, isOpen, message } = props
if (isOpen) {
setTimeout(closeSnackbar, CLOSE_TIME_IN_MILLIS)
}
return (
<SnackbarMI
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
open={isOpen}
SnackbarContentProps={{
'aria-describedby': 'message-id',
}}
message={<span id="message-id">{message}</span>}
/>
)
}
const mapStateToProps = ({ ui }) => ({
isOpen: ui.snackbar.isOpen,
message: ui.snackbar.message
})
const mapDispatchToProps = dispatch => ({
closeSnackbar: () => dispatch(closeSnackbar())
})
export default connect(mapStateToProps, mapDispatchToProps)(Snackbar) |
import React from 'react';
import PropTypes from 'prop-types';
import {withRouter} from 'react-router-dom';
import classes from './index.module.css';
import logo from './image.png';
import {languageHelper} from '../../../tool/language-helper';
export class NotificationCardReact extends React.Component {
constructor(props) {
super(props);
// state
this.state = {};
// i18n
this.text = NotificationCardReact.i18n[languageHelper()];
}
render() {
return (
<div className={classes.content}>
<div className="d-flex">
<div className={classes.border}>
<img src={logo} className="img-fluid"/>
</div>
<div className={classes.text}>
{this.props.text}
</div>
</div>
</div>
);
}
}
NotificationCardReact.i18n = [
{},
{}
];
NotificationCardReact.propTypes = {
id:PropTypes.number.isRequired,
text: PropTypes.string.isRequired,
date:PropTypes.number.isRequired,
isread:PropTypes.bool.isRequired,
// React Router
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired
};
export const NotificationCard = withRouter(NotificationCardReact);
|
const Trust = artifacts.require("Trust");
const Registration = artifacts.require("Registration")
const P1Selection = artifacts.require("P1Selection")
const P2Selection = artifacts.require("P2Selection")
module.exports = async function(deployer,network, accounts ) {
//async keyword is used to deploy in the order needed.
// accounts : all accounts of the network
// Deploy trust
await deployer.deploy(Trust)
const trust = await Trust.deployed()
//deploy the P2 selection
await deployer.deploy(P2Selection, trust.address) //these are used in the sc constructor
const p2selection= await P2Selection.deployed()
p2selection.setGW(accounts[0])
//deploy p1 selection smart contract
await deployer.deploy(P1Selection,trust.address,p2selection.address)//these are used in the sc constructor
//deploy registration SC
await deployer.deploy(Registration,trust.address,p2selection.address)//these are used in the sc constructor
const registr= await Registration.deployed()
// enregistrer les 6 premier accounts dans le systeme de confiance
await registr.register(accounts[0])
await registr.register(accounts[1])
await registr.register(accounts[2])
await registr.register(accounts[3])
await registr.register(accounts[4])
await registr.register(accounts[5])
await trust.blackList(accounts[5])
};
|
(function ($) {
$.fn.extend({
//pass the options variable to the function
confirmModal: function (options) {
var html='<div class="modal fade" >'+
'<div class="modal-dialog">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'+
'<h3>提示信息:</h3>'+
'</div>'+
'<div class="modal-body">'+
'<h4><i class="icon-info-sign"></i> <%=data.title%></h4> '+
'<div class="bordered"><%=data.message%></div>'+
' </div>'+
'<div class="modal-footer">'+'<a href="#" class="btn btn-primary" id="confirmYesBtn">确定</a><a href="#" class="btn" id="confirmCancelBtn">取消</a>'+
'</div></div></div></div>';
var defaults = {
heading: 'Please confirm',
body:'Body contents',
callback : null
};
var options = $.extend(defaults, options);
html = html.replace('#Heading#',options.heading).replace('#Body#',options.body);
$(this).html(html);
$(this).modal({keyboard: false,show:true,backdrop:'static'});
var context = $(this);
$('#confirmYesBtn',this).click(function(){
if(options.callback!=null)
options.callback();
$(context).modal('hide');
$(context).remove();
});
$('#confirmCancelBtn',this).click(function(){
if(options.cancelCallback!=null)
options.cancelCallback();
$(context).modal('hide');
$(context).remove();
});
if(!options.showCancel){
$("#confirmCancelBtn").css("display","none");
}
}
});
})(jQuery); |
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/styles';
import { IconButton, Popover, Typography } from '@material-ui/core';
import { HelpOutlineRounded } from '@material-ui/icons';
import { humanLevel } from '../utils/propTypes';
const propTypes = {
humanLevel,
};
const useStyles = makeStyles(theme => ({
popover: {
maxWidth: 260,
padding: theme.spacing(1),
},
}));
const LegendHelp = ({ humanLevel }) => {
const [anchorEl, setAnchorEl] = useState(null);
const { t } = useTranslation();
const classes = useStyles();
const onClick = ({ currentTarget }) => setAnchorEl(currentTarget);
const onClose = () => setAnchorEl(null);
const helpText = t(`${humanLevel} help`);
return (
<>
<IconButton
aria-label={t('help')}
aria-controls={humanLevel}
aria-haspopup="true"
size="small"
onClick={onClick}
>
<HelpOutlineRounded fontSize="inherit" color="disabled" />
</IconButton>
<Popover
id={humanLevel}
classes={{ paper: classes.popover }}
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={onClose}
>
<Typography variant="caption">{helpText}</Typography>
</Popover>
</>
);
};
export default LegendHelp;
LegendHelp.propTypes = propTypes;
|
function display(list) {
if (list.head === null) {
console.log(list.head)
}
else {
let i = 0;
let item = list.head;
while (item.next !== null) {
console.log(`${i}: ${item.value}`);
i++;
item = item.next;
}
console.log(`${i}: ${item.value}`)
}
}
function size(list) {
let listSize = 0;
let currNode = list.head
while (currNode.next !== null) {
listSize++
currNode = currNode.next
}
listSize++;
return console.log(listSize)
}
function isEmpty(list) {
if (list.head === null) {
return console.log(true);
}
return console.log(false)
}
function findPrevious(item, list) {
let currNode = list.head;
while (currNode.next.value !== item) {
currNode = currNode.next
}
return console.log(currNode.value)
}
function findLast(list) {
let currNode = list.head;
while (currNode.next !== null) {
currNode = currNode.next
}
return console.log(currNode.value)
}
function reverse(list) {
if (list == null) {
return null
}
if (list.next == null) {
return list.next
}
let second = list.next;
list.next = null;
let reversedRest = reverse(second);
second.next = list;
return reversedRest
}
function thirdFromTheEnd(list) {
let third = list.head;
let thirdFromEnd = list.head.next.next.next;
while(thirdFromEnd !== null) {
third = third.next;
thirdFromEnd = thirdFromEnd.next;
}
return third.value
}
function middleList(list){
if(list.head===null){
return null
}
let one = list.head;
let two = list.head;
while(two !==null && two.next!==null){
one = one.next;
two = two.next.next;
}
return one.value
}
function cycle(head) {
let two = head
let one = head
while(two.next !== null) {
two = two.next.next
one = one.next
if (one === two)
return console.log(true)
}
return console.log(false)
}
module.exports = {
display, size, isEmpty, findPrevious, findLast, reverse, thirdFromTheEnd, middleList, cycle
} |
const Elevator = require('./elevator.js');
const Person = require('./person.js');
let elevator = new Elevator();
let jane = new Person("Jane", 1, 6);
let bob = new Person("Bob", 2, 5);
let mark = new Person("Mark", 3, 0);
let tom = new Person("Tom", 5, 1);
elevator.call(tom);
elevator.call(jane);
elevator.call(mark);
setTimeout(elevator.call.bind(elevator, bob), 30000)
|
import React, {useEffect, useState, useRef} from 'react'
import $ from 'jquery';
import Link from "next/link";
import Modal from 'react-modal';
import Slider from "react-slick";
function Testimonies(props) {
const [state, setState] = useState({
show: false
});
let slider = useRef()
const next = () => {
slider.slickNext();
};
const previous = () => {
slider.slickPrev();
};
const settings = {
dots: false,
autoplay: true,
infinite: true,
speed: 200,
autoplaySpeed: 4000,
slidesToShow: 2,
slidesToScroll: 2,
initialSlide: 0,
// cssEase: "linear",
pauseOnHover: true,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
infinite: false,
dots: false
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
initialSlide: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
};
const layoutSettings = {
marginRight: 5,
marginLeft: 5,
}
return (
<div className="rows g-mb-30">
<Slider ref={c => (slider = c)} {...settings}>
<div>
<div className={`g-mr-${layoutSettings.marginRight} g-ml-${layoutSettings.marginLeft}`}>
<blockquote
className="lead u-blockquote-v1 rounded g-pl-60 g-pr-30 g-py-30 g-mb-40">Lorem Ipsum
is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the..
</blockquote>
<div className="media">
<img
className="d-flex align-self-center rounded-circle g-width-60 g-brd-around g-brd-3 g-brd-white mr-3"
src="/img/1.jpg" alt="Image Description"/>
<div className="media-body align-self-center">
<h4 className="h6 g-font-weight-700 g-mb-0">Alexandra Pottorf</h4>
<em className="g-color-gray-dark-v4 g-font-style-normal">Web Developer</em>
</div>
</div>
</div>
</div>
<div>
<div className={`g-mr-${layoutSettings.marginRight} g-ml-${layoutSettings.marginLeft}`}>
<blockquote
className="lead u-blockquote-v1 rounded g-pl-60 g-pr-30 g-py-30 g-mb-40">Lorem Ipsum
is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the..
</blockquote>
<div className="media">
<img
className="d-flex align-self-center rounded-circle g-width-60 g-brd-around g-brd-3 g-brd-white mr-3"
src="/img/1.jpg" alt="Image Description"/>
<div className="media-body align-self-center">
<h4 className="h6 g-font-weight-700 g-mb-0">Alexandra Pottorf</h4>
<em className="g-color-gray-dark-v4 g-font-style-normal">Web Developer</em>
</div>
</div>
</div>
</div>
<div>
<div className={`g-mr-${layoutSettings.marginRight} g-ml-${layoutSettings.marginLeft}`}>
<blockquote
className="lead u-blockquote-v1 rounded g-pl-60 g-pr-30 g-py-30 g-mb-40">Lorem Ipsum
is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the..
</blockquote>
<div className="media">
<img
className="d-flex align-self-center rounded-circle g-width-60 g-brd-around g-brd-3 g-brd-white mr-3"
src="/img/1.jpg" alt="Image Description"/>
<div className="media-body align-self-center">
<h4 className="h6 g-font-weight-700 g-mb-0">Alexandra Pottorf</h4>
<em className="g-color-gray-dark-v4 g-font-style-normal">Web Developer</em>
</div>
</div>
</div>
</div>
<div>
<div className={`g-mr-${layoutSettings.marginRight} g-ml-${layoutSettings.marginLeft}`}>
<blockquote
className="lead u-blockquote-v1 rounded g-pl-60 g-pr-30 g-py-30 g-mb-40">Lorem Ipsum
is simply dummy text of the printing and typesetting industry. Lorem Ipsum has
been the industry's standard dummy text ever since the..
</blockquote>
<div className="media">
<img
className="d-flex align-self-center rounded-circle g-width-60 g-brd-around g-brd-3 g-brd-white mr-3"
src="/img/1.jpg" alt="Image Description"/>
<div className="media-body align-self-center">
<h4 className="h6 g-font-weight-700 g-mb-0">Alexandra Pottorf</h4>
<em className="g-color-gray-dark-v4 g-font-style-normal">Web Developer</em>
</div>
</div>
</div>
</div>
</Slider>
</div>
)
}
export default Testimonies
|
const path = require("path");
const mongoose = require("mongoose");
const Faculty = mongoose.model("Faculty");
const User = mongoose.model("User");
const bcrypte = require("bcrypt-nodejs");
module.exports.facultyHomePage = function(req, res){
dispathPageFaculty("home", res);
}
module.exports.facultyTakeAttendancePage = function(req, res){
dispathPageFaculty("take-attendance", res);
}
module.exports.facultyStudentsPage = function(req, res){
dispathPageFaculty("students", res);
}
module.exports.facultySecretCodePage = function(req, res){
dispathPageFaculty("secret-code", res);
}
module.exports.facultyAddStudentPage = function(req, res){
dispathPageFaculty("student-add", res);
}
dispathPageFaculty = function(pageName, res){
res.status(200).sendFile(path.join(__dirname, "..", "..", "public", "faculty" ,pageName+".html") );
}
module.exports.facultyGetOne = function(req, res){
const id = req.params.id;
Faculty.findById(id).exec(function(err, faculty){
let response = {
status : 201,
message: faculty
}
if(err){
response.status = 500;
response.message = err
}else if(!faculty){
response.status = 500;
response.message = {message: "Faculty not found."}
}
res.status(response.status).json(response.message);
})
}
module.exports.facultyAddOne = function(req, res){
let response = {
status: 201,
message: ""
}
if(req.body && req.body.facultyId && req.body.firstName && req.body.lastName && req.body.password){
Faculty.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
facultyId: req.body.facultyId,
}, function(err, faculty){
if(err){
response.status = 500;
response.message = err;
res.status(response.status).json(response.message);
return;
}else {
User.create({
username : faculty.facultyId,
password: bcrypte.hashSync(req.body.password, bcrypte.genSaltSync(10)),
role: "faculty",
id: faculty._id
}, function(err, user){
if(err){
response.status = 500;
response.message = err;
res.status(response.status).json(response.message);
return;
}else {
response.status = 201;
response.message = faculty;
res.status(response.status).json(response.message);
return;
}
})
}
})
}else{
response.status = 400;
response.message = {"message": "Required data missing from POST"}
res.status(response.status).json(response.message);
return;
}
} |
import { ADD_FRIEND, REMOVE_FRIEND} from './friendsReducer';
const SHOW_MORE_USERS = 'SHOW-MORE-USERS';
// user: id, isActive, lastLogin, accountStatus, firstName, lastName, imgUrl, intro, country, city, gender, isFriend
let initialState = {
users: [],
page: 1
};
export function searchPeopleReducer(state = initialState, action) {
switch (action.type) {
case ADD_FRIEND:
return {
...state,
users: state.users.map(user => {
if (user.id === action.id){
return {...user, isFriend: true}
}
return user
})
};
case REMOVE_FRIEND:
return {
...state,
users: state.users.map(user => {
if (user.id === action.id){
return {...user, isFriend: false}
}
return user
})
};
case SHOW_MORE_USERS:
return {
...state,
users: [...state.users, ...action.users],
page: action.users.length < 20 ? -1 : state.page + 1
}
default:
return state;
}
}
export function showMoreUsersActionCreator(users) {
return {
type: SHOW_MORE_USERS,
users: users
};
}
|
import React from 'react'
import { bindActionCreators } from 'redux'
import Communications from 'react-native-communications'
import { connect } from 'react-redux'
import { Clipboard } from 'react-native'
import * as actions from '../../store/reducer/sendMoney'
import { openLoginForm, LOGIN_STATUSES } from '../../store/reducer/login'
import { setOverlayOpen, closeConfirmation } from '../../store/reducer/navigation'
import InputComponent, { labels } from './InputComponent'
import Config from '@Config/config'
const Page = {
Ready: 0,
EnterAmount: 1,
ConfirmAmount: 2,
MakingPayment: 3,
PaymentComplete: 4
}
let tempClipboardString = ''
class SendMoney extends React.Component {
constructor () {
super()
this.state = {
pin: ''
}
}
setClipboardContent = async () => {
try {
tempClipboardString = await Clipboard.getString()
} catch (e) {
} finally {
Clipboard.setString('')
}
}
nextPage () {
const nextPage = (this.props.inputPage + 1) % Object.keys(Page).length
this.props.updatePage(nextPage)
if (nextPage === Page.EnterAmount) {
this.setClipboardContent()
} else if (nextPage === Page.MakingPayment) {
Clipboard.setString(tempClipboardString)
}
}
prevPage () {
this.props.updatePage(Page.EnterAmount)
}
componentDidUpdate (prevProps) {
if (this.props.payeeId !== prevProps.payeeId) {
this.props.updateAmount('')
this.props.updatePage(Page.Ready)
} else if (prevProps.loading && !this.props.loading && this.props.inputPage === Page.MakingPayment) {
this.nextPage()
} else if (prevProps.inputPage === Page.MakingPayment
&& this.props.inputPage === Page.PaymentComplete
&& !this.props.success) {
setTimeout(() => this.props.inputPage === Page.PaymentComplete && this.nextPage(), 1800)
}
}
isPinInvalid () {
const { pin } = this.state
return !this.props.connection && (pin.length < 4 || pin.indexOf('.') !== -1)
}
isInputInvalid () {
const { amount } = this.props
return (
isNaN(Number(this.props.amount))
|| Number(amount) > this.props.balance
|| Number(amount) <= 0
|| (amount.charAt(0) === '0' && amount.charAt(1) !== '.')
|| amount.charAt(amount.length - 1) === '.'
|| (amount.split('.')[1] && amount.split('.')[1].length > 2)
|| this.isPinInvalid()
)
}
payByTextOnPress (withdrawing) {
var action = withdrawing
? Config.TXT2PAY_ACTION_WITHDRAW
: Config.TXT2PAY_ACTION_PAY
const usernameToPay = withdrawing
? this.props.payee.fields.cashpointUsername
: (this.props.payee.shortDisplay || this.props.payee.fields.username)
const text = Config.TXT2PAY_TEMPLATE
.replace('{ACTION}', action)
.replace('{PIN}', this.state.pin)
.replace('{PAYEE}', usernameToPay)
.replace('{AMOUNT}', this.props.amount)
Communications.textWithoutEncoding(Config.TXT2PAY_NO, text)
this.props.updateAmount('')
this.setState({pin: ''})
this.props.updatePage(Page.Ready)
this.props.setOverlayOpen(false)
}
render () {
let inputProps
const { payee, payeeShortDisplay } = this.props
if (this.props.resetClipboard) {
Clipboard.setString(tempClipboardString)
}
if (this.props.inputPage === Page.PaymentComplete) {
inputProps = {
buttonText: this.props.message,
withdrawText: this.props.message,
onButtonPress: () => {this.props.closeConfirmation() && this.props.updatePage(0)},
accessibilityLabel: labels.PAYMENT_COMPLETE
}
}
else if (!payeeShortDisplay) {
inputProps = {
buttonText: labels.CASH_ONLY_BUSINESS,
onButtonPress: () => {},
accessibilityLabel: labels.CASH_ONLY_BUSINESS
}
}
else if (this.props.loggedIn) {
switch (this.props.inputPage) {
case Page.Ready: // Initial state, ready to begin
// sometimes when pressing on the 'no' on the alert triggers the onPress here
//-> hence the !this.props.alertShouldPopUp check
inputProps = {
buttonText: labels.NO_PAYMENT_AVAILABLE,
withdrawText: labels.NO_PAYMENT_AVAILABLE,
onButtonPress: () => {},
accessibilityLabel: labels.NO_PAYMENT_AVAILABLE,
optionalWithdraw: true
}
if (this.props.paymentTypes && this.props.paymentTypes.length > 0 ) {
inputProps.buttonText = labels.SEND_PAYMENT
inputProps.withdrawText = labels.WITHDRAW_CASH
inputProps.onButtonPress = () => { !this.props.alertShouldPopUp && this.nextPage() }
}
break
case Page.EnterAmount: // provide amount
inputProps = {
buttonText: labels.PAY + ' ' + (payee.display || payee.name || ""),
withdrawText: labels.WITHDRAW,
onButtonPress: () => { this.nextPage() },
input: {
keyboardType: 'numeric',
value: this.props.amount,
placeholder: labels.AMOUNT,
onChangeText: amt => this.props.updateAmount(amt)
},
descriptionInput: {
keyboardType: 'default',
value: this.props.description,
placeholder: labels.DESCRIPTION,
maxLength: 100,
onChangeText: desc => this.props.updateDescription(desc)
},
invalidInput: this.isInputInvalid(),
accessibilityLabel: 'Enter Amount',
balance: this.props.balance
}
if (!this.props.connection) {
inputProps.offlinePaymentLabel = labels.USING_TXT2PAY
inputProps.onButtonPress = () => { this.payByTextOnPress(false) }
inputProps.onWithdrawPress = () => { this.payByTextOnPress(true)}
inputProps.pinInput = {
keyboardType: 'numeric',
value: this.state.pin,
placeholder: labels.PIN,
maxLength: 4,
onChangeText: pin => this.setState({pin: pin})
}
}
break
case Page.ConfirmAmount: // provide amount
inputProps = {
buttonText: labels.CONFIRM,
withdrawText: labels.CONFIRM_WITHDRAWAL,
onButtonPress: () => { this.props.sendTransaction(payeeShortDisplay); this.nextPage() },
onWithdrawPress: () => {this.props.sendTransaction(payee.fields.cashpointUsername); this.nextPage() },
amount: this.props.amount,
payee: payee.display || payee.name || "",
description: this.props.description,
onChangeAmount: () => { this.prevPage() },
accessibilityLabel: labels.CONFIRM
}
if (!this.props.connection) {
inputProps.offlinePaymentLabel = labels.USING_TXT2PAY
inputProps.onButtonPress = () => { this.prevPage() }
inputProps.pinInput = {
keyboardType: 'numeric',
value: this.state.pin,
placeholder: labels.PIN,
maxLength: 4,
onChangeText: pin => this.setState({pin: pin})
}
}
break
case Page.MakingPayment: // in progress
inputProps = {
buttonText: labels.MAKING_PAYMENT,
withdrawText: labels.MAKING_WITHDRAWAL,
loading: true,
accessibilityLabel: labels.MAKING_PAYMENT
}
break
}
} else {
inputProps = {
buttonText: labels.LOGIN_FOR_PAYMENT,
withdrawText: labels.LOGIN_TO_WITHDRAW,
onButtonPress: () => this.props.openLoginForm(true),
accessibilityLabel: labels.LOGIN_FOR_PAYMENT
}
}
let cashpoint = payee.fields
? payee.fields.cashpointUsername
: null
return <InputComponent {...inputProps} setOverlayOpen={this.props.setOverlayOpen} cashpoint={cashpoint} />
}
}
const mapDispatchToProps = (dispatch) =>
bindActionCreators({ ...actions, openLoginForm, setOverlayOpen, closeConfirmation }, dispatch)
const mapStateToProps = (state) => {
const payee = state.business.traderScreenBusiness || state.person.selectedPerson || {}
const payeeShortDisplay = state.business.traderScreenBusinessId
? state.business.businessList[state.business.traderScreenBusinessId].fields.username
: state.person.selectedPerson
? state.person.selectedPerson.shortDisplay
: ''
const paymentTypes = payee && payee.paymentTypes || undefined
return {
...state.sendMoney,
payee,
payeeShortDisplay,
paymentTypes,
balance: state.account.balance,
loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN,
connection: state.networkConnection.status
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SendMoney)
|
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import {
Container,
Alert,
Card,
ListGroup,
ListGroupItem
} from "react-bootstrap";
import "../ReclamoBuscado/ReclamoBuscado.css";
import cerradura from "../../photos/cerradura.png";
export default class ReclamoBuscado extends React.Component {
constructor(props) {
super(props);
this.state = {
reclamo: {},
nombre: "",
edificio: "",
ubicacion: "",
descripcion: "",
estado: "",
unidad: ""
};
}
componentDidMount() {
var url =
"http://localhost:8080/reclamapp/reclamosPorNumero?numero=" +
sessionStorage.getItem("numeroReclamo");
fetch(url, {
method: "GET", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json"
// 'Content-Type': 'application/x-www-form-urlencoded',
}
})
.then(response => {
return response.json();
})
.then(res => {
this.setState({
nombre: res.usuario.nombre,
edificio: res.edificio.nombre + ", " + res.edificio.direccion,
ubicacion: "Ubicacion: " + res.ubicacion,
descripcion: "Descripcion: " + res.descripcion,
estado: "Estado: " + res.estado,
piso: "Piso: " + res.piso,
numero: "numero: " + res.numero
});
});
}
render() {
console.log(this.state);
return (
<Container>
<label className="resultado">Resultado de su busqueda</label>
<Card style={{ width: "500px", top: "120px", left: "300px" }}>
<Card.Img variant="top" src={cerradura} />
<Card.Body>
<Card.Title>{this.state.nombre}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{this.state.edificio}
</Card.Subtitle>
<Card.Text>{this.state.descripcion}</Card.Text>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroupItem>{this.state.estado}</ListGroupItem>
<ListGroupItem>{this.state.unidad}</ListGroupItem>
<ListGroupItem>{this.state.ubicacion}</ListGroupItem>
</ListGroup>
</Card>
</Container>
);
}
}
|
//Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'.
function Mostrar()
{
alert("Funciona 2-EntradaSalida");
var importe;
importe=prompt("ingrese importe");
importe=importe*1.21
importe=document.getElementById("importe").value=importe;
}
|
import React from 'react';
export default class App extends Component {
render() {
return (
<div>
<h1 class="text-primary">Hi I'm Omer, and this is my Drumset app.</h1>
<Controller />
</div>
)
}
}
|
document.getElementById("EGSEAplot1button").addEventListener("click", myFunction3);
function myFunction3() {
var plotHeight = document.getElementById("EGSEA1_plot_height").value + "px";
document.getElementById("EGSEA1").style = "height:" + plotHeight;
}
|
goog.provide('SB.AmbientLight');
goog.require('SB.Light');
SB.AmbientLight = function(param)
{
param = param || {};
SB.Light.call(this, param);
}
goog.inherits(SB.AmbientLight, SB.Light);
SB.AmbientLight.prototype.realize = function()
{
this.object = new THREE.AmbientLight(this.color);
SB.Light.prototype.realize.call(this);
}
|
$(document).ready( function() {
$('.flash_notice').fadeOut(3000);
});
|
import React from 'react';
import Switch from '@material-ui/core/Switch';
const SwitchButton = (props) => {
return (
<Switch
onChange={props.onChange}
color={props.color}
checked={}
/>
)
};
export default SwitchButton; |
'use strict'
const mongo = require('mongodb').MongoClient
const dbUrl = 'mongodb://localhost:27017/' + process.argv[2]
const collection = process.argv[3]
const id = process.argv[4]
mongo.connect(dbUrl, (err, db) => {
if (err) throw err
db.collection(collection).remove({ _id: id }, err => {
if (err) throw err
db.close()
})
}) |
// Select color input and assign to a variable
const color = document.querySelector('#colorPicker');
const table = document.querySelector('#pixelCanvas');
// Select size input
const formSize = document.querySelector('#sizePicker')
//I want to see if this shows up in my git
// When size is submitted by the user, call makeGrid()
formSize.addEventListener('click', function(event) {
event.preventDefault();
const height = document.querySelector('#inputHeight').value;
const width = document.querySelector('#inputWidth').value;
//got this snipet of code from udacity knowledge base
table.innerHTML = null;
makeGrid(height, width);
});
// Your code goes here!
//I was all over internet trying to write this code
//I'm extremely proud that the one thing I got was the
//function but even with that I had to do a lot of research to
//understand how to create the grid. Deleting the border in the
//cell when clicked was my one original idea. :|
function makeGrid(height, width) {
for (let i = 0; i < height; i++) {
let row = table.insertRow(i);
for (let x = 0; x < width; x++) {
let cell = row.insertCell(x);
cell.addEventListener('click', function(evt){
evt.preventDefault();
cell.style.backgroundColor = color.value;
cell.style.border = 0;
row.style.border = 0;
});
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.