text
stringlengths 7
3.69M
|
|---|
import React, {Component} from 'react';
import {Modal, Radio, Select, Button, Table, Input, Col} from 'antd';
import E from 'wangeditor'
const RadioGroup = Radio.Group;
const Option = Select.Option;
export default class ArticleEditModal extends Component {
constructor(props) {
super(props);
this.state = {
itemData: null,
editorContent: '',
title: '',
showClient: 3,
};
};
componentWillReceiveProps(props) {
}
componentWillMount() {
this.state.itemData = this.props.itemData || {}
}
componentDidMount() {
if (this.refs.editorElem) {
this.initEdit()
}
}
editor = null
initEdit = () => {
const elem = this.refs.editorElem
this.editor = new E(elem)
// 使用 onchange 函数监听内容的变化,并实时更新到 state 中
this.editor.customConfig.onchange = html => {
this.state.editorContent = html;
}
this.editor.create()
this.editor.txt.html(this.state.itemData ? this.state.itemData.content : "")
}
saveWord = () => {
let temObj = {
content: this.state.editorContent,
title: this.state.title,
showClient: this.state.showClient,
}
if (this.state.itemData) {
temObj.id = this.state.itemData.id
this.props.coArticleUpdata && this.props.coArticleUpdata(temObj)
} else {
this.props.saveWord && this.props.saveWord(temObj)
}
}
onChangeRadioGroup = (e) => {
this.setState({
showClient: e.target.value
})
}
render() {
return (
<div className='edit-view'>
<div className='edit-view-center'>
<div className='edit-row'>
<div style={{width: '100px'}}>文章标题:</div>
<Input style={{width: '300px'}} value={this.state.title}
onChange={(e) => this.setState({title: e.target.value})}/>
</div>
<div className='edit-row'>
<div style={{width: '100px'}}>
显示客户端:
</div>
<RadioGroup value={
parseInt(this.state.showClient)
} onChange={this.onChangeRadioGroup}>
<Radio value={1}>手机端</Radio>
<Radio value={2}>PC端</Radio>
<Radio value={3}>所有端</Radio>
</RadioGroup>
</div>
<div className='edit-row'>
<div style={{width: '100px'}}>语言:</div>
<RadioGroup onChange={(e) => this.setState({language: e})} value={this.state.language}>
<Radio value={'zh'}>中文</Radio>
<Radio value={'en'}>英文</Radio>
</RadioGroup>
</div>
<div className='edit-row'>
<div style={{width: '100px'}}>状态:</div>
<RadioGroup onChange={(e) => this.setState({language: e})} value={this.state.language}>
<Radio value={1}>停用</Radio>
<Radio value={0}>启用</Radio>
</RadioGroup>
</div>
<div className='edit-row'>
<div style={{width: '100px'}}>关键字:</div>
<Input style={{width: '300px'}} value={this.state.title}
onChange={(e) => this.setState({title: e.target.value})}/>
</div>
<div className='edit-row'>
<div style={{width: '100px'}}>类型:</div>
<Select
placeholder="文章类型"
>
<Option key={1232} value={null}>全部</Option>
{
this.props.type && this.props.type.map((item, index) => {
return <Option key={index} value={item.typeName}>{item.typeName}</Option>
})
}
</Select>
</div>
</div>
<div ref="editorElem"></div>
<div style={{display: 'flex', flexDirection: 'row'}}>
<Button onClick={this.saveWord}
style={{width: '100px'}}>{this.state.itemData ? '更新' : '保存'}</Button>
<Button onClick={() => this.props.delWord && this.props.delWord(this.state.itemData.id)}
style={{width: '100px'}}>删除</Button>
</div>
{this.state.hiddenEdit &&
<div style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>选择你要操作的文件,或者选择新建文章</div>}
</div>
)
}
}
|
var searchData=
[
['valueaccessor_2eh',['ValueAccessor.h',['../ValueAccessor_8h.html',1,'']]],
['valuetransformer_2eh',['ValueTransformer.h',['../ValueTransformer_8h.html',1,'']]],
['vec2_2eh',['Vec2.h',['../Vec2_8h.html',1,'']]],
['vec3_2eh',['Vec3.h',['../Vec3_8h.html',1,'']]],
['vec4_2eh',['Vec4.h',['../Vec4_8h.html',1,'']]],
['vectortransformer_2eh',['VectorTransformer.h',['../VectorTransformer_8h.html',1,'']]],
['velocityfields_2eh',['VelocityFields.h',['../VelocityFields_8h.html',1,'']]],
['version_2eh_2ein',['version.h.in',['../version_8h_8in.html',1,'']]],
['visitor_2eh',['Visitor.h',['../Visitor_8h.html',1,'']]],
['volumeadvect_2eh',['VolumeAdvect.h',['../VolumeAdvect_8h.html',1,'']]],
['volumecomputegenerator_2eh',['VolumeComputeGenerator.h',['../VolumeComputeGenerator_8h.html',1,'']]],
['volumeexecutable_2eh',['VolumeExecutable.h',['../VolumeExecutable_8h.html',1,'']]],
['volumetomesh_2eh',['VolumeToMesh.h',['../VolumeToMesh_8h.html',1,'']]],
['volumetospheres_2eh',['VolumeToSpheres.h',['../VolumeToSpheres_8h.html',1,'']]],
['voxtonanovdb_2eh',['VoxToNanoVDB.h',['../VoxToNanoVDB_8h.html',1,'']]]
];
|
//alert("3ej3epj");
|
Drupal.FileMaintenance = Drupal.FileMaintenance || {};
Drupal.FileMaintenance.opendiv = '';
Drupal.FileMaintenance.action = '';
Drupal.FileMaintenance.active = '';
/**
* Show / hide directory form bulk actions.
*/
Drupal.behaviors.filemaintenance = function() {
$('.dirlink').each(function() {
$(this).click(function(e) {
action = $(this).attr('rel');
content = $(this).parent().parent().find('.container-inline');
// Hide 'old' open content.
if (Drupal.FileMaintenance.opendiv != '' && Drupal.FileMaintenance.opendiv != content.attr('id')) {
$('#' + Drupal.FileMaintenance.opendiv).hide();
$('#' + Drupal.FileMaintenance.opendiv).find('input:first').val('');
Drupal.FileMaintenance.opendiv = '';
Drupal.FileMaintenance.action = '';
Drupal.FileMaintenance.active.removeClass('active');
}
if (Drupal.FileMaintenance.action == '' || Drupal.FileMaintenance.action == action) {
// Toggle content.
if (content.is(':visible')) {
content.hide('fast');
}
else {
content.show('fast');
}
}
else {
Drupal.FileMaintenance.active.removeClass('active');
}
// Mark link as active.
if ($(this).hasClass('active')) {
$(this).removeClass('active');
content.find('input:first').val('');
}
else {
$(this).addClass('active');
content.find('input:first').val(action);
}
// Store the opened div & clicked action.
Drupal.FileMaintenance.opendiv = content.attr('id');
Drupal.FileMaintenance.action = action;
Drupal.FileMaintenance.active = $(this);
// Don't follow href.
e.preventDefault();
});
});
}
|
// == Import npm
import React from 'react';
// == Import composants
import Input from 'src/components/Input';
import Counter from 'src/components/Counter';
import List from 'src/components/List';
// == Data
import tasks from 'src/data/tasks';
// == Style
import './app.scss';
// == Composant
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
listOfTasks: tasks,
};
this.addNewTask = this.addNewTask.bind(this);
}
addNewTask(value) {
const tasksInState = this.state.listOfTasks;
const IDs = this.state.listOfTasks.map((task)=> task.id);
console.log(IDs);
const highestID = Math.max(...IDs);
console.log(highestID);
const newTask = {
id: highestID + 1,
label: value,
done: false,
};
this.setState({ listOfTasks: tasksInState.concat(newTask)});
}
computeCounter() {
// on veut calculer le nombre de tâches encore à effectuer
// on va filter selon que la propriété done est false
const ongoingTasksNb = this.state.listOfTasks.filter((task) => task.done === false).length;
// en fonction du nombre de tâches on modifie le texte du compteur
if (ongoingTasksNb === 0) {
return 'Aucune tâche en cours';
}
if (ongoingTasksNb === 1) {
return 'Une tâche en cours';
}
return `${ongoingTasksNb} tâches en cours`;
}
render() {
return (
<div className="app">
<Input onNewTask={this.addNewTask} />
<Counter text={this.computeCounter()} />
<List listOfTasks={this.state.listOfTasks} />
</div>
);
}
}
// == Export
export default App;
|
import BrowserRules from './BrowserRules';
/**
*
* @param {BrowserRules} rulesheet
* @param {string=} userAgent
*/
function BrowserDetector(rulesheet, userAgent) {
this.au = userAgent || (global.navigator ? (navigator.userAgent || '') : '');
this.rulesheet = rulesheet;
this.os = this.detectByRules(this.rulesheet.os);
this.device = this.detectByRules(this.rulesheet.device);
this.engine = this.detectByRules(this.rulesheet.engine);
this.browser = this.detectByRules(this.rulesheet.browser);
this.isFirefox = this.au.toLowerCase().indexOf('firefox') > -1;
this.isCococ = this.au.toLowerCase().indexOf('coc_coc_browser') >= 1;
this.isSafari = !this.isCococ && this.au.toLowerCase().indexOf('safari') > -1
&& this.au.toLowerCase().indexOf('win') < 0
&& this.au.toLowerCase().indexOf('android') < 0;
// this.isSafari = /constructor/i.test(window.HTMLElement) || window.safari;
this.isMobile = this.au.indexOf('KFFOWI') > -1 || this.au.toLowerCase().indexOf('mobile') > -1
|| this.browser.type === 'iphone';
this.isMacOSWebView = /Macintosh/.test(this.au) && /AppWebkit/.test(this.au) && !/Safari/.test(this.au);
this.isChromeIOS = /CriOS\/[\d]+/.test(this.au);
this.hasTouch = 'ontouchstart' in global ||
global.DocumentTouch && document instanceof global.DocumentTouch ||
(global.navigator && (navigator.maxTouchPoints > 0 || global.navigator.msMaxTouchPoints > 0));
this.isTouchDevice = this.isMobile && this.hasTouch;
this.supportPassiveEvent = (function () {
var supportsPassiveOption = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function () {
supportsPassiveOption = true;
}
});
global.addEventListener('test', null, opts);
global.removeEventListener('test', null, opts);
} catch (e) {
}
return supportsPassiveOption;
})();
this.supportGridLayout =global.document && ( typeof document.createElement('div').style.grid === 'string');
Object.defineProperty(this, 'zoom', {
get: function () {
return this.getZoom();
},
enumerable: true,
configurable: false
});
}
BrowserDetector.prototype.detectByRules = function (rules) {
var result = {};
for (var i = 0; i < rules.length; ++i) {
var rule = rules[i];
var type = rule[0];
var rgx = rule[1];
if (typeof (rgx) == 'function') {
rgx = rgx(this.au.toLowerCase());
}
if (Object.prototype.toString.call(rgx).indexOf('RegExp') >= 0) {
var matched = this.au.toLowerCase().match(rgx);
if (matched) {
result.type = type;
if (matched[1]) {
result.version = matched[1].replace(/_/g, '.');
}
break;
}
}
else if (typeof (rgx) == 'string') {
if (this.au.toLowerCase().indexOf(rgx) >= 0) {
result.type = type;
}
}
}
return result;
};
BrowserDetector.prototype.getZoom = function () {
//todo: wrong on chrome
var type;
if ('chrome' in global) {
type = "chrome";
}
else if (this.isSafari) {
type = 'safari';
}
else if ('orientation' in global && 'webkitRequestAnimationFrame' in global) {
type = 'webkitMobile';
}
else if ('webkitRequestAnimationFrame' in global) {
type = 'webkit';
}
switch (type) {
case 'chrome':
return Math.round(((global.outerWidth) / global.innerWidth) * 100) / 100;
case 'safari':
return Math.round(((document.documentElement.clientWidth) / global.innerWidth) * 100) / 100;
case 'webkitMobile':
return ((Math.abs(global.orientation) == 90) ? screen.height : screen.width) / global.innerWidth;
case 'webkit':
return (() => {
var important = (str) => {
return str.replace(/;/g, " !important;");
};
var div = document.createElement('div');
div.innerHTML = "1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0";
div.setAttribute('style', important('font: 100px/1em sans-serif; -webkit-text-size-adjust: none; text-size-adjust: none; height: auto; width: 1em; padding: 0; overflow: visible;'));
var container = document.createElement('div');
container.setAttribute('style', important('width:0; height:0; overflow:hidden; visibility:hidden; position: absolute;'));
container.appendChild(div);
document.body.appendChild(container);
var zoom = 1000 / div.clientHeight;
zoom = Math.round(zoom * 100) / 100;
document.body.removeChild(container);
return zoom;
})();
default:
return 1;
}
return 1;
};
export function calcBenchmark() {
var now = new Date().getTime();
var i = 0;
while (now === new Date().getTime()) {
}
now++;
while (now === new Date().getTime()) {
++i
}
return i;
}
BrowserDetector.prototype.calcBenchmark = calcBenchmark;
export default new BrowserDetector(BrowserRules);
|
const joinForm = document.getElementById('join-form');
const nameInput = document.getElementById('username');
const roomSelect = document.getElementById('room');
joinForm.addEventListener('submit', e => {
e.preventDefault();
const username = nameInput.value,
room = roomSelect.value;
// clear data before updating ?
sessionStorage.clear();
// update session data
sessionStorage.setItem('username', username);
sessionStorage.setItem('room', room);
// send to chat room client
window.location.href = "/chat.html";
});
window.addEventListener('load', () => {
const username = sessionStorage.getItem('username'),
room = sessionStorage.getItem('room');
if(username != null)
nameInput.value = username;
if(room != null)
roomSelect.value = room;
});
|
import { html } from '@polymer/lit-element';
import { PageViewElement } from './../../components/page-view-element.js';
// import './shared-styles.js';
class pageSide extends PageViewElement {
render() {
return html`
pageSide
<div class="card">
<h1 on-click="${ e => this.test(e)}">go to exporter</h1>
</div>
`;
}
test() {
let nextParams = { x: 2 }
this._redirect('/page-exporter', nextParams)
}
_pageActive(params) {
console.log(params)
}
}
customElements.define('page-side', pageSide);
|
// character.js
export default {
type: 'document',
name: 'character',
title: 'Character',
fields: [
{
name: 'avatar',
title: 'Avatar',
type: 'image'
},
{
name: 'name',
title: 'Name',
type: 'string'
},
{
name: 'slug',
title: 'Slug',
type: 'slug',
description: 'Some frontends will require a slug to be set to be able to show the person',
options: {
source: 'name',
maxLength: 96
}
},
{
name: 'posse',
type: 'array',
title: 'Crew',
of: [{type: 'string'}],
options: {
layout: 'tags'
}
},
{
name: 'physical',
title: 'Stats',
type: 'array',
of: [{type: 'physical'}]
},
{
name: 'magic',
title: 'Magic',
type: 'array',
of: [{type: 'magic'}]
},
{
name: 'bio',
type: 'cbioPortableText',
title: 'Who am I?'
}
],
preview: {
select: {
title: 'name',
subtitle: 'slug.current',
media: 'avatar'
}
}
}
|
class ItemService {
constructor() {
this.items = [
{link:1, name:"test1", summary:"Summary Test 1", year:"2001", country:"us", price:"1000", description:"Desc 1"},
{link:2, name:"test2", summary:"Summary Test 2", year:"2002", country:"uk", price:"2000", description:"Desc 2"},
{link:3, name:"test3", summary:"Summary Test 3", year:"2003", country:"cz", price:"3000", description:"Desc 3"},
];
}
async retrieveItems() {
return Promise.resolve(this.items);
}
async getItem(itemLink) {
for(var i = 0; i < this.items.length; i++) {
if ( this.items[i].link === itemLink) {
return Promise.resolve(this.items[i]);
}
}
return null;
}
async createItem(item) {
console.log("ItemService.createItem():");
console.log(item);
return Promise.resolve(item);
}
async deleteItem(itemId) {
console.log("ItemService.deleteItem():");
console.log("item ID:" + itemId);
}
async updateItem(item) {
console.log("ItemService.updateItem():");
console.log(item);
}
}
export default ItemService;
|
//@ts-check
var classes = ["Scout", "Scout", "Roaming Soldier", "Pocket Soldier", "Demoman", "Medic"];
function shuffle(array){
let counter = array.length;
while (counter > 0) {
let index = Math.floor(Math.random() * counter);
counter--;
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
function d_mix(){
if($("#d_name0").val() && $("#d_name1").val() && $("#d_name2").val() && $("#d_name3").val() && $("#d_name4").val() && $("#d_name5").val()){
var shuffledArray = shuffle(classes);
$("#d_class0").text(shuffledArray[0]);
$("#d_class1").text(shuffledArray[1]);
$("#d_class2").text(shuffledArray[2]);
$("#d_class3").text(shuffledArray[3]);
$("#d_class4").text(shuffledArray[4]);
$("#d_class5").text(shuffledArray[5]);
}
else{
$('#notAllNamesEnteredModal').modal();
}
}
function m_mix(){
if($("#m_name0").val() && $("#m_name1").val() && $("#m_name2").val() && $("#m_name3").val() && $("#m_name4").val() && $("#m_name5").val()){
var shuffledArray = shuffle(classes);
$("#m_class0").text(shuffledArray[0]);
$("#m_class1").text(shuffledArray[1]);
$("#m_class2").text(shuffledArray[2]);
$("#m_class3").text(shuffledArray[3]);
$("#m_class4").text(shuffledArray[4]);
$("#m_class5").text(shuffledArray[5]);
}
else{
$('#notAllNamesEnteredModal').modal();
}
}
function d_openCopyModal(){
if($("#d_class0").text()){
$('#copyModal').modal();
$("#d_copyText").val(
$("#d_name0").val() + ' will be playing ' + $("#d_class0").text() + "\r" +
$("#d_name1").val() + ' will be playing ' + $("#d_class1").text() + "\r" +
$("#d_name2").val() + ' will be playing ' + $("#d_class2").text() + "\r" +
$("#d_name3").val() + ' will be playing ' + $("#d_class3").text() + "\r" +
$("#d_name4").val() + ' will be playing ' + $("#d_class4").text() + "\r" +
$("#d_name5").val() + ' will be playing ' + $("#d_class5").text() + "\r\rBrought to you by mixme.tf on mijuuu.github.io"
);
}
else{
$('#tableNotFilledModal').modal();
}
}
function m_openCopyModal(){
if($("#m_class0").text()){
$('#copyModal').modal();
$("#m_copyText").val(
$("#m_name0").val() + ' will be playing ' + $("#m_class0").text() + "\r" +
$("#m_name1").val() + ' will be playing ' + $("#m_class1").text() + "\r" +
$("#m_name2").val() + ' will be playing ' + $("#m_class2").text() + "\r" +
$("#m_name3").val() + ' will be playing ' + $("#m_class3").text() + "\r" +
$("#m_name4").val() + ' will be playing ' + $("#m_class4").text() + "\r" +
$("#m_name5").val() + ' will be playing ' + $("#m_class5").text() + "\r\rBrought to you by mixme.tf on mijuuu.github.io"
);
}
else{
$('#tableNotFilledModal').modal();
}
}
function d_copyToClipboard(){
var copyText = $("#d_copyText");
copyText.select();
document.execCommand("Copy");
}
function m_copyToClipboard(){
var copyText = $("#m_copyText");
copyText.select();
document.execCommand("Copy");
}
|
import {Component} from '../Component.js';
export class GuiPane extends Component {
constructor(opts) {
var base = {
// The parent container of this pane.
"parent": null,
"id": "dex-ui-guipane",
"class": "dex-ui-guipane",
"targets": []
};
super(new dex.Configuration(base).overlay(opts));
this.componentMap = {};
this.targetList = {};
this.controlCounter = 0;
this.initialize()
}
initialize() {
if (!$.contains(document, this.$root[0])) {
return this;
}
let config = this.config;
//let $parent = $(config.get("parent"));
let components = config.get("targets");
let self = this;
let $root = this.$root;
components.forEach(function (component, ci) {
//dex.logString("COMPONENT[", ci,
// "] = parent='", component.get("parent"), "', id='", component.get("id"),
// "', class='", component.get("class"), "'");
self.componentMap[component.getDomTarget()] = component;
})
this.addControls($root, components);
///////////////////
// Enable booleans
///////////////////
var $toggles = $root.find('.control-boolean input');
//dex.log($root.find("input.dex-toggle[initialValue=true]"))
$root.find("input.dex-toggle[initialValue=true]").prop("checked", true);
// Collapse everything below the third tier:
// GUI Config -> Charts -> Main Sections
$root.find('.depth-1,.depth-2').collapse("show");
return this;
}
update() {
return this;
};
// TODO: Start here, work your way down and componetize everything
addControls($target, components) {
// Used to ensure all target names are unique.
let config = this.config;
this.targetList = {};
var self = this;
let $guiTitle = $(`<div class="dex-h1 text-center" data-toggle='collapse'
data-target='#dex-ui-guipane-body'>Gui Configuration</div>`)
let $guiDiv = $(`<div id="dex-ui-guipane-body" class="collapse depth-1"></div>`)
let $guiTable = $(`<table class="dex-control-table"></table>`);
let $guiBody = $(`<tbody></tbody>`)
$guiDiv.append($guiTable);
$guiTable.append($guiBody)
$target.append($guiTitle)
$target.append($guiDiv)
config.get("targets").forEach(function (component) {
let target = component.getDomTarget();
if (target !== undefined) {
self.addControl(target, $guiBody, component.getGuiDefinition(), 1);
}
});
return this;
}
getTargetName(name) {
let targetList = this.targetList;
var targetName = name.replace(/[\. >\(\)#:]/g, '_');
//dex.console.log("NAME(" + name + ")->" + targetName);
if (targetList[targetName] === undefined) {
targetList[targetName] = 1;
} else {
targetList[targetName]++;
}
return targetName + "-" + targetList[targetName];
}
addControl(targetComponent, $targetElt, guiDef, depth) {
if (guiDef === undefined || guiDef.type === undefined) {
return;
}
switch (guiDef.type) {
case "group" :
this.addGroup(targetComponent, $targetElt, guiDef, depth + 1);
break;
case "string" :
this.addString(targetComponent, $targetElt, guiDef, depth);
break;
case "float" :
this.addFloat(targetComponent, $targetElt, guiDef, depth);
break;
case "int" :
this.addInt(targetComponent, $targetElt, guiDef, depth);
break;
case "boolean" :
this.addBoolean(targetComponent, $targetElt, guiDef, depth);
break;
case "choice" :
this.addChoice(targetComponent, $targetElt, guiDef, depth);
break;
case "multiple-choice" :
this.addMultipleChoice(targetComponent, $targetElt, guiDef, depth);
break;
case "color" :
this.addColor(targetComponent, $targetElt, guiDef, depth);
break;
default:
// Choice, color
//dex.log("UNRECOGNIZED CONTROL TYPE: '" + guiDef.type + "'");
break;
}
return this;
}
addGroup(targetComponent, $targetElt, guiDef, depth) {
var groupTarget = this.getTargetName(
targetComponent + ":" + guiDef.name);
var self = this;
let $row = $(`<tr></tr>`)
let $groupTitle = $(`<tr><td colspan="2"><div class="dex-h${depth} "
data-toggle='collapse' data-target='#${groupTarget}'>${guiDef.name}</div></td></tr>`)
let $groupRow = $(`<tr id="${groupTarget}" class="depth-${depth} collapse"></tr>`);
let $groupCol = $(`<td colspan="2"></td>`);
let $groupDiv = $(`<div></div>`)
let $groupTable = $(`<table class="dex-control-table"></table>`)
$groupDiv.append($groupTable);
$groupCol.append($groupDiv)
$groupRow.append($groupCol)
$targetElt.append($groupTitle)
$targetElt.append($groupRow)
guiDef.contents.forEach(function (contentDef) {
self.addControl(targetComponent, $groupTable, contentDef, depth);
});
}
createRow($left, $right) {
let $row = $(`<tr></tr>`)
let $leftCol = $(`<td class="left-column"></td>`)
let $rightCol = $(`<td class="right-column"></td>`)
$leftCol.append($left)
$rightCol.append($right)
$row.append($leftCol)
$row.append($rightCol)
return $row
}
addColor(targetComponent, $targetElt, guiDef, depth) {
let self = this;
let $label = $(`<label class="dex-label col-lg-4"></label>`)
.attr("title", guiDef.description)
.html(guiDef.name + ":");
let $picker = $(`<input class="dex-ui-guipane-colorpicker col-lg-8" type=""color"></input>`)
.attr("value", guiDef.initialValue)
.attr("targetAttribute", guiDef.target)
.attr("targetComponent", targetComponent);
$targetElt.append(this.createRow($label, $picker));
$picker.spectrum({
showPalette: true,
showAlpha: true,
palette: [
["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", /*"rgb(153, 153, 153)","rgb(183, 183, 183)",*/
"rgb(204, 204, 204)", "rgb(217, 217, 217)", /*"rgb(239, 239, 239)", "rgb(243, 243, 243)",*/ "rgb(255, 255, 255)"],
["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
"rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
"rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
"rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
/*"rgb(133, 32, 12)", "rgb(153, 0, 0)", "rgb(180, 95, 6)", "rgb(191, 144, 0)", "rgb(56, 118, 29)",
"rgb(19, 79, 92)", "rgb(17, 85, 204)", "rgb(11, 83, 148)", "rgb(53, 28, 117)", "rgb(116, 27, 71)",*/
"rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
],
showSelectionPalette: true,
clickoutFiresChange: true,
showInitial: false,
//palette: dex.color.palette['crayola120'],
change: function (color) {
//dex.console.log("COLOR-CHANGE", color, this);
//$("#basic-log").text("change called: " + color.toHexString());
var cmp = self.componentMap[this.getAttribute("targetComponent")];
var attName = this.getAttribute("targetAttribute");
var value = color.toHexString();
if (cmp != undefined) {
cmp.set(attName, value);
cmp.save(attName, value);
cmp.update();
}
}
});
}
addChoice(targetComponent, $targetElt, guiDef, depth) {
let self = this;
self.controlCounter++;
let id = self.controlCounter;
let $label = $(`<label class="dex-label" title="${guiDef.description}">${guiDef.name}:</label>`)
let $select = $(`<div class="dex-h3" id="dex-guipane-choice-${id}"></div>`);
$targetElt.append(this.createRow($label, $select))
var listSelector = new dex.ui.ListSelector({
parent: `#dex-guipane-choice-${id}`,
id: `dex-guipane-choice-selector-${id}`,
name: guiDef.name,
items: guiDef.choices,
selectAll: false,
multiple: false,
selected : [ guiDef.initialValue ]
}).render();
dex.bus.subscribe(listSelector, "select", function(msg) {
//dex.log("MSG", msg)
var cmp = self.componentMap[targetComponent];
if (cmp != undefined) {
//dex.log("set-choice", cmp, attName, option.attr("value"))
cmp.set(guiDef.target, msg.selected).update();
}
})
}
addMultipleChoice(targetComponent, $targetElt, guiDef, depth) {
let self = this;
self.controlCounter++;
let id = self.controlCounter;
let $label = $(`<label class="dex-label" title="${guiDef.description}">${guiDef.name}:</label>`)
let $select = $(`<div class="dex-h3" id="dex-guipane-multi-choice-${id}"></div>`);
$targetElt.append(this.createRow($label, $select))
var listSelector = new dex.ui.ListSelector({
parent: `#dex-guipane-multi-choice-${id}`,
id: `dex-guipane-multi-choice-selector-${id}`,
name: guiDef.name,
items: guiDef.choices,
selectAll: false,
multiple: true,
selected : [ guiDef.initialValue ]
}).render();
dex.bus.subscribe(listSelector, "select", function(msg) {
//dex.log("MSG", msg)
var cmp = self.componentMap[targetComponent];
if (cmp != undefined) {
//dex.log("set-choice", cmp, attName, option.attr("value"))
cmp.set(guiDef.target, msg.selected).update();
}
})
}
addBoolean(targetComponent, $targetElt, guiDef, depth) {
let $label = $(`<label class="dex-label"></label>`)
.attr("title", guiDef.description)
.html(guiDef.name + ":");
let $switch = $(`<label class="switch"></label>`)
let $input = $(`<input class="dex-toggle" type="checkbox"></input>`)
let $span = $(`<span class="slider round"></span>`)
$switch.append($input);
$switch.append($span)
$targetElt.append(this.createRow($label, $switch))
if (guiDef.initialValue !== undefined) {
$input.attr("initialValue", guiDef.initialValue);
}
var handler = function (cmp, guiDef) {
return function () {
var obj = $(this);
var value = obj.prop('checked');
//dex.log("boolean-handler", cmp, guiDef, obj, value)
if (typeof guiDef.filter === "function") {
value = guiDef.filter(value);
}
if (cmp != undefined) {
cmp.set(guiDef.target, value)
cmp.update();
}
}
}(this.componentMap[targetComponent], guiDef);
//$input.bootstrapToggle({
// on: "Yes",
// off: "No",
// onstyle: "primary",
// offstyle: "danger",
// width: 40,
// height: 25
//});
$input.change(handler);
}
addString(targetComponent, $targetElt, guiDef, depth) {
let self = this;
let $label = $(`<label class="dex-label">${guiDef.name}:</label>`)
.attr("title", guiDef.description)
let $input = $(`<input class="dex-string-input" type="text"></input>`)
.attr("targetAttribute", guiDef.target)
.attr("targetComponent", targetComponent)
.attr("value", guiDef.initialValue)
.attr("id", guiDef.target);
$targetElt.append(this.createRow($label, $input))
$input.on('input', function (event) {
var cmp = self.componentMap[event.target.getAttribute("targetComponent")];
var attName = event.target.getAttribute("targetAttribute");
if (cmp != undefined) {
//dex.log("cmp-set", cmp, attName, event.target.value)
cmp.set(attName, event.target.value);
cmp.update();
}
})
}
addFloat(targetComponent, $targetElt, guiDef, depth) {
let self = this;
let $label = $(`<tr><td colspan="2">
<label class="dex-label" title="${guiDef.description}">${guiDef.name}</label>
</td></tr>`)
let $sliderRow = $(`<tr></tr>`)
let $sliderCol = $(`<td colspan="2"></td>`)
$sliderRow.append($sliderCol)
$targetElt.append($label)
$targetElt.append($sliderRow)
var floatSlider = new dex.ui.Slider({
parent: $sliderCol,
min: guiDef.minValue,
max: guiDef.maxValue,
target: guiDef.target,
targetComponent: targetComponent,
step: guiDef.step,
initial: guiDef.initialValue,
onFinish: function (data) {
//dex.log("setting " + guiDef.target + " to " + data.from)
self.componentMap[targetComponent].set(guiDef.target, data.from).update();
}
});
}
addInt(targetComponent, $targetElt, guiDef, depth) {
this.addFloat(targetComponent, $targetElt, guiDef, depth)
}
}
|
import PropTypes from 'prop-types';
import React from 'react';
import { css } from 'styled-components';
import { hashMemo } from '@/utils/hashData';
import injectStyles from '@/utils/injectStyles';
import { COLORS } from '@/utils/styleConstants';
const COLOR = [
COLORS.CHARTS.PIE_CHART.GREY,
COLORS.CHARTS.PIE_CHART.DARK_GRAY,
COLORS.CHARTS.PIE_CHART.LIGHT_BLUE,
COLORS.CHARTS.PIE_CHART.BLUE
];
const Block = ({ valueR, valueL, className }) => (
<div className={className}>
<div></div>
<div></div>
<p>{valueR}</p>
<p>{valueL}</p>
</div>
);
Block.propTypes = {
className: PropTypes.string.isRequired,
valueR: PropTypes.oneOf([0, 1, 2, 3]).isRequired,
valueL: PropTypes.oneOf([0, 1, 2, 3]).isRequired
};
Block.defaultProps = {};
Block.displayName = 'SpiroergometryTestSummaryChartElement';
const styles = css`
position: relative;
height: 110px;
width: 100%;
& > div {
position: absolute;
height: 50px;
top: 60px;
}
& > div:first-child {
width: ${props => (props.valueR + 1) * 68}px;
left: ${props => (3 - props.valueR) * 68}px;
background-color: ${props => COLOR[props.valueR]};
}
& > div:nth-child(2) {
width: ${props => (props.valueL + 1) * 68}px;
left: 312px;
background-color: ${props => COLOR[props.valueL]};
}
& > p {
position: absolute;
margin: 0;
font: 700 28px/36px var(--ff);
}
& > p:nth-child(3) {
left: 7px;
}
& > p:nth-child(4) {
right: -7px;
}
`;
Block.whyDidYouRender = true;
export default injectStyles(hashMemo(Block), styles);
|
'use strict';
/**
* @ngdoc service
* @name thelistwebApp.userService
* @description
* # userService
* Factory in the thelistwebApp.
*/
angular.module('thelistwebApp')
.factory('userService', ['$cookieStore', '$state', 'restService', function ($cookieStore, $state, restService) {
var saveUser = function (user) {
restService.setHeaders(user);
$cookieStore.put('user', user);
};
var getUser = function () {
return $cookieStore.get('user');
};
var loadUser = function () {
var user = getUser();
if (user) {
restService.setHeaders(user);
}
};
var resetUser = function () {
restService.resetHeaders();
$cookieStore.remove('user');
};
var signOut = function () {
resetUser();
$state.go('signin');
};
// Load user from cookie
loadUser();
return {
getUser: function () {
return getUser();
},
isAuthenticated: function () {
return getUser() != undefined;
},
signOut: function () {
signOut();
},
authenticate: function (username, password) {
return restService.post('thelist/auth', { username: username, password: password }).
success(function (data, status) {
var user = {
username: username,
authtoken: data.token
};
saveUser(user);
$state.go('main');
}).
error(function (data, status) {
//signOut();
});
}
};
}]);
|
export default class Router {
constructor(routes) {
this.routes = routes;
this.rootElem = document.querySelector("#app");
this.init();
}
hasChanged = routes => {
if (window.location.hash.length > 0) {
for (const route of routes) {
if (route.isActiveRoute(window.location.hash.substr(1))) {
this.goToRoute(route.htmlName);
break;
}
}
} else {
for (const route of routes) {
if (route.default) {
this.goToRoute(route.htmlName);
break;
}
}
}
};
goToRoute = htmlName => {
(function(scope) {
const url = "views/" + htmlName;
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
scope.rootElem.innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
})(this);
};
init = () => {
const routes = this.routes;
window.addEventListener("hashchange", e => {
this.hasChanged(routes);
});
this.hasChanged(routes);
};
}
|
import React from 'react'
import cxs from 'cxs'
import css from '../../lib/css'
import s from './styles.js'
const renderStyles = (styles) => (
styles.map((style, index) => <link key={index} rel='stylesheet' href={style} />)
)
const renderScripts = (scripts) => (
scripts.map((script, index) => <script key={index} src={script} />)
)
export default ({
head,
content,
state = {},
styles = ['/main.css'],
scripts = ['/main.js']
}) => (
<html className={css(s.root)}>
<head>
<meta charSet='utf-8' />
<meta name='viewport' content='width=device-width, initial-scale=1' />
{head.title.toComponent()}
{head.meta.toComponent()}
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800' rel='stylesheet' />
<script src='https://use.fontawesome.com/325c02e7f1.js' />
<link rel='apple-touch-icon' sizes='180x180' href={`${process.env.BASE_PATH || '/'}favicons/apple-touch-icon.png`} />
<link rel='icon' type='image/png' href={`${process.env.BASE_PATH || '/'}favicons/favicon-32x32.png`} sizes='32x32' />
<link rel='icon' type='image/png' href={`${process.env.BASE_PATH || '/'}favicons/favicon-16x16.png`} sizes='16x16' />
<link rel='manifest' href={`${process.env.BASE_PATH || '/'}favicons/manifest.json`} />
<link rel='mask-icon' href={`${process.env.BASE_PATH || '/'}favicons/safari-pinned-tab.svg`} color='#801648' />
<meta name='theme-color' content='#ffffff' />
{renderStyles(styles)}
<link rel='stylesheet' type='text/css' href='https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.3.15/slick.css' />
<style>{cxs.css || ''}</style>
</head>
<body>
<main
id='mount'
dangerouslySetInnerHTML={{
__html: content
}}
/>
<script
id='initial-state'
type='application/json'
dangerouslySetInnerHTML={{
__html: JSON.stringify(state)
}}
/>
{renderScripts(scripts)}
</body>
</html>
)
|
var form = document.querySelector('form')
var tableInput = document.querySelector('#table_name')
var fileInput = document.querySelector('#csv_file')
var showText = document.querySelector('#show-text')
form.addEventListener('submit', (e) => {
e.preventDefault()
Papa.parse(fileInput.files[0], {
complete: function (results) {
console.log(results)
getResult(results.data)
}
});
})
function getResult(data) {
var tableName = tableInput.value
var cols = data[0]
console.log(cols)
var text = `
INSERT INTO ${tableName} (${cols.join(', ')}) \n
VALUES \n
`
for (var i = 1; i < data.length; i++) {
var values = data[i]
var line = []
values.forEach(value => {
if (isNumber(value)) {
line.push(value)
}
else {
line.push(`'${value}'`)
}
})
text += `(${line.join(', ')}), \n`
}
text += ';'
showText.innerText = text
}
function isNumber(n) {
return /^-?[\d.]+(?:e-?\d+)?$/.test(n);
}
|
(function () {
angular
.module("profileApp")
.controller("WorkController", WorkController);
function WorkController($scope) {
angular.element(document).ready(function () {
scrollSections();
console.log("Owl");
$(".owl-carousel").owlCarousel({
autoplay: true,
autoplayTimeout: 1000,
autoplayHoverPause: true,
dots: true,
loop: true
});
});
function scrollSections() {
console.log("Inside Scrolling");
// init
var controller = new ScrollMagic.Controller({
globalSceneOptions: {
triggerHook: 'onLeave'
}
});
// get all slides
var slides = document.querySelectorAll("work-content");
// create scene for every slide
for (var i = 0; i < slides.length; i++) {
new ScrollMagic.Scene({
triggerElement: slides[i]
})
.setPin(slides[i])
.addIndicators() // add indicators (requires plugin)
.addTo(controller);
}
}
}
})();
|
import React, { Component } from 'react';
import './App.css';
import Header from './components/Header';
import Home from './pages/Home';
import About from './pages/About';
import Works from './pages/Works';
import Contact from './pages/Contact';
import Footer from './components/Footer';
import Photoswipe from './components/Photoswipe';
class App extends Component{
constructor(props){
super(props);
this.state = {
data: {}
}
}
componentDidMount(){
fetch('resumeData.json')
.then(d => d.json())
.then(d => {
this.setState({
data: d
})
})
}
render(){
return(
<div className="App">
<Header />
<Home data= {this.state.data.main}/>
<About data= {this.state.data.main} data2= {this.state.data.resume}/>
<Works/>
<Contact/>
<Footer/>
<Photoswipe />
</div>
)
}
}
export default App;
|
// グローバル空間に変数や関数をセットしないために即時関数で閉じ込めている
(() => {
// 入力したTodoタスクの一覧を保持する配列を定義する
const todos = [];
// HTMLのID値を使って以下のDOM要素を取得する
// - テキストボックス(input[type="text"])
// - 追加ボタン(button要素)
// - Todoリストを一覧表示するul要素
const inputTodoBox = document.getElementById('input-todo-box');
const addButton = document.getElementById('add-button');
const todoList = document.getElementById('todo-list');
//「追加」ボタンがクリックされたときの処理を実装する
// - テキストボックスに入力されたテキストをTodoリスト一覧に追加する
// - テキストボックスの中を空にする
addButton.addEventListener('click', (event) => {
const todoItemText = inputTodoBox.value;
inputTodoBox.value = '';
if (todoItemText) {
todos.push(todoItemText);
showTodos();
}
});
// 「todos」の中身を一覧表示する
// - ul要素にli要素を追加して、li要素内にtodoタスクの内容を表示する
// // - li要素内に削除ボタンを配置して、削除ボタンをクリックしたら対応するタスクを削除する
function showTodos() {
while (todoList.firstChild) {
todoList.removeChild(todoList.firstChild);
}
todos.forEach((todoItemText, index) => {
const todoItem = document.createElement('li');
const itemNumber = index + 1;
todoItem.textContent = `${itemNumber}:${todoItemText}`;
todoList.appendChild(todoItem);
const deleteButton = document.createElement('button');
deleteButton.textContent = '削除';
deleteButton.addEventListener('click', (event) => {
deleteTodos(index);
});
todoItem.appendChild(deleteButton);
});
}
// Todo情報を表すli要素(showTodo関数で作成される要素)の中にある削除ボタンをクリックしたら実行される。
// - todosから対応するtodo情報を削除する
// - 引数はindexを受け取る(インデックス番号)
// - 削除後はshowTodosを実行して、Todoリストを整理する
function deleteTodos(index) {
todos.splice(index, 1);
showTodos();
}
})();
|
const path = require('path')
const paths = require('../paths')
const jsonImporter = require('node-sass-json-importer')
const sassLoader = {
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: [paths.app.cssBase, 'node_modules'],
importer: jsonImporter,
},
},
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
postcssOptions: {
config: path.resolve('.config/postcss.config.js'),
},
},
}
// Note that svg fonts won't be picked up by this loader
const fontLoader = () => ({
test: /\.(ttf|eot|woff|woff2)$/,
use: {
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]',
},
},
})
const imageLoader = ({ isProd, assetHash }) => ({
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: isProd ? '[hash].[ext]' : '[path][name].[ext]',
outputPath: '/files/',
publicPath: assetHash + '/files/',
context: 'frontend',
},
},
{
loader: 'image-webpack-loader',
options: {
disable: true, // disabled in dev mode
optipng: {
enabled: false,
},
pngquant: {
quality: '90-95',
},
},
},
],
})
module.exports = {
sassLoader: sassLoader,
postcssLoader: postcssLoader,
fontLoader: fontLoader,
imageLoader: imageLoader,
}
|
import React, {Component, PropTypes} from 'react';
import DocumentTitle from 'react-document-title';
import classnames from 'classnames';
class PageContainer extends Component {
getClassNames() {
return classnames(
'page-content',
this.props.classNames
);
}
getHeadline() {
let headline;
if (this.props.headline) {
headline = <h2 className="PageContainer__headline">{this.props.headline}</h2>;
}
return headline;
}
render() {
const innerContent = (
<div className={this.getClassNames()}>
{this.getHeadline()}
{this.props.children}
</div>
);
if (this.props.documentTitle) {
const formattedTitle = `${this.props.documentTitle} | Blazar`;
return (
<DocumentTitle title={formattedTitle}>
{innerContent}
</DocumentTitle>
);
}
return innerContent;
}
}
PageContainer.propTypes = {
headline: PropTypes.string,
documentTitle: PropTypes.string,
classNames: PropTypes.string,
children: PropTypes.node
};
export default PageContainer;
|
({
generateSearchToken: function (component, event, helper) {
var deferred = event.getParam('deferred');
var action = component.get('c.getToken');
action.setParams({
searchHub: component.get('v.searchHub')
});
action.setCallback(this, function (response) {
if (component.isValid() && response.getState() === 'SUCCESS') {
deferred.resolve({
searchToken: response.getReturnValue()
})
}
});
$A.enqueueAction(action);
},
executeComponentInitilization: function (cmp, event, helper) {
try {
// Get user context
helper.getUserContext(cmp, event, helper);
// Get Community Site URL
helper.getSiteURL(cmp, event, helper);
} catch (e) {
//console.error(e);
}
},
onInterfaceContentLoaded: function (cmp, event, helper) {
var searchInterface = Coveo.$('#usefulanswers').append();
var placeholder = searchInterface[0].querySelector('.result-placeholder');
var siteUrl = cmp.get('v.siteUrl');
// Get current user region
function getCurrentUserRegion() {
var regionStorageIndex;
var lssIndex = window.sessionStorage.getItem('LSSIndex:SESSION{"namespace":"c"}');
try {
regionStorageIndex = JSON.parse(lssIndex).regionStorage;
} catch (e) {
regionStorageIndex = '';
}
var region = window.sessionStorage.getItem(regionStorageIndex) || window.sessionStorage.getItem('regionStorage');
return region;
}
// Region Filter (XVK-535)
searchInterface.on('buildingQuery', function (e, args) {
var region = getCurrentUserRegion();
// Build region expressions
var noRegionExpressionBuilder = new Coveo.ExpressionBuilder();
var regionExpressionBuilder = new Coveo.ExpressionBuilder();
var allRegionExpressionBuilder = new Coveo.ExpressionBuilder();
var advancedExpression = '';
noRegionExpressionBuilder.add("(NOT @sfdcexpandedcountryregion)");
advancedExpression += noRegionExpressionBuilder.build();
if (region) {
regionExpressionBuilder.addFieldExpression("@sfdcexpandedcountryregion", "=", [region]);
advancedExpression += " OR " + regionExpressionBuilder.build();
}
allRegionExpressionBuilder.addFieldExpression("@sfdcexpandedcountryregion", "==", ["All"]);
advancedExpression += " OR " + allRegionExpressionBuilder.build();
// Apply expression on query
args.queryBuilder.advancedExpression.add(advancedExpression);
});
// Add User Context
searchInterface.on('buildingQuery', function (e, args) {
args.queryBuilder.addContext(cmp.get('v.userContext'));
// Add region filter
args.queryBuilder.context["userRegion"] = getCurrentUserRegion();
});
searchInterface.on('changeAnalyticsCustomData', function(e, args) {
var userContext = cmp.get('v.userContext');
for (var prop in userContext) {
args.metaObject[prop] = userContext[prop];
}
// Add region filter
args.metaObject["userRegion"] = getCurrentUserRegion();
// Overwrite originLevel2 for default
args.originLevel2 = "default";
// Tag widget origin for reporting purposes
args.metaObject["widgetOrigin"] = "PopularAnswers";
});
// Normalize clickable URIs
searchInterface.on('preprocessResults', function (e, args) {
//console.warn('searchInterface preprocessResults');
//console.warn(args.results);
Coveo._.each(args.results.results, function (result) {
if (result.raw.sfkbid) {
result.clickUri = siteUrl + '/s/article/' + result.raw.sfurlname;
}
else if (result.raw.sffeeditemid) {
result.clickUri = siteUrl + '/s/question/' + result.raw.sffeeditemid;
}
else if (result.raw.sftopicid) {
result.clickUri = siteUrl + '/s/topic/' + result.raw.sftopicid;
}
})
});
searchInterface.on('querySuccess', function (e, args) {
/****************************************
Coveo returns the useful answers
****************************************/
// build up the search results as DOM elements so we can add custom CSS to the results returned by Coveo (as opposed to using their ResultsTemplate styling)
let length = args.results.results.length > 6 ? 6 : args.results.results.length;
for (let i = 0; i < length; i++) {
//get useful/popular answer returned by Coveo
let result = args.results.results[i];
//construct elements to hold the single useful answer result
let outerDiv = Coveo.$$('div', {class: 'width-full width-1/2@small width-1/2@medium u-text-left'}).el;
let keylineBottom = Coveo.$$('div', {class: 'u-keyline--bottom'}).el;
//construct anchor link to the useful answer
let link = Coveo.$$('a', {href: result.clickUri}).el;
link.innerHTML = result.title;
//construct heading for the title of the useful answer (title of the article or discussion)
let header = Coveo.$$('h3').el;
header.appendChild(link);
keylineBottom.appendChild(header);
// construct element to hold the breadcrumb for the useful answer
let breadcrumb = Coveo.$$('ul', {class: 'breadcrumb'}).el;
// construct sub-elements which make up the breadcrumb element
let subTitle = Coveo.$$('span', {class: 'title__subtitle'}).el;
let searchType = Coveo.$$('li', {class: 'xc-search-result__type'}).el;
let firstLevel = Coveo.$$('li').el;
let firstLevelText = Coveo.$$('span').el;
let secondLevel = Coveo.$$('li').el;
let secondLevelText = Coveo.$$('span').el;
let arrowIcon = Coveo.$$('li', {class: 'xui-breadcrumb-arrow xui-iconwrapper-medium'}).el;
let imgPath;
let productTag = result.raw.sfcoreproductc;
// Don't set an imgPath if it's tagged with a product
if (typeof productTag !== "undefined") {
firstLevelText.innerHTML = result.raw.sftopicfirstlevelc;
secondLevelText.innerHTML = result.raw.sftopicthirdlevelc;
} else if (result.raw.objecttype === 'Knowledge_Content') {
// give the breadcrumb content based on whether it's a knowledge article or a discussion
imgPath = '/icons/icon-article--fill-grey.svg';
firstLevelText.innerHTML = result.raw.sftopicfirstlevelc;
secondLevelText.innerHTML = result.raw.sftopicthirdlevelc;
// Articles are highly favored to show in Prod.
// Discussions should not be showing very often in Prod,
// but they are still showing in DevTest/LiveStage so will leave this for now
} else if (result.raw.objecttype === 'FeedItem') {
imgPath = '/icons/icon-discussion--fill-grey.svg';
firstLevelText.innerHTML = result.raw.coveochatterfeedtopics;
secondLevelText.innerHTML = 'Discussions';
}
// If it has a product tag, add it instead of an icon
if (typeof productTag !== "undefined") {
let usefulAnswerTag = Coveo.$$('span', {
class: 'xui-tag'
}).el;
searchType.appendChild(usefulAnswerTag);
usefulAnswerTag.innerHTML = productTag;
breadcrumb.appendChild(searchType);
} else if (result.raw.objecttype === 'FeedItem') {
// add icon to breadcrumb & Class for icon position
let usefulAnswerIcon = Coveo.$$('img', {
class: 'icon icon--m icon-discussion--fill-grey',
src: $A.get('$Resource.XC_Theme') + imgPath
}).el;
searchType.appendChild(usefulAnswerIcon);
breadcrumb.appendChild(searchType);
} else {
// add icon to breadcrumb
let usefulAnswerIcon = Coveo.$$('img', {
class: 'icon icon--m',
src: $A.get('$Resource.XC_Theme') + imgPath
}).el;
searchType.appendChild(usefulAnswerIcon);
breadcrumb.appendChild(searchType);
}
// add first level to the breadcrumb
firstLevel.appendChild(firstLevelText);
breadcrumb.appendChild(firstLevel);
// add arrow separating first level from the second level of the breadcrumb. E.g. first level > second level. E.g. 2. Bank accounts & feeds > Discussions.
let arrowIconImg = Coveo.$$('img', {
class: 'icon icon--s',
src: $A.get('$Resource.XC_Theme') + '/icons/icon-arrow-right--fill-grey.svg'
}).el;
arrowIcon.appendChild(arrowIconImg);
breadcrumb.appendChild(arrowIcon);
//add second level to the breadcrumb
secondLevel.appendChild(secondLevelText);
breadcrumb.appendChild(secondLevel);
//append remaining styling elements to container div
subTitle.appendChild(breadcrumb);
keylineBottom.appendChild(subTitle);
outerDiv.appendChild(keylineBottom);
//sending Coveo custom event Analytics
header.onclick= function(){
var eventCause = {name: 'documentOpen', type:'Useful Answers'};
Coveo.$('#usefulanswers').coveo('logClickEvent',eventCause,{},result);
}
placeholder.appendChild(outerDiv);
}
});
// Execute this query in a way that does not count against the monthly query limit
// of a Coveo Cloud organization but may produce cached/outdated query results
try {
Coveo.SearchEndpoint.endpoints[cmp.get('v.name')+'Endpoint'].caller.options.queryStringArguments.staticQuery = true;
} catch(e) {
console.error(e);
}
// Initialize Coveo interface
searchInterface.coveo('initRecommendation');
}
})
|
const mongoose=require('mongoose')
const UserSchema=mongoose.Schema({
firstName:{
type:String,
required:true
},
lastName:{
type:String,
required:true
},
username:{
type:String,
required:true
},
password:{
type:String,
required:true
},
progress:{
type:Number,
default:0
}
})
module.exports=mongoose.model('Users',UserSchema)
|
define([], function(){
return {
"c": {
"name": "clike",
"mime": "text/x-csrc",
"keywords": {
"useCPP": true
}
},
"c++": {
"name": "clike",
"mime": "text/x-c++src",
"keywords": {
"useCPP": true
}
},
"c#": {
"name": "clike",
"mime": "text/x-csharp",
"keywords": {
"useCPP": true
}
},
"json": {
"name": "javascript",
"mime": "application/javascript",
"keywords": {}
},
"java": {
"name": "clike",
"mime": "text/x-java",
"keywords": {
"useCPP": true
}
},
"scala": {
"name": "clike",
"mime": "text/x-scala",
"keywords": {
"useCPP": true
}
}
}
});
|
const fs = require('fs');
const content = fs.readFileSync('../../front-end/src/components/Home/HomeCopy.vue', 'utf-8');
const name = process.argv[2];
const newContent = content.replace(/\$\{name\}/g, name);
fs.writeFileSync('../../front-end/src/components/Home/Home.vue', newContent);
|
/* eslint-env node */
const shell = require('shelljs');
const fs = require('fs');
const replace = require('replace-in-file');
const argv = require('yargs').argv;
const version = argv.v || '0.0.0-dev';
const pruneDev = argv.pruneDev !== undefined;
const removeSpecific = !!argv.remove;
const runSetup = argv.noSetup === undefined;
const runBuild = argv.noBuild === undefined;
const runCommit = argv.noCommit === undefined;
const runPush = argv.noPush === undefined;
const forcePush = !!argv.forcePush;
const runTeardown = argv.noTeardown === undefined;
const cleanOnFail = runTeardown && argv.noCleanOnFail === undefined;
const dryRun = !!argv.dryRun && argv.dryRun !== 'false';
const BASE_URL = '/lime-elements/';
if (argv.h !== undefined) {
shell.echo(`
usage: npm run docs:publish [-- [--v=<version>] [--remove=<pattern>] [--pruneDev]
[--noSetup] [--noBuild] [--noCommit] [--noPush]
[--noTeardown] [--dryRun] [--noCleanOnFail]
[--gitUser=<commit author name>]
[--gitEmail=<commit author email>]]
--v The version number for this release of the documentation.
Defaults to '0.0.0-dev'.
--dryRun Use dry-run mode. Do not push any changes.
--remove Removes all versions matching the given filename-pattern.
--pruneDev Alias for --remove=0.0.0-dev*
--noSetup Run no setup. Only use this if you have previously run the setup step
without running the teardown step afterward.
--noBuild Do not build the documentation.
--noCommit Do not commit any changes.
--noPush Do not push any commits.
--forcePush Force-push commit. Only for use by the automated publish run
when a new version has been released. Any less important
runs, like those publishing the docs for a pull request,
should NOT use this flag.
--noTeardown Run no cleanup at end of script. Implies --noCleanOnFail.
--noCleanOnFail Do not run cleanup if script fails. Unless --noTeardown is set,
cleanup will still be run if script is successful.
--authorName Commit author name. Will update the local git config if set.
Will use existing git config if omitted.
--authorEmail Commit author email address. Will update the local git
config if set. Will use existing git config if omitted.
`);
} else if (removeSpecific || pruneDev) {
let commitMessage;
if (runSetup) {
cloneDocsRepo();
}
if (pruneDev) {
remove('0.0.0-dev*');
commitMessage = 'chore(docs): prune dev-versions';
}
if (removeSpecific) {
remove(argv.remove);
commitMessage = `chore(docs): remove ${argv.remove}`;
}
if (commitMessage && runCommit) {
commit(commitMessage);
}
if (runPush) {
push();
}
if (runTeardown) {
teardown(true);
}
} else {
if (runSetup) {
cloneDocsRepo();
}
if (runBuild) {
build();
}
if (runSetup) {
pullAndRebase();
}
if (runBuild) {
copyBuildOutput();
}
if (runCommit) {
commit();
}
if (runPush) {
push();
}
if (runTeardown) {
teardown(true);
}
}
function cloneDocsRepo() {
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
if (
shell.exec(
'git clone --single-branch --branch gh-pages https://$GH_TOKEN@github.com/Lundalogik/lime-elements.git docsDist'
).code !== 0
) {
shell.echo('git clone failed!');
teardown();
shell.exit(1);
}
}
function pullAndRebase() {
shell.cd('docsDist');
if (shell.exec('git pull --rebase').code !== 0) {
shell.echo('git pull failed!');
shell.cd('..');
teardown();
shell.exit(1);
}
shell.cd('..');
}
function build() {
try {
let options = {
files: ['src/index.html'],
from: [
/<base href="\/">/g,
/="\/build/g,
/="\/style/g,
/="\/assets/g,
/\/kompendium.json/g,
],
to: [
`<base href="${BASE_URL}versions/${version}/">`,
`="${BASE_URL}versions/${version}/build`,
`="${BASE_URL}versions/${version}/style`,
`="${BASE_URL}versions/${version}/assets`,
`${BASE_URL}versions/${version}/kompendium.json`,
],
};
replace.sync(options);
options = {
files: ['stencil.config.docs.ts'],
from: /baseUrl: '\/'/g,
to: `baseUrl: '${BASE_URL}versions/${version}/'`,
};
replace.sync(options);
options = {
files: ['src/index.md'],
from: /<version\\>/g,
to: `${version}`,
};
replace.sync(options);
shell.exec('git diff --name-status');
} catch (error) {
shell.echo('Error occurred:', error);
teardown();
shell.exit(1);
}
if (shell.exec('npm install').code !== 0) {
shell.echo('npm install failed!');
teardown();
shell.exit(1);
}
if (shell.exec('npm run docs:build').code !== 0) {
shell.echo('docs:build failed!');
teardown();
shell.exit(1);
}
}
function copyBuildOutput() {
// Create `versions` folder if it doesn't already exist.
try {
shell.mkdir('docsDist/versions');
} catch (e) {
// If mkdir failed, it's almost certainly because the dir already exists.
// Just ignore the error.
}
shell.cd('docsDist/versions');
shell.echo('Removing old version folder if it already exists.');
shell.rm('-rf', version);
shell.cd('../..');
shell.echo('Copying icons to shared folder in docsDist.');
if (
shell.cp(
'-R',
`www${BASE_URL}versions/${version}/assets/icons/`,
'docsDist/icons/'
).code !== 0
) {
shell.echo('copying icons failed!');
teardown();
shell.exit(1);
}
shell.echo('Removing icons in new docs version.');
if (
shell.rm('-rf', `www${BASE_URL}versions/${version}/assets/icons`)
.code !== 0
) {
shell.echo('removing icons folder failed!');
teardown();
shell.exit(1);
}
shell.echo('Copying new docs version into docsDist/versions/');
if (
shell.cp(
'-R',
`www${BASE_URL}versions/${version}`,
'docsDist/versions/'
).code !== 0
) {
shell.echo('copying output failed!');
teardown();
shell.exit(1);
}
createIconSymlink();
if (
shell.cp('-R', 'www/kompendium.json', `docsDist/versions/${version}`)
.code !== 0
) {
shell.echo('copying kompendium.json failed!');
teardown();
shell.exit(1);
}
updateVersionList();
}
function createIconSymlink() {
const path = `docsDist/versions/${version}/assets/`;
shell.cd(path);
shell.echo('Creating icons-symlink.');
if (shell.ln('-sf', '../../../icons', 'icons').code !== 0) {
shell.echo('Creating icons-symlink failed!');
shell.cd('../../../..');
teardown();
shell.exit(1);
}
shell.cd('../../../..');
}
function remove(pattern) {
shell.cd('docsDist/versions');
shell.rm('-rf', pattern);
shell.cd('../..');
updateVersionList();
}
function updateVersionList() {
shell.cd('docsDist');
const files = fs
.readdirSync('versions')
.filter((file) => file !== 'latest');
fs.writeFileSync(
'versions.js',
`window.versions = ${JSON.stringify(files)};`
);
shell.cd('..');
// We need to sort the strings alphanumerically, which javascript doesn't
// do by default. So I found this neat solution at
// https://blog.praveen.science/natural-sorting-in-javascript/#solution
// /ads
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base',
});
files.sort(collator.compare);
const latestVersion = files.filter((file) => !file.startsWith('PR-')).pop();
shell.echo(`Creating "latest"-link pointing to: ${latestVersion}`);
createLatestSymlink(latestVersion);
}
function createLatestSymlink(folder) {
shell.cd('docsDist/versions');
// eslint-disable-next-line sonarjs/no-collapsible-if
if (shell.ln('-sf', `${folder}`, 'latest').code !== 0) {
if (
shell.rm('latest').code !== 0 ||
shell.ln('-sf', `${folder}`, 'latest').code !== 0
) {
shell.echo('Creating latest-symlink failed!');
shell.cd('../..');
teardown();
shell.exit(1);
}
}
shell.cd('../..');
}
function commit(message) {
message = message || `chore(docs): create docs ${version}`;
shell.cd('docsDist');
if (argv.authorName) {
shell.echo('setting git config user.name');
shell.exec(`git config --local user.name '${argv.authorName}'`);
}
if (argv.authorEmail) {
shell.echo('setting git config user.email');
shell.exec(`git config --local user.email '${argv.authorEmail}'`);
}
shell.exec('git add -A --ignore-errors');
if (shell.exec(`git commit -m "${message}"`).code !== 0) {
shell.echo('git commit failed!');
shell.cd('..');
teardown();
shell.exit(1);
}
shell.cd('..');
}
function push() {
shell.cd('docsDist');
if (forcePush) {
shell.echo('Using `git push --force`!');
}
if (dryRun) {
shell.exec('git log -1');
shell.echo('Dry-run, so skipping push.');
} else if (
shell.exec(
`git push ${
forcePush ? '--force' : ''
} https://$GH_TOKEN@github.com/Lundalogik/lime-elements.git HEAD:gh-pages`
).code !== 0
) {
shell.echo('git push failed!');
shell.cd('..');
teardown();
shell.exit(1);
}
shell.cd('..');
}
function teardown(finished) {
if (finished || cleanOnFail) {
shell.exec(
'git checkout src/index.html src/index.md stencil.config.docs.ts'
);
shell.echo('Removing docs repo clone in docsDist.');
shell.exec('rm -rf docsDist');
}
}
|
var videoDevices = [];
var videoStream = null;
var interval;
function qrcode_file_fallback() {
}
function run_qrcode_scanner(result_callback, camera_num) {
console.log('start qrcode scanner');
qrcode.callback = function(result) {
console.log('scan result [' + result + ']');
result_callback(result);
};
var video = document.getElementById('qr-video');
var canvas = document.getElementById('qr-canvas');
var context = canvas.getContext('2d');
$(canvas).hide();
$('#choose-camera').popover('dispose');
if(!navigator.mediaDevices) { // file input fallback
$('#qr-image-picker').val(null);
$('#qr-image-picker').change(function() {
var url = URL.createObjectURL(document.getElementById('qr-image-picker').files[0]);
var image = new Image();
image.src = url;
image.onload = function() {
$(canvas).show();
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
qrcode.decode();
} catch(error) {
//console.log(error);
}
};
});
return;
}
$('#qr-image-picker').hide();
$('#qr-video-container').show();
$('#choose-camera').show();
// stop previous stream if any
if(videoStream !== null) {
video.pause();
video.srcObject = null;
var tracks = videoStream.getTracks();
console.log(tracks);
for(var i = 0; i < tracks.length; i++) tracks[i].stop();
clearInterval(interval);
}
// update list of devices
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
videoDevices = [];
devices.forEach(function(device) {
if(device.kind == 'videoinput') {
console.log(device);
videoDevices.push(device);
}
});
if(videoDevices.length == 0) throw "No video device found";
var device = videoDevices[camera_num % videoDevices.length];
var constraints = {video: {width: 320, height: 240, deviceId: device.deviceId}};
return navigator.mediaDevices.getUserMedia(constraints);
})
.then(function(stream) {
videoStream = stream;
video.srcObject = stream;
video.play();
interval = setInterval(function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
context.drawImage(video, 0, 0);
try {
qrcode.decode();
} catch(error) {
//console.log(error);
}
}, 250)
}).catch(function(error) {
console.log('Video capture error: ', error);
console.log($('#choose-camera'));
$('#choose-camera').popover('dispose').popover({html: true, content: '<i style="color: var(--danger)" class="fas fa-times-circle"></i> Did you allow video recording?', placement: 'top'}).popover('show');
});
}
function stop_qrcode_scanner() {
console.log('stop qrcode scanner');
var video = document.getElementById('qr-video');
if(videoStream !== null) {
video.pause();
video.srcObject = null;
var tracks = videoStream.getTracks();
for(var i = 0; i < tracks.length; i++) tracks[i].stop();
clearInterval(interval);
}
}
|
// jdyview.html5,
// Copyright (c)2012 Rainer Schneider, Roggenburg.
// Distributed under Apache 2.0 license
// http://jdynameta.de
/*jslint browser: true, strict: false, plusplus: true */
/*global $, moment */
var JDY = JDY || {};
JDY.view = JDY.view || {};
JDY.view.createPrimeFacesMenu = function (allObjects, aMenuConfig) {
"use strict";
var menuUl = $("<ul>");
menuUl.attr("id", "primeID");
menuUl.append($("<li>").append($("<h3>").text("Repositories")));
$.each(allObjects, function (index, value) {
var curMenuLi = $("<li>").append($("<a>").text(value[aMenuConfig.attrName]));
menuUl.append(curMenuLi);
curMenuLi.click(function () {
if (aMenuConfig.callBack) {
aMenuConfig.callBack({lvl1: value, lvl2: null});
}
});
if (aMenuConfig.lvl2Assoc) {
value.assocVals("Classes").done(function (allSubValues) {
var subMenuUl = $("<ul>");
subMenuUl.appendTo(curMenuLi);
subMenuUl.append($("<li>").append($("<h4>").text("Classes")));
$.each(allSubValues, function (index, subValue) {
var curSubMenuLi = $("<li>").append($("<a>").text(subValue[aMenuConfig.lvl2AttrName]));
subMenuUl.append(curSubMenuLi);
curSubMenuLi.click(function (e) {
if (aMenuConfig.callBack) {
aMenuConfig.callBack({lvl1: value, lvl2: subValue});
}
e.stopPropagation();
});
});
});
}
});
return menuUl;
};
JDY.view.createInputComponentVisitor = function (anAttr) {
"use strict";
return {
handleBoolean: function (aType) {
var fieldElem = $('<input type="checkbox">');
return {
field: fieldElem,
validation : null,
getValue: function () {
var result = fieldElem.attr('checked');
result = (result && result.trim().length > 0) ? Boolean(result) : false;
return result;
},
setValue: function (aValue) {
if (aValue) {
fieldElem.attr("checked", true);
} else {
fieldElem.removeAttr("checked");
}
}
};
},
handleDecimal: function (aType) {
var fieldElem = $("<input>");
fieldElem.puiinputtext();
return {
field: fieldElem,
validation : {
min: aType.minValue,
max: aType.maxValue,
number: true,
required: (anAttr.isNotNull ? true : false)
},
getValue: function () {
var result = fieldElem.val();
result = (result && result.trim().length > 0) ? Number(result) : null;
return result;
},
setValue: function (aValue) {
fieldElem.val(aValue);
}
};
},
handleTimeStamp: function (aType) {
var fieldElem = $("<input>"),
result,
formatString;
if (aType.datePartUsed) {
if (aType.datePartUsed && aType.timePartUsed) {
formatString = "MM/DD/YYYY HH:mm";
} else {
formatString = "MM/DD/YYYY";
}
} else {
formatString = "HH:mm";
}
result = {
field: fieldElem,
getValue: function () {
var result = fieldElem.val();
result = (result && result.trim().length > 0) ? moment(result, formatString) : null;
return (result) ? result.toDate() : null;
},
setValue: function (aValue) {
var dateString = null;
if (aValue) {
dateString = moment(aValue).format(formatString);
}
fieldElem.val(dateString);
},
initElem: function () {
if (aType.datePartUsed && !aType.timePartUsed) {
fieldElem.datepicker({
showOn: "button",
buttonImage: "js/icons/calendar.gif",
buttonImageOnly: true,
dateFormat: "mm/dd/yy"
});
}
}
};
if (aType.datePartUsed && !aType.timePartUsed) {
result.validation = {
date: true,
required: (anAttr.isNotNull ? true : false)
};
} else {
result.validation = {
required: (anAttr.isNotNull ? true : false)
};
}
return result;
},
handleFloat: function (aType) {
var fieldElem = $("<input>");
fieldElem.puiinputtext();
return {
field: fieldElem,
validation : {
number: true,
required: (anAttr.isNotNull ? true : false)
},
getValue: function () {
var result = fieldElem.val();
result = (result && result.trim().length > 0) ? Number(result) : null;
return result;
},
setValue: function (aValue) {
fieldElem.val(aValue);
}
};
},
handleLong: function (aType) {
var fieldElem = $("<input>"),
i,
isSelect = false;
fieldElem.puiinputtext();
if ( aType.domainValues && aType.domainValues.length > 0){
isSelect = true;
fieldElem = $("<select>");
// empty object
fieldElem.append(new Option("-", null));
for (i = 0; i < aType.domainValues.length; i++) {
fieldElem.append(new Option(aType.domainValues[i].representation, aType.domainValues[i].dbValue));
}
}
return {
field: fieldElem,
validation : {
min: aType.minValue,
max: aType.maxValue,
number: true,
required: (anAttr.isNotNull ? true : false)
},
getValue: function () {
var result = fieldElem.val();
if (isSelect) {
result = (!result || result === "null") ? null : result;
}
result = (result && result.trim().length > 0) ? Number(result) : null;
return result;
},
setValue: function (aValue) {
fieldElem.val(aValue);
}
};
},
handleText: function (aType) {
var fieldElem = $("<input>"),
i,
isSelect = false;
fieldElem.puiinputtext();
if ( aType.domainValues && aType.domainValues.length > 0){
isSelect = true;
fieldElem = $("<select>");
// empty object
fieldElem.append(new Option("-", null));
for (i = 0; i < aType.domainValues.length; i++) {
fieldElem.append(new Option(aType.domainValues[i].representation, aType.domainValues[i].dbValue));
}
}
// $("<select>")
// attrSelect.append(new Option(curAttrInfo.getInternalName(), curAttrInfo.getInternalName()));
return {
field: fieldElem,
validation : {
minlength: 0,
maxlength: aType.length,
required: (anAttr.isNotNull ? true : false)
},
getValue: function () {
var result = fieldElem.val();
if (isSelect) {
result = (!result || result === "null") ? null : result;
}
return result;
},
setValue: function (aValue) {
fieldElem.val(aValue);
}
};
},
handleVarChar: function (aType) {
var fieldElem = $("<textarea>");
fieldElem.puiinputtext();
return {
field: fieldElem,
validation : {
minlength: 0,
maxlength: aType.length,
required: (anAttr.isNotNull ? true : false)
},
getValue: function () {
var result = fieldElem.val();
return result;
},
setValue: function (aValue) {
fieldElem.val(aValue);
}
};
},
handleBlob: function (aType) {
throw new JDY.base.JdyPersistentException("Blob Values not supported");
//return aAttrValue;
}
};
};
|
export class Misc {
getData() {
return "hello world!";
}
}
|
import Viewport from '../engine/Viewport.js';
import Vector from '../engine/Vector.js';
import Hexagon from '../hexagon/Hexagon.js';
import Crawler from '../hexagon/Crawler.js';
export default class Maze{
constructor() {
this.twoSquared = 1.41421356237;
this.diagonal = 10;
this.horizontal = this.diagonal * this.twoSquared;
this.hexColumns = 20;
this.hexIndices = 20;
this.spaceBetween = (2 * this.horizontal + 2 * this.diagonal)/2;
this.scale = this.spaceBetween;
this.offset = new Vector(0, this.diagonal);
this.viewport = new Viewport(Math.ceil(this.hexColumns*this.spaceBetween) + this.diagonal, Math.ceil(this.hexColumns*this.spaceBetween));
this.context = this.viewport.context;
this.completed = false;
this.hex = [];
this.crawl;
this.running;
}
init() {
this.twoSquared = 1.41421356237;
this.diagonal = 10;
this.horizontal = this.diagonal * this.twoSquared;
this.hexColumns = 20;
this.hexIndices = 20;
this.spaceBetween = (2 * this.horizontal + 2 * this.diagonal)/2;
this.scale = this.spaceBetween;
this.offset = new Vector(0, this.diagonal);
this.viewport.refetchCanvas();
this.context = this.viewport.context;
this.completed = false;
this.hex = [];
clearInterval(this.running);
this.completed = false;
this.hex = [];
this.viewport.clear();
for(let i = 0; i < 20; i++) {
for(let j = 0; j < 20; j++) {
this.hex.push(new Hexagon(j, i));
}
}
this.context.beginPath();
for(let i = 0; i < this.hex.length; i++) {
this.hex[i].render(this.offset, this.scale, this.diagonal, this.context, this.horizontal);
}
this.context.strokeStyle = "black";
this.context.stroke();
this.crawl = new Crawler(this.hex, this.hexIndices, this.hexColumns, this.context, this.offset, this.scale, this.diagonal, this.horizontal);
document.addEventListener("click", () => this.crawl.move());
this.running = setInterval( () => {
if(this.completed) clearInterval(this.running);
this.crawl.move();
}
, 30);
document.getElementById('button').addEventListener("click", () => {
this.restart();
});
}
restart() {
this.viewport.refetchCanvas();
this.completed = false;
this.hex = [];
this.completed = false;
this.hex = [];
this.viewport.clear();
for(let i = 0; i < 20; i++) {
for(let j = 0; j < 20; j++) {
this.hex.push(new Hexagon(j, i));
}
}
this.context.beginPath();
for(let i = 0; i < this.hex.length; i++) {
this.hex[i].render(this.offset, this.scale, this.diagonal, this.context, this.horizontal);
}
this.context.strokeStyle = "black";
this.context.stroke();
this.crawl = new Crawler(this.hex, this.hexIndices, this.hexColumns, this.context, this.offset, this.scale, this.diagonal, this.horizontal);
}
}
|
import { useEffect, Suspense, lazy } from 'react';
import { useDispatch } from 'react-redux';
import { getProductsAction } from '../../redux/products/productActions';
import Loader from '../Loader';
const ProductsList = lazy(() => import ('../productList/ProductListContainer'));
function Home() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getProductsAction())
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<Suspense fallback={<Loader />}>
<ProductsList />
</Suspense>
</div>
)
}
export default Home;
|
$(document).ready(function () {
var inviteList = [];
var src = $('#srcCross').attr('src');
CKEDITOR.replace('inviteMessage', {});
// Обработчик добавления полей для ввода нового пользователя
$('#addUser').click(function () {
$('#assignedUsers tr:last').after('<tr><td></td><td class="inputs"><input class="nameAssignedUser" type="text"></td><td class="inputs"><input class="emailAssignedUser" type="text"></td><td class="inputs"><div class="for-img"><img class="deleteAssignedUserBtn" src="' + src + '"/></div></td></tr>');
redrawRows();
});
// Обработчик удаления полей
$('.deleteAssignedUserBtn').live('click', function() {
$(this).parent().parent().parent().remove();
redrawRows();
});
// Обработчик для отображения контейнера приглашений
$('#showAltWayContainer').click(function () {
$('.alt-way-container').css('display', 'block');
$('.alt-way-container').css('top', '0');
$(this).hide();
redrawRows();
});
$('#sendInvites').click(function() {
prepareInviteList();
sendInviteList();
});
$('#message').keydown(function() {
var less = 2000 - $(this).val().length;
if (less < 0) {
$(this).val($(this).val().substring(0, 1999));
less = 0;
}
$('#lessSymbols').html('Осталось ' + less + ' символов');
});
// Перекрашивание строк таблицы и перерасчет нумерации строк
function redrawRows() {
var i = 1;
$.each($('#assignedUsers td:first-child'), function () {
$(this).html(i++);
if (i % 2 == 0) {
$(this).parent().addClass('bad');
} else {
$(this).parent().removeClass('bad');
}
});
}
// Подготовка/наполнение массива данными пользователей
function prepareInviteList() {
$.each($('#assignedUsers tr:not(:first)'), function (index) {
var name = $(this).find('.nameAssignedUser').val();
var email = $(this).find('.emailAssignedUser').val();
if (index == 0) {
inviteList = [{ name: name, email: email }];
} else {
inviteList.push({ name: name, email: email });
}
});
}
// Отправка инвайт листа на сервер
function sendInviteList() {
$.ajax({
type: "POST",
url: document.SendInvitesList,
data: {
inviteList: JSON.stringify(inviteList),
message: CKEDITOR.instances.inviteMessage.getData(),
subject: $('#subject').val()
},
dataType: "json",
traditional: true
});
}
});
|
import express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import next from 'next';
import path from 'path';
import { setupRoutes } from '../server/src/config';
const { parse } = require('url');
const mongoose = require('mongoose');
const mongo_uri = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@cluster0-qhkdj.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
mongoose.Promise = global.Promise;
mongoose.set('useFindAndModify', false);
mongoose.connect(mongo_uri, { useNewUrlParser: true }).then(
() => {
console.log('[success] : connected to the database ');
},
error => {
console.log('[failed] ' + error);
process.exit();
}
);
const server = express();
server.use(compression());
server.get('/favicon.ico', (req, res) => {
const STATIC_DIR = path.join(__dirname, 'static');
return res.status(200).sendFile(`${STATIC_DIR}/favicon.ico`);
});
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
setupRoutes(server);
const port = parseInt(process.env.CLIENT_PORT, 10) || 3000;
const dev = JSON.parse(process.env.ISDEVMODE);
const app = next({ dev });
const handle = app.getRequestHandler();
// const handle = routes.getRequestHandler(app);
const render = (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
};
app.prepare().then(() => {
// next server
server.use(render);
server.listen(port, err => {
if (err) throw err;
// eslint-disable-next-line no-console
console.log(`> Ready client on ${port} : ${process.env.DMPENV}`);
});
});
|
import { applyDiscount } from "./discounts/percentdiscount.js";
function updateTotal(e) {
const price = document.querySelector('#price');
const discount = document.querySelector('#discount');
const total = document.querySelector('#total');
total.value = applyDiscount(price.value, discount.value);
}
window.onload = function() {
document.querySelector('#price').addEventListener('input', updateTotal);
document.querySelector('#discount').addEventListener('input', updateTotal);
}
|
exports.instanceOf = function(value, constructorName) {
return Object.prototype.toString.apply(value) === '[object ' + constructorName + ']';
};
exports.elm = function(id) {
return document.getElementById(id);
};
exports.generateId = function(prefix) {
return prefix + Math.floor(Math.random() * 10000);
};
exports.isUndefined = function(value) {
return typeof value === 'undefined';
};
exports.isDefined = function(value) {
return !exports.isUndefined(value);
};
|
/**
* Created by mfaivremacon on 05/09/2015.
*/
// user online status monitoring
Tracker.autorun(function() {
try {
if(Meteor.userId()) {
UserStatus.startMonitor({
threshold: 30000,
interval: 1000,
idleOnBlur: true
});
}
else {
UserStatus.stopMonitor();
}
}
catch(err) {
// console.log(err); // Seems that if(UserStatus.isMonitoring) does not work so catching every error
}
});
Meteor.startup(function() {
Accounts.ui.config({
passwordSignupFields: "USERNAME_AND_EMAIL"
});
});
|
import { MoonIcon, SunIcon } from '@chakra-ui/icons'
import { Stack, Button, Center, IconButton, useColorMode } from '@chakra-ui/react'
export default function CustomPage() {
const { colorMode, toggleColorMode } = useColorMode();
return (
<Center h="100vh" maxW="1200px" mx="auto">
<Stack isInline>
<IconButton
icon={colorMode === 'light' ? <SunIcon /> : <MoonIcon /> }
variant="outline"
colorScheme="cyan"
aria-label="Color mode switcher"
onClick={toggleColorMode}
>Switch Mode</IconButton>
<Button variant="solid" colorScheme="green" >
Solid
</Button>
<Button variant="primary">
Primary Color
</Button>
<Button variant="secondary">
Secondary Color
</Button>
<Button variant="secondaryOutline">
Secondary Outline
</Button>
<Button variant="warning">
Warning Color
</Button>
</Stack>
</Center>
)
}
|
const express = require("express");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const router = express.Router();
const User = require("../db/user");
const uuidv4 = require("uuid/v4");
var dateFormat = require("dateformat");
require("dotenv").config();
router.get("/", (req, res) => {
res.json({
message: "😀"
});
});
router.post("/signup", async (req, res, next) => {
try {
let user = await User.getOneByEmail(req.body.email);
console.log("user", user);
if (user) {
return res
.status(422)
.json({ err: "User already exists in the database" });
}
const hash = await bcrypt.hash(req.body.password, 5);
user = {
id: uuidv4(),
username: req.body.username,
email: req.body.email,
password: hash,
created_date: dateFormat(new Date(), "yyyy-mm-dd")
};
const id = await User.create(user);
if (!id) {
throw new Error("Problem with creating user");
}
jwt.sign({ id }, process.env.TOKEN_SECRET, async (err, token) => {
if (err) {
return new Error("Problem with token");
}
const result = await User.setToken(user.id, token);
console.log(result);
if (!result) {
throw new Error("Impossible add token to user");
}
res.json({
id,
token,
username: user.username,
email: user.email,
message: "ok"
});
});
} catch (error) {
console.log(error);
}
});
function setUserIdCookie(req, res, id) {
const isSecure = req.app.get("env") != "development";
res.cookie("user_id", id, {
httpOnly: true,
secure: isSecure,
signed: true
});
}
router.post("/login", async (req, res, next) => {
try {
const user = await User.getOneByEmail(req.body.email);
if (!user) {
return res.status(422).json({ err: "User not found" });
}
const isCorrect = await bcrypt.compare(req.body.password, user.password);
if (!isCorrect) {
return res.status(422).json({ err: "Password isn't correct" });
}
jwt.sign({ id: user.id }, process.env.TOKEN_SECRET, async (err, token) => {
if (err) {
return new Error("Problem with token");
}
const result = await User.setToken(user.id, token);
console.log(result);
if (!result) {
throw new Error("Impossible add token to user");
}
res.json({
id: user.id,
token,
username: user.username,
email: user.email,
message: "ok"
});
});
} catch (error) {
next(error);
}
});
router.get("/logout", (req, res) => {
res.json({
message: "logged out"
});
});
module.exports = router;
|
import Prismic from 'prismic.io'
export const fetchWrapper = () => (dispatch) => {
dispatch({
type: 'FETCH_WRAPPER'
})
return Prismic.api('https://step-up.cdn.prismic.io/api').then((Api) => (
Api.form('everything')
.ref(Api.master())
.query(Prismic.Predicates.at('document.type', 'wrapper'))
.submit()
)).then((response) => (
response.results[0]
)).then((json) => {
dispatch(receiveWrapperSuccess(json))
}).catch((err) => {
dispatch(receiveWrapperFailure(err))
return Promise.reject(err)
})
}
const receiveWrapperFailure = (error) => (
{
type: 'RECEIVE_WRAPPER_FAILURE',
payload: {
error
}
}
)
const receiveWrapperSuccess = (data) => (
{
type: 'RECEIVE_WRAPPER_SUCCESS',
payload: {
data
}
}
)
|
//Page for " pour"
//
// alert('coucou');
for(let i = 0; i<10; i++){// (for 1- initialisation de la variable 2- test ou condition de fin de boucle 3- généralement incrémentation)
document.getElementById('p1').innerHTML += 'i contient la valeur ' + i + ' qui augmente de 1 à chaque passage, de la boucle.<br>';
}
// Pour faire un tableau
for (let i = 0; i < 18; i++) {// for (1- initialisation de la variable 2- test ou condition de sortie 3- incrémentation)
document.getElementById('tr1').innerHTML += '<tr><td>Passage n° ' + (i + 1) + ' de la boucle</td><td>i contient la valeur ' + i + ' qui est incrémenté à chaque passage de la boucle.</td></tr>';
}
// console.log(i);
//root = "racine"
//i = itérator = "curseur"
// for avec in, if et l'instruction break
// if(test) {
// blocdecodeinstruction
// }
for (let arreteToi = 0; arreteToi < 10; arreteToi++) {
if ( arreteToi == 569 ){
break; // "break" arrête toi c'est l'instruction
} // fin du if
document.getElementById('p2').innerHTML += 'arreteToi contient la valeur ' + arreteToi + 'à chaque passage de la boucle for.<br>';
}// fin du for
// for avec une instruction continue qui "saute"
for(let item = 0; item < 10; item ++){
if( item % 2 != 0){// le reste de la division n'est pas égal à 0 ( donc item est un chiffre impair)
continue; //passe à la suivante
} // fin du if
document.getElementById('p3').innerHTML += 'La variable item contient la valeur ' + item + ' à chaque passage de la boucle.<br>';
}// fin du for
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "09a606c8e54c9a355ceed3967b29bdbe",
"url": "/index.html"
},
{
"revision": "420364c407b01352dcf9",
"url": "/static/js/2.f3445bfa.chunk.js"
},
{
"revision": "e88a3e95b5364d46e95b35ae8c0dc27d",
"url": "/static/js/2.f3445bfa.chunk.js.LICENSE.txt"
},
{
"revision": "b72b65266e97e9b19227",
"url": "/static/js/main.683255ca.chunk.js"
},
{
"revision": "f4d2ac87a76b6331fd91",
"url": "/static/js/runtime-main.4234e0d5.js"
}
]);
|
import React, { useState } from 'react';
const AddPizza = () => {
const [valuesPizza, setValuesPizza] = useState({
name: '',
description: '',
image: '',
priceSmall: '',
priceLarge: '',
stock: true
});
const { name, description, image, priceSmall, priceLarge, stock } = valuesPizza;
return (
<>
<p className="h4 mb-5 text-uppercase text-center">Agregar Pizza</p>
<form className="col-6 offset-3 mt-3">
<div class="mb-3">
<label for="name" class="form-label">Nombre pizza</label>
<input
type="text"
class="form-control"
id="name"
aria-describedby="name"
value={name}
/>
</div>
<div className="mb-3">
<label for="description">Descripción</label>
<textarea
class="form-control"
placeholder="Ingresa descripción de la pizza, ingredientes"
id="description"
value={description}
></textarea>
</div>
<div class="mb-3">
<label for="image" class="form-label">URL Imagen</label>
<input
type="url"
class="form-control"
id="image"
value={image}
/>
</div>
<div className="row">
<div class="mb-3 col-6">
<label for="priceSmall" class="form-label">Precio CHICA</label>
<input
type="text"
class="form-control"
id="priceSmall"
value={priceSmall}
/>
</div>
<div class="mb-3 col-6">
<label for="priceLarge" class="form-label">Precio GRANDE</label>
<input
type="text"
class="form-control"
id="priceLarge"
value={priceLarge}
/>
</div>
</div>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
value=""
id="stock"
checked={stock}
/>
<label class="form-check-label" for="stock">
Producto en stock?
</label>
</div>
<button type="submit" class="btn btn-warning mt-3">Agregar pizza</button>
</form>
</>
);
}
export default AddPizza;
|
//Imágenes a 240 * 240
$(document).ready(function () {
/*
Eleccion random para decidir si hay evento a la entrada de una pantalla o no
*/
$(".opcion2_2_jugador").click(numRandom);
$(".opcion1_1_jugador").click(numRandom);
function numRandom() {
$("#contenedor_texto").css("display", "none");
$(".texto_contenedor").text("");
$("#respuestas").text("");
var numero = Math.floor(Math.random() * 10);
if (numero%2==0) {
generaEvento();
}
}
/*
Si ha salido que se genera evento elegimos QUE evento se genera de forma aleatoria
de un numero predefinido
*/
function generaEvento() {
//var numero = Math.floor(Math.random() * 10);
let numero =1;
switch (numero) {
case 1:
eventoPregunta();
break;
default:
break;
}
}
/*
En este caso es el evento de la pregunta recogemos las preguntas de un JSON y mediante
un random (de nuevo) elegimos cual mostrar.
*/
function eventoPregunta() {
var numero = Math.floor(Math.random() * 3);
$.ajax({
url: "php/metodos.php",
type: "POST",
data: {numero:numero+1},
dataType: "JSON",
success: function (jsonStr) {
muestrame(jsonStr);
}
});
}
function muestrame(pregunta) {
$("#contenedor_texto").css("display", "block");
$(".texto_contenedor").text(pregunta[0]);
let index = 1;
pregunta[1].split(",").forEach(element => {
var boton =$("<button>").text(element);
boton.attr("id", index);
boton.attr("class", "botonRespuesta");
var salto =$("<br>");
$("#respuestas").append(boton);
$("#respuestas").append(salto);
index ++;
});
var respuesta =$("<p>").text(pregunta[2]);
respuesta.attr("id", "acertada");
respuesta.css("display", "none");
$("#respuestas").append(respuesta);
escuchaRespuesta();
}
function escuchaRespuesta() {
var respuestas = document.getElementsByClassName("botonRespuesta");
for (let i = 0; i < respuestas.length; i++) {
respuestas[i].addEventListener("click", eventoRespuesta, false);
}
}
function eventoRespuesta(e) {
let respuesta = $(e.currentTarget).text();
let acertada = $("#acertada").text();
if (respuesta == acertada) {
alert("Has acertado");
//mostrarBotones
//cambioPantalla();
}else{
alert("Has fallado");
}
}
/*Función que muestra los botones una vez que se ha completado el evento (respondido a la pregunta, etc.)
*Debe llamarse ANTES de mostrar la pantalla
*/
function mostrarBotones(){
//cambioPantalla();
}
/*Función que cambia la pantalla cuando se muestran los botones para elegir nuevo destino
*Se le llama después de que el usuario haya pulsado uno de los botones mostrados con mostrarBotones()
*Recibe por argumentos un ID del botón que hemos pulsado, que nos sirve para saber qué imagen debemos mostrar a continuación
*/
function cambioPantalla(id){
$("#imagen_fondo1").fadeOut(200, function(){
$("#imagen_fondo2").show();
$(".texto_contenedor").text("VAYA QUE SITIO ES ESTE");
});
}
})
|
"use strict";
/* eslint no-console: "off" */
const sass = require("node-sass");
const fs = require("fs");
const CONSTANTS = require("../package.json").constants;
sass.render({
file: `${CONSTANTS.dirBase.input}/${CONSTANTS.css.input}.scss`,
outputStyle: "expanded"
}, (err, result) => {
if (err) {
console.log(err);
} else {
fs.writeFile(
`${CONSTANTS.dirBase.output}/${CONSTANTS.css.output}.css`,
result.css,
err => {
if (err) {
console.log(err);
} else {
console.log("CSS complete");
}
}
);
}
});
|
/**
* @name AssignProjectToTeamForm
* @author Matthew Darby (CSI 43C9 Spring 2020)
* @overview Form to assign a project to an existing team
* @example <AssignProjectToTeamForm />
*/
import React from "react"
import gql from "graphql-tag"
import { useForm } from "react-hook-form"
import { useQuery, useMutation } from "@apollo/react-hooks"
import FormTitle from "components/titles/formTitle"
import { GenerateOptions } from "utils/componentGeneration"
import Button from "components/btn"
// GQL query to retreive all programs and courses
const GET_DATA = gql`
query {
projects {
id
name
}
teams {
id
name
}
}
`
// GQL mutation to assign a project to a team
const ASSIGN_PROJECT_TO_TEAM = gql`
mutation AssignProjectToTeam($id: ID!, $team: ID!) {
updateProject(input: { where: { id: $id }, data: { team: $team } }) {
project {
name
id
team {
name
id
}
}
}
}
`
export default ({ id }) => {
// Various states for our query
const { loading, error, data } = useQuery(GET_DATA)
// Various states for our mutation
const [
AssignProjectToTeam,
{ loading: mutationLoading, error: mutationError },
] = useMutation(ASSIGN_PROJECT_TO_TEAM)
// Various states for our form
const { handleSubmit, register, errors } = useForm()
// On form submit, we push values from our form to our GQL mutation
const onSubmit = values => {
AssignProjectToTeam({
variables: {
teamID: values.teamName,
projectID: id,
},
})
}
return (
<>
<FormTitle title={"Assign A Project To A Team"} />
<form
onSubmit={handleSubmit(onSubmit)}
name="Assign a Project To a Team Form"
>
<br />
{loading && <tr>Loading...</tr>}
{error && <tr>Error: ${error.message}</tr>}
{data && (
<>
<label htmlFor="team">Team</label>
<br />
<select
name="teamName"
ref={register({
required: "This field is required",
})}
>
<option disabled selected value="">
Select A Team
</option>
{GenerateOptions(data.teams, "id", "name")}
</select>
{errors.name && <p>{errors.name.message}</p>}
<br />
</>
)}
<br />
<hr />
<Button small border textColor="primary-green" type={"submit"}>
Add
</Button>
{mutationLoading && <p>Loading...</p>}
{mutationError && <p>Error submitting form. Please try again.</p>}
</form>
</>
)
}
|
module.exports = {
siteMetadata: {
title: `Pastry Academy by Amaury Guichon`,
description: `Start your new sweet career. Enroll now and join the next class at Pastry Academy by Amaury Guichon.`,
author: `Pastry Academy by Amaury Guichon`
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`
}
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `The pastry academy`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/favicon.png` // This path is relative to the root of the site.
}
},
{
resolve: `gatsby-plugin-google-analytics`,
options: {
// replace "UA-XXXXXXXXX-X" with your own Tracking ID
trackingId: "UA-138054696-1",
head: false
}
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.app/offline
"gatsby-plugin-offline",
`gatsby-plugin-sass`,
{
resolve: `gatsby-plugin-favicon`,
options: {
logo: "./src/favicon.png",
// WebApp Manifest Configuration
appName: null, // Inferred with your package.json
appDescription: null,
developerName: null,
developerURL: null,
dir: "auto",
lang: "en-US",
background: "#fff",
theme_color: "#A29680",
display: "standalone",
orientation: "any",
start_url: "/?homescreen=1",
version: "1.0",
icons: {
android: true,
appleIcon: true,
appleStartup: true,
coast: false,
favicons: true,
firefox: true,
yandex: false,
windows: false
}
}
},
{
resolve: "gatsby-source-wordpress",
options: {
/*
* The base URL of the Wordpress site without the trailingslash and the protocol. This is required.
* Example : 'gatsbyjsexamplewordpress.wordpress.com' or 'www.example-site.com'
*/
baseUrl: "playground.purpleandbold.net",
// The protocol. This can be http or https.
protocol: "https",
// Indicates whether the site is hosted on wordpress.com.
// If false, then the assumption is made that the site is self hosted.
// If true, then the plugin will source its content on wordpress.com using the JSON REST API V2.
// If your site is hosted on wordpress.org, then set this to false.
hostingWPCOM: false,
// If useACF is true, then the source plugin will try to import the Wordpress ACF Plugin contents.
// This feature is untested for sites hosted on wordpress.com.
// Defaults to true.
useACF: true,
// Include specific ACF Option Pages that have a set post ID
// Regardless if an ID is set, the default options route will still be retrieved
// Must be using V3 of ACF to REST to include these routes
// Example: `["option_page_1", "option_page_2"]` will include the proper ACF option
// routes with the ID option_page_1 and option_page_2
// The IDs provided to this array should correspond to the `post_id` value when defining your
// options page using the provided `acf_add_options_page` method, in your WordPress setup
// Dashes in IDs will be converted to underscores for use in GraphQL
acfOptionPageIds: [],
// Set verboseOutput to true to display a verbose output on `npm run develop` or `npm run build`
// It can help you debug specific API Endpoints problems.
verboseOutput: false,
// Set how many pages are retrieved per API request.
perPage: 100,
// Search and Replace Urls across WordPress content.
// Set how many simultaneous requests are sent at once.
concurrentRequests: 10,
// Set WP REST API routes whitelists
// and blacklists using glob patterns.
// Defaults to whitelist the routes shown
// in the example below.
// See: https://github.com/isaacs/minimatch
// Example: `["/*/*/comments", "/yoast/**"]`
// ` will either include or exclude routes ending in `comments` and
// all routes that begin with `yoast` from fetch.
// Whitelisted routes using glob patterns
includedRoutes: [
"**/posts",
"**/pages",
"**/media",
"**/faq",
"**/course_week"
],
// Blacklisted routes using glob patterns
excludedRoutes: [],
// use a custom normalizer which is applied after the built-in ones.
normalizer: function({ entities }) {
return entities;
}
}
},
{
resolve: `gatsby-source-instagram`,
options: {
username: `amauryguichon`
}
}
// {
// resolve: 'gatsby-plugin-snipcart',
// options: {
// apiKey: 'Njg3ZGJmY2EtYTM1OC00Nzc4LTk4NmUtMDFhMjQxMmY4ZWQwNjM2ODg4MTc4Nzk4NzMxMzAy'
// }
// }
]
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import HeroesApp from './HeroesApp';
ReactDOM.render(
<HeroesApp />,
document.getElementById('root')
);
// Borrar todos los archivos de src excepto index.js
// Quitar contenido de este archivo y dejar solo HeroesApp
// Instalar bootstrap en index.html
// Crear carpeta public/assets y copiar en ella las imagenes de heroes desde el zip
// Crear toda la estructura de directorios y componentes (rafce) con los archivos:
// components
// dc
// DcScreen
// marvel
// MarvelScreen
// heroes
// HeroesScreen
// login
// LoginScreen
// ui
// NavBar (copiar codigo para no perder tiempo)
// No olvidar poner un H1 con el nombre del componente para saber que se esta presentando y no perder tiempo
// Crear la carpeta routers y dentro AppRouter que por convencion es el principal
// Revisar https://reactrouter.com/web/guides/quick-start
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
import ReactDOM from "react-dom";
import "./styles.css";
import RandomQuoteMachine from "./App";
ReactDOM.render(<RandomQuoteMachine />, document.getElementById("root"));
|
import DirectionGesture from "./DirectionGesture"
import RotatableImage from "./RotatableImage"
import RotatableView from "./RotatableView"
export {
RotatableImage,
RotatableView,
DirectionGesture,
}
|
import { useState,useContext } from "react";
import Header from "./ChatComp/Header"
import SideBar from "./ChatComp/SideBar";
import Chat from "./ChatComp/Chat";
import "./ChatPage.css"
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import VideoCall from "./ChatComp/VideoCall";
import AudioCall from "./ChatComp/AudioCall";
import {SocketContext} from "../../VideoContext/Context";
function ChatPage() {
const {calling,callEnded,audioCalling} = useContext(SocketContext)
const [roomId, setRoomId] = useState(null);
return (
<>
{!callEnded && audioCalling ? <AudioCall roomId={roomId} />:!callEnded && calling ? <VideoCall roomId={roomId} />
:(<div className="main">
<div className="andar">
<Header />
<div className="components">
<Router>
<SideBar/>
<Switch>
<Route path="/chat/rooms/:roomId" render={(props) => <Chat {...props} setRoomId={setRoomId} />} />
</Switch>
</Router>
</div>
</div>
</div>)}
</>
);
}
export default ChatPage;
|
// Put all your JavaScript in this file!
function color()
{
var enter_color=prompt("enter a color");
document.getElementByTagName("body").style.background-color=enter_color;
}
|
/* global Promise */
import InfiniteList from '../../../src/redux/infinite-list';
const module = InfiniteList('test-key');
let initialState;
describe('Infinite List redux module', () => {
beforeEach(() => {
initialState = module.reducer(undefined, {}); // eslint-disable-line no-undefined
});
describe('reducer', () => {
test('module contains a reducer', () => {
expect(typeof module.reducer).toBe('function');
});
test('initial state', () => {
expect(initialState).toMatchObject({
loading: true,
error: null,
items: [],
moreToLoad: false
});
});
describe('LOADING', () => {
let action;
beforeEach(() => {
action = module.actions.loading();
initialState.loading = false;
initialState.items = [1, 2, 3];
initialState.error = new Error();
});
test('sets the loading state', () => {
const newState = module.reducer(initialState, action);
expect(newState.loading).toBe(true);
});
test('maintains any existing data', () => {
const newState = module.reducer(initialState, action);
expect(newState.items).toBe(initialState.items);
});
test('clears any existing error', () => {
const newState = module.reducer(initialState, action);
expect(newState.error).toBe(null);
});
});
describe('APPEND', () => {
let action;
beforeEach(() => {
action = module.actions.append([4, 5, 6], true);
});
test('appends the new items', () => {
initialState.items = [1, 2, 3];
const newState = module.reducer(initialState, action);
expect(newState.items).toEqual([1, 2, 3, 4, 5, 6]);
});
test('sets the moreToLoad state', () => {
initialState.moreToLoad = false;
const newState = module.reducer(initialState, action);
expect(newState.moreToLoad).toEqual(true);
});
test('clears any existing error and loading state', () => {
initialState.error = new Error();
initialState.loading = true;
const newState = module.reducer(initialState, action);
expect(newState.error).toBe(null);
expect(newState.error).toBe(null);
});
});
describe('REPLACE', () => {
let action;
beforeEach(() => {
action = module.actions.replace(2, 55);
});
test('replaces the given index with the new item', () => {
initialState.items = [8, 9, 10, 11];
const newState = module.reducer(initialState, action);
expect(newState.items).toEqual([8, 9, 55, 11]);
});
});
describe('REMOVE', () => {
let action;
beforeEach(() => {
action = module.actions.remove(2);
});
test('removes the given index', () => {
initialState.items = [8, 9, 10, 11];
const newState = module.reducer(initialState, action);
expect(newState.items).toEqual([8, 9, 11]);
});
});
describe('CREATE', () => {
let action;
beforeEach(() => {
action = module.actions.create(7);
});
test('prepends the given item', () => {
initialState.items = [8, 9, 10, 11];
const newState = module.reducer(initialState, action);
expect(newState.items).toEqual([7, 8, 9, 10, 11]);
});
});
describe('ERROR', () => {
let action;
let error = new Error();
beforeEach(() => {
action = module.actions.error(error);
});
test('sets the error state', () => {
const newState = module.reducer(initialState, action);
expect(newState.error).toBe(error);
});
test('resets loading to false', () => {
initialState.loading = true;
const newState = module.reducer(initialState, action);
expect(newState.loading).toBe(false);
});
test('maintains any existing data', () => {
initialState.items = [1, 2, 3];
const newState = module.reducer(initialState, action);
expect(newState.items).toEqual([1, 2, 3]);
});
});
});
describe('action creators', () => {
test('module contains actions creators', () => {
// The actual action creators are tested above in the reducer tests
for (let key in module.actions) {
expect(typeof module.actions[key]).toBe('function');
}
});
describe('loadMore', () => {
test('returns a thunk function, rather than a standard action object', () => {
expect(typeof module.actions.loadMore()).toBe('function');
});
test('calls loading and the fetcher', () => {
let dispatch = jest.fn();
let fetcher = jest.fn(() => new Promise(() => { })); // that never resolves
module.actions.loadMore(fetcher)(dispatch);
expect(dispatch).toHaveBeenCalledWith(module.actions.loading());
expect(fetcher).toHaveBeenCalled();
});
test('calls append with resolved result from fetcher', async () => {
let dispatch = jest.fn();
let fetcher = jest.fn(() => Promise.resolve({items: ['a', 'b'], moreToLoad: false}));
await module.actions.loadMore(fetcher)(dispatch);
expect(dispatch.mock.calls[1][0]) // the second call to dispatch, after LOADING
.toEqual(module.actions.append(['a', 'b'], false));
});
test('calls error with rejecting promise from fetcher', async () => {
let error = new Error();
let dispatch = jest.fn();
let fetcher = jest.fn(() => Promise.reject(error));
await module.actions.loadMore(fetcher)(dispatch);
expect(dispatch.mock.calls[1][0]) // the second call to dispatch, after LOADING
.toEqual(module.actions.error(error));
});
});
});
describe('selector', () => {
test('will return the slice of state defined by the key', () => {
const state = {
[module.key]: module.reducer(undefined, {}) // eslint-disable-line no-undefined
};
expect(module.selector(state)).toBe(initialState);
});
});
});
|
function calcular() {
const mtf1 = document.getElementById('mtf1').value
const mtf2 = document.getElementById('mtf2').value
const aviso = document.getElementById('aviso')
const resultado = document.getElementById('resultado')
const somaMedia = Number(mtf1.replace(',', '.')) + (Number(mtf2.replace(',', '.')) * 2);
const calculoDosPesos = Number(28.75 - Number(somaMedia)) / 2;
const media3 = String(calculoDosPesos.toFixed(2))
const mediaFinal = String(media3.replace('.', ','));
if (mtf1 == 0 || mtf2 == 0 || (mtf1 == 0 && mtf2 == 0)) {
aviso.innerText = 'Por favor, preencha todos os campos!'
aviso.style.color = 'white'
aviso.style.fontWeight = '500'
resultado.innerText = ``;
} else {
if (calculoDosPesos >= 10) {
aviso.innerText = 'Você ficou na recuperação final!';
aviso.style.color = '#ff3636'
aviso.style.fontWeight = '500'
aviso.style.paddingBottom = '12px'
resultado.innerText = `Para dicas de estudo, deslize a tela.`;
} else {
aviso.style.color = 'white'
aviso.style.fontWeight = '500'
aviso.innerText = 'A nota miníma (com arredondamento) que você precisa tirar para passar é:';
resultado.innerText = `${mediaFinal}`;
resultado.style.fontSize = '36px'
resultado.style.paddingTop = '12px'
}
}
// alert('VALOR BRO: ' + mediaFinal)
}
|
const Controller = require('../../../base/baseController');
class UserRoleService extends Controller {
/**
* 保存角色权限
* @param {json} body
*/
async save(body) {
let user_id = body.id;
let delSQL = "delete from auth_user_role where user_id=?";
let delParams = [user_id];
await this.authorityDB.query(delSQL, delParams);
if (body.roles) {
let roles = body.roles.split(',');
for (var i = 0; i < roles.length; i++) {
let saveBody = {
role_id: roles[i],
user_id: user_id,
create_user_id: this.user.id,
create_time: this.authorityDB.literals.now
};
await this.authorityDB.insert("auth_user_role", saveBody);
}
}
return this.st.success('保存成功', null);
}
/**
* 删除用户角色权限数据,删除用户的时候,会同时调用该方法删除用户的角色数据
* @param {*} userId
*/
async del(userId, conn) {
let sql = "delete from auth_user_role where user_id=?";
let params = [userId];
let connect = conn ? conn : this.authorityDB;
await connect.query(sql, params);
}
}
module.exports = UserRoleService;
|
$(function(){
$('#nuevo-rol').on('click',function(){
$('#formulario')[0].reset();
$('#pro').val('Registro');
$('#edi').hide();
$('#reg').show();
$('#registra-rol').modal({
show:true,
backdrop:'static'
});
});
});
function agregaRegistroRol(){
var url = 'agrega_rol.php';
$.ajax({
type:'POST',
url:url,
data:$('#formulario').serialize(),
success: function(registro){
if ($('#pro').val() == 'Registro'){
$('#formulario')[0].reset();
$('#mensaje').addClass('bien').html('Registro completado con exito').show(200).delay(2500).hide(200);
$('#agrega-registros').html(registro);
window.location="roles.php";
return false;
}else{
$('#mensaje').addClass('bien').html('Edicion completada con exito').show(200).delay(2500).hide(200);
$('#agrega-registros').html(registro);
window.location="roles.php";
return false;
}
}
});
return false;
}
function eliminarRol(id){
var url = 'elimina_rol.php';
var pregunta = confirm('¿Esta seguro de eliminar este rol?');
if(pregunta==true){
$.ajax({
type:'POST',
url:url,
data:'id='+id,
success: function(registro){
$('#agrega-registros').html(registro);
window.location="roles.php";
return false;
}
});
return false;
}else{
return false;
}
}
function editarRol(id){
$('#formulario')[0].reset();
var url = 'edita_rol.php';
$.ajax({
type:'POST',
url:url,
data:'id='+id,
success: function(valores){
var datos = eval(valores);
$('#reg').hide();
$('#edi').show();
$('#pro').val('Edicion');
$('#id-prod').val(id);
$('#nom_rol').val(datos[0]);
$('#responsabilidades').val(datos[1]);
$('#registra-rol').modal({
show:true,
backdrop:'static'
});
return false;
}
});
return false;
}
$(document).ready(function(){
var show = 1;
$('.show').on('click', function(){
if(show == 1){
$('.content-menu').addClass("content-menu2");
show = 0;
}else{
$('.content-menu').removeClass("content-menu2");
show = 1;
}
})
})
|
import {clone, orderBy} from 'lodash'
function ScheduleController ($filter, $state, $location, $scope, FormData, Participant, CurrentProject, RoleCategory) {
'ngInject'
// Temp fix for refresh on schedule detail page
if (!$state.params.fromState && $location.url() === '/schedule/reviewDetail') {
$state.go('base.reviewSchedule.list')
}
if (!$state.params.fromState && $location.url() === '/schedule/updateDetail') {
$state.go('base.updateSchedule.list')
}
let vm = this
vm.currentProject = CurrentProject.getCurrentProject()
vm.participantList = orderBy(Participant._items, ['category'], ['desc']).filter((participant) => {
return participant.is_team_leader === true
})
// schedule logic related
vm.category = clone(RoleCategory.scheduleCategory)
vm.category.unshift({name: '所有安排'})
vm.toggleUpdate = false
vm.selectedCategory = vm.category[0]
vm.selectedDate = $state.params.selectedDate
vm.fromState = $state.params.fromState
vm.readOnly = $state.$current.data.readOnly || $state.params.readOnly
if ($state.params.fromState) {
_getScheduleInfo()
}
vm.saveSchedule = function () {
if (!vm.toggleUpdate) {
vm.toggleUpdate = true
return
}
vm.scheduleInfo.date = $filter('date')(vm.selectedDate, 'yyyy-MM-dd')
vm.scheduleInfo.category = vm.selectedCategory.id
if (vm.scheduleInfo._id) {
FormData.PROJECT_SCHEDULE.put({project_status: vm.currentProject.status, project_id: vm.currentProject._id, id: vm.scheduleInfo._id}, vm.scheduleInfo).$promise
.then(() => {
vm.toggleUpdate = false
})
} else {
FormData.PROJECT_SCHEDULE.save({project_status: vm.currentProject.status, project_id: vm.currentProject._id}, vm.scheduleInfo).$promise
.then(function (data) {
vm.scheduleInfo = data
vm.toggleUpdate = false
})
}
}
$scope.$watch('vm.selectedDate', function (newValue) {
if (newValue) {
var toState = $state.current.name.split('.')
toState[2] = 'detail'
$state.go(toState.join('.'), {
selectedDate: newValue,
readOnly: vm.readOnly,
fromState: (vm.fromState || $state.current.name)
})
}
})
vm.selectCategory = function (selectedCategory) {
vm.selectedCategory = selectedCategory
_getScheduleInfo()
}
function _getScheduleInfo () {
FormData.PROJECT_SCHEDULE.get({
project_id: vm.currentProject._id,
project_status: vm.currentProject.status,
where: Object.assign({}, {category: vm.selectedCategory.id, date: $filter('date')(vm.selectedDate, 'yyyy-MM-dd')})
}).$promise
.then(function (data) {
if (vm.selectedCategory.id) {
if (data._items.length > 0) {
vm.scheduleInfo = data._items[0]
} else {
vm.scheduleInfo = Object.assign({}, {project_id: vm.currentProject._id}, {date: vm.selectedDate}, {category: vm.selectedCategory.id})
}
} else {
_parseScheduleInfoList(data._items)
}
})
.catch(function (fallback) {
})
}
function _parseScheduleInfoList (scheduleInfoList) {
vm.allScheduleInfo = []
vm.category.forEach(function (item) {
if (item.id) {
let scheduleInfo = {
name: item.name
}
scheduleInfoList.forEach(function (schedule) {
if (item.id === schedule.category) {
scheduleInfo.content = schedule.content
}
})
scheduleInfo.content = scheduleInfo.content ? scheduleInfo.content : '暂无'
vm.allScheduleInfo.push(scheduleInfo)
}
})
}
}
ScheduleController.resolver = function (FormData, CurrentProject) {
'ngInject'
const currentProject = CurrentProject.getCurrentProject()
return FormData.PROJECT_PARTICIPANT.get({project_status: currentProject.status, project_id: currentProject._id}).$promise
}
export default ScheduleController
|
import React, { Component } from "react";
import { Link } from "react-router-dom";
import reddit from "./reddit.png";
import facebook from "./facebook.png";
class Footer extends Component {
render() {
return (
<footer className="footer-wrapper">
<div className="footer">
<nav className="footer_navigation">
<div className="footer_spacer" />
<div className="footer_navigation-items">
<ul>
<h2>About</h2>
<li>
<Link to="/about">
<h3>Contact Us</h3>
</Link>
</li>
<li>
<Link to="/about">
<h3>FAQ</h3>
</Link>
</li>
</ul>
</div>
<div className="footer_spacer_769" />
<div className="footer_social-links">
<ul>
<li>
<a
className="img-responsive"
href="https://www.facebook.com/groups/ToyotaMiraiQA/"
rel="noopener"
>
<img src={facebook} alt="" />
</a>
</li>
<li>
<a
className="img-responsive"
href="https://www.reddit.com/r/Mirai/"
rel="noopener"
>
<img src={reddit} alt="" />
</a>
</li>
</ul>
</div>
<div className="footer_spacer" />
</nav>
<div className="main-wrapper">
<div className="content-wrapper65 text-centre">
<div className="breaker60" />
<p>
This website has been created as part of an assignment in an
approved course of study for Curtin University and contains
copyright material not created by the author. All copyright
material used remains copyright of the respective owners and has
been used here pursuant to Section 40 of the Copyright Act 1968
(Commonwealth of Australia). No part of this work may be
reproduced without consent of the original copyright owners. See
code comments for references.
</p>
<div className="breaker60" />
</div>
</div>
</div>
</footer>
);
}
}
export default Footer;
|
module.exports = (bh) => {
bh.match('header__notification', (ctx, json) => {
if (! json.text) {
return null;
}
ctx.tag('section');
ctx.content({
block: 'wrapper',
content: json.text
});
});
};
|
// ==== STYLES ==== //
var gulp = require( 'gulp' ),
$ = require( 'gulp-load-plugins' )({ camelize: true }),
plumber = require( 'gulp-plumber' ),
gcmq = require( 'gulp-group-css-media-queries' ),
config = require( '../../gulpconfig' ),
autoprefixer = require( 'autoprefixer' ),
del = require( 'del' ),
processors = [ autoprefixer( config.styles.autoprefixer ) ];
gulp.task( 'styles-cleanup', function() {
del.sync([ config.styles.dest + '*.css*' ], { force: true });
});
gulp.task( 'styles-cleanup-dist', function() {
del.sync([ config.styles.destDist + '*.css*' ], { force: true });
});
// Build stylesheets from source Sass files, autoprefix, and write source maps (for debugging) with libsass
gulp.task( 'styles', [ 'styles-cleanup' ], function() {
return gulp
.src( config.styles.src )
.pipe( plumber() )
.pipe( $.replace( '<!-- replace_url -->', '' ) )
.pipe( $.sourcemaps.init() )
.pipe( $.sass( config.styles.sass ) )
.pipe( gcmq() )
.pipe( $.postcss( processors ) )
.pipe( gulp.dest( config.styles.dest ) )
.pipe(
$.rename({
extname: '.min.css'
})
)
.pipe( $.cssnano( config.styles.minify ) )
.pipe( $.sourcemaps.write( './' ) ) // Writes an external sourcemap
.pipe( gulp.dest( config.styles.dest ) ); // Drops the unminified CSS file into the `build` folder
});
// Build stylesheets from source Sass files, autoprefix, and write source maps (for debugging) with libsass
gulp.task( 'styles-dist', [ 'styles-cleanup-dist' ], function() {
return gulp
.src( config.styles.src )
.pipe( plumber() )
.pipe( $.replace( '<!-- replace_url -->', config.urls.prod ) )
.pipe( $.sourcemaps.init() )
.pipe( $.sass( config.styles.sass ) )
.pipe( gcmq() )
.pipe( $.postcss( processors ) )
.pipe( gulp.dest( config.styles.destDist ) )
.pipe(
$.rename({
extname: '.min.css'
})
)
.pipe( $.cssnano( config.styles.minify ) )
.pipe( $.sourcemaps.write( './' ) ) // Writes an external sourcemap
.pipe( gulp.dest( config.styles.destDist ) ); // Drops the unminified CSS file into the `build` folder
});
|
window.onload = function(){
var body = new create_div( );
body.style( {"width":"100%", "height":"100%", "overflow":"hidden"} );
var canvas = new create_div( {'t':"canvas", 'p':body} );
canvas.style( {"width":"100%", "height":"100%"} );
var div = [];
div[0] = new create_div( {'p':body} );
div[0].style( {"width":"calc( 100% - 20px)", "height":"100px", "position":"absolute", "top":0, "left":0, "BColor":rgb(255,0,0), "overflow":"hidden", 'P':"10px"} );
div[0].transition( {"height":0.5} );
div[0].div.onclick = function() {
div[0].off = ( (isset(div.off))? div.off : 100 );
div[0].style( {"height":(div.off = ((div.off == 10)?100:10))+"px"} );
};
div[1] = new create_div( {'p':body} );
div[1].style( {"width":"10px", "height":"10px", "position":"absolute", "top":"100px", "left":"100px", "BColor":rgb(255,255,0)} );
if (!BABYLON.Engine.isSupported()) {
window.alert('Browser not supported');
} else {
// Babylon
var engine = new BABYLON.Engine(canvas.div, true);
//Create Rotation/Scaling scene
scene = CreateScene(engine, div);
scene.activeCamera.attachControl(canvas.div);
// Once the scene is loaded, just register a render loop to render it
engine.runRenderLoop(function () {
scene.render();
});
// Resize
window.addEventListener("resize", function () {
engine.resize();
});
}
};
|
import React, {Component, PropTypes} from 'react';
import Image from '../shared/Image.jsx';
import Classnames from 'classnames';
class Logo extends Component {
getRenderedClassNames() {
return Classnames([
'logo',
{crumb: this.props.crumb}
]);
}
render() {
const imgPath = `${window.config.staticRoot}/images/blazar-logo.png`;
return (
<div className={this.getRenderedClassNames()}>
<Image classNames="logo-image" src={imgPath} />
</div>
);
}
}
Logo.defaultProps = {
crumb: true
};
Logo.propTypes = {
crumb: PropTypes.bool
};
export default Logo;
|
const Data = require('../../Data.js');
const WhiteSpace = require('../GameElements/FreeSpace.js');
const BoardPosition= require('../BoardPosition.js');
const imageNames=require("../../imageNames.js");
class EventsManager{
constructor(gameBoard,eventKeys,processingTime, powerCheckingTime,endGame){
this.endGame=endGame;
this.gameBoard=gameBoard;
this.eventsKeys=eventKeys;
//every player and enemy is represented like a dictionary {"id": object}
this.enemies={};
this.players={};
this.inUse=false;
this.eagleWasKilled=false;
this.enemiesQuantity=0;
/****** QUEUES ******/
this.activePowers=[]
this.eventsQueue=[];
/*** Queue time processing controller */
this.processingTime= processingTime;
this.queueInterval;
this.powersInterval;
this.powerCheckingTime= powerCheckingTime;
}
getEagleWasKilled(){
return this.eagleWasKilled;
}
getEnemies(){
return this.enemies;
}
insertInDict(dic,newObject,isPlayer){
if (!isPlayer){
newObject.id = Object.keys(dic).length.toString();
}
dic[newObject.id]=newObject;
}
getPlayers(){
return this.players;
}
setEnemiesQuantity(value){
this.enemiesQuantity+=value;
}
getEnemiesQuantity(){
return this.enemiesQuantity;
}
getElementsQuantity(dic){
return Object.keys(dic).length;
}
deleteFromDic(dic,id){
delete dic[id.toString()];
}
/**
* Delete powers thah have been used
*/
checkPowers(){
if (this.activePowers.length > 0){
var i;
for(i=0; i < this.activePowers.length; i++){
if (!this.activePowers[i].destroy()){
this.activePowers.splice(i,1);
}
}
}
}
calculateNextPosition(x,y,direction){
var mx = x;
var my = y;
if(direction == Data.left){
my = y - 1;
}
else if(direction == Data.right){
my = y + 1;
}
else if(direction == Data.up){
mx = x - 1;
}
else if(direction == Data.down){
mx = x + 1;
}
return [mx, my];
}
moveEnemiesTanks(event){
/*
if (event.object===undefined || !event.object.getIsEnable()){
return;
}
*/
if (event.object===undefined){
return;
}
event.object.setIsEnable(true);
var oldPosition=[event.object.x,event.object.y];
var nextPosition = this.calculateNextPosition(event.object.x, event.object.y,event.direction);
if(nextPosition[0] >= 0 && nextPosition[0] < this.gameBoard.getWidth() && nextPosition[1] >= 0 && nextPosition[1] < this.gameBoard.getHeight())
{
if(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameId === Data.free){
event.object.x = nextPosition[0];
event.object.y = nextPosition[1];
event.object.setCurrentImage(event.direction);
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.enemy,event.object,-1));
this.gameBoard.setPosition(oldPosition[0],oldPosition[1],new BoardPosition(
Data.free,
new WhiteSpace(imageNames.freeSpace),
-1));
}
else if(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameId === Data.power){
event.object.x = nextPosition[0];
event.object.y = nextPosition[1];
this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameElement.setTank(event.object);
event.object.setPower(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameElement);
event.object.setCurrentImage(event.direction);
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.enemy,event.object,-1));
this.gameBoard.setPosition(oldPosition[0],oldPosition[1],new BoardPosition(
Data.free,
new WhiteSpace(imageNames.freeSpace),
-1));
//aplicar el poder tomado
event.object.applyPower();
}
else if(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameId === Data.wall){
if(event.object.getCanCrossObstacles()){
var nPosition= this.calculateNextPosition(nextPosition[0],nextPosition[1],event.direction);
if (this.gameBoard.checkPosition(nPosition[0],nPosition[1])
&& this.gameBoard.getPosition(nPosition[0],nPosition[1]).gameId === Data.free)
{
event.object.x = nPosition[0];
event.object.y = nPosition[1];
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.enemy,event.object,-1));
this.gameBoard.setPosition(oldPosition[0],oldPosition[1],new BoardPosition(
Data.free,
new WhiteSpace(imageNames.freeSpace),
-1));
}
}
}
else{
event.object.setCurrentImage(event.direction);
event.object.x=oldPosition[0];
event.object.y= oldPosition[1];
}
}
}
movePlayersTank(event){
/*
if (event.object===undefined || !event.object.getIsEnable()){
return;
}
*/
if (event.object===undefined){
return;
}
var oldPosition=[event.object.x,event.object.y];
var nextPosition = this.calculateNextPosition(event.object.x, event.object.y,event.direction);
if(nextPosition[0] >= 0 && nextPosition[0] < this.gameBoard.getWidth() && nextPosition[1] >= 0 && nextPosition[1] < this.gameBoard.getHeight())
{
if(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameId === Data.free){
event.object.x = nextPosition[0];
event.object.y = nextPosition[1];
event.object.setCurrentImage(event.direction);
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.player,event.object,-1));
this.gameBoard.setPosition(oldPosition[0],oldPosition[1],new BoardPosition(
Data.free,
new WhiteSpace(imageNames.freeSpace),
-1));
}
else if(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameId === Data.power){
event.object.x = nextPosition[0];
event.object.y = nextPosition[1];
this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameElement.setTank(event.object);
event.object.setPower(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameElement);
event.object.setCurrentImage(event.direction);
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.player,event.object,-1));
this.gameBoard.setPosition(oldPosition[0],oldPosition[1],new BoardPosition(
Data.free,
new WhiteSpace(imageNames.freeSpace),
-1));
}
else if(this.gameBoard.getPosition(nextPosition[0],nextPosition[1]).gameId === Data.wall){
if(event.object.getCanCrossObstacles()){
var nPosition= this.calculateNextPosition(nextPosition[0],nextPosition[1],event.direction);
if (this.gameBoard.checkPosition(nPosition[0],nPosition[1])
&& this.gameBoard.getPosition(nPosition[0],nPosition[1]).gameId === Data.free)
{
event.object.x = nPosition[0];
event.object.y = nPosition[1];
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.player,event.object,-1));
this.gameBoard.setPosition(oldPosition[0],oldPosition[1],new BoardPosition(
Data.free,
new WhiteSpace(imageNames.freeSpace),
-1));
}
}
}
else{
event.object.setCurrentImage(event.direction);
event.object.x=oldPosition[0];
event.object.y= oldPosition[1];
}
}
event.object.setIsEnable(true);
}
checkImpact(event){
/*
if (event.object===undefined || !event.object.getIsEnable()){
return;
}
*/
if (event.object===undefined){
return;
}
if((event.object.x >= 0 && event.object.x < this.gameBoard.getWidth()) && (event.object.y >= 0 && event.object.y < this.gameBoard.getHeight()))
{
if(this.gameBoard.getPosition(event.object.x,event.object.y).gameId === Data.eagle){
event.object.setIsEnable(false);
if (event.object.type === Data.machineTank){
return;
}
this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.decreaseLife(event.object.damage);
if(this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.destroy()){
this.eagleWasKilled = true;
this.endGame=true;
this.gameBoard.setPosition(event.object.x,event.object.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1)
);
}
}
else if (this.gameBoard.getPosition(event.object.x,event.object.y).gameId === Data.wall){
event.object.setIsEnable(false);
if (event.object.type === Data.machineTank){
return;
}
this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.decreaseLife(event.object.damage);
if(this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.destroy()){
this.gameBoard.setPosition(event.object.x,event.object.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1)
);
}
}
else if (this.gameBoard.getPosition(event.object.x,event.object.y).gameId === Data.enemy){
event.object.setIsEnable(false);
if(event.object.type === Data.playerTank)
{
this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.decreaseLife(event.object.damage);
if(this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.destroy())
{
this.deleteFromDic(this.enemies,this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.id.toString());
this.setEnemiesQuantity(-1);
this.gameBoard.setPosition(event.object.x,event.object.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1));
}
}
}
else if(this.gameBoard.getPosition(event.object.x,event.object.y).gameId === Data.player){
event.object.setIsEnable(false);
if(event.object.type === Data.machineTank){
this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.decreaseLife(event.object.damage);
if(this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.destroy())
{
this.deleteFromDic(this.players,this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.id);
this.gameBoard.setPosition(event.object.x,event.object.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1));
}
}
}
else if (this.gameBoard.getPosition(event.object.x,event.object.y).gameId === Data.bullet){
this.gameBoard.getPosition(event.object.x,event.object.y).gameElement.setIsEnable(false);
event.object.setIsEnable(false);
this.gameBoard.setPosition(event.object.x,event.object.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1));
}
else if (this.gameBoard.getPosition(event.object.x,event.object.y).gameId === Data.power){
event.object.setIsEnable(false);
}
else{
this.gameBoard.setPosition(event.object.x,event.object.y,new BoardPosition(Data.bullet,event.object,-1));
}
}
else{
event.object.setIsEnable(false);
}
}
shoot(event){
if (event.object===undefined || !event.object.getIsEnable()){
return;
}
else
{
// var x =;
// var y=event.object.y;
this.gameBoard.setPosition(event.object.x,event.object.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1));
event.object.moveBullet();
this.checkImpact(event);
}
}
applyTankPower(event){
if (event.object===undefined || !event.object.getIsEnable()){
return;
}
else{
event.object.applyPower();
}
}
showBullet(event){
event.object.setIsEnable(true);
this.checkImpact(event);
}
showPower(event){
var insert=true;
while(insert){
var x = this.gameBoard.getRandomPosition(this.gameBoard.getWidth(),0);
var y = this.gameBoard.getRandomPosition(this.gameBoard.getHeight(),0);
if(this.gameBoard.getPosition(x,y).gameId === Data.free){
event.object.x=x;
event.object.y=y;
this.gameBoard.setPosition(x,y,new BoardPosition(Data.power,event.object,-1));
insert=false;
}
}
}
showTank(event){
var iW;
var fW;
if(event.object.playerId!=-1){
iW=0;
fW=(Math.round(this.gameBoard.getWidth()/2));
this.gameBoard.setNewTank(event.object,iW,fW);
}
else{
iW=(Math.round(this.gameBoard.getWidth()/2));;
fW=this.gameBoard.getWidth();
this.gameBoard.setNewTank(event.object,iW,fW);
}
}
proccessEvents(){
var event = this.eventsQueue.shift();
if (event===undefined){
return;
}
if (this.inUse===false){
this.inUse=true;
if(event.getType()===0){
this.showTank(event);
}
else if (event.getType()===1){
this.showBullet(event);
}
else if (event.getType()===2){
/** generar poder, appear tank */
this.showPower(event);
}
else if (event.getType()===3){
if(event.object != undefined && event.object.playerId!=-1){
this.movePlayersTank(event);
}
else if (event.object != undefined){
this.moveEnemiesTanks(event);
}
}
else if(event.getType()===4 && event.object.getIsEnable()){
this.shoot(event);
}
else if(event.getType()===5){
this.applyTankPower(event);
}
this.inUse= false;
}
else{
this.eventsQueue.push(event);
}
}
deletePlayerTank(tank){
this.gameBoard.setPosition(tank.x,tank.y,
new BoardPosition(Data.free,new WhiteSpace(imageNames.freeSpace),-1));
this.deleteFromDic(this.players, tank.playerId);
}
initProcessing(){
var that= this;
this.queueInterval = setInterval(function(){
that.proccessEvents();
},this.processingTime);
this.powersInterval= setInterval(function(){
that.checkPowers();
},this.powerCheckingTime);
}
addEvent(event){
if(event.type ==0 || event.type==2 || event.type==5){
this.eventsQueue.unshift(event);
}
else{
this.eventsQueue.push(event);
}
}
}
module.exports= EventsManager;
|
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .
// app/assets/javascripts/application.js
//= require gmaps/google
//= require jquery-fileupload/basic
//= require cloudinary/jquery.cloudinary
//= require attachinary
// app/assets/javascripts/application.js
// app/assets/javascripts/navbar.js
// app/assets/javascripts/parallax.js
// app/assets/javascripts/textscramble.js
// app/assets/javascripts/curtain.js
|
import React from 'react'
import Grid from '../../components/Grid'
import { Button, Card, ListGroup } from 'react-bootstrap'
import { Link } from 'react-router-dom'
export default function Welcome() {
return (
<>
<Grid cols="4" rows="1">
<Card>
<Card.Img variant="top" src="http://placehold.it/500x500" />
<Card.Body>
<Card.Title>Hello World</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
Welcome to Dashboard
</Card.Subtitle>
<Link to="/form">
<Button>Click me</Button>
</Link>
</Card.Body>
</Card>
<Card>
<Card.Header>Features</Card.Header>
<ListGroup variant="flush">
<ListGroup.Item>
<Link to="/form">Form</Link>
</ListGroup.Item>
<ListGroup.Item>
<Link to="/table">Table</Link>
</ListGroup.Item>
</ListGroup>
</Card>
</Grid>
</>
)
}
|
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
export default {
input: './src/index.js',
output: {
file: './dist/index.js',
format: 'cjs',
},
globals: {
react: 'React',
'react-native': 'ReactNative',
},
plugins: [
peerDepsExternal(),
replace({
exclude: 'node_modules/**',
'process.env.NODE_ENV': JSON.stringify('production'),
}),
babel({
exclude: 'node_modules/**',
}),
resolve(),
commonjs(),
terser({
parse: {
// we want terser to parse ecma 8 code. However, we don't want it
// to apply any minfication steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending futher investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
}),
],
};
|
import React, { useState, useEffect, useContext } from 'react'
import styled from 'styled-components';
import WeeksNavBar from './WeeksNavBar/WeeksNavBar'
import DaysContainer from './MenuComponents/DaysContainer';
import { AppContext } from '../../AppContext';
import { FetchMenus } from '../../Helpers/DataHelper';
const Container = styled.div`
flex-grow:1;
`;
function MenusManager()
{
//UseContext
const { dataState, dataDispatch } = useContext(AppContext);
const weekDates = dataState.weekDates;
const [isDataLoading, setIsDataLoading] = useState(false);
//Called when the week has been changed, at the start or in the weeknavbar
const weekChanged = async (startDate, endDate) =>
{
setIsDataLoading(true);
// await new Promise(r => setTimeout(r, 500));
await FetchMenus(dataDispatch, startDate, endDate)
.then(async () =>
{
dataDispatch({ type: 'weekDates/update', payload: { startDate: startDate, endDate: endDate } })
setIsDataLoading(false)
});
}
return (
<Container>
<WeeksNavBar
weekChanged={weekChanged}
startDate={weekDates.startDate}
endDate={weekDates.endDate}
/>
<DaysContainer
menus={dataState.menus}
startDate={weekDates.startDate}
endDate={weekDates.endDate}
dataLoading={isDataLoading}
/>
</Container>
)
}
export default MenusManager
|
import io from 'socket.io-client'
const serverUri = 'http://localhost:4000'
let socket
if (!socket) {
socket = io(serverUri)
}
export default socket
|
(function () {
'use strict';
angular
.module('app.stkMvnt')
.controller('StkMvntController', StkMvntController);
StkMvntController.$inject = ['logger',
'$stateParams',
'$location',
'StkMvnt',
'TableSettings',
'StkMvntForm',
'utils'];
/* @ngInject */
function StkMvntController(logger,
$stateParams,
$location,
StkMvnt,
TableSettings,
StkMvntForm,
utils) {
var vm = this;
vm.data = {
total: 0,
list: []
};
//vm.tableParams = TableSettings.getParams(StkMvnt);
vm.stkMvnt = {};
// Initialize Search input and pagination
vm.searchInput = utils.searchInputInit().searchInput;
vm.searchInput.className = 'org.adorsys.adstock.jpa.StkMvntSearchInput';
vm.pagination = utils.searchInputInit().pagination;
vm.setFormFields = function(disabled) {
vm.formFields = StkMvntForm.getFormFields(disabled);
};
vm.create = function() {
// Create new StkMvnt object
var stkMvnt = new StkMvnt(vm.stkMvnt);
// Redirect after save
stkMvnt.$save(function(response) {
logger.success('StkMvnt created');
$location.path('stk-mvnt/' + response.id);
}, function(errorResponse) {
vm.error = errorResponse.data.summary;
});
};
// Remove existing StkMvnt
vm.remove = function(stkMvnt) {
if (stkMvnt) {
stkMvnt = StkMvnt.get({stkMvntId:stkMvnt.id}, function() {
stkMvnt.$remove(function() {
logger.success('StkMvnt deleted');
});
});
} else {
vm.stkMvnt.$remove(function() {
logger.success('StkMvnt deleted');
$location.path('/stk-mvnt');
});
}
};
// Update existing StkMvnt
vm.update = function() {
var stkMvnt = vm.stkMvnt;
stkMvnt.$update(function() {
logger.success('StkMvnt updated');
$location.path('stk-mvnt/' + stkMvnt.id);
}, function(errorResponse) {
vm.error = errorResponse.data.summary;
});
};
vm.toViewStkMvnt = function() {
vm.stkMvnt = StkMvnt.get({stkMvntId: $stateParams.stkMvntId});
vm.setFormFields(true);
};
vm.toEditStkMvnt = function() {
vm.stkMvnt = StkMvnt.get({stkMvntId: $stateParams.stkMvntId});
vm.setFormFields(false);
};
// Paginate over the list
vm.paginate = function(newPage){
utils.pagination(vm.searchInput, vm.pagination, newPage);
findCustomStkArticlesLots();
};
activate();
//findAllStkmvnts();
findCustomStkmvnts();
function activate() {
//logger.info('Activated StkMvnt View');
}
function findAllStkmvnts(){
StkMvnt.listAll(function (response) {
vm.data.list = response.resultList;
vm.data.total = response.total;
}, function(errorResponse) {
vm.error = errorResponse.data.summary;
});
}
function findCustomStkmvnts(){
StkMvnt.findCustom(vm.searchInput, function(response){
vm.data.list = response.resultList;
vm.data.total = response.total;
},
function(errorResponse) {
vm.error = errorResponse.data.summary;
});
}
}
})();
|
/*
PART 3 [General Information]:
Type the correct answer below each question:
Q1) Why do we use databases?
easy to develpobe data andd controole data more scure to save time
Q2) What are JWTs used for?.
jasn web token iss a packageto create new token
Q3) What are the main three sections of a JWT?
payload
secret
signture
Q4) Name three types of express middle-wares.
Q5) What is the `effect` hook used for in react?
use to import data from external api
Q6) What is the `state` hook used for in react?
use to control the life cycle of the variabl and make it statfull
Q7) List three thing you can use to create a responsive web application.
Q8) Name two of mongoose middle-wares and explain what they are used for.
per andd post
pre is used to change data befor save it in data base
post use to find data then excute function to do things to that data
Q9) What is the difference between authentication and authorization?
authntication is the process to cheak if ihave email and password to the user
authorization is used to صلاحيات المستخدم تحديد الصلاجيات
Q10) Why do we save some information as an environment variable (in .env file)?
when i have some varible i dont wanna other to see it like my mongodb url and my secret i save it in env file
*/
|
module.exports = function(builder) {
builder.addModule(responseHelper);
function responseHelper() {
//definition
var helper = this;
helper.sendSuccess = sendSuccess;
helper.sendError = sendError;
//implementation
function sendSuccess(res, data, next) {
res.status(200).send({
"ResultCode": "OK",
"Data": data
});
next();
}
function sendError(res, msg, next) {
if(typeof msg !== "string") {
msg = JSON.stringify(msg);
}
res.status(200).send({
"ResultCode": "Error",
"Messages": [
{
"Message": msg
}
]
});
next();
}
return helper;
}
};
|
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack'
import GameScreen from '../screens/GameScreen';
import HomeScreen from '../screens/HomeScreen';
const Stack = createStackNavigator()
export default function Routes() {
return (
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name='Home' component={HomeScreen} />
<Stack.Screen name='GameScreen' component={GameScreen} />
</Stack.Navigator>
)
}
|
'use strict';
angular.module('ExportSetupService', [])
.factory('ExportSetup', function(ChartInit, $rootScope) {
var fieldOptions = function () {
var resultObj = {};
resultObj.activeRLOptions = {
label: $rootScope.t('crm.export.recurring-status'),
data: [{
"id":-1,
"name": $rootScope.t('services.crm.exportsetup.any'),
checked: 'checked'
},
{
"id":1,
"name": $rootScope.t('services.crm.exportsetup.active')
},
{
"id":0,
"name": $rootScope.t('services.crm.exportsetup.inactive')
}]
};
resultObj.clientsSettings = {
enableSearch: true,
scrollableHeight: '163px',
scrollable: true,
idProp: 'ClientID',
displayProp: 'CompanyName',
selectName: $rootScope.t('common.clients'),
valRequired: true
};
// 2nd select
resultObj.sitesSettings = {
idProp: 'SiteID',
displayProp: 'Name',
enableSearch: true,
scrollableHeight: '163px',
scrollable: true,
searchPlaceholder: $rootScope.t('common.sites-type-here-or-select-from-list'),
selectName: $rootScope.t('common.sites'),
valRequired: true
};
// 3rd select
resultObj.reportOptionsSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '207px',
scrollable: true,
selectName: $rootScope.t('crm.export.report-options'),
selectionLimit: 1,
valRequired: true,
};
// 4th select
resultObj.chargeTypeSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '115px',
scrollable: true,
selectName: $rootScope.t('crm.export.charge-type'),
};
// 5th select
resultObj.transactionTypeSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '115px',
scrollable: true,
selectName: $rootScope.t('crm.export.transaction-type'),
};
// 6th select
resultObj.transactionResultSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '115px',
scrollable: true,
searchPlaceholder: $rootScope.t('crm.export.transaction-result.type-transaction-result'),
selectName: $rootScope.t('crm.export.transaction-result'),
};
resultObj.stepTypeSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '156px',
scrollable: true,
selectName: $rootScope.t('crm.export.last-step')
};
resultObj.fromDateOptions = {
//width: 110,
label: $rootScope.t('common.from'),
id: 304,
inline: true
};
resultObj.toDateOptions = {
//width: 110,
label: $rootScope.t('common.to'),
id: 305,
inline: true
};
resultObj.fromDateOptionsSmall = {
label: $rootScope.t('common.from'),
id: 304,
small: true
};
resultObj.toDateOptionsSmall = {
label: $rootScope.t('common.to'),
id: 305,
small: true
};
return resultObj;
};
return {
fieldOptions: fieldOptions,
};
});
|
import React, { useEffect, useState } from 'react'
import UpdateItem from '../../components/UpdateItem'
const UpdateProduct = ({ onUpdate }) => {
return (
<UpdateItem onUpdate={onUpdate}/>
)
}
export default UpdateProduct
|
angular.module('ContactBookApp').factory('Contact', [
'$resource',
function($resource) {
return $resource(
'/api/v1/contact/:contactId',
{contactId:'@id'},
{update: {method: 'PUT'}}
);
}
]);
|
import React, { Component } from 'react';
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css"
const MainCarousel = props => {
const settings = {
dots: true,
infinite: false,
/*
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
*/
}
const { banners } = props;
return(
<div className="mainCarousel">
<Slider {...settings}>
{ banners.map( item => (
<div key={item.id}>
<img src={item.download_url} alt="Banner" />
</div>
))}
</Slider>
</div>
)
}
export default MainCarousel;
|
import React from 'react';
import OutbreakActions from '../actions/OutbreakActions';
export default class OutbreakReport extends React.Component {
constructor(props) {
super(props);
this.state = {
editing: false
};
}
// Master function for rendering, chooses render mode(s).
render() {
if (this.state.editing) {
return this.renderEdit();
}
return this.renderOutbreakReport();
}
// Renders the control in edit mode.
renderEdit = () => {
return (
<div>
<div className="date">{this.props.outbreak.date}</div>
<div className="origin">{this.props.outbreak.origin}</div>
<div><br/></div>
<div className="severity">{this.props.outbreak.severity}</div>
<div className="description">
<input type="text"
ref={
(e) => e ? e.selectionStart = this.props.outbreak.description.length : null
}
autoFocus={true}
defaultValue={this.props.outbreak.description}
onBlur={this.finishEdit}
onKeyPress={this.checkEnter} />
</div>
</div>
);
}
// Switch the control into edit mode. Does NOT invoke a store-changing action.
edit = () => {
console.log('Switching to edit mode.');
this.setState({
editing: true
});
};
checkEnter = (e) => {
if(e.key === 'Enter') {
this.finishEdit(e);
}
};
// Blurred out of edit control. Commit changes to store via Action.
finishEdit = (e) => {
console.log('Exited edit')
const value = e.target.value;
//this.props.onEdit(value);
this.setState({
editing: false
});
if(!value.trim()) {
return;
}
this.props.outbreak.description = value;
OutbreakActions.changeOutbreak(this.props.outbreak);
}
// Invoke delete action to modify store.
onDelete = (e) => {
console.log('Clicked delete');
OutbreakActions.deleteOutbreak(this.props.outbreak);
}
// Renders read-only version of report.
renderOutbreakReport = () => {
const onDelete = this.props.onDelete;
return (
<div>
<div className="date">{this.props.outbreak.date}</div>
<div className="origin">{this.props.outbreak.origin}</div>
<div><br/></div>
<div className="severity">{this.props.outbreak.severity}</div>
<div className="description" onClick={this.edit}>{this.props.outbreak.description}</div>
{this.renderDelete()}
</div>
);
}
renderDelete = () => {
return <button
className="delete-outbreak" onClick={this.onDelete}>X</button>;
}
}
|
// Initialize
requirejs([
"modules/player",
// Songs
"songs/default"
],
function (Player, defaultSong) {
"use strict";
var player = new Player({song: defaultSong});
});
|
import React from "react";
import EmailIcon from "@material-ui/icons/Email";
import LocationOnIcon from "@material-ui/icons/LocationOn";
import { MDBFooter } from "mdb-react-ui-kit";
export default function Footer() {
return (
<MDBFooter>
<div
className="text-center p-3"
style={{ backgroundColor: "rgba(0, 0, 0, 0.2)" }}
>
<h5>
<LocationOnIcon /> San Francisco Bay Area | <EmailIcon />{" "}
info@bellacharity.org
</h5>
<p data-testid="footer-1">
The Bella Charity is registered as a 501(c)(3) non-profit
organization. Contributions to The Bella Charity are tax-deductible to
the extent permitted by law.
</p>
<h5 className="text-dark">
© {new Date().getFullYear()} Bella Charity
</h5>
</div>
</MDBFooter>
);
}
|
import { LitElement, html } from '@polymer/lit-element';
import '@polymer/iron-icon'
// import '@polymer/iron-icons/iron-icons'
import { FlexboxGridLit, FlexboxGridRemovePadding } from '../../../style/flexbox-grid-lit';
// import './shared-styles.js';
import { StyleFile } from './style-file.js'
class ListFile extends LitElement {
static get properties() {
return {
dataFile: Object,
}
}
render() {
return html`
${FlexboxGridLit} ${FlexboxGridRemovePadding} ${StyleFile}
<style>
iron-icon {
-iron-icon-height: 25px;
--iron-icon-width: 25px;
padding: 0px 16px 0px 16px;
color: #5F6368;
}
</style>
<div class="row line-file">
<div class="col-xs-6 files">
<iron-icon icon="${dataFile.type === 'folder' ? 'folder' : 'description'}"></iron-icon> ${dataFile.name}
</div>
<div class="col-xs-2 files">
${dataFile.own}
</div>
<div class="col-xs-2 files">
${dataFile.date_updatest}
</div>
<div class="col-xs-2 files">
${dataFile.size}
</div>
</div>
`;
}
}
customElements.define('list-file', ListFile);
|
import mongoose from './mongoose';
import findOneLoaderFactory from '../utils/dataloaders/findOneLoaderFactory';
const Schema = mongoose.Schema;
// A safeguard against people spamming the perspective api endpoint
const PictureTemplateSchema = new Schema({
resourceId: String,
// The following are percentages represented by floats in between 0 and 1
offset: {
left: Number,
right: Number,
top: Number,
bottom: Number,
},
variant: String, // right now "flip" or "impose",
backgroundColor: String,
textColor: String
});
PictureTemplateSchema.statics.idLoader = findOneLoaderFactory("PictureTemplate");
const PictureTemplate =
mongoose.models.PictureTemplate || mongoose.model('PictureTemplate', PictureTemplateSchema);
export default PictureTemplate;
/*
{
"resourceId": "6_mazbcx",
"textColor": "black",
"offset": {
"top": 0,
"bottom": 0,
"left": 0,
"right": 0
},
"variant": "impose"
}
*/
|
const rolesModel = require('../models/roles');
const checkToken = require('../shared/middlewares/mw_checkToken');
module.exports = function(app, passport){
app.get('/roles/pag/:pag', checkToken, (req, res) => {
rolesModel.getPage(req.params.pag, (err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
app.get('/roles/get/all', checkToken, (req, res) => {
rolesModel.getAll((err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
app.get('/roles/:id', checkToken, (req, res) => {
rolesModel.get(req.params.id, (err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
app.get('/roles/filtrar/:texto/:pag', checkToken, (req, res) => {
rolesModel.filter(req.params.texto, req.params.pag, (err, data) => {
if(err){
res.json(err);
}else{
res.json( data);
}
});
});
app.post('/roles', checkToken, (req, res) => {
rolesModel.insert(req.body, (err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
app.put('/roles/:id', checkToken, (req, res) => {
rolesModel.update(req.params.id, req.body, (err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
app.delete('/roles/:id', checkToken, (req, res) => {
rolesModel.softDelete(req.params.id, (err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
app.delete('/roles/kill/:id', checkToken, (req, res) => {
rolesModel.delete(req.params.id, (err, data) => {
if(err){
res.json(err);
}else{
res.json(data);
}
});
});
}
|
$(document).ready(function(){
function check_new_contact(){
if($('#new_contact').is(":checked")){
$('.table-new-contact').removeClass('hide');
}else{
$('.table-new-contact').addClass('hide');
}
}
check_new_contact();
$('#new_contact').change(function(){
check_new_contact();
});
function check_called(){
if($('#called').is(":checked")){
$('.box-fminute').removeClass('hide');
}else{
$('.box-fminute').addClass('hide');
}
}
check_called();
$('#called').change(function(){
check_called();
});
// function check_fminute_push(){
// var fminute = $('input[type=radio][name=fminute]:checked').val();
// var push = $('input[type=radio][name=push]:checked').val();
// if(fminute==1 || push==1){
// $('.box-push').removeClass('hide');
// }else{
// $('.box-push').addClass('hide');
// }
// }
// check_fminute_push();
// function check_fminute(){
// var radio = $('input[type=radio][name=fminute]:checked').val();
// if(radio==1){
// $('.box-push-ya').removeClass('hide');
// $('.box-push-tidak').addClass('hide');
// }else if(radio==2){
// $('.box-push-ya').addClass('hide');
// $('.box-push-tidak').removeClass('hide');
// }
// }
// check_fminute();
// $('input[type=radio][name=fminute]').change(function(){
// check_fminute();
// check_fminute_push();
// });
function check_fminute(){
var radio = $('input[type=radio][name=fminute]:checked').val();
if(radio==1){
$('.box-attend').removeClass('hide');
$('.box-fminute-ya').removeClass('hide');
$('.box-fminute-tidak').addClass('hide');
}else if(radio==2){
$('.box-attend').addClass('hide');
$('.box-fminute-ya').addClass('hide');
$('.box-fminute-tidak').removeClass('hide');
}
}
check_fminute();
$('input[type=radio][name=fminute]').change(function(){
check_fminute();
});
function check_push(){
var radio = $('input[type=radio][name=push]:checked').val();
if(radio==1){
$('.box-attend').removeClass('hide');
$('.push-ya').removeClass('hide');
$('.push-tidak').addClass('hide');
}else if(radio==2){
$('.box-attend').addClass('hide');
$('.push-ya').addClass('hide');
$('.push-tidak').removeClass('hide');
}
}
check_push();
$('input[type=radio][name=push]').change(function(){
check_push();
});
function check_attend(){
var radio = $('input[type=radio][name=attend]:checked').val();
if(radio==1){
$('.box-attend-ya').removeClass('hide');
$('.box-attend-tidak').addClass('hide');
}else if(radio==2){
$('.box-attend-ya').addClass('hide');
$('.box-attend-tidak').removeClass('hide');
}
}
check_attend();
$('input[type=radio][name=attend]').change(function(){
check_attend();
});
function check_email(){
var radio = $('input[type=radio][name=email]:checked').val();
if(radio==1){
$('.box-email-ya').removeClass('hide');
$('.box-email-tidak').addClass('hide');
}else if(radio==2){
$('.box-email-ya').addClass('hide');
$('.box-email-tidak').removeClass('hide');
}
}
check_email();
$('input[type=radio][name=email]').change(function(){
check_email();
});
});
|
import Vue from 'vue'
import Router from 'vue-router'
import { routerMode } from '@/config/application'
const Main = r => require.ensure([], () => r(require('@/components/main')), 'Main')
const Login = r => require.ensure([], () => r(require('@/components/login/login')), 'Login')
const Register = r => require.ensure([], () => r(require('@/components/login/register')), 'Register')
const ForgotPass = r => require.ensure([], () => r(require('@/components/login/forgotPass')), 'ForgotPass')
const Dashboard = r => require.ensure([], () => r(require('@/components/plugins/dashboard')), 'Dashboard')
const LineChart = r => require.ensure([], () => r(require('@/components/echarts/lineChart')), 'LineChart')
const JobTask = r => require.ensure([], () => r(require('@/components/job/JobTask')), 'JobTask')
const CronExpress = r => require.ensure([], () => r(require('@/components/job/CronExpress')), 'CronExpress')
const AssetsList = r => require.ensure([], () => r(require('@/components/job/AssetsList')), 'AssetsList')
const User = r => require.ensure([], () => r(require('@/components/author/UserMain')), 'UserMain')
const Role = r => require.ensure([], () => r(require('@/components/author/RoleMain')), 'RoleMain')
const Permission = r => require.ensure([], () => r(require('@/components/author/PermissionMain')), 'PermissionMain')
Vue.use(Router)
export default new Router({
mode: routerMode,
routes: [
// 登录页面
{
path: '/',
name: 'Login',
component: Login,
meta: {
keepAlive: true
}
},
// 注册页
{
path: '/register',
name: 'Register',
component: Register,
meta: {
keepAlive: true
}
},
// 忘记密码页
{
path: '/forgotPass',
name: 'ForgotPass',
component: ForgotPass
},
// 主页
{
path: '/main',
name: 'Main',
component: Main,
meta: {
keepAlive: true // 缓存
},
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: Dashboard
},
{
path: 'lineChart',
name: 'LineChart',
component: LineChart
},
{
path: 'jobTask',
name: 'JobTask',
component: JobTask
},
{
path: 'cronExpress',
name: 'CronExpress',
component: CronExpress
},
{
path: 'assetsList',
name: 'AssetsList',
component: AssetsList
},
{
path: 'user',
name: 'User',
component: User
},
{
path: 'role',
name: 'Role',
component: Role
},
{
path: 'permission',
name: 'Permission',
component: Permission
}
]
}
],
// 滚动行为
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
if (from.meta.keepAlive) {
from.meta.savedPosition = document.body.scrollTop
}
return { x: 0, y: to.meta.savedPosition || 0 }
}
}
})
|
const http = require('http');
var fs = require('fs');
// var express = require('express');
const hostname = '127.0.0.1'; // <= DNS <= localhost
const port = 3000;
const server = http.createServer((req, res) => {
//console.log(req);
// fs.appendFile('logs.txt', 'Hello content!\n', function (err) {
// if (err) throw err;
// console.log('Saved!');
// });
// console.log("Got Request from Client...");
// fs.readFile('logs.txt', (err, data) => {
// res.writeHead(200, {'Content-Type': 'text/plain'});
// res.write(data);
// res.end();
// });
// let x = fs.readFileSync('logs.txt');
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Hello World</h1>\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
|
var t1s = $('.time');
var btns = $('.btn');
var cot = $('.countDown');
var item = $('.item');
var hid = $('.hidden');
function func(k){
var spans = $('span',cot[k]);
console.log(k)
var fut = t1s[k].value;
var future = new Date(fut);//将来的时间
var now = new Date();//现在的时间
//未来时间和现在时间的差值 (毫秒)
var dValue = (future.getTime()-now.getTime())/1000; // 秒
if(dValue <= 0){
hid[k].style.display = 'block';
dValue = 0
return
}
var hours = parseInt(dValue/3600); // 剩余的时
var min = parseInt(dValue%86400%3600/60) // 剩余的分
var se = parseInt(dValue % 60);
var timeDf = addZero(hours)+addZero(min)+addZero(se)
for (var i = 0; i < spans.length; i++) {
spans[i].innerHTML = timeDf.charAt(i)
}
if (dValue < 1) {//处理将来时间比现在时间小的情况
dValue = 0
clearInterval(item[k].timer)
shake(item[k],'left',40)
setTimeout(function(){
hid[k].style.display = 'block'
},400)
setTimeout(function(){
auto(k);
},600)
}
};
for (var i = 0; i < btns.length; i++) {
fc(i)
}
function fc(m){
btns[m].onclick = function(){
if (item[m].timer) {//处理定时器累计的情况
return
}
func(m)
item[m].timer = setInterval(function(){
func(m)
},1000)
};
}
//生成结构
var arr = [
{
name:"iPhone7s plus 酷派手机",
money:"抢购价: <b>¥8000",
img:"1"
},
{
name:"27 英寸配备 Retina 5K显示屏",
money:"抢购价: <b>¥15999",
img:"2"
},
{
name:"iPad mini 4",
money:"抢购价: <b>¥1799",
img:"3"
},
{
name:"Apple iPhone 7 Plus 64g",
money:"抢购价: <b>¥5799</b>",
img:"4"
}
]
var shop = $('.shop');
function auto(z){
var inHtml = '';
inHtml = `<div class="product">
<p class="introduction">${arr[z].name}</p>
<span class="price">${arr[z].money}</span>
<div class="pro"><img src="images/goods_${arr[z].img}.png" /></div>
</div>`
shop[0].innerHTML += inHtml;
}
|
var bot = require('./nlp/n-grams/ngrams')
const text = 'Queru piza'
var response = bot(text)
console.log(response[0].response);
|
/**
* Created by wen on 2016/8/17.
*/
import React from 'react';
import BMmodifyPwd from './BMmodifyPwd';
export default {
path: '/bmmodifyPwd',
async action() {
return <BMmodifyPwd />;
},
};
|
import React from 'react';
import PropTypes from 'prop-types';
import Grid from '../Components/Grid/Grid';
import DataContainer from '../Components/DataContainer/DataConterer';
const Projects = () => {
return (
<DataContainer url={'https://api.github.com/users/acodexm/repos'}>{(data) => <Grid data={data} />}</DataContainer>
);
};
export default Projects;
|
const mongoose = require("mongoose");
let commentSchema = mongoose.Schema({
userCommentId: { type: String, ref: "User" },
content: { type: String },
createdAt: {
type: Number,
default: new Date().getTime(),
},
});
let imageSchema = mongoose.Schema({
url: { type: String },
width: {
type: Number,
default: 0,
},
height: {
type: Number,
default: 0,
},
publicId: { type: String },
});
let voteSchema = {
voterId: {
type: String,
ref: "User",
},
voteType: {
type: Number, // 0 is down, 1 is up
},
};
let postSchema = mongoose.Schema({
title: { type: String },
ownerId: { type: String, ref: "User" },
typeId: { type: String, ref: "PostCategory" },
status: {
type: Number,
default: 1, // 0 is private, 1 is public
},
votes: [voteSchema],
comments: [commentSchema],
images: [imageSchema],
createdAt: {
type: Number,
default: new Date().getTime(),
},
updatedAt: {
type: Number,
default: new Date().getTime(),
},
deletionFlag: { type: Boolean, default: false },
});
postSchema.index({ title: "text", "ownerId.appName": "text" });
(module.exports = mongoose.model("Post", postSchema));
postSchema.pre("save", async function(next) {
const currTime = new Date().getTime();
this.updatedAt = currTime;
if (this.isNew) {
this.createdAt = currTime;
}
next();
});
commentSchema.pre("save", async function(next) {
const currTime = new Date().getTime();
if (this.isNew) {
this.createdAt = currTime;
}
next();
});
|
'use strict';
class Util {
static getTrue(){
return true;
}
static getFalse(){
return false;
}
}
module.exports=Util;
|
import React from 'react';
const ItemCard = (props) => {
return (
<div className="col-12 col-lg-4 mb-3">
<div className="card item-card">
<div className="card-body item-card-body">
<div className="row">
<div className="col-12 col-lg-12 d-flex justify-content-between">
<strong>{props.name}</strong>
<div className="item-quantity">{props.quantity} <span className="item-unity">{props.measure ? props.measure : 'unidades'}</span> </div>
</div>
<div className="col-12">
<hr/>
<strong>Descripción: </strong> {props.description}</div>
</div>
<div className="row">
<div className="col-12 my-2">
<button onClick={props.onEdit} className="btn btn-sm btn-info mr-2">Editar</button>
<button onClick={props.onDelete} className="btn btn-sm btn-danger mr-2">Borrar</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default ItemCard;
|
export default {
CANTRADELIST:'lyjfapp/api/v1/ctrade/findCanTrade',
};
|
import React from 'react';
import { BarChart, Bar, Cell, Brush, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine } from 'recharts';
// const data = [
// {
// name: 'Page A',
// pv: 2
// },
// {
// name: 'Page B',
// pv: -1.5
// },
// {
// name: 'Page C',
// pv: -9
// },
// {
// name: 'Page D',
// pv: 3
// }
// ];
const VerticalChart = ({ data }) => {
// const jsfiddleUrl = 'https://jsfiddle.net/alidingling/q68cz43w/';
console.log('@@@@@@@@@@@@', data);
return (
// <BarChart
// width={400}
// height={500}
// data={data}
// margin={{
// top: 5,
// right: 0,
// left: 0,
// bottom: 5
// }}
// >
// <CartesianGrid strokeDasharray='3 3' />
// <XAxis dataKey='month' />
// <YAxis dataKey='returns' />
// <Tooltip />
// <Legend />
// <ReferenceLine y={0} stroke='#000' />
// <Bar dataKey='returns' fill='#8884d8' />
// </BarChart>
<BarChart
width={350}
height={500}
data={data}
margin={{ top: 5, right: 5, bottom: 5, left: 5 }}
layout='vertical'
stackOffset='expand'
maxBarSize={30}
>
<CartesianGrid x='2' y='2' />
<XAxis
dataKey='returns'
type='number'
// padding={{ left: 5, right: 5 }}
// allowDataOverflow='true'
domain={[-1, 1]}
// domain={['dataMin', 'dataMax']}
tickFormatter={returns => `${returns}%`}
/>
<YAxis dataKey='month' type='category' />
<Tooltip />
{/* <Legend payload= /> */}
<ReferenceLine y={0} stroke='#000' />
<Bar
dataKey='returns'
fill={'#8884d8'}
isAnimationActive='true'
animationEasing='ease-in-out'
label={{ fill: '#000', fontSize: 15 }}
>
{data.map((entry, index) => {
const color = entry.returns > 0 ? '#8DF30C' : '#F91D12';
return <Cell fill={color} />;
})}
</Bar>
</BarChart>
);
};
export default VerticalChart;
|
import Blog1 from "../assets/blog/blog-1.png";
import Blog2 from "../assets/blog/blog2.jpg";
import Blog3 from "../assets/blog/blog3.jpg";
import Blog4 from "../assets/blog/blog4.png";
import Blog5 from "../assets/blog/blog5.jpg";
import Blog6 from "../assets/blog/blog6.jpg";
import Blog7 from "../assets/blog/blog7.jpg";
import Blog8 from "../assets/blog/blog8.jpg";
import Blog9 from "../assets/blog/blog9.jpg";
import Blog10 from "../assets/blog/blog10.jpg";
import Blog11 from "../assets/blog/blog11.jpg";
import BlogInfo from "../assets/blog/blog-info.png";
import BlogUser from "../assets/blog/blog-user.jpg";
const blogs = [
{
id: "0",
title: "Why you must see Dunns River Fall Jamaica?",
tag: "Money, Tips",
img: Blog1,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"Near Ocho Rios town, the waterfalls of Dunn's River are one of the most famous attractions in the country. Climb the limestone on your own or...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 1,
title: "Which Bob Marley tour is better?",
tag: "Money, Tips",
img: Blog2,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"Bob Marley is considered one of the absolute titans of world music, known for his thrilling reggae melodies and strong attachment to political and social justice....",
tags: [{ name: "island" }, { name: "Jamaica" }],
},
{
id: 2,
title: "Top beaches to visit in Jamaica ",
tag: "Money, Tips",
img: Blog3,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"Beach vacations are loved for many reasons; relax and unwind, campfires at night, walks, cocktails, a romantic dinner on the beach with a beautiful sunset and...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 3,
title: "Top 10 hotels in Jamaica for tourists",
tag: "Money, Tips",
img: Blog4,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"Warming sun rays, vast beaches, beautiful sunsets, waterfalls and forests, delicious rum and addictive music. That's Jamaica! As soon as you are in Jamaica you dance...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 4,
title: "Best places to visit in Jamaica",
tag: "Money, Tips",
img: Blog5,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "04 Dec",
desc:
"If you say Jamaica, Bob Marley is directly on your retina, including rasta, reggae and a lot of weed. You can taste the 'don't worry be...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 5,
title: "Best time to holiday in Jamaica",
tag: "Money, Tips",
img: Blog6,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"Jamaica is a popular destination for a sunny holiday. The Caribbean island is not only tropical hot but also quite humid. This naturally results in lush...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 6,
title: "Montego Bay Airport Transfer",
tag: "Money, Tips",
img: Blog7,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"JamRock Taxi quality and attention to detail is second to none, all our airport transfers are done privately in a fleet of vehicles which are fully air-conditioned,...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 7,
title: "Planning a holiday to Jamaica?",
tag: "Money, Tips",
img: Blog8,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "27 Dec",
desc:
"Jamaica is the land of legends such as Bob Marley and Usain Bolt to name a few. Jamaicans are proud and spontaneous people who are never...",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 8,
title: "Playing Golf In Jamaica",
tag: "Money, Travel",
img: Blog9,
infoImg: BlogInfo,
infolabel: "JamRockTaxi",
date: "03 Jun",
desc: "Learn all about golf in Jamaica!",
tags: [{ name: "Golf" }, { name: "Jamaica" }],
},
{
id: 9,
title: "Welcome to Jamaica!",
tag: "Money",
img: Blog10,
infoImg: BlogUser,
infolabel: "Kimarotec",
date: "03 Jun",
desc: "Experience Jamaica! There will be a post about this magical island!",
tags: [{ name: "Island" }, { name: "Jamaica" }],
},
{
id: 10,
title: "Waterfalls in Jamaica",
tag: "Fun",
img: Blog11,
infoImg: BlogUser,
infolabel: "Kimarotec",
date: "03 Jun",
desc:
"Embark on a journey through the incredibly beautiful waterfalls in Jamaica!",
tags: [{ name: "Jamaica" }],
},
];
export default blogs;
|
// MeasurementsTable.js
import React from 'react';
import { connect } from 'react-redux';
import { Table } from 'reactstrap';
import { utils } from "../../utils";
import MeasurementsTableRow from '../MeasurementsTableRow';
class MeasurementsTable extends React.Component {
render () {
const { measurements, isFetchingMeasurements, getAQIScaleCustom, aqiScale, pollutant } = this.props,
isEmpty = measurements.length === 0;
return (
<Table responsive>
<thead>
<tr>
<th>Starting Date</th>
<th>Starting Time</th>
<th>SiteId</th>
<th>Monitor</th>
<th>Value</th>
<>
{
pollutant !== 'aqi' ?
<th>AQI Index</th> :
<></>
}
</>
<th>AQI Category Description</th>
</tr>
</thead>
<tbody>
{!isEmpty
?
measurements.map(measurement => {
return (
<MeasurementsTableRow measurement={ measurement } key={ measurement.DateTimeStart } getAQIScaleCustom={getAQIScaleCustom} aqiScale={aqiScale} pollutant={pollutant}/>
);
})
:
<tr>
<td colSpan="7" style={{textAlign: "center", maxHeight: '100px'}}>
{isFetchingMeasurements ? utils.loaders.TableLoader({style: { height: '100px' }}) : <h5>No measurements available.</h5>}
</td>
</tr>
}
</tbody>
</Table>
);
}
}
function parseAqiScale (pollutant='aqi', aqiScale=null) {
if (!aqiScale) return null;
const extraCheck = utils.aqiScaleTools.extraChecks(aqiScale.abbreviation),
extended = true,
aqiThresholds = utils.charts.parseScale(aqiScale, pollutant, extraCheck, extended);
return (val) => {
let thresh;
for (thresh in aqiThresholds.upperLimits) {
if (val < aqiThresholds.upperLimits[thresh]) {
break;
}
}
return {
bgColour: aqiThresholds.backgroundColors[thresh],
description: aqiThresholds.descriptions[thresh],
fgColour: aqiThresholds.foregroundColors[thresh]
};
}
}
const mapStateToProps = state => {
const { currentUser } = state,
{ measurements, isFetchingMeasurements } = state.measurements,
{ aqiScales } = state.aqiScales,
user = currentUser.user || utils.auth.getUser(),
aqiScale = utils.aqiScaleTools.getUserAqiScale(aqiScales, user),
pollutant = measurements && measurements.Parameters ?
utils.charts.getMeasurementPollutantName(measurements.Parameters): 'aqi';
return {
isFetchingMeasurements,
measurements: measurements.Measurements || [],
getAQIScaleCustom: parseAqiScale(pollutant, aqiScale),
pollutant: utils.aqiScaleTools.normalizePollutantId(pollutant),
aqiScale
};
};
export default connect(
mapStateToProps,
null
)(MeasurementsTable);
|
import fs from 'fs-extra';
export default async function(templateDirectory, targetDirectory) {
return fs.copy(templateDirectory, targetDirectory).catch(err => {
console.log(err);
process.exit(1);
});
}
|
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
let DbManager = class {
db;
adapter;
constructor(){
// On initialise la DB
this.adapter = new FileSync('./data/db.json')
this.db = low(this.adapter);
// On crée les tables dont on va avoir besoin
this.db.defaults({ messages: [], value: [] }).write()
}
getDb(){
this.adapter = new FileSync('./data/db.json')
this.db = low(this.adapter);
return this.db;
}
}
module.exports = DbManager;
|
import React, {useState} from 'react'
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import Alert from 'react-bootstrap/Alert';
import api from "../../services/api";
import './style.css';
export default function RemoveContact({contact, removeFromContactList}) {
const [show, setShow] = useState(false);
const [showAlert, setShowAlert] = useState(false);
const [deletedName, setDeletedName] = useState("")
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleRemoval = () => {
api.removeContact(contact.id)
.then((response) => {
removeFromContactList(response.data.id)
setShow(false);
triggerAlert(contact)
})
}
const triggerAlert = (contact) => {
setDeletedName(contact.first_name + " " + contact.last_name)
setShowAlert(true)
setInterval(() => {
setShowAlert(false)
}, 4000);
}
return (
<>
<div className="position-relative">
<button className="btn-close custom_btn-close" onClick={handleShow}></button>
</div>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Remove Contact</Modal.Title>
</Modal.Header>
<Modal.Body>Are you sure you want to remove {contact.first_name} {contact.last_name} ?</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleRemoval}>
Remove
</Button>
</Modal.Footer>
</Modal>
{showAlert &&
<Alert className="alert" onClose={() => setShowAlert(false)} dismissible>
The contact {deletedName} was removed!
</Alert>
}
</>
)
}
|
// JavaScript Array methods filter(), map(), flatMap(), forEach()
let userlist = [
{
"id": "d9218fe4-ae03-48ae-af68-92b9289a42f3",
"full_name": "Vivek Ganesan",
"email": "vivek.ganesan@ampyard.com",
"created_timestamp": "2021-05-25T19:36:14.756Z",
"updated_timestamp": "2021-05-25T19:36:14.756Z",
"external_id": "0055g000007E8QPAA0",
"permissions": [
"MANAGE_LICENSES",
"MANAGE_USERS"
]
},
{
"id": "bb24b9d5-30f9-4898-a10c-d494cda28b99",
"full_name": "Jake Williams",
"email": "caliberoviv@gmail.com",
"created_timestamp": "2021-06-01T00:47:02.219Z",
"updated_timestamp": "2021-06-01T00:47:02.219Z",
"external_id": "0055g000009VUq1AAG",
"permissions": [
"MANAGE_LICENSES",
"MANAGE_USERS"
]
},
{
"id": "63edccdc-7f47-412c-ac46-144781f76263",
"full_name": "Data.com Clean",
"email": "automatedclean@00d5g000004jslgea2",
"created_timestamp": "2021-06-01T01:45:21.520Z",
"updated_timestamp": "2021-06-01T01:45:21.520Z",
"external_id": "0055g000007aXQjAAM",
"permissions": [
"MANAGE_USERS"
]
},
{
"id": "7e0f3823-9093-44cc-a6f6-c8a5465a9b27",
"full_name": "Integration User",
"email": "integration@example.com",
"created_timestamp": "2021-06-01T02:15:28.422Z",
"updated_timestamp": "2021-06-01T02:15:28.422Z",
"external_id": "0055g000007aXQfAAM",
"permissions": [
"MANAGE_LICENSES"
]
},
{
"id": "b02e1ab0-b3d9-4fd6-a9c1-58380bfa6979",
"full_name": "Platform Integration User",
"email": "noreply@00d5g000004jslgea2",
"created_timestamp": "2021-06-01T23:54:36.720Z",
"updated_timestamp": "2021-06-01T23:54:36.720Z",
"external_id": "0055g000007aXQiAAM",
"permissions": [
"MANAGE_LICENSES",
"MANAGE_USERS"
]
},
{
"id": "edf8e9ce-4037-4ea2-a9e6-70f75d8ba948",
"full_name": "Automated Process",
"email": "autoproc@00d5g000004jslgea2",
"created_timestamp": "2021-06-01T23:57:29.933Z",
"updated_timestamp": "2021-06-01T23:57:29.933Z",
"external_id": "0055g000007aXQgAAM",
"permissions": [
"MANAGE_LICENSES",
"MANAGE_USERS"
]
},
{
"id": "7f2570d1-a37e-4272-a4dd-c9f3be7c3bfc",
"full_name": "Security User",
"email": "insightssecurity@example.com",
"created_timestamp": "2021-06-03T02:03:56.862Z",
"updated_timestamp": "2021-06-03T02:03:56.862Z",
"external_id": "0055g000007aXQlAAM",
"permissions": []
}
]
// let data = () => {
// userlist.map(user => {
// return console.log(user)
// })
// }
// data()
let userId = 'd9218fe4-ae03-48ae-af68-92b9289a42f3'
let d = () => {
userlist.filter((user) => {
if (user.id === userId) {
console.log(user.id, user.permissions)
}
} )
}
d() // d9218fe4-ae03-48ae-af68-92b9289a42f3 [ 'MANAGE_LICENSES', 'MANAGE_USERS' ]
// foreach
let e = () => {
userlist.forEach((user) => {
if (user.id === userId) {
console.log(user.id, user.permissions)
}
} )
}
e()
// d9218fe4-ae03-48ae-af68-92b9289a42f3 [ 'MANAGE_LICENSES', 'MANAGE_USERS' ]
// MAP method
let f = () => {
userlist.map((user) => {
if (user.id === userId) {
console.log(user.id, user.permissions)
}
} )
}
f()
// d9218fe4-ae03-48ae-af68-92b9289a42f3 [ 'MANAGE_LICENSES', 'MANAGE_USERS' ]
// flatMap - flat result in new array.
let g = () => {
userlist.flatMap((user) => {
if (user.id === userId) {
console.log(user.id, user.permissions)
}
} )
}
g()
// d9218fe4-ae03-48ae-af68-92b9289a42f3 [ 'MANAGE_LICENSES', 'MANAGE_USERS' ]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.