text
stringlengths 7
3.69M
|
|---|
/*
* Global clause object and operator object, which models the conditionals and their relationships.
*/
var all_operators = {};
var all_clauses = {};
var initial_groups = {};
var colorPalette = ['cs-1','cs-2','cs-3'];
function getSubclauses(clauseObj) {
var cList = {};
for(var clause in clauseObj) {
if(clauseObj.hasOwnProperty(clause)) {
if(typeof clauseObj[clause] != 'object') {
cList[clause] = clauseObj[clause];
}
else {
cList[clause] = clauseObj[clause].label;
}
}
}
return cList;
}
// Recursive function to search applicable clauses
function _getApplicableClauses(node, clause) {
if(typeof clause == 'undefined' || clause === '') {
return '';
}
if(typeof node == 'undefined' || node === '') {
return '';
}
if(typeof node.clauses == 'undefined')
return '';
var subclauses = node.clauses;
for(var sc in subclauses) {
if(subclauses.hasOwnProperty(sc)) {
if(sc == clause) {
if(typeof subclauses[sc].clauses != 'undefined') {
return getSubclauses(subclauses[sc].clauses);
}
}
else {
var obj = _getApplicableClauses(subclauses[sc], clause);
if(obj !== '') {
return obj;
}
}
}
}
return '';
}
function getApplicableClauses(clause) {
return _getApplicableClauses(all_clauses, clause);
}
function _getClauseProperties(targetClause, currentClause, currentClauseObj) {
if(typeof currentClauseObj == 'undefined' || currentClauseObj === '' ) {
return false;
}
if(typeof currentClauseObj == 'object') {
if(currentClause == targetClause)
return currentClauseObj;
if(!currentClauseObj.clauses)
return false;
var clauses = currentClauseObj.clauses;
for(var property in clauses) {
if(clauses.hasOwnProperty(property)) {
var r =_getClauseProperties(targetClause, property, clauses[property]);
if(r) {
return r;
}
}
}
}
return false;
}
function getClauseObject(clause) {
if(typeof clause == 'undefined' || clause === '') {
return;
}
var temp = _getClauseProperties(clause, 'all_clauses', all_clauses);
temp.clauseName = clause;
var cObj = new Clause();
cObj.setClause(temp);
return cObj;
}
function _getJson($node) {
if(typeof $node == 'undefined' || $node.length == 0) {
return ;
}
var json ={};
var cond = $node.find('> .block-header select.condition')
.find(':selected')
.val();
json.condition = cond;
var $allBlocks = $node.find('> .block-body > .block-rules > div.block-container');
if($allBlocks.length == 0) {
var isDependent = $node.data('is-dependent') || false;
var cname = [],
operator = [],
value = [];
if(isDependent == true) {
var $depClauses = $node.find('.multiple-clause');
$depClauses.each(function() {
$this = $(this);
cname.push($this.find('.clause-name').data('clause-name'));
operator.push($this.find('select.operator-list :selected').val());
var $values = $this.find('.clause-field');
if($values.length > 1) {
var v = [];
$values.each(function() {
v.push($(this).val());
});
value.push(v);
} else {
value.push($values.val());
}
});
}
else {
cname.push($node.find('.clause-name').data('clause-name'));
operator.push($node.find('select.operator-list :selected').val());
// value.push($node.find('.clause-field').val());
var $values = $node.find('.clause-field');
if($values.length > 1) {
var v = [];
$values.each(function() {
v.push($(this).val());
});
value.push(v);
} else {
value.push($values.val());
}
}
var t = {};
t.id = cname;
t.operator = operator;
t.value = value;
return t;
}
json.rules = [];
$allBlocks.each(function (index) {
var rule = {};
var ruleName = $(this).data('clause');
rule[ruleName] = _getJson($(this));
json.rules.push(rule);
});
return json;
}
function _jsonToBuilder($node, json) {
for(var prop in json) {
if(json.hasOwnProperty(prop)) {
var c = '';
if(prop == 'condition') {
c = json[prop];
$node.find('> .block-header select.condition').val(c);
}
if(prop == 'value') {
var $c = $node.find('.clause-name');
var $o = $node.find('select.operator-list');
var $f = $node.find('.clause-field');
var op = '';
if($c.length > 1) {
$mf = $node.find('.multiple-clause');
for(var j=0; j<$c.length; j++) {
$c.eq(j).val(json.id[j]);
$o.eq(j).val(json.operator[j]).trigger('change');
$f = $mf.eq(j).find('.clause-field');
op = getOperatorFromVal(json.operator[j]);
if(all_operators[op].nb_inputs == 1) {
if($.isArray(json.value[j])) {
for(var k=0; k<json.value[j].length; k++) {
$f.find('option[value="'+json.value[j][k]+'"]').prop('selected', true);
}
$f.trigger('change');
} else {
$f.val(json.value[j]);
}
} else if(all_operators[op].nb_inputs == 2) {
$f.eq(0).val(json.value[0][0]);
$f.eq(1).val(json.value[0][1]);
}
}
} else {
$c.val(json.id);
$o.val(json.operator).trigger('change');
$f = $node.find('.clause-field');
op = getOperatorFromVal(json.operator);
if(all_operators[op].nb_inputs == 1) {
if($.isArray(json.value[0])) {
for(var j=0; j<json.value[0].length; j++) {
$f.find('option[value="'+json.value[0][j]+'"]').prop('selected', true);
}
$f.trigger('change');
} else {
$f.val(json.value[0]);
}
} else if(all_operators[op].nb_inputs == 2) {
$f.eq(0).val(json.value[0][0]);
$f.eq(1).val(json.value[0][1]);
}
}
return;
}
if(prop =='rules') {
var rules = json[prop];
for(var i=0; i<rules.length; i++) {
for(var r in rules[i]) {
if(rules[i].hasOwnProperty(r)) {
$node.find('> .block-footer select.rule')
.val(r)
.trigger('change');
if($node.hasClass('query-builder')) {
$node.find('> .block-footer .add-group-btn')
.prop('disabled', false)
.trigger('click');
} else {
$node.find('> .block-footer .add-clause-btn')
.prop('disabled', false)
.trigger('click');
}
var $block = $node.find('> .block-body > .block-rules > .block-container').last();
_jsonToBuilder($block, rules[i][r]);
}
}
}
}
}
}
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
function _validateBuilder($node) {
var o = {};
o.status = 'valid';
o.element = $node.data('clause') || '';
o.message = '';
if($node.hasClass('clause-container')) {
var $fields = $node.find('.clause-field');
for(var f=0; f<$fields.length; f++) {
if($($fields[f]).val() === '') {
$($fields[f]).addClass('error-in-input');
o.status = 'invalid';
o.element = $node.data('clause') || '';
o.message = 'No '+o.element+' defined';
return o;
}
}
o.status = 'valid';
o.element = $node.data('clause') || '';
o.message = '';
return o;
}
var $allBlocks = $node.find('> .block-body > .block-rules > .block-container');
if($allBlocks.length === 0) {
o.status = 'invalid';
o.element = $node.data('clause');
o.message = 'No subclause selected.';
return o;
}
for(var b=0; b<$allBlocks.length; b++) {
var t =_validateBuilder($($allBlocks[b]));
if(t.status == 'invalid') {
return t;
}
}
return o;
}
function getOperatorFromVal(op) {
for(var operator in all_operators) {
if(all_operators.hasOwnProperty(operator)) {
if(all_operators[operator].val == op)
return operator;
}
}
return '';
}
function fetchConditionals(cb) {
$('.loading').show();
// Fetch Conditionals
$.get('./sample/sample1.json', function(response) {
all_clauses = response.conditionalRelationships;
all_operators = response.operators;
$('.loading').hide();
cb();
}, 'json');
}
function getInitialGroups() {
var result = {};
for(var prop in all_clauses.clauses) {
if(all_clauses.clauses.hasOwnProperty(prop)) {
result[prop] = all_clauses.clauses[prop].label;
}
}
return result;
}
var Clause = function() {
this.getClause = function() {
};
this.setClause = function(clause) {
this.clauseName = clause.clauseName;
if(typeof clause.clauseText === 'undefined' || clause.clauseText === '') {
this.clauseText = clause.label;
} else {
this.clauseText = clause.clauseText;
}
this.operators = clause.operators;
this.label = clause.label;
this.multiple = clause.multiple || false;
this.input = clause.input || 'text';
this.values = clause.values;
this.dependency = clause.dependency || '';
this.type = clause.type || '';
this.placeholder = clause.placeholder || '';
this.popoverText = clause.popoverText || 'None';
};
};
var HTMLGenerator = function() {
var id;
var nextId = 0;
this.preinit = function() {
var html = ''+
'<div class="row is-signed-up">'+
'<div class="col-md-2">'+
'<label for="">Is User signed up</label>'+
'</div>'+
'<div class="col-md-3">'+
'<input type="radio" name="isSignedUp" value="signedUp"> Yes '+
'<input type="radio" name="isSignedUp" value="onlySubscriber"> No '+
'<input type="radio" name="isSignedUp" value="registered"> Not Required '+
'</div>'+
'</div>'+
'<hr style="border-top: 1px solid #BFBFBF;">';
return html;
};
this.inithtml = function(groups) {
var html = ''+
'<div class="row block-header">'+
'<div class="col-md-2 condition-wrapper">'+
'<select class="condition-selector select-picker condition">'+
'<option value="and">AND</option>'+
'<option value="or">OR</option>'+
'</select>'+
'</div>'+
'<div class="col-md-8">'+
''+
'</div>'+
'</div>'+
'<div class="row block-body">'+
'<div class="col-md-12 block-rules">'+
'</div>'+
'</div>'+
'<div class="row block-footer">'+
'<div class="col-md-4">'+
'<select class="group-filter select-picker rule"><option value="-1">Select a Condition</option>';
for(var group in groups) {
html += '<option value="'+group+'">'+groups[group]+'</option>';
}
html += '</select>'+
'</div>'+
'<div class="col-md-2">'+
'<button class="btn btn-primary add-group-btn" disabled><strong>+</strong> ADD</button>'+
'</div>'+
'</div>';
return html;
};
this.getBlock = function(clause, subClauseList) {
this.id = 'builder-block-'+nextId++;
var clauseObj = getClauseObject(clause);
var html = ''+
'<div class="row block-container" data-clause="'+clause+'">'+
'<div class="row block-header">'+
'<div class="col-md-2 condition-wrapper">'+
'<select class="condition-selector select-picker condition">'+
'<option value="and">AND</option>'+
'<option value="or">OR</option>'+
'</select>'+
'</div>'+
'<div class="col-md-8">'+
'<label>'+clauseObj.clauseText+'</label>'+
'</div>'+
'<div class="col-md-2 button-group">'+
'<button class="delete-clause-btn btn btn-danger">Delete</button>'+
'</div>'+
'</div>'+
'<div class="row block-body">'+
'<div class="col-md-12 block-rules">'+
'</div>'+
'</div>'+
'<div class="row block-footer">'+
'<div class="col-md-4">'+
'<select class="clause-list select-picker rule">'+
this.getClauseList(subClauseList)+
'</select>'+
'</div>'+
'<div class="col-md-2">'+
'<button class="btn btn-primary add-clause-btn" disabled><strong>+</strong> ADD</button>'+
'</div>'+
'</div>'+
'</div>';
return html;
};
this.getClause = function(clauseObj) {
// If dependency is present, spawn dependency fields
if(clauseObj.dependency !== '') {
return this.getClauseMultiple(clauseObj);
}
this.id = 'builder-clause-'+nextId++;
var input = this.getInputFields(clauseObj);
var dataDate = '';
if(clauseObj.type == 'date') {
dataDate += 'data-type="date"';
}
return '<div id="'+this.id+'" class="row block-container clause-container" data-clause="'+clauseObj.clauseName+'">'+
'<div class="col-md-3">'+
'<input type="text" class="clause-name" data-clause-name="'+clauseObj.clauseName+'"'+
'value="'+clauseObj.label+'" '+dataDate+' style="background-color: initial;border: none;" disabled>'+
'</div>'+
'<div class="col-md-3">'+
'<select class="operator-list select-picker">'+
this.getOperatorsList(clauseObj.operators)+
'</select>'+
'</div>'+
'<div class="col-md-4 input-wrapper">'+
input+
'</div>'+
'<div class="col-md-2 button-group">'+
'<a tabindex="0" role="button" class="btn btn-info" style="margin-right:5px;" data-toggle="popover"'+
'title = "Info"'+
'data-placement="left" data-trigger="focus"'+
'data-content = "'+clauseObj.popoverText+'">'+
'<span class="glyphicon glyphicon-info-sign"></span>'+
'</a>'+
'<button type="button" class="btn btn-danger delete-clause-btn">Delete</button>'+
'</div>'+
'</div>';
};
this.getClauseMultiple = function(clauseObj) {
this.id = 'builder-clause-'+nextId++;
var dataDate = '';
if(clauseObj.type == 'date') {
dataDate += 'data-type="date"';
}
var mainInput = this.getInputFields(clauseObj);
var dependency = clauseObj.dependency;
var input = this.getInputFields(clauseObj);
var html = '<div id="'+this.id+'" class="row block-container clause-container" data-clause="'+clauseObj.clauseName+'" data-is-dependent = "true" '+dataDate+'>'+
'<div class="row multiple-clause" data-dep-clause='+clauseObj.clauseName+'>'+
'<div class="col-md-3">'+
'<input type="text" class="clause-name" data-clause-name="'+clauseObj.clauseName+'"'+
'value="'+clauseObj.clauseText+'" style="background-color: initial;border: none;" disabled>'+
'</div>'+
'<div class="col-md-3">'+
'<select class="operator-list select-picker">'+
this.getOperatorsList(clauseObj.operators)+
'</select>'+
'</div>'+
'<div class="col-md-4 input-wrapper">'+
input+
'</div>'+
'<div class="col-md-2 button-group" style="position:relative;">'+
'<a tabindex="0" role="button" class="btn btn-info" style="margin-right:5px;" data-toggle="popover"'+
'title = "Info"'+
'data-placement="left" data-trigger="focus"'+
'data-content = "'+clauseObj.popoverText+'">'+
'<span class="glyphicon glyphicon-info-sign"></span>'+
'</a>'+
'<button type="button" class="btn btn-danger delete-clause-btn">Delete</button>'+
'</div>'+
'</div>';
for(var dep in dependency) {
if(dependency.hasOwnProperty(dep)) {
input = this.getInputFields(dependency[dep]);
if(dependency[dep].type == 'date') {
dataDate = 'data-type="date"';
}
html+= ''+
'<div class="row multiple-clause" data-dep-clause='+dep+'>'+
'<div class="col-md-4">'+
'<input type="text" class="clause-name" data-clause-name="'+dep+'"'+
'value="'+dependency[dep].label+'" '+dataDate+' style="background-color: initial;border: none;" disabled>'+
'</div>'+
'<div class="col-md-3">'+
'<select class="operator-list select-picker">'+
this.getOperatorsList(dependency[dep].operators)+
'</select>'+
'</div>'+
'<div class="col-md-5 input-wrapper">'+
input+
'</div>'+
'</div>';
}
}
html+='</div>';
return html;
};
this.getInputFields = function(clause) {
var inputHtml = '';
var multiple = clause.multiple || false;
var inputType = clause.input;
var defaultOp = clause.operators[0];
var placeholderText = '';
if(typeof clause.placeholder != 'undefined' && clause.placeholder !== '') {
if(typeof clause.placeholder[defaultOp] == 'undefined') {
placeholderText = clause.placeholder.default;
} else {
placeholderText = clause.placeholder[defaultOp];
}
}
if(inputType == 'text') {
var dataType = clause.type;
if(dataType == 'date') {
inputHtml += '<input type="text" class="clause-field datetime-picker" value="" placeholder="'+placeholderText+'">';
}
else {
inputHtml += '<input type="text" class="clause-field" value="" placeholder="'+placeholderText+'">';
}
} else if(inputType == 'select') {
if(multiple) {
inputHtml += '<select class="clause-field" multiple="multiple">';
} else {
inputHtml += '<select class="clause-field">';
}
var values = clause.values;
for(var i=0; i<values.length; i++) {
for(var v in values[i]) {
inputHtml += '<option value="'+v+'">'+values[i][v]+'</option>';
break;
}
}
inputHtml += '</select>';
}
return inputHtml;
};
this.updatedInputFields = function(clause, operator) {
var inputHtml = '';
var multiple = clause.multiple || false;
var inputType = clause.input;
var o = getOperatorFromVal(operator);
// Get placeholder text
var placeholderText = '';
if(typeof clause.placeholder != 'undefined' && clause.placeholder !== '') {
if(typeof clause.placeholder[o] == 'undefined') {
placeholderText = clause.placeholder.default;
} else {
placeholderText = clause.placeholder[o];
}
}
if(inputType == 'text') {
var dataType = clause.type;
var numInputs = all_operators[o].nb_inputs;
while (numInputs-- > 0) {
if(dataType == 'date') {
inputHtml += '<input type="text" class="clause-field datetime-picker" value="" placeholder="'+placeholderText+'>';
}
else {
inputHtml += '<input type="text" class="clause-field" value="" placeholder="'+placeholderText+'">';
}
}
} else if(inputType == 'select') {
if(multiple) {
inputHtml += '<select class="clause-field" multiple="multiple">';
} else {
inputHtml += '<select class="clause-field">';
}
var values = clause.values;
for(var i=0; i<values.length; i++) {
for(var v in values[i]) {
inputHtml += '<option value="'+v+'">'+values[i][v]+'</option>';
break;
}
}
inputHtml += '</select>';
}
return inputHtml;
};
this.getClauseList = function(pClause) {
clauseList = pClause;
var optionList = '<option value="-1">Select Condition</option>';
for(var clause in clauseList) {
if(clauseList.hasOwnProperty(clause)) {
optionList += '<option value="'+clause+'">'+clauseList[clause]+'</option>';
}
}
return optionList;
};
this.getOperatorsList = function(clauseOperators) {
var optionList = '';
if (clauseOperators.indexOf('ago') > -1) {
optionList +='<optgroup label="Absolute Date">';
}
for(var operator in clauseOperators) {
var o = clauseOperators[operator];
var val = all_operators[o].val;
if(o == 'ago') {
optionList += '</optgroup><optgroup label="Relative Date">';
}
optionList += '<option value="'+val+'">'+all_operators[o].name+'</option>';
}
if (clauseOperators.indexOf('ago') > -1) {
optionList +='</optgroup>';
}
return optionList;
};
this.getGroup = function(group) {
this.id = 'builder-group-'+group;
var subclauses = getApplicableClauses(group);
var list = this.getClauseList(subclauses);
var clauseObj = getClauseObject(group);
var html = ''+
'<div class="row block-container" data-clause="'+group+'">'+
'<div class="row block-header">'+
'<div class="col-md-2 condition-wrapper">'+
'<select class="condition-list select-picker condition">'+
'<option value="and">AND</option>'+
'<option value="or">OR</option>'+
'</select>'+
'</div>'+
'<div class="col-md-8">'+
'<label>'+clauseObj.clauseText+'</label>'+
'</div>'+
'<div class="col-md-2 button-group">'+
'<button class="delete-clause-btn btn btn-danger">Delete</button>'+
'</div>'+
'</div>'+
'<div class="row block-body">'+
'<div class="col-md-12 block-rules">'+
'</div>'+
'</div>'+
'<div class="row block-footer">'+
'<div class="col-md-4">'+
'<select class="clause-list select-picker rule">'+
list+
'</select>'+
'</div>'+
'<div class="col-md-2">'+
'<button class="btn btn-primary add-clause-btn" disabled><strong>+</strong> ADD</button>'+
'</div>'+
'</div>'+
'</div>';
return html;
};
};
var QueryBuilder = function($el) {
this.$el = $el;
this.htmlGenerator = new HTMLGenerator();
// Init Querybuilder
this.$el.addClass('query-builder row').show();
this.init = function() {
var that = this;
fetchConditionals(function() {
that.bgcounter = 0;
that.existingClauses = [];
that.groups = getInitialGroups();
that.$el.append(that.htmlGenerator.inithtml(that.groups));
// Init select2
that.$el.find('select').css('width','100%').select2();
// Init popover
$('[data-toggle="popover"]').popover();
that.$addBtn = that.$el.find('.add-block-btn');
});
};
this.addClause = function(clause, $parent, condition) {
this.setClause(clause);
var subclauses = getApplicableClauses(clause);
if(subclauses !== '') {
var blockHtml = this.htmlGenerator.getBlock(clause, subclauses);
// Check if previous block is present, if present replace
if($parent.find('.block-container').length > 0) {
$parent.find('.block-container').first().remove();
}
$b = $(blockHtml).appendTo($parent).addClass('push-right-5');
// $b.find('')
}
else {
var clauseObj = getClauseObject(clause);
var clauseHtml = this.htmlGenerator.getClause(clauseObj);
// Check if previous clause is present, if present replace that clause
if($parent.find('.block-container').length > 0) {
$parent.find('.block-container').first().remove();
}
var $c = $(clauseHtml).appendTo($parent).addClass('push-right-5');
$c.find('select').selectize();
}
};
this.cloneClause = function(clause, $parent, condition) {
this.setClause(clause);
var subclauses = getApplicableClauses(clause);
// var bg = colorPalette[this.bgcounter];
// this.bgcounter = (this.bgcounter+1) % (colorPalette.length);
if(subclauses !== '') {
var blockHtml = this.htmlGenerator.getBlock(clause, subclauses);
/*$blocks = $parent.find('.block-container[data-clause]');
if($blocks.length > 0) {
$blocks.last().after('<div class="condition-name label label-primary">'+condition.toUpperCase()+'</div>');
}*/
$b = $(blockHtml).appendTo($parent.find('> .block-body > .block-rules')).addClass('push-right-5');
$b.find('select')
.not($b.find(' >.block-container select'))
.css('width','100%')
.select2();
// $b.addClass(bg);
$parent.find('> .block-footer select.rule').val('-1').trigger('change');
}
else {
var clauseObj = getClauseObject(clause);
var clauseHtml = this.htmlGenerator.getClause(clauseObj);
/*$blocks = $parent.find('.block-container[data-clause]');
if($blocks.length > 0) {
$blocks.last().after('<div class="condition-name label label-primary">'+condition.toUpperCase()+'</div>');
}*/
var $c = $(clauseHtml).appendTo($parent.find('> .block-body > .block-rules')).addClass('push-right-5');
$c.find('select').css('width','100%').select2();
// $c.addClass(bg);
$parent.find('> .block-footer select.rule').val('-1').trigger('change');
if($c.find('input.datetime-picker').length >0)
{
$c.find('input.datetime-picker').datepicker({
format : 'yyyy-mm-dd'
});
}
}
// Init popover
$('[data-toggle="popover"]').popover();
};
this.updateClause = function(clause, operator, $c) {
var $cobj = $c;
var clauseObject = getClauseObject(clause);
var o = getOperatorFromVal(operator);
if(typeof $c.attr('data-is-dependent') != 'undefined' && $c.attr('data-is-dependent') != false) {
$cobj = $c.find('.multiple-clause[data-dep-clause="'+clause+'"]');
}
$cobj.find('select.operator-list').val(operator);
var isDatePicker = false;
if(operator != 'AGO' && operator != 'INTERVAL' && operator != 'UPTO') {
isDatePicker = ($cobj.find('.clause-name').data('type')) == 'date' ? true:false ;
// $cobj.find('.input-wrapper').removeClass('label-inc');
}
$fields = $cobj.find('.clause-field');
var fieldType = 'text';
if($fields.length == 1) {
if($fields.prop('tagName') == 'SELECT') {
fieldType = 'select';
} else {
fieldType = 'text';
}
}
if(o !== '') {
var numInputs = all_operators[o].nb_inputs;
var placeholderText = '';
if(typeof clauseObject.placeholder != 'undefined' && clauseObject.placeholder !== '') {
if(typeof clauseObject.placeholder[o] == 'undefined') {
placeholderText = clauseObject.placeholder.default;
} else {
placeholderText = clauseObject.placeholder[o];
}
}
for(var k =0; k<numInputs; k++) {
if(fieldType == 'text') {
var ptext = ($.isArray(placeholderText)) ? placeholderText[k] : placeholderText;
$fields.remove();
if(isDatePicker) {
$('<input type="text" class="clause-field datetime-picker" value="" '+
'placeholder="'+ptext+'">')
.appendTo($cobj.find('.input-wrapper'))
.datepicker({
format : 'yyyy-mm-dd'
});
// $cobj.find('.input-wrapper').addClass('label-inc');
}
else {
$('<input type="text" class="clause-field" value=""'+
'placeholder="'+ptext+'">')
.appendTo($cobj.find('.input-wrapper'));
// $cobj.find('.input-wrapper').addClass('label-inc');
}
} else if(fieldType == 'select') {
$fields.select2('destroy').remove();
var fieldhtml = this.htmlGenerator.updatedInputFields(clauseObject, operator);
$(fieldhtml).appendTo($cobj.find('.input-wrapper'))
.css('width', '100%')
.select2();
}
}
/*if(numInputs >1) {
var $ips = $cobj.find('.input-wrapper input');
$($ips[0]).attr('placeholder','From');
$($ips[1]).attr('placeholder', 'To');
}*/
}
};
this.setClause = function(clause) {
var c = {};
c.clauseName = clause;
this.existingClauses.push(c);
};
this.addGroup = function(group, condition) {
// if(condition != '-1') {
var groupHtml = this.htmlGenerator.getGroup(group);
//console.log(groupHtml);
$g = $(groupHtml).appendTo(this.$el.find('> .block-body > .block-rules'));
$g.addClass('push-right-5')
.find('select')
.not($g.find('> .block-container select'))
.css('width','100%')
.select2();
this.$el.find('> .block-footer select.rule').val('-1').trigger('change');
// }
};
this.cloneGroup = function(group, condition) {
var groupHtml = this.htmlGenerator.getGroup(group);
$groups = this.$el.find('> .block-container');
// if($groups.length > 0) {
// $groups.last().after('<div class="condition-name label label-primary">'+condition.toUpperCase()+'</div>');
// }
this.$el.append(groupHtml);
};
this.getJson = function() {
$root = this.$el;
var output = _getJson($root);
return JSON.stringify(output, null, 2);
};
this.parseJson = function(json) {
$root = this.$el;
try {
var jsonObj = JSON.parse(json);
this.clear();
this.init();
_jsonToBuilder($root, jsonObj);
} catch(e) {
console.log("Invalid Json.\n Exception: "+e);
}
};
this.validate = function() {
return _validateBuilder(this.$el);
};
this.clear = function() {
$root = this.$el;
$root.empty();
};
};
$.fn.querybuilder = function() {
$el = this;
$builder = new QueryBuilder($el);
return $builder;
};
|
define([
'client/controllers/module',
'common/modules/visitors-realtime',
'client/collections/realtime',
'client/views/visualisations/visitors-realtime'
],
function (ModuleController, RealtimeModule, RealtimeCollection, VisitorsRealtimeView) {
return ModuleController.extend(RealtimeModule).extend({
visualisationClass: VisitorsRealtimeView,
collectionClass: RealtimeCollection
});
});
|
import HttpHelper from './http-helper';
import Storage from './storage';
class Utils {
constructor(args = {}) {
const { baseUrl } = args;
this.baseUrl = baseUrl;
this.httpHelper = new HttpHelper();
this.storage = new Storage();
}
getAll() {
return {
httpHelper: this.httpHelper,
storage: this.storage,
};
}
static getNameInitials = (name) => {
const initials = name.match(/\b\w/g) || [];
return ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
};
}
export default Utils;
|
/**
* Created by Vincent on 2014/5/15.
*/
YIGO.ui.portal.intro = function(force){
var version = 1;
var cKey = 'yigoPortalIntro'+version;
var start = document.cookie.indexOf(cKey),end;
var date = new Date();
date.setTime(date.getTime() + 30*24*60*60*1000);
if(start<0)
document.cookie = cKey + '=1;expires='+ date.toGMTString();
else{
end = document.cookie.indexOf(';',start);
var value = document.cookie.substring(start,end);
var visitTime = value.split('=')[1];
if(visitTime>0 && !force){
document.cookie = cKey + '=' + (Number(visitTime)+1)+";expires="+ date.toGMTString();
return;
}
else
document.cookie = cKey + '=' + (Number(visitTime)+1)+";expires="+ date.toGMTString();
}
$.getScript('../js/intro.js-0.8.0/intro.min.js',function(){
var intro = introJs();
intro.setOptions({
nextLabel : '继续',
prevLabel : '上一步',
skipLabel : '退出引导',
doneLabel : '结束',
exitOnOverlayClick : false,
steps: [
{
intro: "<b>您好!Portal页面已更新,简单介绍一下!</b><p>回车和方向键控制步骤,ESC键退出。点击下面小圆点可直接跳至该步骤</p>"
},
{
element: document.querySelector('.head'),
intro: "<b>页面头部空间缩小至原来的一半</b>"
},
{
element: document.querySelector('.p_logo'),
intro: "<b>替换掉YIGO Cloud logo</b>"
},
{
element: document.querySelector('.funcEntrance'),
intro: "<b>功能导航相对位置保持一致</b>"
},
{
element: '搜索面板',
intro:'<dt>输入框</dt><dd>可以搜索当前用户可以使用的菜单入口。</dd><dd>支持汉字拼音及模糊查询。</dd><dd>例如想要找到"工作流执行图"这个入口,可以输入"工作执行","gzzhix","工作zhixing"进行搜索。</dd><dd>搜索结果显示六条记录,项目中可根据需求增加或减少。</dd>'
+'<dt>常用功能</dt><dd>根据用户打开菜单入口的频率,呈现出最频繁使用的入口。默认显示四个,可根据需求调整此数量。</dd><dd>此项功能需要HTML5 INDEXDB支持,如果您无法使用此功能,请根据面板里的提示升级浏览器。</dd>'
},
{
element: '菜单',
intro:"<b>Allmenu菜单</b>"
},
{
element: '#logInfo',
intro: '<dt>用户信息</dt><dd>这里只显示用户名,<em>请将鼠标悬停至用户名,</em>可以看见整个登录信息菜单。</dd><dd>这里呈现后台配置statusBar的所有内容</dd><dd><em>"退出系统"</em>的功能也被移动到这个悬浮面板当中。</dd>',
position: 'left'
},
{
element: '#portalOpts',
intro: '<dt>设置</dt><dd><em>请将鼠标悬停至此</em>,可以看见设置功能面板。</dd><dd>目前有"修改密码"和"RebuilAll",添加了操作向导重播按钮,项目上也可根据自己的需求二次开发添加或删除相关功能。</dd>',
position: 'left'
},
{
element: '.p_treeMenu_trigger',
intro: '<dt>树形菜单按钮</dt><dd>默认情况下该页面中并不直接显示树形allMenu,通过点击此按钮可触发显示隐藏的树形菜单。</dd><dd>项目上可以通过相关配置决定使用哪种菜单UI,目前新WEB已经提供三种allMenu的渲染方式。</dd>',
position:'right'
},
{
element: '树形菜单',
intro: '<dt>树形菜单</dt><dd>与applet版本操作相似的树形allMenu。</dd><dd>搜索功能目前只能搜索汉字,<em>输入关键字以后按下回车即可。</em></dd><dd>加入了便捷的<em>"关注单据"</em>功能,菜单中"关注菜单"节点中罗列了用户关注过的具体单据,例如张三在某天填写的某一张出库通知单。</dd><dd>"关注单据"目前暂时为隐藏功能,打开具体单据后<em>按下"Ctrl+K"添加关注,"Ctrl+L"取消关注</em>。</dd>'
},
{
intro: '<b>开始!</b><p><a href="http://scmhacks.yi.org:8000/trac/yigo/wiki/WikiStart" target="_blank">点击查阅更多版本更新信息</a></p><p>Tips:该向导只会在出现重要更新时第一次访问出现,重播功能在页面右上角的设置中</p>'
}
]
});
intro.onchange(function() {
switch(this._currentStep){
case 3:
var menuNav = YIGO.portalCompMgr.get('allMenuNav');
if(menuNav && menuNav.menu.el)
menuNav.hideMenu();
break;
case 4:
var menuNav = YIGO.portalCompMgr.get('allMenuNav');
if(menuNav)
menuNav.showMenu();
this._introItems[4].element = $('.p_menu_srchPanel')[0];
this._introItems[4].position='right';
break;
case 5:
var menuNav = YIGO.portalCompMgr.get('allMenuNav');
if(menuNav)
menuNav.showMenu();
this._introItems[5].element = $('.y_menu_navBox')[0];
this._introItems[5].position='right';
break;
case 6:
var menuNav = YIGO.portalCompMgr.get('allMenuNav');
if(menuNav)
menuNav.hideMenu();
break;
case 8:
var treeMenuPanel = YIGO.portalCompMgr.get('treeMenuPanel');
if(treeMenuPanel)
treeMenuPanel.expandPanel(false);
break;
case 9:
var treeMenuPanel = YIGO.portalCompMgr.get('treeMenuPanel');
if(treeMenuPanel)
treeMenuPanel.el.style.left=0;
this._introItems[9].element = treeMenuPanel.el;
this._introItems[9].position='right';
break;
case 10:
var treeMenuPanel = YIGO.portalCompMgr.get('treeMenuPanel');
treeMenuPanel.expandPanel(false);
break;
}
});
intro.onexit(function(){
if(YIGO.portalCompMgr.get('treeMenuPanel'))
YIGO.portalCompMgr.get('treeMenuPanel').expandPanel(false);
if(YIGO.portalCompMgr.get('allMenuNav'))
YIGO.portalCompMgr.get('allMenuNav').hideMenu();
})
intro.start();
})
}
|
import React from 'react';
import { withRouter } from 'react-router-dom';
import { Query, graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { Polyline } from 'react-leaflet'
import { withStyles } from '@material-ui/core/styles';
import Toolbar from '@material-ui/core/Toolbar';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import ResortLiftsMap from './ResortLiftsMap';
import ResortNotFound from '../../app/ResortNotFound';
import withQuery from '../../common/withQuery';
import Locations from '../../app/Locations';
export const query = gql`
query ResortAndLifts($id: Int!) {
resort(id: $id) {
id,
name,
location { lat, lng },
liftEnvelope { lat, lng},
lifts { id },
}
}
`;
const intersectingLiftsQuery = gql`
query IntersectingLifts($topLeft: LocationInput!, $bottomRight: LocationInput!) {
intersectingLifts(topLeft: $topLeft, bottomRight: $bottomRight) {
id,
name,
resort { id },
stations { location { lat, lng } },
}
}
`;
const updateAssignedLiftsMutation = gql`
mutation UpdateResortAssignedLifts($id: Int!, $liftIDs: [Int!]) {
updateResortAssignedLifts(id: $id, liftIDs: $liftIDs) {
id,
name,
location { lat, lng },
liftEnvelope { lat, lng},
lifts { id },
}
}
`;
const styles = theme => ({
map: {
height: 'calc(100vh - 160px)',
},
});
class ResortLifts extends React.Component {
state = {};
handleAssignLift = id => {
this.setState({
assignedLiftIDs: [
id,
...this.state.assignedLiftIDs
]
});
}
handleUnassignLift = id => {
const assignedLiftIDs = this.state.assignedLiftIDs.slice();
const index = assignedLiftIDs.indexOf(id);
if (index > -1) {
assignedLiftIDs.splice(index, 1);
this.setState({
assignedLiftIDs
});
}
}
handleMapBoundsChange = boundingBox => {
this.setState({
topLeft: boundingBox.getNorthWest(),
bottomRight: boundingBox.getSouthEast(),
});
};
handleSave = () => {
this.props.saveAssignedLifts(this.props.id, this.state.assignedLiftIDs);
this.navigateBack();
}
handleCancel = () => this.navigateBack();
navigateBack() {
const { id, history } = this.props;
history.push(Locations.Resort.toUrl({ id }));
}
render() {
const { id, resort, classes } = this.props;
const { assignedLiftIDs, topLeft, bottomRight } = this.state;
return (
<Paper>
<Toolbar>
<Typography variant='headline' style={{ flex: 'auto' }}>{`Assign ${resort.name} lifts`}</Typography>
<Button color='primary' onClick={this.handleCancel}>Cancel</Button>
<Button color='primary' variant='outlined' onClick={this.handleSave}>Save</Button>
</Toolbar>
<div className={classes.map}>
<ResortLiftsMap
resortLocation={resort.location}
bounds={resort.liftEnvelope}
onBoundsChange={this.handleMapBoundsChange}
>
{topLeft && <Query
query={intersectingLiftsQuery}
variables={{ topLeft, bottomRight }}
>
{({ error, data }) => {
if (error) {
console.log(error);
return null;
}
if (data.intersectingLifts === undefined) {
return null;
}
return data.intersectingLifts.map(lift => {
const assigned = assignedLiftIDs.includes(lift.id);
return <Polyline
positions={lift.stations.map(station => station.location)}
key={lift.id}
id={lift.id}
onClick={() => assigned ? this.handleUnassignLift(lift.id) : this.handleAssignLift(lift.id)}
color={assigned ? 'blue' : 'grey'}
/>;
});
}}
</Query>}
</ResortLiftsMap>
</div>
</Paper>
);
}
static getDerivedStateFromProps(props, state) {
const { assignedLiftIDs } = state || {};
const { resort } = props;
if (resort && assignedLiftIDs === undefined) {
return {
assignedLiftIDs: resort.lifts.map(lift => lift.id),
}
} else {
return null;
}
}
}
export default compose(
withStyles(styles),
withRouter,
withQuery(query, 'resort', ResortNotFound),
graphql(updateAssignedLiftsMutation, {
name: 'updateAssignedLifts',
props: ({ updateAssignedLifts }) => ({
saveAssignedLifts: (id, liftIDs) =>
updateAssignedLifts({
variables: {
id,
liftIDs,
}
}),
})
}),
)(ResortLifts);
|
const hola = "hola ";
function name(params) {
console.log('hola');
}
|
/* eslint-disable no-undef */
window.addEventListener('load', () => {
/* Set up a Realtime client that authenticates with the local web server auth endpoint */
var result = document.getElementById('result');
result.value += 'On login page now\n';
function login(e) {
e.preventDefault();
result.value += 'Fetching JWT token from auth server\n';
const realtime = new Ably.Realtime({ authUrl: 'https://ably.com/ably-auth/jwt-token/demos' });
realtime.connection.once('connected', () => {
console.log('Client connected to Ably');
result.value += 'Client connected to Ably using JWT\n';
alert('Client successfully connected to Ably using JWT auth');
});
}
document.querySelector('p:submit > button').onclick = login;
});
|
'use strict';
const heredoc = require('heredoc'),
sendQuery = require('./helpers/accessDb').sendQuery,
getAllFriends = require('./getAllFriends');
const getUserQuery = heredoc(function () {/*
SELECT * FROM users WHERE key = ?;
*/});
const getUserFromWalletIdQuery = heredoc(function () {/*
SELECT * FROM users WHERE wallet_id = $wallet_id;
*/});
const getUserLocation = heredoc(function () {/*
SELECT * FROM location WHERE user_id = ?;
*/});
const getRandomIntInclusive = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const getLocationForRandomUser = function(friendsArray, cb) {
let randomNum = getRandomIntInclusive(0, friendsArray.length - 1);
let randomUser = friendsArray[randomNum];
let location;
sendQuery(getUserLocation, randomUser.key, (err, rows) => {
if (err) {
cb(err);
} else {
cb(null, location);
}
})
}
const calculateLocation = function(userInfo, cb) {
if (userInfo instanceof Object) {
getLocation(userInfo, cb);
} else {
sendQuery(getUserFromWalletIdQuery, {$wallet_id: userInfo}, (err, rows) => {
if (err) {
cb(err);
} else {
getLocation(rows[0], cb);
}
})
}
}
const getLocation = function(userObj, cb) {
console.log(userObj);
let user, friends;
sendQuery(getUserQuery, userObj.key, (err, rows) => {
if (err) {
cb(err);
} else {
user = rows[0];
getAllFriends(userObj, (err, results) => {
if (err) {
cb(err);
} else {
friends = results;
if (friends && friends.length > 0) {
friends.push(user);
getLocationForRandomUser(friends, cb);
}
}
});
}
});
}
module.exports = calculateLocation;
|
/* eslint-disable indent */
module.exports = {
friendlyName: 'Tester',
description: 'Tester.',
inputs: {},
exits: {
success: {
description: 'Tester: persons were found',
responseType: ''
},
notFound: {
description: 'Tester: no persons were found.',
responseType: 'notFound'
}
},
fn: async function(inputs, exits) {
var TesterTree = await sails.sendNativeQuery('call tester()', []);
console.log('ReturnVal= ' + JSON.stringify(TesterTree));
if (TesterTree.rows[0].length === 0) {
return exits.notFound({
message: 'TesterTree NO persons were found downwards!'
});
} else {
return exits.success({
message: 'TesterTree persons were found downwards!',
data: TesterTree.rows
});
}
}
};
|
import React, { useState } from 'react';
export default function Wishlist() {
const [hoverstate, setHoverstate] = useState();
const mouseEnter = (i) => {
const change = new Array(9).fill(0);
change[i] = 1;
setHoverstate(change);
};
const mouseLeave = (i) => {
const change = new Array(9).fill(0);
change[i] = 0;
setHoverstate(change);
};
return (
<div className="col-lg aside container">
<h2 className = "text-center">My Wishlist</h2>
<div
className="prd-grid product-listing data-to-show-3 data-to-show-md-3 data-to-show-sm-2 js-category-grid"
data-grid-tab-content=""
>
<div
onMouseEnter={() => mouseEnter(0)}
onMouseLeave={() => mouseLeave(0)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${
hoverstate?.[0] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-02-1.webp"
data-src="images/skins/fashion/products/product-02-1.webp"
alt="Oversize Cotton Dress"
className="js-prd-img fade-up ls-is-cached lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels"></div>
</a>
<div className="prd-circle-labels">
<a
href="/"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="/"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="/"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
<div className="colorswatch-label colorswatch-label--variants js-prd-colorswatch">
<i className="icon-palette">
<span className="path1"></span>
<span className="path2"></span>
<span className="path3"></span>
<span className="path4"></span>
<span className="path5"></span>
<span className="path6"></span>
<span className="path7"></span>
<span className="path8"></span>
<span className="path9"></span>
<span className="path10"></span>
</i>
<ul>
<li data-image="images/skins/fashion/products/product-02-1.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img
src="images/colorswatch/color-orange.webp"
alt=""
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-color-2.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img src="images/colorswatch/color-red.webp" alt="" />
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-color-3.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img
src="images/colorswatch/color-yellow.webp"
alt=""
/>
</a>
</li>
</ul>
</div>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-02-1.webp"
className="active"
>
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-1.webp"
data-src="images/skins/fashion/products/product-02-1.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-2.webp">
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-2.webp"
data-src="images/skins/fashion/products/product-02-2.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-3.webp">
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-3.webp"
data-src="images/skins/fashion/products/product-02-3.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="/">Seiko</a>
</div>
<h2 className="prd-title">
<a href="product.html">Oversize Cotton Dress</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="/"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="/"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="/"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(1)}
onMouseLeave={() => mouseLeave(1)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${
hoverstate?.[1] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-03-1.webp"
data-src="images/skins/fashion/products/product-03-1.webp"
alt="Oversized Cotton Blouse"
className="js-prd-img fade-up lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels">
<div className="label-new">
<span>New</span>
</div>
<div className="label-sale">
<span>
-10% <span className="sale-text">Sale</span>
</span>
<div className="countdown-circle">
<div
className="countdown js-countdown"
data-countdown="2021/07/01"
>
<span>
<span>39</span>DAYS
</span>
<span>
<span>04</span>HRS
</span>
<span>
<span>42</span>MIN
</span>
<span>
<span>43</span>SEC
</span>
</div>
</div>
</div>
</div>
</a>
<div className="prd-circle-labels">
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="#"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-03-1.webp"
className="active"
>
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-1.webp"
data-src="images/skins/fashion/products/product-03-1.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-03-2.webp">
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-2.webp"
data-src="images/skins/fashion/products/product-03-2.webp"
className="fade-up lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-03-3.webp">
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-3.webp"
data-src="images/skins/fashion/products/product-03-3.webp"
className="fade-up lazyloaded"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="#">Banita</a>
</div>
<h2 className="prd-title">
<a href="product.html">Oversized Cotton Blouse</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversized Cotton Blouse", "path":"images/skins/fashion/products/product-03-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="#"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-old">$ 200</div>
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversized Cotton Blouse", "path":"images/skins/fashion/products/product-03-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(2)}
onMouseLeave={() => mouseLeave(2)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-outstock prd-w-xl ${
hoverstate?.[2] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-07-1.webp"
data-src="images/skins/fashion/products/product-07-1.webp"
alt="Denim Mini Skirt"
className="js-prd-img fade-up lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels">
<div className="label-outstock">
<span>Sold Out</span>
</div>
</div>
</a>
<div className="prd-circle-labels">
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="#"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-07-1.webp"
className="active"
>
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
data-src="images/skins/fashion/products/product-07-1.webp"
className="lazyload fade-up"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="#">Banita</a>
</div>
<h2 className="prd-title">
<a href="product.html">Denim Mini Skirt</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Denim Mini Skirt", "path":"images/skins/fashion/products/product-07-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="#"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Denim Mini Skirt", "path":"images/skins/fashion/products/product-07-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(3)}
onMouseLeave={() => mouseLeave(3)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${
hoverstate?.[3] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-02-1.webp"
data-src="images/skins/fashion/products/product-02-1.webp"
alt="Oversize Cotton Dress"
className="js-prd-img fade-up ls-is-cached lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels"></div>
</a>
<div className="prd-circle-labels">
<a
href="/"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="/"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="/"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
<div className="colorswatch-label colorswatch-label--variants js-prd-colorswatch">
<i className="icon-palette">
<span className="path1"></span>
<span className="path2"></span>
<span className="path3"></span>
<span className="path4"></span>
<span className="path5"></span>
<span className="path6"></span>
<span className="path7"></span>
<span className="path8"></span>
<span className="path9"></span>
<span className="path10"></span>
</i>
<ul>
<li data-image="images/skins/fashion/products/product-02-1.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img
src="images/colorswatch/color-orange.webp"
alt=""
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-color-2.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img src="images/colorswatch/color-red.webp" alt="" />
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-color-3.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img
src="images/colorswatch/color-yellow.webp"
alt=""
/>
</a>
</li>
</ul>
</div>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-02-1.webp"
className="active"
>
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-1.webp"
data-src="images/skins/fashion/products/product-02-1.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-2.webp">
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-2.webp"
data-src="images/skins/fashion/products/product-02-2.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-3.webp">
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-3.webp"
data-src="images/skins/fashion/products/product-02-3.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="/">Seiko</a>
</div>
<h2 className="prd-title">
<a href="product.html">Oversize Cotton Dress</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="/"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="/"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="/"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(4)}
onMouseLeave={() => mouseLeave(4)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${
hoverstate?.[4] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-03-1.webp"
data-src="images/skins/fashion/products/product-03-1.webp"
alt="Oversized Cotton Blouse"
className="js-prd-img fade-up lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels">
<div className="label-new">
<span>New</span>
</div>
<div className="label-sale">
<span>
-10% <span className="sale-text">Sale</span>
</span>
<div className="countdown-circle">
<div
className="countdown js-countdown"
data-countdown="2021/07/01"
>
<span>
<span>39</span>DAYS
</span>
<span>
<span>04</span>HRS
</span>
<span>
<span>42</span>MIN
</span>
<span>
<span>43</span>SEC
</span>
</div>
</div>
</div>
</div>
</a>
<div className="prd-circle-labels">
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="#"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-03-1.webp"
className="active"
>
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-1.webp"
data-src="images/skins/fashion/products/product-03-1.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-03-2.webp">
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-2.webp"
data-src="images/skins/fashion/products/product-03-2.webp"
className="fade-up lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-03-3.webp">
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-3.webp"
data-src="images/skins/fashion/products/product-03-3.webp"
className="fade-up lazyloaded"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="#">Banita</a>
</div>
<h2 className="prd-title">
<a href="product.html">Oversized Cotton Blouse</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversized Cotton Blouse", "path":"images/skins/fashion/products/product-03-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="#"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-old">$ 200</div>
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversized Cotton Blouse", "path":"images/skins/fashion/products/product-03-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(5)}
onMouseLeave={() => mouseLeave(5)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-outstock prd-w-xl ${
hoverstate?.[5] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-07-1.webp"
data-src="images/skins/fashion/products/product-07-1.webp"
alt="Denim Mini Skirt"
className="js-prd-img fade-up lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels">
<div className="label-outstock">
<span>Sold Out</span>
</div>
</div>
</a>
<div className="prd-circle-labels">
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="#"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-07-1.webp"
className="active"
>
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
data-src="images/skins/fashion/products/product-07-1.webp"
className="lazyload fade-up"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="#">Banita</a>
</div>
<h2 className="prd-title">
<a href="product.html">Denim Mini Skirt</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Denim Mini Skirt", "path":"images/skins/fashion/products/product-07-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="#"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Denim Mini Skirt", "path":"images/skins/fashion/products/product-07-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(6)}
onMouseLeave={() => mouseLeave(6)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${
hoverstate?.[6] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-02-1.webp"
data-src="images/skins/fashion/products/product-02-1.webp"
alt="Oversize Cotton Dress"
className="js-prd-img fade-up ls-is-cached lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels"></div>
</a>
<div className="prd-circle-labels">
<a
href="/"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="/"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="/"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
<div className="colorswatch-label colorswatch-label--variants js-prd-colorswatch">
<i className="icon-palette">
<span className="path1"></span>
<span className="path2"></span>
<span className="path3"></span>
<span className="path4"></span>
<span className="path5"></span>
<span className="path6"></span>
<span className="path7"></span>
<span className="path8"></span>
<span className="path9"></span>
<span className="path10"></span>
</i>
<ul>
<li data-image="images/skins/fashion/products/product-02-1.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img
src="images/colorswatch/color-orange.webp"
alt=""
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-color-2.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img src="images/colorswatch/color-red.webp" alt="" />
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-color-3.webp">
<a
className="js-color-toggle"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Color Name"
>
<img
src="images/colorswatch/color-yellow.webp"
alt=""
/>
</a>
</li>
</ul>
</div>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-02-1.webp"
className="active"
>
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-1.webp"
data-src="images/skins/fashion/products/product-02-1.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-2.webp">
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-2.webp"
data-src="images/skins/fashion/products/product-02-2.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-02-3.webp">
<a
href="/"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-02-3.webp"
data-src="images/skins/fashion/products/product-02-3.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="/">Seiko</a>
</div>
<h2 className="prd-title">
<a href="product.html">Oversize Cotton Dress</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="/"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="/"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="/"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversize Cotton Dress", "path":"images/skins/fashion/products/product-02-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(7)}
onMouseLeave={() => mouseLeave(7)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-w-xl ${
hoverstate?.[7] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-03-1.webp"
data-src="images/skins/fashion/products/product-03-1.webp"
alt="Oversized Cotton Blouse"
className="js-prd-img fade-up lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels">
<div className="label-new">
<span>New</span>
</div>
<div className="label-sale">
<span>
-10% <span className="sale-text">Sale</span>
</span>
<div className="countdown-circle">
<div
className="countdown js-countdown"
data-countdown="2021/07/01"
>
<span>
<span>39</span>DAYS
</span>
<span>
<span>04</span>HRS
</span>
<span>
<span>42</span>MIN
</span>
<span>
<span>43</span>SEC
</span>
</div>
</div>
</div>
</div>
</a>
<div className="prd-circle-labels">
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="#"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-03-1.webp"
className="active"
>
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-1.webp"
data-src="images/skins/fashion/products/product-03-1.webp"
className="fade-up ls-is-cached lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-03-2.webp">
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-2.webp"
data-src="images/skins/fashion/products/product-03-2.webp"
className="fade-up lazyloaded"
alt="Color Name"
/>
</a>
</li>
<li data-image="images/skins/fashion/products/product-03-3.webp">
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="images/skins/fashion/products/product-03-3.webp"
data-src="images/skins/fashion/products/product-03-3.webp"
className="fade-up lazyloaded"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="#">Banita</a>
</div>
<h2 className="prd-title">
<a href="product.html">Oversized Cotton Blouse</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversized Cotton Blouse", "path":"images/skins/fashion/products/product-03-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="#"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-old">$ 200</div>
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Oversized Cotton Blouse", "path":"images/skins/fashion/products/product-03-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div
onMouseEnter={() => mouseEnter(8)}
onMouseLeave={() => mouseLeave(8)}
className={`prd prd--style2 prd-labels--max prd-labels-shadow prd-outstock prd-w-xl ${
hoverstate?.[8] ? 'hovered' : ''
}`}
>
<div className="prd-inside">
<div className="prd-img-area">
<a
href="product.html"
className="prd-img image-hover-scale image-container"
style={{ paddingBottom: '128.48%' }}
>
<img
src="images/skins/fashion/products/product-07-1.webp"
data-src="images/skins/fashion/products/product-07-1.webp"
alt="Denim Mini Skirt"
className="js-prd-img fade-up lazyloaded"
/>
<div className="generic-loader"></div>
<div className="prd-big-squared-labels">
<div className="label-outstock">
<span>Sold Out</span>
</div>
</div>
</a>
<div className="prd-circle-labels">
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
<a
href="#"
className="circle-label-qview js-prd-quickview prd-hide-mobile"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
<ul className="list-options color-swatch">
<li
data-image="images/skins/fashion/products/product-07-1.webp"
className="active"
>
<a
href="#"
className="js-color-toggle"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Color Name"
>
<img
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
data-src="images/skins/fashion/products/product-07-1.webp"
className="lazyload fade-up"
alt="Color Name"
/>
</a>
</li>
</ul>
</div>
<div className="prd-info">
<div className="prd-info-wrap">
<div className="prd-info-top">
<div className="prd-rating">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
</div>
<div className="prd-rating justify-content-center">
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
<i className="icon-star-fill fill"></i>
</div>
<div className="prd-tag">
<a href="#">Banita</a>
</div>
<h2 className="prd-title">
<a href="product.html">Denim Mini Skirt</a>
</h2>
<div className="prd-description">
Quisque volutpat condimentum velit. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Nam nec ante sed lacinia.
</div>
<div className="prd-action">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Denim Mini Skirt", "path":"images/skins/fashion/products/product-07-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
<div className="prd-hovers">
<div className="prd-circle-labels">
<div>
<a
href="#"
className="circle-label-compare circle-label-wishlist--add js-add-wishlist mt-0"
title="Add To Wishlist"
>
<i className="icon-heart-stroke"></i>
</a>
<a
href="#"
className="circle-label-compare circle-label-wishlist--off js-remove-wishlist mt-0"
title="Remove From Wishlist"
>
<i className="icon-heart-hover"></i>
</a>
</div>
<div className="prd-hide-mobile">
<a
href="#"
className="circle-label-qview js-prd-quickview"
data-src="ajax/ajax-quickview.html"
>
<i className="icon-eye"></i>
<span>QUICK VIEW</span>
</a>
</div>
</div>
<div className="prd-price">
<div className="price-new">$ 180</div>
</div>
<div className="prd-action">
<div className="prd-action-left">
<form action="#">
<button
className="btn js-prd-addtocart"
data-product='{"name": "Denim Mini Skirt", "path":"images/skins/fashion/products/product-07-1.webp", "url":"product.html", "aspect_ratio":0.778}'
>
Add To Cart
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
|
var scriptFiles= [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/bootstrap/dist/js/bootstrap.bundle.js',
'source/js/wizard.js',
]
module.exports = {
scripts: scriptFiles
};
|
import React from "react";
export default function Info(props) {
return (
<div className="radio-info">
<h3 className="btm-txt">CURRENTLY PLAYING</h3>
<p className="radio-info-msg">{props.radioName}</p>
</div>
);
}
|
//工厂应该有厂长,来决定运行哪条生产线
// 消费者->子类
var gongchang={};//定义工厂
//工厂生产衣服方法
gongchang.chanyifu=function(argument){
this.gongren=50; //工人属数量
this.shengchangxiaolv=2;//生产效率
console.log("我们有"+this.gongren+"个工人");
console.log("生产了"+this.gongren*this.shengchangxiaolv+"件衣服")
}
//工厂生产鞋子方法
gongchang.chanxie=function(){
console.log("产鞋子");
}
gongchang.yunshu=function(){
console.log("运输");
}
gongchang.changzhang=function(para){
return new gongchang[para]();
}
var me=gongchang.changzhang('chanyifu');
|
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions.js'
import mutations from './mutations.js'
import getters from './getters.js'
Vue.use(Vuex)
// 存放着组件中信息的状态
const state = {
toPageName: '', //页面返回的路由名字
loginname: '', //用户名称
formPageName: '', //页面来的路由名字
clientDetail: '', //获取的联系人详情
uintDetailList: [], //获取单元列表
reserveObj: '', //获取预订新增的暂存对象
scrollTop: '' //记录高度
}
export default new Vuex.Store({
state,
mutations,
actions,
getters,
})
|
exports.donasi = (id, BotName, tampilTanggal, tampilWaktu, instagram, whatsapp, kapanbotaktif) => {
return `DONASI ${BotName}
*${tampilTanggal}* ⚡️
*${tampilWaktu}* ⚡️
(Waktu Server)
KALIAN BISA DONASI MENGGUNAKAN
🛡 *PULSA*: 089630171792
🛡 *DANA* : 089630171792
🛡 *Untuk yang lain tanyakan*: https://wa.me/6289630171792
*Follow Me On Instagram*
${instagram}
WhatsApp : ${whatsapp}
`
}
|
const updatePrice = () => {
const kitters = document.getElementById('booking_number_of_kiters');
kitters.addEventListener('change', function(){
const price_per_day = parseInt(document.getElementById('experience_price_per_day').innerHTML);
document.getElementById('btn-submit-booking').value = "Book for " + parseInt(kitters.value) * price_per_day + "€";
});
}
export { updatePrice };
|
import { LitElement, html } from 'lit-element';
import { connect } from 'pwa-helpers';
import { deleteFilm } from '../src/redux/actions.js';
import { store } from '../src/redux/store.js';
class ListElement extends connect(store)(LitElement) {
render() {
return html`
<div>
<style>
li {
margin: 20px;
}
.delete-btn {
padding: 2px 10px;
height: 6px;
background-color: red;
border-radius: 2px;
color: #fff;
cursor: pointer;
}
</style>
${this.films === undefined ? html`<p>Nothing found !!!</p>` : ''}
<ul>
${this.films !== undefined ?
this.films.map((item, i) => html`<li>${item.Title} <span class="delete-btn" @click="${() => {store.dispatch(deleteFilm(this.films, i));}}">-</span></li>`)
:
''}
</ul>
</div>
`;
}
static get properties() {
return {
films: {type: Array}
}
}
}
customElements.define('list-element', ListElement);
|
angular.module('lisaApp')
.controller('foodCtrl', ['$scope', '$stateParams', '$rootScope', '$ionicScrollDelegate'
, 'AlimentoService', '$ionicLoading', '$timeout'
, function ($scope, $stateParams, $rootScope, $ionicScrollDelegate
, AlimentoService, $ionicLoading, $timeout) {
var sc = $scope;
var rs = $rootScope;
sc.params = $stateParams;
sc.q = null;
sc.searchBoxChange = function(){
$ionicLoading.show({
content: 'Carregando...',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0,
});
if(sc.q != null){
$timeout(function(){
AlimentoService.findByAttr(sc.q).then(function(res){
if(res.length <= 0){
sc.searchEmpty = 'Nenhum resultado';
}else{
sc.searchEmpty = '';
}
sc.alimentos = res;
$ionicLoading.hide();
rs.$broadcast('scroll.refreshComplete');
$ionicScrollDelegate.scrollTop();
})
}, 2000);
}else{
sc.loadData();
}
}
sc.loadData = function(){
$timeout(function(){
AlimentoService.all().then(function(res){
rs.alimentos = res;
$ionicLoading.hide();
rs.$broadcast('scroll.refreshComplete');
});
}, 2000);
}
sc.searchBoxChange();
}])
|
/*-----------------------------------------------
collision3.js
3剛体の衝突
------------------------------------------------*/
var canvas; //canvas要素
var gl; //WebGL描画用コンテキスト
var camera; //カメラ
var light; //光源
var numRigid = 3;
var rigid = [];
var dummy;
var floor0;
var coord = [];//座標軸表示用
var plane = [0.0, 0.0, 1.0, 0.0];//床平面(z = 0)
var shadow_value = 0.2;
var flagWorld = false;
var dt;
var kind0No = 1;
var kind1No = 1;
//animation
var fps = 0;
var lastTime = new Date().getTime();
var elapseTime = 0.0;//全経過時間
var elapseTime0 = 0.0;
var elapseTime1 = 0.0;
//var time0;
var flagStart = false;
//var flagFreeze = false;
var flagStep = false;
var flagReset = false;
var flagDebug = false;
//軌跡データ用
var flagTrace = false;
var tracePos0 = []; //軌跡配列
var tracePos1 = [];
var tracePos2 = [];
var maxTrace = 100; //軌跡点個数の最大値
var countTrace = 0; //軌跡点個数のカウント
var periodTrace = 0.1;//軌跡点を表示する時間間隔
var timeTrace = 0; //その経過時間
function webMain()
{
// Canvas要素を取得する
canvas = document.getElementById('WebGL');
// WebGL描画用のコンテキストを取得する
gl = WebGLUtils.setupWebGL(canvas);
if (!gl)
{
alert('WebGLコンテキストの取得に失敗');
return;
}
var VS_SOURCE = document.getElementById("vs").textContent;
var FS_SOURCE = document.getElementById("fs").textContent;
if(!initGlsl(gl, VS_SOURCE, FS_SOURCE))
{
alert("GLSL初期化に失敗");
return;
}
//Canvasをクリアする色を設定し、隠面消去機能を有効にする
gl.clearColor(0.4, 0.4, 0.6, 1.0);
gl.enable(gl.DEPTH_TEST);
initCamera();
initObject();
readyTexture();
var animate = function()
{
//繰り返し呼び出す関数を登録
requestAnimationFrame(animate, canvas); //webgl-utilsで定義
//時間計測
var currentTime = new Date().getTime();
var frameTime = (currentTime - lastTime) / 1000.0;//時間刻み[sec]
elapseTime += frameTime;
elapseTime1 += frameTime;
fps ++;
if(elapseTime1 >= 0.5)
{
form1.fps.value = 2*fps.toString(); //1秒間隔で表示
var timestep = 0.5 / fps;
form1.step.value = timestep.toString();
fps = 0;
elapseTime1 = 0.0;
}
lastTime = currentTime;
if(flagStart)
{
collision(dt);
elapseTime0 = elapseTime;//現在の経過時間を保存
form1.time.value = elapseTime.toString();
if(flagStep) { flagStart = false; }
//軌跡データ作成
if(timeTrace == 0)
{
tracePos0[countTrace].copy(rigid[0].vPos);
tracePos1[countTrace].copy(rigid[1].vPos);
tracePos2[countTrace].copy(rigid[2].vPos);
countTrace ++;
if(countTrace >= maxTrace) countTrace = 0;
}
timeTrace += dt;
if(timeTrace >= periodTrace) timeTrace = 0;
display();
}
}
animate();
}
//------------------------------------------------------------------------
function readyTexture()
{
//テクスチャオブジェクトを作成する
var tex = [];
tex[0] = gl.createTexture();
tex[1] = gl.createTexture();
tex[2] = gl.createTexture();
//Imageオブジェクトを作成する
var image = [];
for(var i = 0; i < numRigid; i++) image[i] = new Image();
image[0].src = '../imageJPEG/check3.jpg';
image[1].src = '../imageJPEG/check2.jpg';
image[2].src = '../imageJPEG/check4.jpg';
var flagLoaded = [];//画像読み込み終了フラグ
flagLoaded[0] = false;
flagLoaded[1] = false;
flagLoaded[2] = false;
// 画像の読み込み完了時のイベントハンドラを設定する
image[0].onload = function(){ setTexture(0); }
image[1].onload = function(){ setTexture(1); }
image[2].onload = function(){ setTexture(2); }
function setTexture(no)
{
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);// 画像のY軸を反転する
// テクスチャユニット0を有効にする
if(no == 0) gl.activeTexture(gl.TEXTURE0);
else if(no == 1) gl.activeTexture(gl.TEXTURE1);
else gl.activeTexture(gl.TEXTURE2);
// テクスチャオブジェクトをターゲットにバインドする
gl.bindTexture(gl.TEXTURE_2D, tex[no]);
// テクスチャ画像を設定する
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image[no]);
//ミップマップ自動生成
gl.generateMipmap(gl.TEXTURE_2D);
// テクスチャパラメータを設定する
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
flagLoaded[no] = true;
//2つの画像の読み込み終了後描画
if(flagLoaded[0] && flagLoaded[1] && flagLoaded[2]) display();
}
}
//--------------------------------------------
function initCamera()
{
//カメラと光源の初期設定
//光源インスタンスを作成
light = new Light();
light.pos = [5, 5, 20, 1];
//初期設定値をHTMLのフォームに表示
form2.lightX.value = light.pos[0];
form2.lightY.value = light.pos[1];
form2.lightZ.value = light.pos[2];
//カメラ・インスタンスを作成
camera = new Camera();
camera.dist = 20;
camera.cnt[2] = 5.0;
camera.getPos();//カメラ位置を計算
mouseOperation(canvas, camera);//swgSupport.js
}
function initObject()
{
flagStart = false;
periodTrace = parseFloat(form1.periodTrace.value);
dt = parseFloat(form1.dt.value);//計算時のタイムステップ[s]
restitution = parseFloat(form1.restitution.value);
muK = parseFloat(form1.muK.value);
//オブジェクトの位置,マテリアルを決定する
for(var i = 0; i < numRigid; i++) rigid[i] = new Rigid();
//オブジェクト0
if(kind0No == 0) rigid[0].kind = "CUBE";
else if(kind0No == 1) rigid[0].kind = "SPHERE";
else if(kind0No == 2) rigid[0].kind = "CYLINDER";
rigid[0].vSize.x = parseFloat(form2.size0X.value);
rigid[0].vSize.y = parseFloat(form2.size0Y.value);
rigid[0].vSize.z = parseFloat(form2.size0Z.value);
rigid[0].vPos.x = parseFloat(form2.pos0X.value);
rigid[0].vPos.y = parseFloat(form2.pos0Y.value);
rigid[0].vPos.z = parseFloat(form2.pos0Z.value);
rigid[0].vVel = new Vector3(0, 10, 0);
rigid[0].vEuler.x = parseFloat(form2.ang0X.value);
rigid[0].vEuler.y = parseFloat(form2.ang0Y.value);
rigid[0].vEuler.z = parseFloat(form2.ang0Z.value);
rigid[0].q = getQFromEulerXYZ(rigid[0].vEuler);
rigid[0].vOmega.x = parseFloat(form2.omg0X.value) * 2 * Math.PI;
rigid[0].vOmega.y = parseFloat(form2.omg0Y.value) * 2 * Math.PI;
rigid[0].vOmega.z = parseFloat(form2.omg0Z.value) * 2 * Math.PI;
rigid[0].nSlice =8;// 12;
rigid[0].nStack =8;// 12;
rigid[0].radiusRatio = 1.0;
rigid[0].flagTexture = true;
rigid[0].flagDebug = flagDebug;
rigid[0].mass = parseFloat(form1.mass0.value);//kg
rigid[0].ready();
//オブジェクト1
if(kind1No == 0) rigid[1].kind = "CUBE";
else if(kind1No == 1) rigid[1].kind = "SPHERE";
else if(kind1No == 2) rigid[1].kind = "CYLINDER";
rigid[1].vSize.x = parseFloat(form2.size1X.value);
rigid[1].vSize.y = parseFloat(form2.size1Y.value);
rigid[1].vSize.z = parseFloat(form2.size1Z.value);
rigid[1].vPos.x = parseFloat(form2.pos1X.value);
rigid[1].vPos.y = parseFloat(form2.pos1Y.value);
rigid[1].vPos.z = parseFloat(form2.pos1Z.value);
rigid[1].vVel = new Vector3(0, -10, 0);
rigid[1].vEuler.x = parseFloat(form2.ang1X.value);
rigid[1].vEuler.y = parseFloat(form2.ang1Y.value);
rigid[1].vEuler.z = parseFloat(form2.ang1Z.value);
rigid[1].q = getQFromEulerXYZ(rigid[1].vEuler);
rigid[1].vOmega.x = parseFloat(form2.omg1X.value) * 2 * Math.PI;
rigid[1].vOmega.y = parseFloat(form2.omg1Y.value) * 2 * Math.PI;
rigid[1].vOmega.z = parseFloat(form2.omg1Z.value) * 2 * Math.PI;
rigid[1].nSlice = 12;
rigid[1].nStack = 12;
rigid[1].radiusRatio = 1.0;
rigid[1].flagTexture = true;
rigid[1].flagDebug = flagDebug;
rigid[1].mass = parseFloat(form1.mass1.value);//kg
rigid[1].ready();
rigid[2].kind = "SPHERE";
rigid[2].vPos = new Vector3(-5, 0, 10);
rigid[2].vSize = new Vector3(1, 1, 1);
rigid[2].vVel = new Vector3(10, 0, 0);
rigid[2].vEuler = new Vector3();
rigid[2].q = getQFromEulerXYZ(rigid[2].vEuler);
rigid[2].vOmega = mul(new Vector3(), 2 * Math.PI);
rigid[2].nSlice = 12;
rigid[2].nStack = 12;
rigid[2].radiusRatio = 1.0;
rigid[2].flagTexture = true;
rigid[2].flagDebug = flagDebug;
rigid[2].mass = 1;//kg
rigid[2].ready();
//軌跡用点表示のためのダミー(レンダリングはしない)
dummy = new Rigid();
dummy.vPos = new Vector3(0, 0, 1);
dummy.nSlice = 30;
dummy.nStack = 30;
//軌跡用オブジェクトの位置座標配列
for(var i = 0; i < maxTrace; i++) {
tracePos0[i] = new Vector3(1000,0,0);//初期値は遠方
tracePos1[i] = new Vector3(1000,0,0);//初期値は遠方
tracePos2[i] = new Vector3(1000,0,0);//初期値は遠方
}
//座標軸
var lenCoord = 2.0;
var widCoord = 0.05;
for(var i = 0; i < 9; i++)
{
coord[i] = new Rigid();
coord[i].specular = [0.0, 0.0, 0.0, 1.0];
coord[i].shininess = 10.0;
coord[i].nSllice = 8;
}
coord[0].diffuse = [0.5, 0.0, 0.0, 1.0];//worldX
coord[0].ambient = [0.5, 0.0, 0.0, 1.0];//worldX
coord[1].diffuse = [0.0, 0.5, 0.0, 1.0];//worldY
coord[1].ambient = [0.0, 0.5, 0.0, 1.0];//worldY
coord[2].diffuse = [0.0, 0.0, 0.5, 1.0];//worldZ
coord[2].ambient = [0.0, 0.0, 0.5, 1.0];//worldZ
//ワールド座標
coord[0].kind = "CYLINDER_X";
coord[0].vPos = new Vector3(0.0, 0.0, 0.0);
coord[0].vSize = new Vector3(lenCoord, widCoord, widCoord);
coord[1].kind = "CYLINDER_Y";
coord[1].vSize = new Vector3(widCoord, lenCoord, widCoord);
coord[1].vPos = new Vector3(0.0, 0.0, 0.0);
coord[2].kind = "CYLINDER_Z";
coord[2].vSize = new Vector3(widCoord, widCoord, lenCoord);
coord[2].vPos = new Vector3(0.0, 0.0, 0.0);
for(var i = 0; i < 3; i++) coord[i].q = getQFromEulerXYZ(coord[i].vEuler);
//フロア
floor0 = new Rigid();
floor0.kind = "CHECK_PLATE";
floor0.vPos = new Vector3(0.0, 0.0, -plane[3]-0.01);
floor0.vSize = new Vector3(40, 40, 1);
floor0.nSlice = 20;//x方向分割数
floor0.nStack = 20;//y方向分割数
floor0.specular = [0.5, 0.5, 0.5, 1.0];
floor0.shininess = 50;
floor0.flagCheck = true;
display();
}
//---------------------------------------------
function display()
{
//光源
var lightPosLoc = gl.getUniformLocation(gl.program, 'u_lightPos');
gl.uniform4fv(lightPosLoc, light.pos);
var lightColLoc = gl.getUniformLocation(gl.program, 'u_lightColor');
gl.uniform4fv(lightColLoc, light.color);
var cameraLoc = gl.getUniformLocation(gl.program, 'u_cameraPos');
gl.uniform3fv(cameraLoc, camera.pos);
//ビュー投影行列を計算する
var vpMatrix = new Matrix4();// 初期化
vpMatrix.perspective(camera.fovy, canvas.width/canvas.height, camera.near, camera.far);
//vpMatrix.lookAt(camera.pos[0], camera.pos[1], v, 0, 0, 0, 0, 0, 1);
if(Math.cos(Math.PI * camera.theta /180.0) >= 0.0)//カメラ仰角90度でビューアップベクトル切替
vpMatrix.lookAt(camera.pos[0], camera.pos[1], camera.pos[2], camera.cnt[0], camera.cnt[1], camera.cnt[2], 0.0, 0.0, 1.0);
else
vpMatrix.lookAt(camera.pos[0], camera.pos[1], camera.pos[2], camera.cnt[0], camera.cnt[1], camera.cnt[2], 0.0, 0.0, -1.0);
var vpMatrixLoc = gl.getUniformLocation(gl.program, 'u_vpMatrix');
gl.uniformMatrix4fv(vpMatrixLoc, false, vpMatrix.elements);
// カラーバッファとデプスバッファをクリアする
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.viewport(0, 0, canvas.width, canvas.height);
var flagPointLoc = gl.getUniformLocation(gl.program, 'u_flagPoint');
gl.uniform1i(flagPointLoc, false);
var samplerLoc = gl.getUniformLocation(gl.program, 'u_sampler');
var n;
for(var k = 0; k < numRigid; k++)
{
if(k == 0) gl.activeTexture(gl.TEXTURE0);
else if(k == 1) gl.activeTexture(gl.TEXTURE1);
else if(k == 2) gl.activeTexture(gl.TEXTURE2);
gl.uniform1i(samplerLoc, k);
//オブジェクトの描画
n = rigid[k].initVertexBuffers(gl);
rigid[k].draw(gl, n);
}
if(flagTrace)
{
n = dummy.initVertexBuffers(gl);
//軌跡用オブジェクト
gl.uniform1i(flagPointLoc, true);
n = initVertexPoints();
gl.drawArrays(gl.POINTS, 0, n);
gl.uniform1i(flagPointLoc, false);
}
if(flagWorld)
{
for(var i = 0; i < 3; i++)
{
n = coord[i].initVertexBuffers(gl);
coord[i].draw(gl, n);
}
}
n = floor0.initVertexBuffers(gl);
floor0.draw(gl, n);
//影
drawShadow();
function drawShadow()
{
gl.depthMask(false);
gl.blendFunc(gl.SRC_ALPHA_SATURATE,gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND);
for(var k = 0; k < numRigid; k++)
{
rigid[k].shadow = shadow_value;
n = rigid[k].initVertexBuffers(gl);
rigid[k].draw(gl, n);
rigid[k].shadow = 0;//影描画後は元に戻す
}
gl.disable(gl.BLEND);
gl.depthMask(true);
}
}
//---------------------------------------------------
//イベント処理
function onClickC_Size()
{
canvas.width = form1.c_sizeX.value;
canvas.height = form1.c_sizeY.value;
display();
}
function onChangeData()
{
initObject();
}
function onChangeKind0()
{
var radioK0 = document.getElementsByName("radioK0");
for(var i = 0; i < radioK0.length; i++)
{
if(radioK0[i].checked) kind0No = i;
}
initObject();
}
function onChangeKind1()
{
var radioK1 = document.getElementsByName("radioK1");
for(var i = 0; i < radioK1.length; i++)
{
if(radioK1[i].checked) kind1No = i;
}
initObject();
}
function onClickDrag()
{
if(form1.drag.checked) flagDrag = true;
else flagDrag = false;
initObject();
}
function onClickLight()
{
light.pos[0] = parseFloat(form2.lightX.value);
light.pos[1] = parseFloat(form2.lightY.value);
light.pos[2] = parseFloat(form2.lightZ.value);
display();
}
function onClickCoord()
{
if(form1.world.checked) flagWorld = true;
else flagWorld = false;
display();
}
function onClickDebug()
{
if(form1.debug.checked) flagDebug = true;
else flagDebug = false;
rigid[0].flagDebug = flagDebug;
rigid[1].flagDebug = flagDebug;
display();
}
function onClickStart()
{
fps = 0;
elapseTime = elapseTime0;
elapseTime = 0.0;
elapseTime1 = 0.0;
countTrace = 0;
timeTrace = 0;
flagStart = true;
flagStep = false;
lastTime = new Date().getTime();
}
function onClickFreeze()
{
if(flagStart) { flagStart = false; }
else { flagStart = true; elapseTime = elapseTime0; }
flagStep = false;
}
function onClickStep()
{
flagStep = true;
flagStart = true;
elapseTime = elapseTime0;
}
function onClickReset()
{
elapseTime0 = 0;
flagStart = false;
flagStep = false;
initObject();
form1.time.value = "0";
display();
}
function onClickCameraReset()
{
initCamera();
display();
}
function onClickShadow()
{
shadow_value = parseFloat(form1.shadow.value);
display();
}
function onClickTrace()
{
flagTrace = form1.trace.checked;
display();
}
function onClickPeriod()
{
periodTrace = parseFloat(form1.period.value);
}
function initVertexPoints()
{
//軌跡用オブジェクトを点で描画するときの点座標を作成
var vertices = [];
var len = tracePos0.length;
for(var i = 0; i < len; i++)
{
vertices.push(tracePos0[i].x);
vertices.push(tracePos0[i].y);
vertices.push(tracePos0[i].z);
vertices.push(0);//オブジェクト番号
vertices.push(tracePos1[i].x);
vertices.push(tracePos1[i].y);
vertices.push(tracePos1[i].z);
vertices.push(1);
vertices.push(tracePos2[i].x);
vertices.push(tracePos2[i].y);
vertices.push(tracePos2[i].z);
vertices.push(2);
}
// バッファオブジェクトを作成する
var vertexBuffer = gl.createBuffer();
// バッファオブジェクトをバインドにする
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// バッファオブジェクトにデータを書き込む
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
vertexLoc = gl.getAttribLocation(gl.program, 'a_vertex');
// a_vertex変数にバッファオブジェクトを割り当てる
gl.vertexAttribPointer(vertexLoc, 4, gl.FLOAT, false, 0, 0);
// バッファオブジェクトのバインドを解除する
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// a_verte変数でのバッファオブジェクトの割り当てを有効化する
gl.enableVertexAttribArray(vertexLoc);
//軌跡用点データは3組
return 3*len;
}
|
import React from 'react';
import PropTypes from 'prop-types';
import NewsTabsNav from './NewsTabsNav';
import NewsList from './../NewsList';
/**
* Компонент "Табы новостей"
*/
function NewsTabs({
items,
selectedIndex
}) {
return (
<div>
<NewsTabsNav>
{items.map(item => (
<span key={item.label}>{item.label}</span>
))}
</NewsTabsNav>
{items.map(item => (
<div key={item.label}>
<NewsList items={item.news} />
</div>
))}
</div>
);
}
NewsTabs.propTypes = {
/** Список новостей и их категорий */
items: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string.isRequired,
news: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
icon: PropTypes.string,
text: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}))
})),
/** Индекс активного таба */
selectedIndex: PropTypes.number
};
NewsTabs.defaultProps = {
nav: [],
panels: [],
selectedIndex: 0
};
export default NewsTabs;
|
module.exports = {
name: 'cd',
description: 'Testing for cooldown commands',
cooldown: 5,
execute(message) {
message.channel.send(`Cooldown command`);
},
};
|
import React from "react";
import ReactDOM from "react-dom";
// import './assets/css/argon-dashboard-react.css'
// import './assets/css/argon-dashboard-react.css.map'
// import './assets/css/argon-dashboard-react.min.css'
// import './assets/fonts/nucleo.eot'
// import './assets/fonts/nucleo.ttf'
// import './assets/fonts/nucleo.woff'
// import './assets/fonts/nucleo.woff2'
// import './assets/img/brand/cropped-PSU_PHUKET-EN.png'
// import './assets/img/brand/favicon.png'
// import './assets/plugins/nucleo/css/nucleo-svg.css'
// import './assets/plugins/nucleo/css/nucleo.css'
// import './assets/plugins/nucleo/fonts/nucleo-icons.eot'
// import './assets/plugins/nucleo/fonts/nucleo-icons.svg'
// import './assets/plugins/nucleo/fonts/nucleo-icons.ttf'
// import './assets/plugins/nucleo/fonts/nucleo-icons.woff'
// import './assets/plugins/nucleo/fonts/nucleo-icons.woff2'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_alert.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_background-variant.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_badge.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_border-radius.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_box-shadow.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_breakpoints.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_buttons.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_caret.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_float.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_forms.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_gradients.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_grid-framework.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_grid.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_hover.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_image.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_list-group.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_lists.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_nav-divider.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_pagination.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_reset-text.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_resize.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_screen-reader.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_size.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_text-emphasis.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_text-hide.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_text-truncate.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_transition.scss'
// import './assets/scss/argon-dashboard/bootstrap/mixins/_visibility.scss'
// import './assets/scss/argon-dashboard/bootstrap/utilities/_align.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_background.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_borders.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_clearfix.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_display.scss'
// import './assets/scss/argon-dashboard/bootstrap/utilities/_embed.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_flex.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_float.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_position.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_screenreaders.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_shadows.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_sizing.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_spacing.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_text.scss'
// // import './assets/scss/argon-dashboard/bootstrap/utilities/_visibility.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_alert.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_background-variant.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_badge.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_buttons.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_forms.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_icon.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_modals.scss'
// import './assets/scss/argon-dashboard/custom/mixins/_popover.scss'
// // import './assets/scss/argon-dashboard/custom/modals/_modal.scss'
// // import './assets/scss/argon-dashboard/custom/navbars/_navbar-collapse.scss'
// // import './assets/scss/argon-dashboard/custom/navbars/_navbar-dropdown.scss'
// // import './assets/scss/argon-dashboard/custom/navbars/_navbar-search.scss'
// // import './assets/scss/argon-dashboard/custom/navbars/_navbar-vertical.scss'
// // import './assets/scss/argon-dashboard/custom/navbars/_navbar.scss'
// // import './assets/scss/argon-dashboard/custom/navs/_nav-pills.scss'
// // import './assets/scss/argon-dashboard/custom/navs/_nav.scss'
// // import './assets/scss/argon-dashboard/custom/paginations/_pagination.scss'
// // import './assets/scss/argon-dashboard/custom/popovers/_popover.scss'
// // import './assets/scss/argon-dashboard/custom/progresses/_progress.scss'
// // import './assets/scss/argon-dashboard/custom/separators/_separator.scss'
// // import './assets/scss/argon-dashboard/custom/tables/_table.scss'
// import './assets/scss/argon-dashboard/custom/type/_article.scss'
// // import './assets/scss/argon-dashboard/custom/type/_display.scss'
// // import './assets/scss/argon-dashboard/custom/type/_heading.scss'
// // import './assets/scss/argon-dashboard/custom/type/_type.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_backgrounds.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_blurable.scss'
// import './assets/scss/argon-dashboard/custom/utilities/_floating.scss'
// import './assets/scss/argon-dashboard/custom/utilities/_helper.scss'
// import './assets/scss/argon-dashboard/custom/utilities/_image.scss'
// import './assets/scss/argon-dashboard/custom/utilities/_opacity.scss'
// import './assets/scss/argon-dashboard/custom/utilities/_overflow.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_position.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_shadows.scss'
// import './assets/scss/argon-dashboard/custom/utilities/_sizing.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_spacing.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_text.scss'
// // import './assets/scss/argon-dashboard/custom/utilities/_transform.scss'
// // import './assets/scss/argon-dashboard/custom/vendors/_bootstrap-datepicker.scss'
// // import './assets/scss/argon-dashboard/custom/vendors/_headroom.scss'
// // import './assets/scss/argon-dashboard/custom/vendors/_nouislider.scss'
// import './assets/scss/argon-dashboard/custom/vendors/_scrollbar.scss'
// // import './assets/scss/argon-dashboard/docs/_clipboard-js.scss'
// // import './assets/scss/argon-dashboard/docs/_component-examples.scss'
// // import './assets/scss/argon-dashboard/docs/_content.scss'
// // import './assets/scss/argon-dashboard/docs/_footer.scss'
// // import './assets/scss/argon-dashboard/docs/_nav.scss'
// import './assets/scss/argon-dashboard/docs/_prism.scss'
// // import './assets/scss/argon-dashboard/docs/_sidebar.scss'
// // import './assets/scss/argon-dashboard/docs/_variables.scss'
// import './assets/scss/react/bootstrap/_spinners.scss'
// // import './assets/scss/react/plugins/_plugin-react-datetime.scss'
import "assets/plugins/nucleo/css/nucleo.css";
import "@fortawesome/fontawesome-free/css/all.min.css";
import "assets/scss/argon-dashboard-react.scss";
import App from './App'
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<App/>,
document.getElementById("root")
)
serviceWorker.unregister();
|
module.exports = require('./dist/react-code-prettify.js');
|
let numbers = [];
for (let i = 1; i <=25 ; i+=1) {
numbers.push(i)
}
console.log(numbers)
|
angular.module('WeathersService', [])
.factory('WeathersService', function ($http, SettingFactory) {
var baseUrl = "http://localhost:8080/weathers";
return {
dailyWeather: function () {
var place = SettingFactory.getCity();
var setting = SettingFactory.getSetting();
var dailyUrl = baseUrl + "/daily?latitude=" + place.latitude + "&longitude=" + place.longitude + "&lang=" + setting.abbr;
return $http.get(dailyUrl).then(function (response) {
return response.data;
});
},
hourlyWeather: function () {
var place = SettingFactory.getCity();
var setting = SettingFactory.getSetting();
var hourlyUrl = baseUrl + "/hourly?latitude=" + place.latitude + "&longitude=" + place.longitude + "&lang=" + setting.abbr;
return $http.get(hourlyUrl).then(function (response) {
return response.data;
});
}
};
});
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import angular from 'angular';
import fileStoreBrowserTemplate from './fileStoreBrowser.html';
import './fileStoreBrowser.css';
import sha512 from 'js-sha512';
const localStorageKey = 'fileStoreBrowser';
class FileStoreBrowserController {
static get $$ngIsClass() { return true; }
static get $inject() { return ['maFileStore', '$element', 'maDialogHelper', '$q', '$filter', '$injector',
'localStorageService', '$scope', 'maScript', 'maDiscardCheck', 'maUser']; }
constructor(maFileStore, $element, maDialogHelper, $q, $filter, $injector, localStorageService,
$scope, maScript, maDiscardCheck, maUser) {
this.maFileStore = maFileStore;
this.$element = $element;
this.maDialogHelper = maDialogHelper;
this.$q = $q;
this.$filter = $filter;
this.localStorageService = localStorageService;
this.$scope = $scope;
this.maScript = maScript;
this.maDiscardCheck = maDiscardCheck;
this.maUser = maUser;
if ($injector.has('$state')) {
this.$state = $injector.get('$state');
this.$stateParams = $injector.get('$stateParams');
}
this.tableOrder = ['-directory', 'filename'];
this.filterAndReorderFilesBound = (...args) => {
return this.filterAndReorderFiles(...args);
};
}
$onInit() {
this.$element.on('keydown', event => this.keyDownHandler(event));
this.scriptExtensions = new Set();
this.scriptMimes = new Set();
this.scriptEnginesPromise = this.maScript.scriptEngines().then(engines => {
this.scriptEngines = engines;
engines.forEach(e => {
e.mimeTypes.forEach(m => this.scriptMimes.add(m));
e.extensions.forEach(e => this.scriptExtensions.add(e));
});
}, error => this.scriptEngines = []);
this.path = [this.restrictToStore || this.defaultStore || 'default'];
this.ngModelCtrl.$render = (...args) => {
return this.render(...args);
};
this.discardCheck = new this.maDiscardCheck({
$scope: this.$scope,
isDirty: () => this.editFile && this.editFileModified()
});
}
$onChanges(changes) {
if (changes.mimeTypes) {
const mimeTypeMap = this.mimeTypeMap = {};
if (this.mimeTypes) {
this.mimeTypes.split(/\s*,\s*/).forEach(mimeType => {
if (!mimeType) return;
mimeTypeMap[mimeType.toLowerCase()] = true;
});
}
}
if (changes.extensions) {
const extensionMap = this.extensionMap = {};
if (this.extensions) {
this.extensions.split(/\s*,\s*/).forEach(ext => {
if (!ext) return;
if (ext[0] === '.') ext = ext.substr(1);
extensionMap[ext.toLowerCase()] = true;
});
}
}
if (changes.extensions || changes.mimeTypes) {
const accept = [];
Object.keys(this.extensionMap).forEach(ext => {
accept.push('.' + ext);
});
Object.keys(this.mimeTypeMap).forEach(mime => {
accept.push(mime);
});
this.acceptAttribute = accept.join(',');
}
}
// ng-model value changed outside of this directive
render() {
let urls = this.ngModelCtrl.$viewValue;
if (!Array.isArray(urls)) {
urls = urls ? [urls] : [];
}
const settings = this.localStorageService.get(localStorageKey) || {};
let userPath;
if (this.$stateParams && this.$stateParams.fileStore) {
userPath = [this.$stateParams.fileStore]
if (this.$stateParams.folderPath) {
userPath.push(...this.$stateParams.folderPath.split('/'));
}
} else if (settings.fileStore) {
userPath = [settings.fileStore];
if (Array.isArray(settings.folderPath)) {
userPath.push(...settings.folderPath);
}
}
const defaultStore = this.defaultStore || 'default';
if (this.restrictToStore) {
this.path = userPath && userPath[0] === this.restrictToStore ? userPath : [this.restrictToStore];
} else {
this.path = userPath || [defaultStore];
}
const filenames = {};
urls.forEach((url, index) => {
let path;
try {
path = this.maFileStore.fromUrl(url);
} catch (e) {
return;
}
if (!path.directory) {
const filename = path.pop(); // remove filename from path
filenames[filename] = true;
}
if (index === 0) {
this.path = path;
}
});
this.listFiles().then(files => {
this.filenames = filenames;
let firstSelected = true;
this.selectedFiles = files.filter((file, index) => {
if (filenames[file.filename]) {
if (firstSelected) {
// set the preview file to the first file in filenames
this.previewFile = file;
// set the lastIndex for shift clicking to the first selected file
this.lastIndex = index;
firstSelected = false;
}
return true;
}
});
if (this.$stateParams) {
const editFile = this.$stateParams && this.$stateParams.editFile;
const foundFile = editFile && files.find(f => f.filename === editFile);
if (foundFile) {
this.doEditFile(null, foundFile);
}
}
});
}
hasFileStoreWritePermission() {
return this.fileStore && this.maUser.current &&
this.maUser.current.hasPermission(this.fileStore.writePermission);
}
listFiles() {
const listErrorHandler = () => {
this.files = [];
this.filteredFiles = [];
this.previewFile = null;
this.filenames = {};
this.selectedFiles = [];
delete this.lastIndex;
const defaultStore = this.restrictToStore || this.defaultStore || 'default';
if (!(this.path.length === 1 && this.path[0] === defaultStore)) {
this.path = [defaultStore];
return this.listFiles();
}
return this.filteredFiles;
};
this.previewFile = null;
this.filenames = {};
this.selectedFiles = [];
delete this.lastIndex;
if (this.path.length) {
const storeXid = this.path[0];
if (!this.fileStore || this.fileStore.xid !== storeXid) {
this.maFileStore.get(storeXid).then(store => {
this.fileStore = store;
}, error => delete this.fileStore);
}
this.listPromise = this.maFileStore.listFiles(this.path).then(files => {
this.files = files;
this.filterAndReorderFiles();
return this.filteredFiles;
}, error => listErrorHandler());
} else {
delete this.fileStore;
this.listPromise = this.maFileStore.query().then(fileStores => {
this.files = fileStores.map(store => {
return this.storeToFile(store);
});
this.filterAndReorderFiles();
return this.filteredFiles;
}, listErrorHandler);
}
this.listPromise['finally'](() => {
delete this.listPromise;
});
const folderPath = this.path.slice();
const fileStore = folderPath.shift() || null;
if (this.$state) {
const params = {
fileStore,
folderPath: folderPath.join('/')
};
this.$state.go('.', params, {location: 'replace', notify: false});
}
const settings = this.localStorageService.get(localStorageKey) || {};
settings.fileStore = fileStore;
settings.folderPath = folderPath;
this.localStorageService.set(localStorageKey, settings);
return this.listPromise;
}
filterFiles(file) {
if (this.path.length) {
const currentFolderPath = this.path.slice(1).join('/');
if (file.folderPath !== currentFolderPath) {
return false;
}
}
if (file.directory) return true;
if (this.extensions) {
const match = /\.([^\.]+)$/.exec(file.filename);
if (match && this.extensionMap[match[1].toLowerCase()]) return true;
}
if (this.mimeTypes) {
if (this.mimeTypeMap['*/*']) return true;
if (!file.mimeType) return false;
if (this.mimeTypeMap[file.mimeType.toLowerCase()]) return true;
if (this.mimeTypeMap[file.mimeType.toLowerCase().replace(/\/.+$/, '/*')]) return true;
}
return !this.extensions && !this.mimeTypes;
}
filterAndReorderFiles(file) {
const files = this.files.filter(this.filterFiles, this);
let tableOrder = typeof this.tableOrder === 'string' ? this.tableOrder.split(',') : this.tableOrder;
if (!this.path.length && Array.isArray(tableOrder)) {
tableOrder = tableOrder.map(key => key.replace(/\bfilename\b/g, 'store.name'));
}
this.filteredFiles = this.$filter('orderBy')(files, tableOrder);
}
pathClicked(event, index) {
let popNum = this.path.length - index - 1;
while(popNum-- > 0) {
this.path.pop();
}
this.listFiles();
if (!this.multiple && this.selectDirectories && this.path.length) {
this.ngModelCtrl.$setViewValue(this.maFileStore.toUrl(this.path, true));
}
}
fileClicked(event, file, index) {
this.previewFile = file;
if (file.directory) {
this.path.push(file.filename);
this.listFiles();
if (!this.multiple && this.selectDirectories) {
this.ngModelCtrl.$setViewValue(file.url);
}
return;
}
if (this.multiple && (event.ctrlKey || event.metaKey)) {
this.lastIndex = index;
if (this.filenames[file.filename]) {
this.removeFileFromSelection(file);
} else {
this.addFileToSelection(file);
}
} else if (this.multiple && event.shiftKey && isFinite(this.lastIndex)) {
event.preventDefault();
let fromIndex, toIndex;
if (this.lastIndex < index) {
fromIndex = this.lastIndex;
toIndex = index;
} else {
fromIndex = index;
toIndex = this.lastIndex;
}
this.setSelection(this.filteredFiles.slice(fromIndex, toIndex + 1));
} else {
this.lastIndex = index;
this.setSelection([file]);
}
this.setViewValueToSelection();
}
setViewValueToSelection() {
const urls = this.selectedFiles.map(file => {
return file.url;
});
this.ngModelCtrl.$setViewValue(this.multiple ? urls : urls[0]);
}
setSelection(files) {
this.selectedFiles = [];
this.filenames = {};
for (let i = 0; i < files.length; i++) {
this.addFileToSelection(files[i]);
}
}
addFileToSelection(file) {
this.filenames[file.filename] = true;
this.selectedFiles.push(file);
}
removeFileFromSelection(file) {
delete this.filenames[file.filename];
const index = this.selectedFiles.indexOf(file);
if (index >= 0)
return this.selectedFiles.splice(index, 1);
}
cancelClick(event) {
event.stopPropagation();
}
deleteFile(event, file) {
event.stopPropagation();
let messageKey;
if (file.store) {
messageKey = 'ui.filestore.confirmDelete';
} else {
messageKey = file.directory ? 'ui.app.areYouSureDeleteFolder' : 'ui.app.areYouSureDeleteFile';
}
this.maDialogHelper.confirm(event, messageKey).then(() => {
if (file.store) {
// TODO Mango 4.0 recursive param
return file.store.delete();
}
return this.maFileStore.remove(this.path.concat(file.filename), true);
}).then(() => {
const index = this.files.indexOf(file);
if (index >= 0) {
this.files.splice(index, 1);
}
this.filterAndReorderFiles();
if (this.removeFileFromSelection(file)) {
this.setViewValueToSelection();
}
if (this.previewFile === file) {
this.previewFile = this.selectedFiles.length ? this.selectedFiles[0] : null;
}
this.maDialogHelper.toast(['ui.fileBrowser.deletedSuccessfully', file.filename]);
}, error => {
if (!error) return; // dialog cancelled
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorDeleting', file.filename, msg], 'md-warn');
});
}
uploadFilesButtonClicked(event) {
this.$element.maFind('input[type=file]')
.val(null)
.maClick();
}
uploadFilesChanged(event, allowZip = true) {
const files = event.target.files;
if (!files.length) return;
this.uploadFiles(files, allowZip);
}
fileDropped(data) {
const types = data.getDataTransferTypes();
if (types.includes('Files')) {
const files = data.getDataTransfer();
if (files && files.length) {
this.uploadFiles(files);
}
}
}
uploadFiles(files, allowZip = true) {
this.uploadPromise = this.$q.when().then(() => {
if (allowZip && files.length === 1) {
const file = files[0];
if (file.type === 'application/x-zip-compressed' || file.type === 'application/zip' || file.name.substr(-4) === '.zip') {
return this.maDialogHelper.confirm(event, 'ui.fileBrowser.confirmExtractZip').then(() => {
return this.maFileStore.uploadZipFile(this.path, file, this.overwrite);
}, angular.noop);
}
}
}).then(uploaded => {
// already did zip upload
if (uploaded) {
return uploaded;
}
return this.maFileStore.uploadFiles(this.path, files, this.overwrite);
}).then((uploaded) => {
// this code block is a little complicated, could just refresh the current folder?
const strPath = this.path.slice(1).join('/');
uploaded.forEach(file => {
if (file.folderPath === strPath) {
// file is in this folder
const existingFileIndex = this.files.findIndex(f => f.filename === file.filename);
if (existingFileIndex >= 0) {
this.files[existingFileIndex] = file;
} else {
this.files.push(file);
}
} else if (file.folderPath.indexOf(strPath) === 0) {
// file is in a subdirectory
const uploadedFilePath = file.folderPath.split('/');
const folderName = uploadedFilePath[this.path.length - 1];
const existingSubFolder = this.files.findIndex(f => f.filename === folderName);
if (existingSubFolder < 0) {
// file upload created a subdirectory, add it to the view
this.files.push(new this.maFileStore.newFileStoreFile(this.path[0], {
directory: true,
filename: folderName,
folderPath: strPath,
lastModified: file.lastModified,
mimeType: null,
size: 0
}));
}
}
});
this.filterAndReorderFiles();
if (uploaded.length) {
this.setSelection(uploaded.filter(this.filterFiles, this));
this.setViewValueToSelection();
this.previewFile = this.selectedFiles.length ? this.selectedFiles[0] : null;
this.maDialogHelper.toast(['ui.fileBrowser.filesUploaded', uploaded.length]);
}
}, (error) => {
let msg;
if (error.status && error.data) {
msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
} else {
msg = '' + error;
}
this.maDialogHelper.toast(['ui.fileBrowser.uploadFailed', msg], 'md-warn');
}).finally(() => {
delete this.uploadPromise;
this.$element.maFind('input[type=file]').val('');
});
}
downloadFiles(event) {
this.downloadPromise = this.maFileStore.downloadFiles(this.path).finally(() => {
delete this.downloadPromise;
});
}
createNewFolder(event) {
let folderName;
this.maDialogHelper.prompt(event, 'ui.app.createNewFolder', null, 'ui.app.folderName').then(_folderName => {
if (!_folderName) {
return this.$q.reject();
}
folderName = _folderName;
return this.maFileStore.createNewFolder(this.path, folderName);
}).then(folder => {
this.files.push(folder);
this.filterAndReorderFiles();
this.maDialogHelper.toast(['ui.fileBrowser.folderCreated', folder.filename]);
}, error => {
if (!error) return; // dialog cancelled
if (error.status === 409) {
this.maDialogHelper.toast(['ui.fileBrowser.folderExists', folderName], 'md-warn');
} else {
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorCreatingFolder', folderName, msg], 'md-warn');
}
});
}
createNewFile(event) {
let fileName;
this.maDialogHelper.prompt(event, 'ui.app.createNewFile', null, 'ui.app.fileName').then(_fileName => {
if (!_fileName) {
return this.$q.reject();
}
fileName = _fileName;
return this.maFileStore.createNewFile(this.path, fileName);
}).then(file => {
this.files.push(file);
this.filterAndReorderFiles();
this.maDialogHelper.toast(['ui.fileBrowser.fileCreated', file.filename]);
if (file.editMode)
this.doEditFile(event, file);
}, error => {
if (!error) return; // dialog cancelled
if (error.status === 409) {
this.maDialogHelper.toast(['ui.fileBrowser.fileExists', fileName], 'md-warn');
} else {
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorCreatingFile', fileName, msg], 'md-warn');
}
});
}
doEditFile(event, file) {
if (event) {
event.stopPropagation();
}
this.maFileStore.downloadFile(file).then(textContent => {
this.editFile = file;
this.editText = textContent;
this.editHash = sha512.sha512(textContent);
if (this.$state) {
this.$state.go('.', {editFile: file.filename}, {location: 'replace', notify: false});
}
this.scriptEnginesPromise.then(() => {
this.supportedEngines = this.scriptEngines.filter(e => {
return e.mimeTypes.includes(file.mimeType) || e.extensions.includes(file.extension);
});
this.selectedEngine = this.supportedEngines[0];
});
if (this.editingFile) {
this.editingFile({
$file: this.editFile,
$save: (...args) => {
return this.saveEditFile(...args);
}
});
}
}, error => {
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorDownloading', file.filename, msg], 'md-warn');
});
}
saveEditFile(event) {
const currentHash = sha512.sha512(this.editText);
if (this.editHash === currentHash) {
this.maDialogHelper.toast(['ui.fileBrowser.fileNotChanged', this.editFile.filename]);
return this.$q.resolve();
}
const files = [this.editFile.createFile(this.editText)];
return this.maFileStore.uploadFiles(this.path, files, true).then(uploaded => {
const index = this.files.indexOf(this.editFile);
this.editHash = currentHash;
this.editFile = uploaded[0];
this.files.splice(index, 1, this.editFile);
this.filterAndReorderFiles();
this.maDialogHelper.toast(['ui.fileBrowser.savedSuccessfully', this.editFile.filename]);
}, error => {
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorUploading', this.editFile.filename, msg], 'md-warn');
});
}
cancelEditFile(event) {
if (!this.discardCheck.canDiscard()) {
return;
}
this.editFile = null;
this.editText = null;
this.editHash = null;
this.supportedEngines = [];
delete this.selectedEngine;
delete this.aceEditor;
if (this.$state) {
this.$state.go('.', {editFile: null}, {location: 'replace', notify: false});
}
if (this.editingFile) {
this.editingFile({$file: null, $save: null});
}
}
renameFile(event, file) {
event.stopPropagation();
let newName;
this.maDialogHelper.prompt(event, 'ui.app.renameOrMoveTo', null, 'ui.app.fileName', file.filename).then(_newName => {
newName = _newName;
if (newName === file.filename)
return this.$q.reject();
return this.maFileStore.renameFile(this.path, file, newName);
}).then(renamedFile => {
const index = this.files.indexOf(file);
if (renamedFile.folderPath === file.folderPath) {
// replace it
this.files.splice(index, 1, renamedFile);
} else {
// remove it
this.files.splice(index, 1);
}
this.filterAndReorderFiles();
if (renamedFile.filename === file.filename) {
this.maDialogHelper.toast(['ui.fileBrowser.fileMoved', renamedFile.filename, renamedFile.fileStore + '/' + renamedFile.folderPath]);
} else {
this.maDialogHelper.toast(['ui.fileBrowser.fileRenamed', renamedFile.filename]);
}
}, error => {
if (!error) return; // dialog cancelled or filename the same
if (error.status === 409) {
this.maDialogHelper.toast(['ui.fileBrowser.fileExists', newName], 'md-warn');
} else {
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorCreatingFile', newName, msg], 'md-warn');
}
});
}
copyFile(event, file) {
event.stopPropagation();
let newName;
this.maDialogHelper.prompt(event, 'ui.app.copyFileTo', null, 'ui.app.fileName', file.filename).then(_newName => {
newName = _newName;
if (newName === file.filename)
return this.$q.reject();
return this.maFileStore.copyFile(this.path, file, newName);
}).then(copiedFile => {
if (copiedFile.folderPath === file.folderPath) {
this.files.push(copiedFile);
this.filterAndReorderFiles();
}
this.maDialogHelper.toast(['ui.fileBrowser.fileCopied', copiedFile.filename, copiedFile.fileStore + '/' + copiedFile.folderPath]);
}, error => {
if (!error) return; // dialog cancelled or filename the same
if (error.status === 409) {
this.maDialogHelper.toast(['ui.fileBrowser.fileExists', newName], 'md-warn');
} else {
const msg = 'HTTP ' + error.status + ' - ' + error.data.localizedMessage;
this.maDialogHelper.toast(['ui.fileBrowser.errorCreatingFile', newName, msg], 'md-warn');
}
});
}
selectionKeyDown(event) {
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey || ![38, 40].includes(event.keyCode)) return;
if (this.selectedFiles.length > 1) return;
const selectedFile = this.selectedFiles.length && this.selectedFiles[0];
const selectedFileIndex = this.filteredFiles.indexOf(selectedFile);
let nextIndex = 0;
if (event.keyCode === 38) {
// up
nextIndex = selectedFileIndex - 1;
} else if (event.keyCode === 40) {
// down
nextIndex = selectedFileIndex + 1;
}
event.preventDefault();
const newSelectedFile = this.filteredFiles[nextIndex];
if (newSelectedFile) {
this.previewFile = newSelectedFile;
this.setSelection([newSelectedFile]);
this.setViewValueToSelection();
}
}
keyDownHandler(event) {
const keyActions = {
// Ctrl-s
83: {ctrl: true, action: () => this.saveEditFile(event)},
// Ctrl-e
69: {ctrl: true, action: () => this.evalScript(event)},
// ESC
27: {action: () => this.cancelEditFile(event)}
};
if (this.editFile && event.which in keyActions) {
const action = keyActions[event.which];
if (!action.ctrl || event.ctrlKey || event.metaKey) {
event.stopPropagation();
event.preventDefault();
this.$scope.$apply(() => {
action.action();
})
};
}
}
evalScript(event) {
event.stopPropagation();
if (this.editFileModified()) {
this.maDialogHelper.errorToast(['ui.fileBrowser.saveScriptBeforeEval']);
return;
}
this.scriptResult = {
file: this.editFile
};
if (this.aceEditor) {
this.aceEditor.session.clearAnnotations();
}
this.scriptResult.evalPromise = this.editFile.evalScript(undefined, {
engineName: this.selectedEngine.engineName
}, {
responseType: 'blob',
transformResponse: blob => blob
}).then(response => {
const result = response.data;
this.scriptResult.success = true;
this.scriptResult.outputBlob = result;
this.scriptResult.outputBlobUrl = URL.createObjectURL(result);
const isText = result.type.indexOf('text/') === 0;
const isJson = result.type === 'application/json';
if (response.filename) {
this.scriptResult.outputFilename = response.filename;
} else {
let outputFilename = this.scriptResult.file.filename;
const lastDot = outputFilename.lastIndexOf('.');
if (lastDot >= 0) {
outputFilename = outputFilename.slice(0, lastDot);
}
outputFilename += '_response';
if (isText) {
outputFilename += '.txt';
} else if (isJson) {
outputFilename += '.json';
}
this.scriptResult.outputFilename = outputFilename;
}
if (isText || isJson) {
this.scriptResult.canShowText = true;
// automatically show text if the size is less than 100 KiB
if (result.size < 100 * 1024) {
this.getScriptResultText();
}
}
}, error => {
this.scriptResult.error = error;
let filesMatch = false;
if (error.data.fileName) {
const normalized = error.data.fileName.replace(/\\/g, '/');
if (normalized.indexOf('/') >= 0) {
filesMatch = normalized.endsWith(this.editFile.filePath)
} else {
filesMatch = error.data.fileName === this.editFile.filename;
}
}
if (this.aceEditor && error.data && error.data.lineNumber != null && filesMatch) {
this.aceEditor.session.setAnnotations([{
row: error.data.lineNumber - 1,
column: error.data.columnNumber,
text: error.data.shortMessage || error.mangoStatusText,
type: 'error'
}]);
}
}).finally(() => delete this.scriptResult.evalPromise);
}
getScriptResultText() {
this.scriptResult.canShowText = false;
this.scriptResult.textLoading = true;
this.$q.resolve(this.scriptResult.outputBlob.text()).then(text => {
delete this.scriptResult.textLoading;
this.scriptResult.output = text;
});
}
canEvalScript(file) {
return file.mimeType != null && this.scriptMimes.has(file.mimeType) || file.extension != null && this.scriptExtensions.has(file.extension);
}
editFileModified() {
const currentHash = sha512.sha512(this.editText);
return this.editHash !== currentHash;
}
createNewFileStore(event) {
this.showFileStoreEditDialog = {
targetEvent: event,
fileStore: new this.maFileStore()
};
}
editFileStore(event, file) {
event.stopPropagation();
this.showFileStoreEditDialog = {
targetEvent: event,
file,
fileStore: file.store
};
}
fileStoreSaved() {
const file = this.showFileStoreEditDialog.file;
const fileStore = this.showFileStoreEditDialog.fileStore;
if (file && !fileStore) {
// deleted
const index = this.files.indexOf(file);
if (index >= 0) {
this.files.splice(index, 1);
}
} else if (file && fileStore) {
// updated, ensure filename updated
file.filename = fileStore.xid;
file.store = fileStore;
} else if (fileStore) {
// created
this.files.push(this.storeToFile(fileStore));
}
this.filterAndReorderFiles();
delete this.showFileStoreEditDialog;
}
fileStoreEditorCancelled() {
delete this.showFileStoreEditDialog;
}
storeToFile(store) {
return {
store: store,
filename: store.xid,
directory: true
};
}
}
const fileStoreBrowser = {
controller: FileStoreBrowserController,
template: fileStoreBrowserTemplate,
require: {
'ngModelCtrl': 'ngModel'
},
bindings: {
restrictToStore: '@?store',
defaultStore: '@?',
selectDirectories: '<?',
mimeTypes: '@?',
extensions: '@?',
preview: '<?',
disableEdit: '<?',
editingFile: '&?',
multiple: '<?'
},
designerInfo: {
attributes: {
selectDirectories: {type: 'boolean'},
multiple: {type: 'boolean'}
},
translation: 'ui.components.fileStoreBrowser',
icon: 'folder_open'
}
};
export default fileStoreBrowser;
|
/**
* File Description: Invite manager, where actual business logic related to token generation, validation, check lies
*/
const mongoose = require('mongoose');
const config = require('../config/index');
const random = require('../common/helpers/random');
const self = this;
/**
* function to generate invitation token
*/
module.exports.generate = () => {
try {
return new Promise((resolve, reject) => {
// generate random string
let referToken = random.randomString(Math.floor(Math.random() * (config.token.max - config.token.min + 1) + config.token.min), config.token.str);
if (!referToken) {
reject({ status: false, msg: 'Oops! Something went wrong. Please try again', code: 500 });
}
// check if this token already exist or not
self.checkToken(referToken).then((response) => {
// token exists,create new one and return
let referToken = random.randomString(Math.floor(Math.random() * (config.token.max - config.token.min + 1) + config.token.min), config.token.str);
//save token in DB and return
self.saveToken(referToken).then((response) => {
resolve({ status: true, msg: 'token generated', referToken: referToken, code: 200 });
}).catch((err) => {
reject({ status: false, msg: 'Failed to generate token', code: 403 });
});
}).catch((notExists) => {
//save token in DB and return
self.saveToken(referToken).then((response) => {
resolve({ status: true, msg: 'token generated', referToken: referToken, code: 200 });
}).catch((err) => {
reject({ status: false, msg: 'Failed to generate token', code: 403 });
});
});
});
} catch (err) {
throw err;
}
};
/**
* function to save token into DB
* @param {*} referToken
*/
module.exports.saveToken = (referToken) => {
try {
return new Promise((resolve, reject) => {
mongoose.model('Token').create({ token: referToken, createdOn: config.token.expiry, active: true }, (err, response) => {
console.log(err);
if (err) {
reject(err);
}
resolve(response);
});
});
} catch (err) {
throw err;
}
};
/**
* Function to validate the generated Refer token
* @param {*} referToken
*/
module.exports.validate = (referToken) => {
try {
return new Promise((resolve, reject) => {
self.checkToken(referToken).then((response) => {
if (response.length > 0) {
// check token expiry
let currentTime = new Date();
let dayDiff = parseInt((response[0].createdOn - (Math.floor(Date.now() / 1000))) / 1000 / 60 / 60 / 24)
if (dayDiff <= config.token.days) {
resolve({ status: true, msg: 'Invite is valid', code: 200 });
} else {
reject({ status: false, msg: 'Invite Expired', code: 403 })
}
}
}).catch((err) => {
reject({ status: false, msg: 'Invalid invite provided', code: 400 })
})
});
} catch (err) {
throw err;
}
}
/**
* function to check whether the generated token exist in DB or not
* @param {*} token
*/
module.exports.checkToken = (token) => {
try {
return new Promise((resolve, reject) => {
mongoose.model('Token').find({ token: token, active: true }, (err, response) => {
if (err) {
reject(err);
}
if (response.length > 0) {
resolve(response);
} else {
reject(err);
}
});
})
} catch (err) {
throw err;
}
}
|
const btRecibir = document.querySelector("#jsonAstr");
const btMandar = document.querySelector("#srtAjson");
const inPrimerNombre = document.querySelector("#fname");
const inApellido = document.querySelector("#lname");
const inEdad = document.querySelector("#edad");
const inCorreo = document.querySelector("#correo");
const cajabox = document.querySelector("#w3mission");
btRecibir.addEventListener("click", (e)=> {
cajabox.textContent = "";
let inJson = { nombre: inPrimerNombre.value, apellido: inApellido.value, edad: inEdad.value, correo: inCorreo.value };
let strJson = JSON.stringify(inJson);
cajabox.value = strJson;
});
btMandar.addEventListener("click", (e)=> {
let outJson;
if (cajabox.value === "") {
outJson = { nombre: "", apellido: "", edad: "", correo:""};
} else {
let strJson = cajabox.value;
outJson = JSON.parse(strJson);
}
inPrimerNombre.value = outJson.nombre;
inApellido.value = outJson.apellido;
inEdad.value = outJson.edad;
inCorreo.value = outJson.correo;
});
|
var loadedCount = 0;
var limit = 10;
var skills = ["c#", "vb", "test", "a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefgh", "abcdefghij"];
var selectedSkills = [];
var courses = ["BSCS", "BSMA", "COE", "ECE", "BSIT", "BSA"];
var selectedCourses = [];
var jobTitles = ["Programmer", "Software Engineer", "Mobile Developer", "Wev Developer", "Graphics Artist"];
var selectedJobTitles = [];
var desiredSalaryRange = [0,0];
var yearsOfExperienceRange = [0,0];
function InitializeCandidateSearch()
{
CreateSlider("#desiredSalary", desiredSalaryRange, ["$", " - $", ""]);
CreateSlider("#yearsOfExperience", yearsOfExperienceRange, ["<br>", "-", "yrs"], 0, 50, 2);
CreateAutoComplete("#addSkill", skills, "#activatedSkills", selectedSkills, "skills", "selectedSkills");
CreateAutoComplete("#addCourse", courses, "#activatedCourses", selectedCourses, "courses", "selectedCourses");
CreateAutoComplete("#addJobTitle", jobTitles, "#activatedJobTitles", selectedJobTitles, "jobTitles", "selectedJobTitles");
$.post("amsServer.php", {method:"GetFolders"}, function(data){
// alert(data);
var folders = data.split("|");
folders.forEach(function(e, index){
var parts = e.split(",");
$("#selectBatchFolder").append("<option value = '"+parts[0]+"' >"+parts[1]+"</option>");
});
});
}
function CreateAutoComplete(id, sourceArray, activatedBoxID, selectedArray, sourceArrayStringName, selectedArrayStringName)
{
$(id).autocomplete({
source: sourceArray,
select: function( event, ui )
{
$(activatedBoxID).append("<span id = '"+ui.item.value+"' >" + ui.item.value + "<span onclick = \"removeFromSelectedBox('"+ui.item.value+"', "+sourceArrayStringName+", "+selectedArrayStringName+", '"+activatedBoxID+"');\">x</span></span>");
selectedArray.push(ui.item.value);
removeElement(sourceArray, ui.item.value);
$(id).autocomplete("option", { source: sourceArray });
$(this).val(''); return false;
}
});
}
function CreateSlider(id, valueHolder, unit, min, max, step, values)
{
min = min || 0;
max = max || 100;
step = step || 10;
values = values || [min, max];
unit = unit || ["","",""];
$( id ).slider({
range: true,
min: min,
max: max,
step: step,
values: values,
slide: function( event, ui ) {
if(ui.values[1] - ui.values[0] < step){
return false;
}
valueHolder = [ui.values[ 0 ] , ui.values[ 1 ]];
$(this).siblings("#amount").children("span" ).html(unit[0] + ui.values[ 0 ] + unit[1] + ui.values[ 1 ] + unit[2] );
}
});
}
function removeFromSelectedBox(value, src, selected, boxID )
{
src.push(value);
src.sort();
removeElement(selected, value);
$(boxID + " #" + value).remove();
}
function removeElement(collection, element)
{
var index = collection.indexOf(element);
if (index > -1)
collection.splice(index, 1);
}
function SetBatchFolder()
{
var folder = $("#selectBatchFolder").val();
MessageBox.Show("Apply to all", "Are you sure you want to put all the profile results to "+folder+" folder?</br>You cannot undo this action",
[{'title':'Cancel', 'callBack': MessageBox.Hide}, {'title':'Yes', 'callBack': function(){
}}]);
}
function RefreshResults(append)
{
if(!append)
{
$("#overFlow").html("");
}
else
{
loadedCount += limit;
}
$.post( "filtersCore.php", { method: "Search", limit: 10, loaded:loadedCount}, function(data){
// alert(data);
if(!append)
loadedCount = loadedCount;
// alert($("#overFlow #loadMore").html());
$("#overFlow").append(data);
});
// var url = "ProfileSearch.php";
// $.post( url, {count: 10}, function(data){
// $("#overFlow").html(data);
// });
}
|
{
"document_tone": {
"tone_categories": [
{
"tones": [
{
"score": 0.564948,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.157435,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.138658,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.087785,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.612799,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.772928,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.214325,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.265888,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.407522,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.827054,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.529213,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
"sentences_tone": [
{
"sentence_id": 0,
"text": "Man I can understand how it might be Kinda hard to love a girl like me I don't blame you much for wanting to be free I just wanted you to know For all my southside niggas that know me best I feel like me and taylor might still have sex Why?",
"input_from": 0,
"input_to": 241,
"tone_categories": [
{
"tones": [
{
"score": 0.028454,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.169816,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.024556,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.119018,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.595376,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0.641954,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.662312,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.308669,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.740588,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.569504,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.990547,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.15723,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
{
"sentence_id": 1,
"text": "I made that bitch famous (god damn) I made that bitch famous For all the girls that got dick from kanye west If you see 'em in the streets give 'em kanye's best Why? they mad they ain't famous (god damn) they mad they're still nameless (Talk that talk, man) Her man in the store tryna try his best But he just can't seem to get kanye fresh But we still hood famous (god damn) Yeah we still hood famous I just wanted you to know I loved you better than your own kin did From the very start I don't blame you much for wanting to be free I just wanted you to know I be puerto rican day parade floatin' That benz marina del rey coastin' She in school to be a real estate agent Last month I helped her with the car payment Young and we alive, whoo!",
"input_from": 242,
"input_to": 987,
"tone_categories": [
{
"tones": [
{
"score": 0.855281,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.104103,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.009754,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.011214,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.064333,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.036855,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.429528,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.385915,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.647487,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.84061,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.797784,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
{
"sentence_id": 2,
"text": "We never gonna die, whoo!",
"input_from": 988,
"input_to": 1013,
"tone_categories": [
{
"tones": [
{
"score": 0.129526,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.028271,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.157725,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.037398,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.655104,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0.849827,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.078582,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.29291,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.465276,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.588112,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.247837,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
{
"sentence_id": 3,
"text": "I just copped a jet to fly over personal debt Put one up in the sky The sun is in my eyes, whoo!",
"input_from": 1014,
"input_to": 1110,
"tone_categories": [
{
"tones": [
{
"score": 0.048488,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.454915,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.258117,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.120751,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.13686,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.423239,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.232102,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.186387,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.460563,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.092478,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.666559,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
{
"sentence_id": 4,
"text": "Woke up and felt the vibe, whoo!",
"input_from": 1111,
"input_to": 1143,
"tone_categories": [
{
"tones": [
{
"score": 0.050036,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.11371,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.291912,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.269423,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.163799,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.681699,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.100936,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.302654,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.5403,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.523006,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.091122,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
{
"sentence_id": 5,
"text": "No matter how hard they try, whoo!",
"input_from": 1144,
"input_to": 1178,
"tone_categories": [
{
"tones": [
{
"score": 0.147581,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.073955,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.135214,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.107112,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.491896,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0.920855,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.75152,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.076763,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.474357,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.381626,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.496419,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.533824,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
},
{
"sentence_id": 6,
"text": "We never gonna die I just wanted you to know",
"input_from": 1179,
"input_to": 1224,
"tone_categories": [
{
"tones": [
{
"score": 0.11148,
"tone_id": "anger",
"tone_name": "Anger"
},
{
"score": 0.017332,
"tone_id": "disgust",
"tone_name": "Disgust"
},
{
"score": 0.173227,
"tone_id": "fear",
"tone_name": "Fear"
},
{
"score": 0.012367,
"tone_id": "joy",
"tone_name": "Joy"
},
{
"score": 0.719189,
"tone_id": "sadness",
"tone_name": "Sadness"
}
],
"category_id": "emotion_tone",
"category_name": "Emotion Tone"
},
{
"tones": [
{
"score": 0,
"tone_id": "analytical",
"tone_name": "Analytical"
},
{
"score": 0,
"tone_id": "confident",
"tone_name": "Confident"
},
{
"score": 0.497569,
"tone_id": "tentative",
"tone_name": "Tentative"
}
],
"category_id": "language_tone",
"category_name": "Language Tone"
},
{
"tones": [
{
"score": 0.036738,
"tone_id": "openness_big5",
"tone_name": "Openness"
},
{
"score": 0.486887,
"tone_id": "conscientiousness_big5",
"tone_name": "Conscientiousness"
},
{
"score": 0.044086,
"tone_id": "extraversion_big5",
"tone_name": "Extraversion"
},
{
"score": 0.723795,
"tone_id": "agreeableness_big5",
"tone_name": "Agreeableness"
},
{
"score": 0.305698,
"tone_id": "emotional_range_big5",
"tone_name": "Emotional Range"
}
],
"category_id": "social_tone",
"category_name": "Social Tone"
}
]
}
]
}
|
var WsModel = function(model) {
var data = model;
{
if (!(data.pages instanceof Array)
|| data.pages.length === 0) {
data.pages = [ [] ];
}
if (!(data.runningTitles instanceof Array)) {
data.runningTitles = [];
}
}
function getPreferredIndex(page, item) {
var index = -1;
var i = 0;
var top = -1;
var rowHeight = 0;
while (i < data.pages[page].length && index === -1) {
var otherItem = data.pages[page][i];
if (top !== otherItem.y) {
top = otherItem.y;
rowHeight = getRowHeight(page, i);
}
if (item.x < (otherItem.x + otherItem.w)
&& otherItem.x < (item.x + item.w)
&& item.y < (otherItem.y + rowHeight)
&& otherItem.y < (item.y + item.h)) {
index = item.x < (otherItem.x + otherItem.w / 2) ? i : i + 1;
}
i++;
}
if (index === -1) {
return data.pages[page].length;
}
return index;
}
function getRowHeight(page, index, reverseLoop) {
var height = 0;
var y = data.pages[page][index].y;
var i = index;
var condition = function(i) {
return i < data.pages[page].length;
};
var step = 1;
if (reverseLoop) {
condition = function(i) {
return i >= 0;
};
step = -1;
}
while (condition(i)) {
var item = data.pages[page][i];
if (item.y !== y) {
break;
}
if (item.h > height
&& (item.type !== 'ls' && item.type !== 'ps')) {
height = item.h;
}
i += step;
}
return height;
}
function alignItem(page, index, item) {
var pageBottom = data.height - data.padding.bottom;
var pageHeight = pageBottom - data.padding.top;
if (item.w > data.width) {
item.w = data.width;
}
if (index === 0) {
item.x = 0;
item.y = data.padding.top;
} else {
var prevItem = data.pages[page][index - 1];
if (prevItem.type === 'ps'/* && item.type != 'ps' */) {
return null;
}
if ((prevItem.type === 'ls'
|| (prevItem.x + prevItem.w + item.w) > data.width)
&& (item.type !== 'ls' && item.type !== 'ps')) {
item.x = 0;
item.y = prevItem.y + getRowHeight(page, index - 1, true);
} else {
item.x = prevItem.x + prevItem.w;
item.y = prevItem.y;
}
}
if ((item.y + (item.type === 'ls' || item.type === 'ps' ? 0 : item.h))
>= pageBottom) {
if (index === 0) {
item.y = 0;
} else {
return null;
}
}
item.p = page;
item.i = index;
return item;
}
function alignedItem(page, index, item) {
return alignItem(page, index, $.extend(true, {}, item));
}
function update(page, index) {
if (data.pages[page].length == 0) {
if (page > 0) {
data.pages.splice(page, 1);
if (page < data.pages.length) {
return update(page, 0);
}
return [
data.pages[page - 1][data.pages[page - 1].length - 1],
data.pages[page - 1][data.pages[page - 1].length - 1] ];
}
} else if (index == 0
&& page > 0
&& alignedItem(page - 1, data.pages[page - 1].length,
data.pages[page][index]) !== null) {
return update(page - 1, data.pages[page - 1].length);
}
var length = data.pages[page].length;
var i = index;
while (i < data.pages[page].length
&& length == data.pages[page].length) {
if ((lastItem = alignItem(page, i, data.pages[page][i])) === null) {
var extraItems = data.pages[page].splice(i,
data.pages[page].length - i);
if (page + 1 == data.pages.length) {
data.pages.push(extraItems);
} else {
data.pages[page + 1] = extraItems
.concat(data.pages[page + 1]);
}
}
i++;
}
while (page + 1 < data.pages.length
&& i == data.pages[page].length
&& data.pages[page + 1].length != 0) {
var missingItem = alignedItem(page, i, data.pages[page + 1][0]);
if (missingItem === null) {
var p = page + 1;
if (data.pages[page + 1][0].p != p) {
while (p < data.pages.length) {
for ( var j = 0; j < data.pages[p].length; j++) {
data.pages[p][j].p = p;
}
p++;
}
lastItem = data.pages[data.pages.length - 1]
[data.pages[data.pages.length - 1].length - 1];
}
} else {
data.pages[page].push(data.pages[page + 1].shift());
data.pages[page][i].p = page;
data.pages[page][i].i = i;
data.pages[page][i].x = missingItem.x;
data.pages[page][i].y = missingItem.y;
}
i++;
}
var firstItem = index < data.pages[page].length
? data.pages[page][index]
: data.pages[page][data.pages[page].length - 1];
if (!firstItem) {
firstItem = {
p : page,
i : 0
};
}
var lastItem = data.pages[page][data.pages[page].length - 1];
if (!lastItem) {
lastItem = {
p : page,
i : 0
};
}
var range = [ firstItem, lastItem ];
if (length != data.pages[page].length
&& page + 1 < data.pages.length) {
range[1] = update(page + 1, 0)[1];
}
return range;
}
var pagesChangeEventListeners = [];
function firePagesChangeEvent() {
for (var i in pagesChangeEventListeners) {
pagesChangeEventListeners[i]
.onPagesChange(data.pages.length);
}
}
var changeEventListeners = [];
function fireChangeEvent(range) {
for (var i in changeEventListeners) {
changeEventListeners[i].onChange(range);
}
}
var self = this;
this.getWidth = function() {
return data.width;
};
this.getHeight = function() {
return data.height;
};
this.getPadding = function(padding) {
return data.padding;
};
this.setPadding = function(padding) {
if (typeof data.padding !== 'object') {
data.padding = {
top : 0,
left : 0,
right : 0,
bottom : 0,
};
}
Object.extend(data.padding, padding, true);
};
this.get = function(page, index) {
if (typeof page == 'number') {
if (typeof index == 'number') {
return data.pages[page][index];
}
return data.pages[page];
}
return data;
};
this.add = function(page, item) {
var index = getPreferredIndex(page, item);
if (!alignedItem(page, index, item)) {
item.p = -1;
item.i = -1;
return false;
}
data.pages[page].splice(index, 0, item);
return this.update(page, index);
};
this.insert = function(page, index, item) {
if (!alignedItem(page, index, item)) {
return false;
}
data.pages[page].splice(index, 0, item);
return this.update(page, index);
};
this.remove = function(page, index) {
var item = data.pages[page].splice(index, 1)[0];
item.p = -1;
item.i = -1;
return this.update(page, index);
};
this.realign = function(page, index) {
var pageCount = data.pages.length;
var item = data.pages[page].splice(index, 1)[0];
item.p = -1;
item.i = -1;
var range = update(page, index);
if (page >= data.pages.length) {
alignItem(page, 0, item);
data.pages.push([ item ]);
} else {
index = getPreferredIndex(page, item);
if (alignedItem(page, index, item)) {
data.pages[page].splice(index, 0, item);
var range2 = update(page, index);
if (range) {
if (range2[0].p < range[0].p
|| range2[0].p == range[0].p
&& range2[0].i < range[0].i) {
range[0] = range2[0];
}
if (range2[1].p > range[1].p
|| range2[1].p == range[1].p
&& range2[1].i > range[1].i) {
range[1] = range2[1];
}
} else {
range = range2;
}
}
}
if (range) {
fireChangeEvent(range);
}
if (pageCount != data.pages.length) {
firePagesChangeEvent();
}
return index;
};
this.update = function(page, index) {
var pageCount = data.pages.length;
var range = [];
if (typeof page === 'undefined' && typeof index === 'undefined') {
for (var p = 0; p < data.pages.length; p++) {
if (range.length === 0) {
range = update(p, 0);
} else {
if (range[0].p <= p && range[1].p >= p) {
continue;
}
var newRange = update(p, 0);
if (newRange[0].p <= range[0].p
&& newRange[0].i <= range[0].i) {
range[0] = newRange[0];
}
if (newRange[1].p >= range[1].p
&& newRange[1].i >= range[1].i) {
range[1] = newRange[1];
}
}
}
} else {
range = update(page, index);
}
fireChangeEvent(range);
if (pageCount != data.pages.length) {
firePagesChangeEvent();
}
return range;
};
this.find = function(query) {
var items = [];
for (var page = 0; page < data.pages.length; page++) {
for (var index = 0; index < data.pages[page].length; index++) {
var item = data.pages[page][index];
if (Object.matches(data.pages[page][index], query)) {
items.push(item);
}
}
}
return items;
};
this.addPagesChangeEventListener = function(listener) {
pagesChangeEventListeners.push(listener);
};
this.removePagesChangeEventListener = function(listener) {
var index = pagesChangeEventListeners.indexOf(listener);
if (index == -1) {
return;
}
pagesChangeEventListeners.splice(index, 1);
};
this.addChangeEventListener = function(listener) {
changeEventListeners.push(listener);
};
this.removeChangeEventListener = function(listener) {
var index = changeEventListeners.indexOf(listener);
if (index == -1) {
return;
}
changeEventListeners.splice(index, 1);
};
};
|
function saveChange() {
var user = {};
user.lastName = $("#mf1").val();
user.firstName = $("#mf2").val();
user.patronymicName = $("#mf3").val();
user.login = $("#mf4").val();
$.ajax({
type: 'POST',
url: '/api/profile/update',
headers: {
'X-CSRF-TOKEN': $('meta[name=_csrf]').attr("content")
},
processData: false,
contentType: 'application/json',
data: JSON.stringify(user),
success: function (data) {
var alert;
if (data.status == 'success') {
console.log("Update success! " + JSON.stringify(data));
alert = $('<div id="update-profile-alert" class="alert alert-success" role="alert">' +
data.message + "</div>");
var account = $('#navbar-account-button');
account.text("Welcome, " + user.firstName + " " + user.lastName + "!");
} else {
console.log("Error! " + JSON.stringify(data));
alert = $('<div id="update-profile-alert" class="alert alert-danger" role="alert">' +
data.message + '</div>');
}
$("#update-profile-alert").replaceWith(alert);
},
error: function (data) {
console.error("Error" + JSON.stringify(data));
var alert = $('<div id="update-profile-alert" class="alert alert-danger" role="alert">' +
"Error</div>");
$("#update-profile-alert").replaceWith(alert);
}
});
}
function changePassword() {
var currentPassword = $("#currentPassword").val();
var newPassword = $("#newPassword").val();
$.ajax({
type: 'POST',
url: '/api/profile/changePassword',
headers: {
'X-CSRF-TOKEN': $('meta[name=_csrf]').attr("content")
},
data: {
currentPassword : currentPassword,
newPassword : newPassword
},
success: function (data) {
var alert;
if (data.status == 'success') {
console.log("Update success! " + JSON.stringify(data));
alert = $('<div id="change-password-alert" class="alert alert-success" role="alert">' +
data.message + "</div>");
} else {
console.log("Error! " + JSON.stringify(data));
alert = $('<div id="change-password-alert" class="alert alert-danger" role="alert">' +
data.message + '</div>');
}
$("#change-password-alert").replaceWith(alert);
},
error: function (data) {
console.error("Error" + JSON.stringify(data));
var alert = $('<div id="change-password-alert" class="alert alert-danger" role="alert">' +
"Error </div>");
$("#change-password-alert").replaceWith(alert);
}
});
}
function loadInfo() {
$.ajax({
url: '/api/profile/get',
success: function (data) {
showInfo(data);
},
error: function (data) {
showInfo(data);
}
}
);
}
function showInfo(data) {
$("#mf1").val(data.lastName);
$("#mf2").val(data.firstName);
$("#mf3").val(data.patronymicName);
$("#mf4").val(data.login);
}
$(document).ready(function () {
loadInfo();
});
|
import Carousel from "./Carousel";
import "./MyWork.css"
const MyWork = (props) => {
return(
<div id="my-work" style={{marginBottom:'20px'}}>
<div style={{height:"725px"}} className="myWork">
<h1>My Work</h1>
<Carousel />
</div>
</div>
)
}
export default MyWork;
|
const header = document.getElementsByTagName("logo")[0].nodeValue
header.addEventListener('click',function(){
window.location.href = "/WEB-INF/crm/home"
})
|
import React from 'react'
import { connect } from 'react-redux'
import TagList from '../common/TagList'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
UPDATE_FIELD_RECORD_EDITOR,
REMOVE_KEY
} from '../../constants'
const mapStateToProps = state => ({
keyList: state.recordEditor.keyList
})
const mapDispatchToProps = dispatch => ({
onUpdateKeyList: value => dispatch({
type: UPDATE_FIELD_RECORD_EDITOR,
key: 'keyList',
value
}),
onRemoveKey: index => dispatch({
type: REMOVE_KEY,
index
})
})
class Keys extends React.Component {
constructor(props){
super(props)
this.state = { keyInput: '' }
this.changeKeyInput = ev => this.setState({ keyInput: ev.target.value })
this.watchForEnter = ev => {
ev.preventDefault()
if(ev.keyCode === 13 && ev.target.value !== ''){
this.props.onUpdateKeyList(this.props.keyList.concat([this.state.keyInput]))
this.setState({ keyInput: '' })
}
}
this.removeKey = index => ev => {
ev.preventDefault()
this.props.onRemoveKey(index)
}
}
render(){
return (
<div className="record-section keys">
<div className="row">
<div className="col-xs-1">
<FontAwesomeIcon icon='tags' />
</div>
<div className="col-xs-11">
<TagList tagList={this.props.keyList} removeTag={this.removeKey} />
</div>
</div>
<input type="text" value={this.state.keyInput} onChange={this.changeKeyInput} onKeyUp={this.watchForEnter} />
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Keys)
|
import Player from '../prefabs/Player'
import Mouse from '../prefabs/Mouse'
import NumberBox from '../prefabs/NumberBox'
export default class Level2 extends Phaser.State {
constructor() {
super()
}
create() {
// physics
this.physics.startSystem(Phaser.Physics.ARCADE)
this.physics.arcade.gravity.y = 800
// map start
this.map = this.add.tilemap('level2')
// parallax background
this.map.addTilesetImage('gamebg')
this.bg = this.map.createLayer('bg')
this.bg.scrollFactorX = 0.6
this.bg.scrollFactorY = 0.6
// walkable tiles
this.map.addTilessetImage('Tiles')
this.layer = this.map.createLayer('Level1')
// collision
this.layer.resizeWorld()
this.map.setCollisionBetween(6, 25, true, this.layer)
// coin layer
this.coins = this.add.group()
this.coins.physicsBodyType = Phaser.Physics.ARCADE
this.coins.enableBody = true
this.map.createFromObjects('Collectables', 241, 'coin', null, true, false, this.coins)
this.coins.setAll('body.gravity', 0)
// place doors
this.doors = this.add.group()
this.doors.physicsBodyType = Phaser.Physics.ARCADE
this.doors.enableBody = true
this.map.createFromObjects('Doors', 242, 'sign', null, true, false, this.doors)
this.doors.setAll('body.gravity', 0)
// player
this.map.createFromObjects('Player', 243, null, null, true, false, this.world, Player)
this.player = this.world.getTop()
// enemies
this.enemies = this.add.group()
this.map.createFromObjects('Enemies', 225, null, null, true, false, this.enemies, Mouse)
// UI
this.UIGroup = this.add.group()
this.scoreField = new NumberBox(this.game, 'scoreholder', this.game.score, this.UIGroup)
this.scoreField.fixedToCamera = true
this.sfx = this.add.audioSprite('sfx')
this.camera.follow(this.player)
}
update() {
this.physics.arcade.collide(this.player, this.layer)
this.physics.arcade.collide(this.enemies, this.layer)
this.physics.arcade.overlap(this.player, this.doors, this.hitDoor, null, this)
this.physics.arcade.overlap(this.player, this.coins, this.collectCoin, null, this)
this.physics.arcade.overlap(this.player, this.enemies, this.hitEnemy, null, this)
}
collectCoin(playerRef, coinRef) {
coinRef.kill()
this.game.score ++
this.scoreField.setValue(this.game.score)
this.sfx.play('coin')
}
hitDoor(playerRef, doorRef) {
this.game.state.start('GameOver')
}
hitEnemy() {
if (playerRef.flashEffect.isRunning) {
playerRef.flash()
this.sfx.play('hit')
if (this.game.score > 0) {
this.game.score --
this.scoreField.setValue(this.game.score)
}
}
}
}
|
/* eslint-disable react/jsx-filename-extension */
/* eslint-disable linebreak-style */
import React, { useState, useEffect} from 'react';
import PageDefault from '../../../Componentes/PageDefault';
import FormField from '../../../Componentes/FormField';
import Button from '../../../Componentes/Button';
export default function CadastroCategoria() {
const valoresIniciais = {
nome: '',
descrição: '',
cor: '#ffffff',
};
const [categorias, setCategorias] = useState([]);
const [values, setValues] = useState(valoresIniciais);
function setValue(chave, valor) {
setValues({
...values,
[chave]: valor,
});
}
function handleChange(props) {
const { name, value } = props.target;
setValue(
name,
value,
);
}
useEffect(() => {
const URL_DB = 'http://localhost:8080/Categorias';
fetch(URL_DB)
.then(async (respostadoservidor) => {
const resposta = await respostadoservidor.json();
setCategorias([
...resposta,
]);
})
.then((converteu) => {
console.log(converteu);
});
});
return (
<PageDefault>
<h1>
Cadastro da categoria:
{values.name}
</h1>
<form onSubmit={function handleSubmit(Props) {
Props.preventDefault();
setCategorias([...categorias, values]);
setValues(valoresIniciais);
}}
>
<FormField
label="Nome da categoria"
type="text"
name="nome"
value={values.nome}
onChange={handleChange}
/>
<FormField
label="Descrição"
type="textarea"
name="descrição"
value={values.descrição}
onChange={handleChange}
/>
<FormField
label="Cor"
type="color"
name="cor"
value={values.cor}
onChange={handleChange}
/>
<Button>
Cadastrar
</Button>
<ul>
{categorias.map((categoria, indice) => (
<li key={`${categoria.nome}`}>
<h1 style={{ color: categoria.cor }}>{categoria.nome}</h1>
<p>{categoria.descrição}</p>
</li>
))}
</ul>
</form>
</PageDefault>
);
}
|
// Generated by CoffeeScript 1.7.1
(function() {
var INTERVAL, SIZE, per_page, wall, wall_id;
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
}
wall_id = null;
wall = {};
SIZE = 5;
per_page = SIZE;
INTERVAL = 3000;
window.main = {
initialize: function(id) {
return this.load(id);
},
wall_url: function(id) {
return "/walls/" + id + ".json";
},
load: function(id) {
return $.get(this.wall_url(id), function(data) {
wall = data.wall;
way.set("wall", wall);
wall_id = id;
if (wall.background_image_url) {
$("body").css("background-image", "url(" + wall.background_image_url + ")");
}
return main.draw(0);
});
},
draw: function(start) {
var current, next_start, normal, sticky;
normal = wall.messages;
sticky = wall.sticky_messages;
current = wall.messages.slice(start, start + per_page);
if (sticky.length > 0) {
per_page = SIZE - sticky.length;
current = sticky.concat(normal.slice(start, start + per_page));
}
next_start = start + (per_page - sticky.length);
way.set("messages", current);
this.updateClass();
if (normal[next_start]) {
return setTimeout(function() {
return main.draw(start + per_page);
}, INTERVAL);
} else {
return setTimeout(function() {
return main.load(wall_id);
}, INTERVAL);
}
},
updateClass: function() {
return $(".message-box .content").each(function() {
var length;
length = $(this).text().trim().length;
if (length < 10) {
return $(this).addClass('text-large');
} else if (length > 10 && length < 40) {
return $(this).addClass('text-medium');
} else {
return $(this).addClass('text-small');
}
});
}
};
$(document).ready(function() {
if (screenfull.isFullscreen) {
$("#exit_full_screen").show();
} else {
$("#enter_full_screen").show();
}
if (screenfull.enabled) {
$("#enter_full_screen").click(function() {
screenfull.request();
$("#enter_full_screen").hide();
return $("#exit_full_screen").show();
});
return $("#exit_full_screen").click(function() {
screenfull.exit();
$("#exit_full_screen").hide();
return $("#enter_full_screen").show();
});
}
});
}).call(this);
|
const toggle = document.querySelector(".nav__toggle");
const navLinks = document.querySelector(".nav__links");
navLinks.classList.remove("open");
function openNav() {
toggle.classList.add("open");
navLinks.classList.add("open");
window.addEventListener("click", closeNav);
}
function closeNav() {
toggle.classList.remove("open");
navLinks.classList.remove("open");
window.removeEventListener("click", closeNav);
}
toggle.addEventListener("click", e => {
e.stopPropagation();
if (toggle.classList.contains("open")) {
closeNav();
} else {
openNav();
}
});
|
const todoInput = document.querySelector('.todo-input');
const todoButton = document.querySelector('.todo-button');
const todoList = document.querySelector('.todo-list');
const filterTodo = document.querySelector('.filter-todo');
document.addEventListener('DOMContentLoaded', function (e) {
getTodo();
});
todoButton.addEventListener('click', addTodos);
todoList.addEventListener('click', deleteCheck);
filterTodo.addEventListener('click', filtertodos);
function addTodos(e) {
const todoDiv = document.createElement('div');
todoDiv.className = 'todo';
const todos = document.createElement('li');
todos.className = 'todo-item';
setTodos(todoInput.value);
todos.appendChild(document.createTextNode(todoInput.value));
todoDiv.appendChild(todos);
todoInput.value = '';
//creating complete button
const completeBtn = document.createElement('button');
completeBtn.className = 'complete-btn';
completeBtn.innerHTML = '<li class="fas fa-check"></li>';
todoDiv.appendChild(completeBtn);
//creating trash button
const trashBtn = document.createElement('button');
trashBtn.className = 'trash-btn';
trashBtn.innerHTML = '<li class="fas fa-trash"></li>';
todoDiv.appendChild(trashBtn);
todoList.appendChild(todoDiv);
e.preventDefault();
}
function deleteCheck(e) {
const items = e.target;
if (items.className === 'trash-btn') {
const todo = items.parentElement;
todo.classList.add('fall');
removeTodo(todo);
todo.addEventListener('transitionend', function () {
todo.remove();
});
}
if (items.className === 'complete-btn') {
const todo = items.parentElement;
todo.classList.toggle('completed');
}
e.preventDefault();
}
function filtertodos(e) {
const todos = todoList.childNodes;
todos.forEach(function (todo) {
switch (e.target.value) {
case 'all':
todo.style.display = 'flex';
break;
case 'completed':
if (todo.classList.contains('completed')) {
todo.style.display = 'flex';
} else {
todo.style.display = 'none';
}
break;
case 'uncompleted':
if (!todo.classList.contains('completed')) {
todo.style.display = 'flex';
} else {
todo.style.display = 'none';
}
break;
}
});
e.preventDefault();
}
//getting to local storage
function setTodos(todo) {
let todos;
if (localStorage.getItem('todos') === null) {
todos = [];
} else {
todos = JSON.parse(localStorage.getItem('todos'));
}
todos.push(todo);
//set items to llocalstorage
localStorage.setItem('todos', JSON.stringify(todos));
}
function getTodo(todo) {
let todos;
if (localStorage.getItem('todos') === null) {
todos = [];
} else {
todos = JSON.parse(localStorage.getItem('todos'));
}
todos.forEach(function (todo) {
const todoDiv = document.createElement('div');
todoDiv.className = 'todo';
const todos = document.createElement('li');
todos.className = 'todo-item';
todos.appendChild(document.createTextNode(todo));
todoDiv.appendChild(todos);
todoInput.value = '';
//creating complete button
const completeBtn = document.createElement('button');
completeBtn.className = 'complete-btn';
completeBtn.innerHTML = '<li class="fas fa-check"></li>';
todoDiv.appendChild(completeBtn);
//creating trash button
const trashBtn = document.createElement('button');
trashBtn.className = 'trash-btn';
trashBtn.innerHTML = '<li class="fas fa-trash"></li>';
todoDiv.appendChild(trashBtn);
todoList.appendChild(todoDiv);
});
}
function removeTodo(todo) {
let todos;
if (localStorage.getItem('todos') === null) {
todos = [];
} else {
todos = JSON.parse(localStorage.getItem('todos'));
}
const todoIndex = todo.children[0].innerText;
todos.splice(todos.indexOf(todoIndex), 1);
localStorage.setItem('todos', JSON.stringify(todos));
}
|
import BorderConfig, { borders } from './border'
import ColorConfig, { color } from './color'
import GridConfig, { grid } from './grid'
import PaddingConfig from './padding'
import RadiusConfig, { radius } from './radius'
import SizingConfig, { sizing } from './sizing'
import TypographyConfig, { typography } from './typography'
// @TODO use this.
// eslint-disable-next-line no-unused-vars
const defaultTheme = {
...borders,
...color,
...grid,
...radius,
...sizing,
...typography,
}
// const defaultTheme = {
// color: {
// // mode: MODE_DEFAULT,
// // pallet: {
// // primary: basePallet.primary,
// // secondary: basePallet.secondary,
// // tertiary: basePallet.tertiary,
// // light: basePallet.white,
// // neutral: basePallet.gray,
// // dark: basePallet.black,
// // success: basePallet.green,
// // info: basePallet.blue,
// // warning: basePallet.orange,
// // danger: basePallet.red,
// // prominent: basePallet.primary,
// // },
// // factors: {
// // alpha: 0.3,
// // dark: {
// // min: 0.08,
// // less: 0.15,
// // more: 0.2,
// // max: 0.5,
// // },
// // light: {
// // min: 0.2,
// // less: 0.5,
// // more: 25,
// // max: 50,
// // },
// // },
// },
// spacing: {
// min: '0',
// tiny: '2px',
// xxSmall: '4px',
// xSmall: '8px',
// small: '12px',
// medium: '16px',
// large: '24px',
// xLarge: '32px',
// xxLarge: '48px',
// giant: '64px',
// max: '88px',
// },
// grid: {
// gap: 'medium',
// columnMin: '280px',
// breakpoints: {
// min: '320px',
// small: '480px',
// mobile: '480px',
// medium: '768px',
// large: '992px',
// container: '1200px',
// max: '1200px',
// },
// },
// radius: {
// size: 'tiny',
// corners: {
// topLeft: 'tiny',
// topRight: 'tiny',
// bottomRight: 'tiny',
// bottomLeft: 'tiny',
// },
// },
// borders: {
// width: 'tiny',
// style: 'solid',
// structures: false,
// elements: false,
// controls: true,
// buttons: false,
// },
// typography: {
// families: {
// primary: {
// base: 'Helvetica',
// fallback: 'sans-serif',
// kerning: '', // letter-spacing
// tracking: '', // word-spacing
// },
// secondary: {
// base: 'Times New Roman',
// fallback: 'serif',
// kerning: '',
// tracking: '',
// },
// tertiary: {
// base: 'Monaco',
// fallback: 'monospace',
// kerning: '',
// tracking: '',
// },
// },
// weights: {
// base: 400,
// lighter: 100,
// light: 200,
// semiBold: 600,
// bold: 700,
// bolder: 900,
// },
// sizes: {
// base: 'inherit',
// small: '0.75em',
// large: '1.5em',
// // Min and max are used for body font size scaling with all other sizes being calculated from that using ems.
// min: '12px',
// max: '16px',
// h1: '3.21em',
// h2: '2.36em',
// h3: '1.64em',
// h4: '1.29em',
// h5: '1.15em',
// h6: '1em',
// },
// // margin; space before and after the text
// spacing: {
// base: '0',
// paragraph: '1em 0',
// heading: '1.25em 0 1em 0',
// },
// // line-height
// leading: {
// base: '1.6em',
// min: '1em',
// max: '2em',
// },
// indent: '1em',
// hyphenation: {
// wrap: 'normal',
// break: 'normal',
// },
// styles: {
// paragraph: {
// family: 'primary',
// style: 'normal',
// weight: 'base',
// size: 'base',
// align: 'justify',
// justify: 'auto',
// transform: 'none',
// decoration: 'none',
// // these are modifiers for the base value provided by the typeface.
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// heading: {
// family: 'primary',
// style: 'normal',
// weight: 'bold',
// // Size is intentionally commented out; heading size is set based on the level prop.
// // size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'min',
// },
// quote: {
// family: 'primary',
// style: 'italic',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// text: {
// family: 'primary',
// style: 'normal',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// label: {
// family: 'primary',
// style: 'normal',
// weight: 'bold',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'min',
// },
// message: {
// family: 'primary',
// style: 'normal',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// button: {
// family: 'primary',
// style: 'normal',
// weight: 'bold',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// link: {
// family: 'primary',
// style: 'normal',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// hover: {
// decoration: 'underline',
// },
// active: {
// decoration: 'underline',
// },
// },
// caption: {
// family: 'primary',
// style: 'normal',
// weight: 'light',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// legal: {
// family: 'secondary',
// style: 'italic',
// weight: 'base',
// size: 'small',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// code: {
// family: 'tertiary',
// style: 'normal',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// emphasized: {
// family: 'primary',
// style: 'italic',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// strong: {
// family: 'primary',
// style: 'normal',
// weight: 'bold',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// variable: {
// family: 'tertiary',
// style: 'italic',
// weight: 'base',
// size: 'base',
// align: 'left',
// justify: 'none',
// transform: 'none',
// decoration: 'none',
// kerning: 'base',
// tracking: 'base',
// leading: 'base',
// },
// },
// },
//
// // Component configuration.
// links: {
// base: 'primary',
// hover: 'secondary',
// active: 'tertiary',
// visited: 'tertiary',
// disabled: 'neutral',
// },
// buttons: {
// spacing: {
// x: 'medium',
// y: 'small',
// },
// },
// navItems: {
// spacing: {
// x: 'small',
// y: 'small',
// },
// paginationSpacing: {
// x: 'xSmall',
// y: 'xSmall',
// },
// current: {
// effect: 'line|background|color',
// background: 'primary',
// color: 'primary',
// lineColor: 'primary',
// lineSize: 'tiny',
// },
// },
// }
class Theme {
constructor(config = {}) {
this.name = config.name || 'horns-theme'
// Base Configs
this.color = new ColorConfig(config.color)
this.typography = new TypographyConfig(config.typography)
this.sizing = new SizingConfig(config.sizing)
// Dependent Configs
this.borders = new BorderConfig(this.sizing, config.borders)
this.padding = new PaddingConfig(this.sizing, config.padding)
this.radius = new RadiusConfig(this.sizing, config.radius)
this.grid = new GridConfig(this.sizing, config.grid)
// Components
this.links = {}
this.buttons = {}
this.navItems = {}
// etc.
}
}
export default Theme
|
export default function () {
const example = document.getElementById('example')
const newText = document.createTextNode('Hola Mundo')
example.appendChild(newText)
}
|
import React from 'react';
import './App.css';
import NestedComponentsExample from './nesting_components/nested_components_main_container';
import ComponentStateAndInteractions from './component_state_and_interactions/component_state_and_interactions_main_container';
import ConditionalRendering from './conditional_rendering/conditional_rendering_main_container';
import LifecycleComponentExample from './lifecycle/lifecycle_example_main_container';
import HttpCallExample from './http_call_example/http_call_example';
import {
BrowserRouter as Router,
Route,
Switch,
NavLink
} from 'react-router-dom'
import ContextExample from "./context_example/context_main_container";
class App extends React.Component {
render() {
return (
<Router>
<div>
<header className="App-header">
<h1 className="App-title">Welcome to KindGeek React School</h1>
</header>
<ul>
<li><NavLink to="/">Context</NavLink></li>
<li><NavLink to="/http_call_example">Http call example</NavLink></li>
<li><NavLink activeClassName='loandbehold' to="/nested">Nested</NavLink></li>
<li><NavLink to="/conditional">Conditional rendering</NavLink></li>
<li><NavLink activeClassName='loandbehold' to="/products/1">Internal state</NavLink></li>
<li><NavLink activeClassName='loandbehold' to='/lifecycle'>Lifecycle</NavLink></li>
</ul>
<hr/>
<Switch>
<Route exact path="/" component={ContextExample}></Route>
<Route path="/nested" component={NestedComponentsExample}/>
<Route path="/conditional" component={ConditionalRendering}/>
show difference between switch and route
<Route path="/lifecycle" component={LifecycleComponentExample}></Route>
<Route path="/products/:id" component={ComponentStateAndInteractions}/>
<Route path="/products/step1" component={ComponentStateAndInteractions}/>
<Route path="/products/step1/step2" component={ComponentStateAndInteractions}/>
<Route path="/http_call_example" component={HttpCallExample}/>
<Route component={NoMatch}/>
</Switch>
{/*<Switch>*/}
{/*/!*<Route path="/" exact component={Home} />*!/*/}
{/*/!*<Route path="/will-match" component={WillMatch} />*!/*/}
</div>
</Router>
);
}
}
export default App;
const NoMatch = ({location, match}) => (
<div>
<h3>
No match for <code>{location.pathname}</code>
</h3>
</div>
);
|
import CONFIG from "web.config";
import MasterPage from "components/website/master/MasterPage";
import BasicLayout from "components/diginext/layout/BasicLayout";
import { useRouter } from "next/router";
import Header from "components/website/elements/Header";
import DashkitButton from "components/dashkit/Buttons";
import { BS } from "components/diginext/elements/Splitters";
import BannerTop from "components/website/pages/contact-us/section-banner-top/BannerTop";
import SectionAddress from "components/website/pages/contact-us/section-address/Address";
import Footer from "components/website/elements/Footer";
import Axios from "axios";
import {useEffect, useRef, useState, useContext } from "react";
import {MainContent} from "components/website/contexts/MainContent";
export async function getServerSideProps(context) {
// const params = context.params;
// const query = context.query;
// context.req.session ,
// context.res
// console.log(context.query);
console.log("SERVER CODE");
// var json = { data: [1, 2, 3, 4, 5] };
return {
props: {
// params
},
};
}
export default function ContactUs(props) {
const router = useRouter();
if (typeof window == "undefined") {
console.log("This code is on server-side");
}
const valueLanguageContext = useContext(MainContent);
const [dataOffice, setDataOffice] = useState();
const callAPI = async (url, callbackFn)=>{
let config = {
headers: {
'X-localization': valueLanguageContext.languageCurrent,
}
}
await Axios
.get(`${url}`, config)
.then((response) => callbackFn(response.data))
.catch((error) => console.log(error));
}
useEffect(() => {
callAPI(
"https://api.lipovitan.zii.vn/api/v1/offices?limit=3&page=1",
setDataOffice
)
}, []);
useEffect(() => {
callAPI(
"https://api.lipovitan.zii.vn/api/v1/offices?limit=3&page=1",
setDataOffice
)
}, [valueLanguageContext.languageCurrent]);
useEffect(() => {
if(dataOffice){
console.log(dataOffice.data.list);
}
}, [dataOffice]);
return (
<MasterPage pageName={"Contact us"}>
<Header hideButtons></Header>
<main id="contactPage">
<BannerTop></BannerTop>
{
dataOffice
? <SectionAddress data={ dataOffice }></SectionAddress>
: <> </>
}
</main>
<Footer></Footer>
</MasterPage>
);
}
|
// redux
// import store from '@/store';
// import { changeShowChartStatus, getChartData } from '@/store/actions';
// import { GET } from '@/plugins/fetch/';
import AppConfig from '@/AppConfig';
import scene from '@/three/scene';
import { Group } from 'three';
import {
jsonLoader
} from '@/three/loaders';
import { domEvents } from '@/three/controls';
import transparent from '@/utils/three/material/transparent';
// 异步加载模型
// import(/* webpackChunkName: 'car-part' */ '@/static/json/car-part/A2056300403/A2056300403.json')
// .then(function (moduleCarPart) {
// console.log(moduleCarPart)
// // loadCompleted(moduleCarPart);
// })
// GET('/src/static/json/car-part/A2056300303/A2056300303.json')
// .then(function(moduleCarPart) {
// // loadCompleted(moduleCarPart);
// });
// GET('/src/static/json/car-part/A2056300403/A2056300403.json')
// .then(function(moduleCarPart) {
// // loadCompleted(moduleCarPart);
// });
// GET('/src/static/json/data.json')
// .then(function(moduleCarPart) {
// // loadCompleted(moduleCarPart);
// });
// 用来装所有零件
export var carPart = new Group();;
/**
* 模型加载完成处理
* @param {Object} car_part model
* @return {void}
*/
function loadCompleted(moduleCarPart) {
// 解析JSON为three的scene;
carPart.add(jsonLoader.parse(moduleCarPart));
carPart.position.z = -10;
carPart.scale.set(0.04, 0.04, 0.04)
// 设为透明
// transparent(carPart, 0);
carPart.visible = false;
scene.add(carPart);
// 通知store加载完成
domEvents.addEventListener(carPart, 'click', function(ev) {
// 非隐藏状态
if (ev.target.material.opacity !== 0) {
store.dispatch(changeShowChartStatus(true));
store.dispatch(getChartData());
}
}, false);
}
var getAllParts = function() {
return carPart;
}
export default getAllParts;
|
(function() {
"use strict";
/*
Home module for displaying home page content.
*/
var app;
app = angular.module("koan.home", ["ngRoute", "monospaced.elastic", "koan.common"]);
app.config(function($routeProvider) {
return $routeProvider.when("/", {
title: "KOAN Home",
templateUrl: "modules/home/home.html",
controller: "HomeCtrl"
});
});
}).call(this);
|
class File {
constructor(options) {
const {
id,
name = 'default',
figures = [],
} = options
this.id = id
this.name = name
this.figures = figures
}
}
export default File
|
import Department from '../../../../../models/erp/department'
import User from '../../../../../models/auth/user'
import Employee from '../../../../../models/erp/employee'
export default [
{
prop: 'username',
label: '用户名',
trim: true,
rule: { required: true, validator: async(rule, value, form, defaultForm, callback) => {
if (!value) {
callback(new Error('用户名不能为空'))
return
}
const data = await User.page(1, 10, [{ filterType: 'EQ', property: 'nickname', value: value }], [])
if (defaultForm.username !== value && data.content.length !== 0) {
callback(new Error('用户名已经存在'))
return
}
callback()
}, trigger: 'blur' },
render(h) {
return <i-input v-model={this.model} placeholder='请填写用户名'></i-input>
}
},
{
prop: 'name',
label: '姓名',
render(h) {
return <i-input v-model={this.model} placeholder='请填写姓名'></i-input>
}
},
{
prop: 'sn',
label: '工号',
trim: true,
rule: { required: true, validator: async(rule, value, form, defaultForm, callback) => {
if (!value) {
callback(new Error('员工工号不能为空'))
return
}
const data = await Employee.search(1, 10, [{ filterType: 'EQ', property: 'sn', value: value }], [])
if (defaultForm.sn !== value && data.content.length !== 0) {
callback(new Error('员工工号已经存在'))
return
}
callback()
}, trigger: 'blur' },
render(h) {
return <i-input v-model={this.model} placeholder='请填写工号'></i-input>
}
},
{
prop: 'departmentIds',
label: '部门',
default: [[]],
transform(value) {
const arr = []
value.forEach(it => { if (_.last(it)) arr.push(_.last(it)) })
return arr.length > 0 ? arr : null
},
rule: { required: true, validator: (rule, value, form, defaultForm, callback) => {
const arr = []
if (value[0].length === 0) {
callback(new Error('请选择上级部门'))
return false
}
value.forEach(it => { arr.push(_.last(it)) })
const deweightingArr = _.uniq(arr)
if (deweightingArr.length !== value.length) {
callback(new Error('选择的部门不能重复'))
return false
}
callback()
}, trigger: 'blur' },
render(h) {
h = this.$root.$createElement
const tranformData = (data) => {
data.forEach(it => {
it.value = it.id
it.label = it.name
if (it.children && it.children.length > 0) {
tranformData(it.children)
}
})
}
const loadData = async() => {
const result = await Department.expand()
tranformData(result)
return result
}
return <multiple-department v-model={this.model} load-data={loadData}></multiple-department>
}
},
{
prop: 'roleIds',
label: '角色',
default: [],
render(h) {
const roles = this.$root.roles
const options = roles.map(it => { return <i-option value={it.id}>{it.name}</i-option> })
return <i-select v-model={this.model} multiple clearable>{options}</i-select>
}
},
{
prop: 'status',
label: '在职状态',
default: 'DUTY',
render(h) {
return <radio-group v-model={this.model}>
<radio label='DUTY'>在职</radio>
<radio label='NONDUTY'>离职</radio>
</radio-group>
}
}
]
|
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { makeStyles } from '@material-ui/styles';
import MaterialTable from 'material-table';
import PropTypes from 'prop-types';
import PerfectScrollbar from 'react-perfect-scrollbar';
import { useUserPreferencePaginationData } from 'redux/UserPreference/selectors';
import {
generatePaginateOptions,
getPaginationOption,
getPaginationOptionIndexMapper
} from 'utils/pagination';
import { updateUserPreferenceData } from 'redux/UserPreference/operators';
import { LargeCircularLoader } from '../Loader/CircularLoader';
const useStyles = makeStyles((theme) => ({
tableWrapper: {
'& tbody>.MuiTableRow-root:hover': {
background: '#EEE'
}
},
cursorPointer: {
cursor: 'pointer'
}
}));
export default function CustomMaterialTable({
className,
style,
userPreferencePaginationKey,
pointerCursor,
...props
}) {
const classes = useStyles();
const dispatch = useDispatch();
const tableRef = useRef(null);
const userPreferencePaginationData = useUserPreferencePaginationData();
const pageSizeOptions = generatePaginateOptions(props.data.length);
const [defaultPageSize, setDefaultPageSize] = useState(
getPaginationOption(userPreferencePaginationData[userPreferencePaginationKey], pageSizeOptions)
);
const pageSizeMapper = getPaginationOptionIndexMapper(pageSizeOptions);
useEffect(() => {
const newPageSize = getPaginationOption(
userPreferencePaginationData[userPreferencePaginationKey],
pageSizeOptions
);
setDefaultPageSize(newPageSize);
if (tableRef.current) {
tableRef.current.dataManager.changePageSize(newPageSize);
}
}, [pageSizeOptions]);
props = {
...props,
tableRef,
options: {
...(props.options || {}),
pageSizeOptions: pageSizeOptions,
pageSize: defaultPageSize,
sorting: true
},
onChangeRowsPerPage: (pageSize) => {
const itemsPerPage = pageSizeMapper[pageSize] || defaultPageSize;
dispatch(
updateUserPreferenceData('pagination', {
[userPreferencePaginationKey]: itemsPerPage
})
);
}
};
return (
<div
className={
className || `${classes.tableWrapper} ${pointerCursor ? classes.cursorPointer : ''}`
}
style={style || {}}
>
<PerfectScrollbar>
<div className={classes.tableWrapper}>
{props.loading ? (
<div>
<LargeCircularLoader />
</div>
) : (
<MaterialTable {...props} />
)}
</div>
</PerfectScrollbar>
</div>
);
}
CustomMaterialTable.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
userPreferencePaginationKey: PropTypes.string,
pointerCursor: PropTypes.bool,
data: PropTypes.array,
options: PropTypes.object
};
|
require('./zepto.min');
require('./zepto-tap');
var $ =require('./jquery-1.10.1.min.js');
var load = require('./loadfooter.js');
load.loadHtml(3);
|
import Pieces from './Pieces';
class King extends Pieces {
constructor(player) {
super(player, (player === 1 ? "https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg" :
"https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg"));
}
possibleMove(srcIndex, destIndex) {
return (
srcIndex - 9 === destIndex || srcIndex - 7 === destIndex ||
srcIndex - 8 === destIndex || srcIndex + 1 === destIndex ||
srcIndex + 9 === destIndex || srcIndex + 8 === destIndex ||
srcIndex + 7 === destIndex || srcIndex - 1 === destIndex
)
}
destPath() {
return []
}
}
export default King;
|
import { getAccessToken } from "./getAccessToken"
import { URL, credentials, WS_DEMO_URL } from './data'
import { TradovateSocket } from "./socket/tvSocket"
const syncSocket = new TradovateSocket({debugLabel: 'sync data'})
const main = async () => {
const { accessToken, userId } = await getAccessToken(URL, credentials)
await syncSocket.connect(WS_DEMO_URL, accessToken)
const unsubscribe = await syncSocket.subscribe({
url: 'user/syncrequest',
body: { users: [userId] },
subscription: item => {
if(item.users) {
//this is the initial response. You will get any of these fields in the response
const {
accountRiskStatuses,
accounts,
cashBalances,
commandReports,
commands,
contractGroups,
contractMaturities,
contracts,
currencies,
exchanges,
executionReports,
fillPairs,
fills,
marginSnapshots,
orderStrategies,
orderStrategyLinks,
orderStrategyTypes,
orderVersions,
orders,
positions,
products,
properties,
spreadDefinitions,
userAccountAutoLiqs,
userPlugins,
userProperties,
userReadStatuses,
users
} = item
console.log(`initial response:\n${JSON.stringify(item, null, 2)}`)
} else {
//otherwise this is a user data event, they look like this
const { entityType, entity, eventType } = item
console.log(`update event:\n${JSON.stringify(item, null, 2)}`)
}
}
})
}
main()
|
/* eslint-env node */
module.exports = function(grunt) {
"use strict";
var SOURCE_FILES = [
"Gruntfile.js",
"src/**/*.js",
"test/*.js"
];
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
clean: {
options: {},
build: ["test/*.tap", "test/coverage"]
},
concat: {
options: {
stripBanners: false,
seperator: ";"
},
dist: {
src: [
"src/utils.js",
"src/domainnamerule.js",
"src/saltthepass.js"
],
dest: "dist/<%= pkg.name %>.js"
},
"dist-withdeps": {
src: [
"bower_components/cryptojslib/components/core.js",
"bower_components/cryptojslib/components/x64-core.js",
"bower_components/cryptojslib/components/sha1.js",
"bower_components/cryptojslib/components/sha512.js",
"bower_components/cryptojslib/components/sha3.js",
"bower_components/cryptojslib/components/md5.js",
"bower_components/cryptojslib/components/ripemd160.js",
"bower_components/cryptojslib/components/enc-base64.js",
"src/utils.js",
"src/domainnamerule.js",
"src/saltthepass.js"
],
dest: "dist/<%= pkg.name %>.withdeps.js"
}
},
uglify: {
options: {
banner: "/*! <%= pkg.name %> v<%= pkg.version %> */\n",
mangle: true,
sourceMap: true
},
build: {
files: {
"dist/<%= pkg.name %>.min.js": ["dist/<%= pkg.name %>.js"],
"dist/<%= pkg.name %>.withdeps.min.js": ["dist/<%= pkg.name %>.withdeps.js"]
}
}
},
eslint: {
console: {
src: SOURCE_FILES
},
build: {
options: {
outputFile: "eslint.xml",
format: "jslint-xml",
silent: true
},
src: SOURCE_FILES
}
},
mochaTest: {
test: {
options: {
reporter: "tap",
captureFile: "test/mocha.tap"
},
src: [
"src/saltthepass.js",
"test/*.js"
]
}
},
karma: {
options: {
singleRun: true,
colors: true,
configFile: "./karma.config.js",
preprocessors: {
"dist/saltthepass.withdeps.js": ["coverage"]
},
basePath: "./",
files: [
"bower_components/mocha/mocha.css",
"bower_components/mocha/mocha.js",
"bower_components/expect/index.js",
"dist/saltthepass.withdeps.js",
"test/test-*.js"
]
},
console: {
browsers: ["PhantomJS"],
frameworks: ["mocha"]
}
}
});
//
// Plugins
//
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-karma");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("gruntify-eslint");
//
// Tasks
//
grunt.registerTask("test", ["mochaTest", "karma:console"]);
grunt.registerTask("lint", ["eslint:console"]);
grunt.registerTask("lint:build", ["eslint:build"]);
grunt.registerTask("build", ["concat", "uglify"]);
//
// Task Groups
//
grunt.registerTask("default", ["lint", "build"]);
grunt.registerTask("travis", ["clean", "lint", "build", "test"]);
grunt.registerTask("all", ["clean", "lint:console", "lint:build", "build", "test"]);
};
|
/* eslint-disable import/no-anonymous-default-export */
import {nanoid} from 'nanoid'
export default {
name: 'course',
type: 'document',
title: 'Course',
fields: [
{
name: 'title',
type: 'string',
title: 'Title',
description: 'Titles should be catchy, descriptive, and not too long',
validation: (Rule) => Rule.required(),
},
{
name: 'slug',
type: 'slug',
title: 'Slug',
validation: (Rule) => Rule.required(),
description: 'unique slug for the course, this will go in the URL',
options: {
source: 'title',
maxLength: 96,
},
},
{
name: 'sharedId',
type: 'string',
title: 'Shared ID',
validation: (Rule) => Rule.required(),
initialValue: () => nanoid(),
},
{
name: 'productionProcessState',
title: 'Production Process State',
type: 'productionProcessState',
validation: (Rule) => Rule.required(),
},
{
name: 'description',
type: 'markdown',
title: 'Description',
description: 'A full description of the course.',
},
{
name: 'summary',
description: 'Short description, like for a tweet',
title: 'Summary',
type: 'text',
rows: 3,
validation: (Rule) => Rule.max(180),
options: {
maxLength: 180,
},
},
{
name: 'byline',
description:
'Metadata to display on cards (e.g. "Kent C. Dodds • 2h 29m • Course")',
title: 'Byline',
type: 'string',
validation: (Rule) => Rule.max(90),
options: {
maxLength: 90,
},
},
{
name: 'publishedAt',
description: 'The date this course was published',
title: 'Published At',
type: 'date',
},
{
name: 'updatedAt',
description: 'The last time this resource was meaningfully updated',
title: 'Updated At',
type: 'date',
},
{
name: 'image',
description: 'Links to a full-sized primary image/illustration',
title: 'Image/Illustration Url',
type: 'url',
},
{
name: 'softwareLibraries',
description: 'Versioned Software Libraries',
title: 'NPM or other Dependencies',
type: 'array',
of: [
{
type: 'versioned-software-library',
},
],
},
{
name: 'collaborators',
description:
'Humans that worked on this resource and get credit for the effort.',
title: 'Collaborators',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'collaborator'}],
},
],
},
{
name: 'imageIllustrator',
description: 'Human that illustrated the course cover image',
title: 'Image Illustrator',
type: 'reference',
to: [{type: 'collaborator'}],
},
{
name: 'lessons',
description: 'the individual lessons that make up this course',
title: 'Lessons',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'lesson'}],
},
],
},
{
title: 'Access Level',
description:
'Does this course require Pro access or is it a community resource?',
name: 'accessLevel',
type: 'string',
options: {
list: [
{title: 'Free', value: 'free'},
{title: 'Pro', value: 'pro'},
],
layout: 'radio',
},
initialValue: 'pro',
validation: (Rule) => Rule.required(),
},
{
title: 'Search Indexing State',
description: 'Is this course ready to be indexed for search?',
name: 'searchIndexingState',
type: 'string',
options: {
list: [
{title: 'Hidden', value: 'hidden'},
{title: 'Indexed', value: 'indexed'},
],
layout: 'radio',
},
initialValue: 'hidden',
validation: (Rule) => Rule.required(),
},
{
title: 'Duration (minutes)',
description: 'How many minutes does the course take to complete?',
name: 'durationInMinutes',
type: 'number',
},
{
name: 'related',
description:
'Any content that pairs well with this course (for now just Courses and Resources, but could be Articles, Podcasts, etc.).',
title: 'Related Resources',
type: 'array',
of: [
{
type: 'reference',
title: 'Course/Resource Refs',
to: [{type: 'resource'}, {type: 'course'}],
},
],
},
],
}
|
angular.module('starter.services', [])
.factory('Missions', function($http) {
// Might use a resource here that returns a JSON array
// Some fake testing data
var missions = [];
return {
download: function() {
return $http.get("http://artifact-server.azurewebsites.net/missions");
},
upload: function(data) {
return $http.post("http://artifact-server.azurewebsites.net/missions", data);
},
remove: function(mission, callback) {
global_var.missions.splice(missions.indexOf(mission), 1);
callback();
},
get: function(missionId) {
missions = global_var.missions;
for (var i = 0; i < missions.length; i++) {
if (missions[i].id === parseInt(missionId)) {
return missions[i];
}
}
return null;
},
add: function(mission, callback) {
var maxId = -1;
for (var i = 0; i < global_var.missions.length; i++) {
if (global_var.missions[i].id > maxId) {
maxId = global_var.missions[i].id;
}
}
maxId++;
global_var.missions.push({
id: maxId,
name: mission.name,
descr: mission.descr,
details: mission.details,
logo: mission.logo
});
callback();
}
};
})
.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
// Do any magic you need
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}]);
|
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import moment from "moment";
import AppRouter from "./routers/AppRouter";
import configureStore from "./store/configureStore";
import getVisibleExpenses from "./selectors/expenses";
import "./styles/styles.scss";
import "normalize.css/normalize.css";
import "./firebase/firebase";
const store = configureStore();
// store.subscribe(() => {
// const state = store.getState();
// console.log(getVisibleExpenses(state.expenses, state.filters));
// });
// store.dispatch(
// addExpense({
// description: "Macbook Pro",
// amount: 1200,
// createdAt: 1602333902,
// })
// );
// store.dispatch(addExpense({ description: "Iphone 12", amount: 1000 }));
// store.dispatch(
// addExpense({ description: "Ipad Pro", amount: 900, createdAt: 1602333901 })
// );
console.log(moment().format("X"));
const state = store.getState();
const visibleExpenses = getVisibleExpenses(state.expenses, state.filters);
console.log(visibleExpenses);
const jsx = (
<Provider store={store}>
<AppRouter />
</Provider>
);
ReactDOM.render(jsx, document.getElementById("app"));
|
import { connect } from 'react-redux';
import SignupPasswordScreen from '../components/SignupPasswordScreen';
import { apiSignup, signupSavePassword, navigatePush } from '../actions';
const mapStateToProps = (state) => {
return {
error: state.authState.error ? state.authState.error.message : ''
};
};
const mapDispatchToProps = (dispatch) => {
return {
onEnterPassword: (password) => {
dispatch(signupSavePassword(password));
},
onSubmitPress: () => {
dispatch(apiSignup());
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SignupPasswordScreen);
|
import React from "react";
import "./App.css";
import PostList from "./components/PostList";
import PostNew from "./components/PostNew";
import PostShow from "./components/PostShow";
import { BrowserRouter, Route, Switch } from "react-router-dom";
function App(props) {
return (
<div className="App">
<BrowserRouter>
<Route exact path="/" component={PostList} />
<Route exact path="/posts" component={PostList} />
<Switch>
<Route exact path="/posts/new" component={PostNew} />
<Route exact path="/posts/:id" component={PostShow} />
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
|
//第一个
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i,",");
}, 1000);
}
console.log(i,"->");
//第二个
// var output = function (i) {
// setTimeout(function() {
// console.log(i);
// }, 1000);
// };
// for (var i = 0; i < 5; i++) {
// output(i); // 这里传过去的 i 值被复制了
// }
// console.log(i);
//第三个
// for (var i = 0; i < 5; i++) {
// (function(i) {
// setTimeout(function() {
// console.log(new Date, i);
// }, 1000 * i);
// })(i);
// }
// setTimeout(function() {
// console.log(new Date, i);
// }, 1000 * i);
|
import React,{useState} from 'react'
import Dudeme_Logo from "../IMAGES/Dudeme_Logo.png";
import image1 from "../IMAGES/image1.png";
import cart from "../IMAGES/cart.png"; //category-1
import category1 from "../IMAGES/category1.png";
import product1 from "../IMAGES/product1.jpg";
import watch from "../IMAGES/watch.png";
import user from "../IMAGES/user.png";
import brands from "../IMAGES/brands.png";
import menu from "../IMAGES/menu.png";
import './Header.css';
const Header = () => {
const [open,setOpen] = useState(true)
// js for toggle menu
const menuToggle=()=>{
let menuItems=document.getElementById("MenuItems");
open ? menuItems.style.maxHeight="200px" : menuItems.style.maxHeight="0px";
setOpen(!open)
}
return (
<div>
<div className="header">
<div className="container">
<div className="navbar">
<div className="logo">
<img src={Dudeme_Logo} alt="logo" width="125px" />
</div>
<nav>
<ul id="MenuItems">
<li><a href="">Home</a></li>
<li><a href="">Products</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Account</a></li>
</ul>
</nav>
<img src={cart} alt="cart" width="30px" height="30px" />
<img src={menu} alt="menu-icon" className="menu-icon" onClick={menuToggle} />
</div>
<div className="row">
<div className="col-2">
<h1>Give Your Workout<br></br> A New Style!</h1>
<p>Success isn't always about greatness. It"s about consistency.
Consistent<br></br> hard work gains success. Greatness will come.
</p>
<a href="" className="btn">Explore Now →</a>
</div>
<div className="col-2">
<img src={image1} alt="images1" />
</div>
</div>
</div>
</div>
{/* -------------featured categories----------------- */}
<div className="categories">
<div className="small-container">
<div className="row">
<div className="col-3">
<img src={category1} alt="" />
</div>
<div className="col-3">
<img src={category1} alt="" />
</div>
<div className="col-3">
<img src={category1} alt="" />
</div>
</div>
</div>
</div>
{/* -------------featured products----------------- */}
<div className="small-container">
<h2 className="title">Featured Products</h2>
<div className="row">
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
</div>
<h2 className="title">Latest Products</h2>
<div className="row">
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
</div>
</div>
{/* ------------offer----------------- */}
<div className="offer" >
<div className="small-container" >
<div className="row" >
<div className="col-2" >
<img className="offer-img" src={watch} alt="" />
</div>
<div className="col-2">
<p>Exclusively Available on RedStore</p>
<h1>Smart Band 4</h1>
<small>Choose from new collection of Watches Online in India.
Buy Wrist Watches for men, women & kids at best price from Myntra Online store.
</small>
<a href="" className="btn">Buy Now →</a>
</div>
</div>
</div>
</div>
{/* ---------------testimonial---------------- */}
<div className="testimonial">
<div className="small-container">
<div className="row">
<div className="col-3">
<i className="fa fa-quote-left"></i>
<p>
1,399 Free images of Avatar. Related Images:
person woman female people face user man girl cartoon avatar · Social Media,
Connections, Networking. 866 416.
</p>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<img src={user} alt="" />
<h3>MAARI Boys</h3>
</div>
<div className="col-3">
<i className="fa fa-quote-left"></i>
<p>
1,399 Free images of Avatar. Related Images:
person woman female people face user man girl cartoon avatar · Social Media,
Connections, Networking. 866 416.
</p>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<img src={user} alt="" />
<h3>MAARI Boys</h3>
</div>
<div className="col-3">
<i className="fa fa-quote-left"></i>
<p>
1,399 Free images of Avatar. Related Images:
person woman female people face user man girl cartoon avatar · Social Media,
Connections, Networking. 866 416.
</p>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<img src={user} alt="" />
<h3>MAARI Boys</h3>
</div>
</div>
</div>
</div>
{/* ----------------brands----------------------- */}
<div className="brands">
<div className="small-container">
<div className="row">
<div className="col-5">
<img src={brands} alt="" />
</div>
<div className="col-5">
<img src={brands} alt="" />
</div>
<div className="col-5">
<img src={brands} alt="" />
</div>
<div className="col-5">
<img src={brands} alt="" />
</div>
<div className="col-5">
<img src={brands} alt="" />
</div>
</div>
</div>
</div>
{/* -----------------footer--------------------------------- */}
<div className="footer">
<div className="container">
<div className="row">
<div className="footer-col-1">
<h3>Download our app</h3>
<p>download app for android and ios mobile phones</p>
</div>
<div className="footer-col-2">
<img src={Dudeme_Logo} alt="" />
<p>download app for android and ios mobes download app for
android and ios mobile phones</p>
</div>
<div className="footer-col-3">
<h3>Useful Links</h3>
<ul>
<li>Coupons</li>
<li>Blog Post</li>
<li>Return Policy</li>
<li>Join Affilitate</li>
</ul>
</div>
<div className="footer-col-4">
<h3>Follow Us</h3>
<ul>
<li>Facebook</li>
<li>Twitter</li>
<li>Instagram</li>
<li>Youtube</li>
</ul>
</div>
</div>
<hr></hr>
<p className="copyright">Copyright 2021 - Maari bOYZ</p>
</div>
</div>
</div>
)
}
export default Header
|
/**
* A module that contains all functions to handle user requests
* Accesses functions from userModel
* @module users/userController
*/
var users = require('./userModel.js');
var jwt = require('jwt-simple');
var db = require('../db');
module.exports = {
/**
* Calls three functions from userModel.
* Checks if user name is available. If not, then will send error message.
* If user name is available, will call userModel signup function to post to database.
* If post is successful, will retrieve user info.
*
* @param {object} req - Request with username, first name, last name, and password from the client
* @param {object} res - Response with token and user id to be sent to the client
*/
signup: function (req, res, next) {
var params = [req.body.userName, req.body.firstName, req.body.lastName, req.body.password];
users.checkNameAvailability(params[0], function(err, results) {
if(err) {
console.error(err);
res.status(400).json({error: err});
} else {
users.signup(params, function(err, results) {
if(err) {
res.status(404).json({error: err});
} else {
users.getUserInfo(params[0], function(err, user) {
if(err) {
res.status(404).json({error: err});
} else {
if (user) {
var token = jwt.encode(user.id, 'secret');
res.status(200).json({token: token, userId: user.id});
}
}
});
}
});
}
});
},
/**
* Calls comparePassword function from userModel.
* Checks if user name exists. If not, then will send error message.
* Checks if password is correct.
* If there is a match, will retrieve user info.
*
* @param {object} req - Request with username and password from the client
* @param {object} res - Response with token and user id to be sent to the client
*/
login: function (req, res, next) {
var params = [req.body.userName, req.body.password];
users.comparePassword(params, function(err, user) {
if(err) {
console.error(err);
res.status(400).json({error: err});
next(err);
} else {
var token = jwt.encode(user.id, 'secret');
res.status(200).json({token: token, userId: user.id});
}
});
},
/**
* Checks from token in request header and uses jwt to decode the token to get the userId
* Uses userId decoded from token to check if that user exists in the database. If the user exists, invoke next function.
* If there is no match, send a 401 status.
*
* @param {object} req - Request from the client
* @param {object} res - Response to be sent to the client
* @param {object} next - Function to be invoked next with the same request and response parameters
*/
checkAuth: function (req, res, next) {
var token = req.headers['x-access-token'];
if (!token) {
res.sendStatus(401);
} else {
var user = jwt.decode(token, 'secret');
var queryStr = "select * from users where id = ?";
db.query(queryStr, user, function(err, userInfo) {
if(userInfo.length !== 0) {
next();
} else {
console.log('user is not in DB');
res.sendStatus(401);
}
});
}
}
};
|
import styled from 'styled-components'
import { useDispatch, useSelector } from 'react-redux'
import { updateProfilePhoto,logout, showDialog, updateProfile,showToast } from '../../features/appSlice'
import authFetch from '../../utils/authFetch'
import { SERVER_URL } from '../../Constants/api'
import { ReactComponent as BackIcon } from '../../imgs/back-arrow.svg'
import PrimaryButton from '../PrimaryButton'
import Switch from '../Switch'
import MediaList from './MediaList'
import ProfileAvatar from './ProfileAvatar'
import dialogContent from '../../Constants/dialog'
import Progress from '../Progress'
import MembersList from './MembersList'
export default function Profile({ location }) {
let isMyProfile = false
let noProfile = true
if (location.pathname.endsWith('profile')) {
noProfile = false
} else if (location.hash === '#profile') {
isMyProfile = true
noProfile = false
}
const dispatch = useDispatch()
const conv_id = location.pathname.split('/')[2]
let [data, user,messages] = useSelector(state => [isMyProfile ? state.app.user : state.app.conversations, state.app.user,!isMyProfile && state.app.messages && state.app.messages[conv_id]])
if (noProfile) return <></>
if (!isMyProfile) {
data = data?.find(conv => conv._id === conv_id)
data = data && { name: data?.name ?? data?.users?.map(u => u.name).join(', ') ,...data}
}
if (!data) return <ProfileContainer><Progress/></ProfileContainer>
const isGrp = data?.users?.length>2
const handleFileChange = async e => {
const file = e.target.files[0]
if (!file) return
const formData = new FormData()
formData.append('img', file)
const res = await authFetch(`${SERVER_URL}upload/${!isGrp?'profile':'group/'+conv_id}`, user.token, 'POST', formData,false).catch(err => console.error('Error', err))
if (res.success) {
dispatch(updateProfilePhoto({img:res.data,isGrp,conv_id}))
}else{
dispatch(showToast({message:res.message}))
}
}
const handlePrivacyChange = async e =>{
const res = await authFetch(SERVER_URL+'user/privacy',user?.token,'PUT',{isPrivate:e.target.checked});
if(res.success){
dispatch(updateProfile({privacy:res.isPrivate}))
}else{
dispatch(showToast({message:res.message}))
}
}
return (
<ProfileContainer>
<ProfileAvatar data={data} isMyProfile={isMyProfile} onChange={handleFileChange} uId={user._id} isGrp={isGrp}/>
<StyledContainer>
<StyledName>{data.name}</StyledName>
{isMyProfile && <StyledEmail>{data.email}</StyledEmail>}
</StyledContainer>
{isMyProfile &&
<>
<ActionsContainer>
<StyledAction onClick={()=>dispatch(showDialog({show:true,content:dialogContent.CHANGE_PASSWORD}))}>
<h3>Change Password</h3>
<BackIcon/>
<p>Change your account password</p>
</StyledAction>
<StyledAction>
<h3>Private Account</h3>
<Switch initialValue={user?.isPrivate} onChange={handlePrivacyChange}/>
<p>No one can create conversation with you</p>
</StyledAction>
</ActionsContainer>
<ButtonsContainer>
<DeleteButton onClick={()=>dispatch(showDialog({show:true,content:dialogContent.DELETE_ACCOUNT}))}>Delete Account</DeleteButton>
<PrimaryButton style={{ fontSize: '1rem' }} onClick={()=>dispatch(logout())}>Log out</PrimaryButton>
</ButtonsContainer>
</>
}
{!isMyProfile &&
<>
{isGrp &&
<>
<StyledTitle>Members</StyledTitle>
<MembersList members={data.users}/>
</>
}
<StyledTitle>Media</StyledTitle>
<MediaList
items={messages?.filter(msg => msg.type === 'image')}
/>
</>
}
</ProfileContainer>
)
}
const ProfileContainer = styled.div`
display:flex;
flex-direction: column;
min-height: 80%;
align-items:center;
gap:1em;
`
const StyledContainer = styled.div`
text-align: center;
`
const ActionsContainer = styled.div`
display: flex;
flex-direction: column;
width: 100%;
gap:.5rem;
flex-grow:1;
margin-top: max(1rem,5vh);
`
const StyledAction = styled.label`
display:grid;
grid-template-columns: 1fr auto;
grid-template-rows: auto auto;
text-align: start;
column-gap: 1rem;
padding: .7rem 2rem;
cursor:pointer;
&:hover{
background-color: rgba(100,100,100,.3);
}
&>p{
color:var(--text-second);
}
&>input,svg{
grid-row: 1/3;
grid-column: 2;
align-self: center;
}
&>svg{
height: 50%;
transform: rotate(180deg);
}
`
const StyledTitle = styled.h2`
align-self: flex-start;
padding-inline: 1.2rem;
`
const StyledName = styled.p`
text-transform: capitalize;
font-size:1.5rem;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow-wrap: anywhere;
text-overflow: ellipsis;
overflow: hidden;
`
const StyledEmail = styled.p`
color: var(--text-second);
`
const ButtonsContainer = styled.div`
display:flex;
justify-content: space-evenly;
margin-top: 2rem;
align-self: stretch;
`
const DeleteButton = styled.button`
background-color: #00000000;
color: var(--error-color);
padding: .3em .83em;
border: 0;
font-family: inherit;
font-size: 1.1rem;
cursor:pointer;
border-radius: var(--border-radius);
transition: background-color .3s;
&:hover{
background-color: var(--error-color20);
}
`
|
/**
* Created by Yonatan.Vainer on 7/9/2015.
*/
angular.module('UsersController', [])
.controller('UsersController', ['UsersManagerService','AuthService','FileUploader', function(UsersManagerService,AuthService,FileUploader){
var vm = this;
vm.name = "";
vm.username = "";
vm.password = "";
vm.role = "";
vm.photo = "";
vm.users = UsersManagerService.users;
vm.uploader = new FileUploader();
vm.uploader.url = "http://localhost:3000/api/images";
vm.uploader.onAfterAddingFile = function(item){
vm.photo = item.file.name;
};
vm.submit = function(){
UsersManagerService.create(
{
"name": vm.name,
"username": vm.username,
"password": vm.password,
"role": vm.role,
"photo": vm.photo
}
);
};
vm.getUsers = function(role){
UsersManagerService.get(role);
};
vm.promote = function(user){
UsersManagerService.promote(user)
}
vm.demote = function(user){
UsersManagerService.demote(user)
}
}]);
|
/**
* @param {string} address
* @return {string}
*/
var defangIPaddr = function(address) {
address = address.split(".");
defIP = "";
for (let i = 0; i < address.length - 1; i++) {
defIP += address[i] + "[.]";
}
return defIP + address[address.length - 1];
};
|
var express = require('express');
var app = express();
var git = require('simple-git');
app.post('/', function (req, res) {
console.log(__dirname);
git(__dirname)
.pull(function(err, update) {
if(err){
console.log(err);
}
require('child_process').exec('npm restart',function(error, stdout, stderr) {
if (error) {
console.error('exec error: ', error);
console.log('stderr: ', stderr);
res.json({success: false, err: error});
}
res.json({success: true});
console.log(stdout);
});
});
});
app.listen(6591, function () {
console.log('Fedora LATAM WebHook listen on 6591!');
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'gatsby';
import { global, styles } from '@storybook/design-system';
import styled from 'styled-components';
import Helmet from 'react-helmet';
import Release from './Release';
const { GlobalStyle } = global;
const { pageMargins, breakpoint } = styles;
const Content = styled.div`
${pageMargins}
padding-top: 3rem;
padding-bottom: 3rem;
@media (min-width: ${breakpoint * 1.333}px) {
padding-top: 4rem;
padding-bottom: 4rem;
}
`;
function IframeReleasesScreen({ data }) {
const {
currentPage: {
body,
frontmatter: { title },
},
} = data;
return (
<>
<GlobalStyle />
<Helmet>
<meta name="robots" content="noindex" />
</Helmet>
<Content>
<Release title={title} body={body} />
</Content>
</>
);
}
IframeReleasesScreen.propTypes = {
data: PropTypes.any.isRequired, // eslint-disable-line react/forbid-prop-types
};
export default IframeReleasesScreen;
export const query = graphql`
query IframeReleasesScreenQuery($slug: String!) {
currentPage: mdx(fields: { slug: { eq: $slug } }) {
body
frontmatter {
title
}
fields {
version
slug
}
}
}
`;
|
import {TopPanel} from "./components/topPanel.js";
import {IconButton} from "./components/iconButton.js";
import {SiteForm} from "./components/siteForm.js"
let appContainer = document.querySelector("#app-container");
let leftOptions =[
"HOME",
"FAQS",
"CONTACT",
"USD"
].map(optionName=>{
let option = document.createElement("a");
option.innerHTML = optionName;
return option;
});
let rightOptions = [
"fab fa-facebook-f",
"fab fa-twitter",
"fab fa-pinterest-p","fab fa-instagram",
"fas fa-phone","fas fa-envelope"
].map(iconClass=>{
let iconContainer = document.createElement("a");
let icon = document.createElement("i");
icon.className = iconClass;
iconContainer.appendChild(icon);
return iconContainer;
});
let topPanel = new TopPanel(leftOptions,rightOptions);
let secondaryLeftOptions = ["Canvas"].map(text=>{
let h1Ele = document.createElement("h1");
h1Ele.innerHTML =text;
return h1Ele;
});
let secondaryRightOptions = [
{text:"HOME",iconClass:"fas fa-home"},
{text:"FLIGHTS",iconClass:"fas fa-plane"},
{text:"HOTELS",iconClass:"fas fa-building"},
{text:"HOLIDAYS",iconClass:"fas fa-archive"},
{text:"1800 105 2541", iconClass:"fas fa-phone"}
].map(btnSchemaItem=>{
let cssOptions = {backgroundColor:"transparent",color:"white"};
if(btnSchemaItem.text=="HOME"){
cssOptions = Object.assign({},cssOptions,{border:"1px solid lightgray"});
}
else
{
cssOptions = Object.assign({},cssOptions,{border:"none"});
}
return (new IconButton(btnSchemaItem.text,btnSchemaItem.iconClass,cssOptions)).createElement();
})
let secondaryTopPanel = new TopPanel(secondaryLeftOptions,secondaryRightOptions);
let secondaryTopPanelEle = secondaryTopPanel.createElement();
secondaryTopPanelEle.style.alignItems = "baseline";
appContainer.append(topPanel.createElement());
appContainer.append(secondaryTopPanelEle);
//creating form
let siteForm = new SiteForm();
let siteFormElement = siteForm.createSiteForm();
let formContainer = document.createElement("div");
let formButtonsContainer = document.createElement("div");
formButtonsContainer.classList.add("form-buttons-container");
formContainer.classList.add("form-container");
let formButtons = [
{text:"FLIGHTS",iconClass:"fas fa-plane"},
{text:"HOTELS",iconClass:"fas fa-building"},
{text:"FLIGHTS + HOTELS",iconClass:""},
{text:"HOLIDAYS",iconClass:"fas fa-archive"},
].map((btnSchemaItem,index)=>{
let cssOptions = {backgroundColor:"rgb(8, 20, 38)",color:"white",border:"none"};
if(btnSchemaItem.text=="FLIGHTS"){
cssOptions = Object.assign({},cssOptions,{backgroundColor:"maroon"});
}
else
{
cssOptions = Object.assign({},cssOptions,{border:"none",borderLeft:"1px solid gray"});
}
return (new IconButton(btnSchemaItem.text,btnSchemaItem.iconClass,cssOptions)).createElement();
});
formButtons.forEach(btn=>formButtonsContainer.appendChild(btn));
formContainer.appendChild(formButtonsContainer);
formContainer.appendChild(siteFormElement);
appContainer.appendChild(formContainer);
let saveBtn = document.createElement("a");
saveBtn.innerHTML = "Save"
saveBtn.classList.add("save-btn")
formButtonsContainer.querySelector("[name='FLIGHTS + HOTELS']").childNodes[1].after(saveBtn)
|
function nthPrime(n) {
const primes = [2];
let test = 3;
while(primes.length < n) {
if(isPrime(test)) {
primes.push(test);
}
test += 2;
}
return primes.pop();
function isPrime(num) {
const stopPoint = Math.sqrt(num);
for(const prime of primes) {
if(num % prime === 0) return false;
else if(prime > stopPoint) break;
}
return true;
}
}
console.log(nthPrime(10001))
|
var link = document.querySelector(".hostel-search");
var popup = document.querySelector(".modal-date");
var date = popup.querySelector("[name=date-arrival]");
link.addEventListener("click", function (evt) {
evt.preventDefault();
popup.classList.toggle("modal-show");
date.focus();
});
|
var movedata =[
{Nov:0,Name:"Petal Dance",Type:"Grass",Attack:156,Wait_time:5},
{Nov:1,Name:"Vine Whip",Type:"Grass",Attack:237,Wait_time:5},
{Nov:2,Name:"Synthesis",Type:"Grass",Attack:0,Wait_time:5},
{Nov:3,Name:"Tackle",Type:"Normal",Attack:163,Wait_time:5},
{Nov:4,Name:"Take Down",Type:"Normal",Attack:189,Wait_time:5},
{Nov:5,Name:"Poison Powder",Type:"Poison",Attack:67,Wait_time:4},
{Nov:6,Name:"Leech Seed",Type:"Grass",Attack:103,Wait_time:9},
{Nov:7,Name:"Toxic",Type:"Poison",Attack:59,Wait_time:4},
{Nov:8,Name:"Mega Drain",Type:"Grass",Attack:165,Wait_time:9},
{Nov:9,Name:"Solar Beam",Type:"Grass",Attack:227,Wait_time:7},
{Nov:10,Name:"Scratch",Type:"Normal",Attack:231,Wait_time:5},
{Nov:11,Name:"Ember",Type:"Fire",Attack:109,Wait_time:7},
{Nov:12,Name:"Fire Spin",Type:"Fire",Attack:97,Wait_time:5},
{Nov:13,Name:"Fire Punch",Type:"Fire",Attack:229,Wait_time:5},
{Nov:14,Name:"Dragon Claw",Type:"Dragon",Attack:296,Wait_time:5},
{Nov:15,Name:"Metal Claw",Type:"Steel",Attack:211,Wait_time:5},
{Nov:16,Name:"Flamethrower",Type:"Fire",Attack:94,Wait_time:5},
{Nov:17,Name:"Flame Charge",Type:"Fire",Attack:0,Wait_time:5},
{Nov:18,Name:"Flare Blitz",Type:"Fire",Attack:128,Wait_time:5},
{Nov:19,Name:"Fire Blast",Type:"Fire",Attack:179,Wait_time:5},
{Nov:20,Name:"Bubble",Type:"Water",Attack:68,Wait_time:7},
{Nov:21,Name:"Whirlpool",Type:"Water",Attack:94,Wait_time:5},
{Nov:22,Name:"Withdraw",Type:"Water",Attack:0,Wait_time:5},
{Nov:23,Name:"Waterfall",Type:"Water",Attack:252,Wait_time:5},
{Nov:24,Name:"Aqua Jet",Type:"Water",Attack:182,Wait_time:5},
{Nov:25,Name:"Surf",Type:"Water",Attack:127,Wait_time:5},
{Nov:26,Name:"Aqua Ring",Type:"Water",Attack:0,Wait_time:9},
{Nov:27,Name:"Blizzard",Type:"Ice",Attack:52,Wait_time:5},
{Nov:28,Name:"Hydro Pump",Type:"Water",Attack:213,Wait_time:5},
{Nov:29,Name:"String Shot",Type:"Bug",Attack:118,Wait_time:2},
{Nov:30,Name:"Lunge",Type:"Bug",Attack:180,Wait_time:5},
{Nov:31,Name:"Electroweb",Type:"Electric",Attack:0,Wait_time:2},
{Nov:32,Name:"Harden",Type:"Normal",Attack:0,Wait_time:5},
{Nov:33,Name:"Iron Defense",Type:"Steel",Attack:0,Wait_time:5},
{Nov:34,Name:"Rage Powder",Type:"Bug",Attack:0,Wait_time:2},
{Nov:35,Name:"Silver Wind",Type:"Bug",Attack:53,Wait_time:5},
{Nov:36,Name:"U-turn",Type:"Bug",Attack:243,Wait_time:5},
{Nov:37,Name:"Poison Sting",Type:"Poison",Attack:107,Wait_time:7},
{Nov:38,Name:"Agility",Type:"Psychic",Attack:0,Wait_time:2},
{Nov:39,Name:"Aerial Ace",Type:"Flying",Attack:124,Wait_time:5},
{Nov:40,Name:"Pin Missile",Type:"Bug",Attack:110,Wait_time:7},
{Nov:41,Name:"Gust",Type:"Flying",Attack:61,Wait_time:7},
{Nov:42,Name:"Whirlwind",Type:"Normal",Attack:0,Wait_time:2},
{Nov:43,Name:"Tailwind",Type:"Flying",Attack:0,Wait_time:2},
{Nov:44,Name:"Twister",Type:"Dragon",Attack:115,Wait_time:7},
{Nov:45,Name:"Hurricane",Type:"Flying",Attack:105,Wait_time:5},
{Nov:46,Name:"Mud-Slap",Type:"Ground",Attack:56,Wait_time:7},
{Nov:47,Name:"Sky Attack",Type:"Flying",Attack:125,Wait_time:5},
{Nov:48,Name:"Heat Wave",Type:"Fire",Attack:123,Wait_time:7},
{Nov:49,Name:"Roost",Type:"Flying",Attack:0,Wait_time:9},
{Nov:50,Name:"Crunch",Type:"Dark",Attack:370,Wait_time:5},
{Nov:51,Name:"Focus Energy",Type:"Normal",Attack:0,Wait_time:5},
{Nov:52,Name:"Flame Wheel",Type:"Fire",Attack:57,Wait_time:5},
{Nov:53,Name:"Zen Headbutt",Type:"Psychic",Attack:370,Wait_time:5},
{Nov:54,Name:"Taunt",Type:"Dark",Attack:0,Wait_time:2},
{Nov:55,Name:"Iron Tail",Type:"Steel",Attack:67,Wait_time:5},
{Nov:56,Name:"Fury Swipes",Type:"Normal",Attack:146,Wait_time:5},
{Nov:57,Name:"Growl",Type:"Normal",Attack:0,Wait_time:4},
{Nov:58,Name:"Leer",Type:"Normal",Attack:0,Wait_time:3},
{Nov:59,Name:"Fly",Type:"Flying",Attack:243,Wait_time:5},
{Nov:60,Name:"Steel Wing",Type:"Steel",Attack:81,Wait_time:5},
{Nov:61,Name:"Drill Peck",Type:"Flying",Attack:321,Wait_time:5},
{Nov:62,Name:"Tri Attack",Type:"Normal",Attack:81,Wait_time:5},
{Nov:63,Name:"Mud Bomb",Type:"Ground",Attack:215,Wait_time:5},
{Nov:64,Name:"Rock Tomb",Type:"Rock",Attack:212,Wait_time:5},
{Nov:65,Name:"Sludge Bomb",Type:"Poison",Attack:173,Wait_time:5},
{Nov:66,Name:"Sucker Punch",Type:"Dark",Attack:130,Wait_time:5},
{Nov:67,Name:"Earthquake",Type:"Ground",Attack:390,Wait_time:5},
{Nov:68,Name:"Thunder Shock",Type:"Electric",Attack:173,Wait_time:5},
{Nov:69,Name:"Spark",Type:"Electric",Attack:81,Wait_time:5},
{Nov:70,Name:"Thunderbolt",Type:"Electric",Attack:80,Wait_time:5},
{Nov:71,Name:"Volt Tackle",Type:"Electric",Attack:110,Wait_time:6},
{Nov:72,Name:"Thunder",Type:"Electric",Attack:204,Wait_time:5},
{Nov:73,Name:"Electric Terrain",Type:"Electric",Attack:0,Wait_time:5},
{Nov:74,Name:"Charge",Type:"Electric",Attack:0,Wait_time:9},
{Nov:75,Name:"Giga Impact",Type:"Normal",Attack:176,Wait_time:5},
{Nov:76,Name:"Dig",Type:"Ground",Attack:243,Wait_time:5},
{Nov:77,Name:"Sandstorm",Type:"Rock",Attack:117,Wait_time:5},
{Nov:78,Name:"Rollout",Type:"Rock",Attack:130,Wait_time:5},
{Nov:79,Name:"Swords Dance",Type:"Normal",Attack:0,Wait_time:5},
{Nov:80,Name:"Night Slash",Type:"Dark",Attack:83,Wait_time:5},
{Nov:81,Name:"Flatter",Type:"Dark",Attack:0,Wait_time:6},
{Nov:82,Name:"Supersonic",Type:"Normal",Attack:0,Wait_time:3},
{Nov:83,Name:"Venom Drench",Type:"Poison",Attack:118,Wait_time:5},
{Nov:84,Name:"Stealth Rock",Type:"Rock",Attack:120,Wait_time:5},
{Nov:85,Name:"Sing",Type:"Normal",Attack:0,Wait_time:3},
{Nov:86,Name:"Rock Smash",Type:"Fighting",Attack:29,Wait_time:1},
{Nov:87,Name:"Amnesia",Type:"Psychic",Attack:0,Wait_time:8},
{Nov:88,Name:"Megahorn",Type:"Bug",Attack:513,Wait_time:5},
{Nov:89,Name:"Work Up",Type:"Normal",Attack:0,Wait_time:8},
{Nov:90,Name:"Follow Me",Type:"Normal",Attack:0,Wait_time:2},
{Nov:91,Name:"Flash",Type:"Normal",Attack:0,Wait_time:2},
{Nov:92,Name:"Light Screen",Type:"Psychic",Attack:0,Wait_time:3},
{Nov:93,Name:"Soft-Boiled",Type:"Normal",Attack:0,Wait_time:9},
{Nov:94,Name:"Psychic",Type:"Psychic",Attack:121,Wait_time:7},
{Nov:95,Name:"Belly Drum",Type:"Normal",Attack:0,Wait_time:5},
{Nov:96,Name:"Dazzling Gleam",Type:"Fairy",Attack:146,Wait_time:5},
{Nov:97,Name:"Charm",Type:"Fairy",Attack:0,Wait_time:3},
{Nov:98,Name:"Roar",Type:"Normal",Attack:0,Wait_time:2},
{Nov:99,Name:"Confuse Ray",Type:"Ghost",Attack:0,Wait_time:3},
{Nov:100,Name:"Will-O-Wisp",Type:"Fire",Attack:19,Wait_time:3},
{Nov:101,Name:"Mega Punch",Type:"Normal",Attack:561,Wait_time:5},
{Nov:102,Name:"Rest",Type:"Normal",Attack:0,Wait_time:9},
{Nov:103,Name:"Sweet Kiss",Type:"Fairy",Attack:165,Wait_time:3},
{Nov:104,Name:"Dynamic Punch",Type:"Fighting",Attack:87,Wait_time:5},
{Nov:105,Name:"Bounce",Type:"Flying",Attack:186,Wait_time:5},
{Nov:106,Name:"Play Rough",Type:"Fairy",Attack:98,Wait_time:5},
{Nov:107,Name:"Leech Life",Type:"Bug",Attack:185,Wait_time:9},
{Nov:108,Name:"Nasty Plot",Type:"Dark",Attack:0,Wait_time:5},
{Nov:109,Name:"Stun Spore",Type:"Grass",Attack:21,Wait_time:3},
{Nov:110,Name:"Bullet Seed",Type:"Grass",Attack:168,Wait_time:7},
{Nov:111,Name:"Spore",Type:"Grass",Attack:0,Wait_time:9},
{Nov:112,Name:"Psybeam",Type:"Psychic",Attack:69,Wait_time:7},
{Nov:113,Name:"Rock Throw",Type:"Rock",Attack:234,Wait_time:5},
{Nov:114,Name:"Shore Up",Type:"Ground",Attack:0,Wait_time:9},
{Nov:115,Name:"Flail",Type:"Normal",Attack:130,Wait_time:5},
{Nov:116,Name:"Icy Wind",Type:"Ice",Attack:126,Wait_time:7},
{Nov:117,Name:"Ice Beam",Type:"Ice",Attack:133,Wait_time:7},
{Nov:118,Name:"Submission",Type:"Fighting",Attack:130,Wait_time:5},
{Nov:119,Name:"Meditate",Type:"Psychic",Attack:0,Wait_time:5},
{Nov:120,Name:"Cross Chop",Type:"Fighting",Attack:273,Wait_time:5},
{Nov:121,Name:"Close Combat",Type:"Fighting",Attack:245,Wait_time:5},
{Nov:122,Name:"Extreme Speed",Type:"Normal",Attack:130,Wait_time:5},
{Nov:123,Name:"Bulk Up",Type:"Fighting",Attack:0,Wait_time:8},
{Nov:124,Name:"Power-Up Punch",Type:"Fighting",Attack:64,Wait_time:5},
{Nov:125,Name:"Ice Punch",Type:"Ice",Attack:175,Wait_time:5},
{Nov:126,Name:"Teleport",Type:"Psychic",Attack:0,Wait_time:3},
{Nov:127,Name:"Barrier",Type:"Psychic",Attack:0,Wait_time:5},
{Nov:128,Name:"Recover",Type:"Normal",Attack:0,Wait_time:9},
{Nov:129,Name:"Shadow Ball",Type:"Ghost",Attack:63,Wait_time:7},
{Nov:130,Name:"Psycho Cut",Type:"Psychic",Attack:311,Wait_time:5},
{Nov:131,Name:"Rolling Kick",Type:"Fighting",Attack:156,Wait_time:5},
{Nov:132,Name:"Razor Leaf",Type:"Grass",Attack:118,Wait_time:7},
{Nov:133,Name:"Slam",Type:"Normal",Attack:211,Wait_time:5},
{Nov:134,Name:"Hyper Beam",Type:"Normal",Attack:300,Wait_time:10},
{Nov:135,Name:"Self-Destruct",Type:"Normal",Attack:494,Wait_time:5},
{Nov:136,Name:"Explosion",Type:"Normal",Attack:683,Wait_time:5},
{Nov:137,Name:"Rock Polish",Type:"Rock",Attack:0,Wait_time:2},
{Nov:138,Name:"Stomp",Type:"Normal",Attack:180,Wait_time:5},
{Nov:139,Name:"Flash Cannon",Type:"Steel",Attack:170,Wait_time:7},
{Nov:140,Name:"Metal Sound",Type:"Steel",Attack:0,Wait_time:3},
{Nov:141,Name:"Lick",Type:"Ghost",Attack:233,Wait_time:5},
{Nov:142,Name:"Aurora Veil",Type:"Ice",Attack:0,Wait_time:7},
{Nov:143,Name:"Acid Armor",Type:"Poison",Attack:0,Wait_time:5},
{Nov:144,Name:"Spikes",Type:"Ground",Attack:221,Wait_time:5},
{Nov:145,Name:"Rock Blast",Type:"Rock",Attack:168,Wait_time:7},
{Nov:146,Name:"Icicle Crash",Type:"Ice",Attack:143,Wait_time:5},
{Nov:147,Name:"Astonish",Type:"Ghost",Attack:180,Wait_time:5},
{Nov:148,Name:"Smog",Type:"Poison",Attack:188,Wait_time:5},
{Nov:149,Name:"Hypnosis",Type:"Psychic",Attack:0,Wait_time:5},
{Nov:150,Name:"Egg Bomb",Type:"Normal",Attack:201,Wait_time:5},
{Nov:151,Name:"Bonemerang",Type:"Ground",Attack:131,Wait_time:7},
{Nov:152,Name:"Outrage",Type:"Dragon",Attack:104,Wait_time:5},
{Nov:153,Name:"Comet Punch",Type:"Normal",Attack:201,Wait_time:5},
{Nov:154,Name:"High Jump Kick",Type:"Fighting",Attack:402,Wait_time:5},
{Nov:155,Name:"Drain Punch",Type:"Fighting",Attack:223,Wait_time:9},
{Nov:156,Name:"Thunder Punch",Type:"Electric",Attack:194,Wait_time:5},
{Nov:157,Name:"Lava Plume",Type:"Fire",Attack:132,Wait_time:5},
{Nov:158,Name:"Dragon Rush",Type:"Dragon",Attack:141,Wait_time:5},
{Nov:159,Name:"Substitute",Type:"Normal",Attack:0,Wait_time:5},
{Nov:160,Name:"Dragon Dance",Type:"Dragon",Attack:0,Wait_time:8},
{Nov:161,Name:"Dragon Pulse",Type:"Dragon",Attack:188,Wait_time:7},
{Nov:162,Name:"Splash",Type:"Normal",Attack:56,Wait_time:3},
{Nov:163,Name:"Draining Kiss",Type:"Fairy",Attack:165,Wait_time:9},
{Nov:164,Name:"Transform",Type:"Normal",Attack:0,Wait_time:0},
{Nov:165,Name:"Draco Meteor",Type:"Dragon",Attack:377,Wait_time:5},
{Nov:166,Name:"Psystrike",Type:"Psychic",Attack:129,Wait_time:5}
]
|
const express = require('express');
const router = express.Router();
const { ensureAuthenticated, forwardAuthenticated } = require('../config/auth');
const Job = require('../models/Job');
// Dashboard
router.get('/post-Job', ensureAuthenticated, (req, res) =>
res.render('post-job', {
user: req.user
})
);
router.get('/view-Jobs', ensureAuthenticated, (req, res) =>{
Job.find({ owner: req.user.id }).then(jobs => {
if(!jobs){
errors.push({ msg: 'You have not posted a job yet' });
res.render('dashboard', { errors });
}
else{
res.render('company-job-view', {jobs})
}
})
});
router.get('/delete/:id', ensureAuthenticated, (req, res) =>{
Job.deleteOne(Job.findById(req.params.id), function(err){
if(err){
console.log(err);
}
else{
Job.find({owner: req.user.id}).then(jobs => {
if(!jobs){
errors.push({ msg: 'You have not posted a job yet' });
res.render('dashboard', { errors });
}
else{
res.render('company-job-view', {jobs})
}
})
}
});
});
router.get('/update/:id', ensureAuthenticated, (req, res) =>{
Job.findById(req.params.id).then(job => {
res.render('post-job',{
post:job.post,
responsibilities: job.responsibilities,
deadline: job.deadline,
nov: job.nov
})
});
});
router.post('/post-job',ensureAuthenticated, (req, res) => {
const { post, responsibilities, deadline, nov } = req.body;
let errors = [];
if (!post || !responsibilities || !deadline || !nov) {
errors.push({ msg: 'Please enter all fields' });
}
if (errors.length > 0) {
res.render('post-job', {
errors,
post,
responsibilities,
deadline,
nov
});
} else {
const owner = req.user.id
const newJob = new Job({
post: post,
owner: owner,
responsibilities: responsibilities,
deadline: deadline,
nov: nov
});
newJob.save()
.then(user => {
req.flash(
'success_msg',
'Job posted successfully'
);
res.redirect('/dashboard');
})
}
});
module.exports = router;
|
function solve(input) {
const saveValidData = {};
const letterPattern = /[a-zA-Z]{1,}/;
for (let i = 0; i < input.length; i++) {
line = input[i].split(/--|=|<</g);
if (line === "Stop!") {
return;
}
if (line.length !== 4) {
continue;
}
let [name, length, count, organism] = line;
[length, count] = [+length, +count];
if (name.includes(">")) {
continue;
}
let nameOnlyOfLetters = "";
name.split("").forEach(ch => {
if (letterPattern.test(ch)) {
nameOnlyOfLetters += ch;
}
});
if (nameOnlyOfLetters.length !== length) {
continue;
}
if (!saveValidData.hasOwnProperty(organism)) {
saveValidData[organism] = 0;
}
saveValidData[organism] += count;
}
let arr = [];
for (let k in saveValidData) {
const organism = k;
const count = saveValidData[k];
arr.push({ organism, count });
}
arr.sort((a, b) => b.count > a.count);
arr.forEach(entity =>
console.log(`${entity.organism} has genome size of ${entity.count}`)
);
}
solve([
`!@ру?би#=4--57<<polecat`,
`?do?@#ri#=4--89<<polecat`,
`=12<<cat`,
`!vi@rus?=2--142`,
`@pa!rcu>ba@cteria$=13--234<<mouse`,
`?!cur##viba@cter!!=11--680<<cat`,
`Stop!`
]);
|
import React, { useState } from 'react'
import { render, fireEvent } from '@testing-library/react'
import FieldBase from '../index'
const TestComponent = props => {
const [value, setValue] = useState('')
const onChange = e => setValue(e.target.value)
return (
<FieldBase {...props}>
<input
value={value}
onChange={onChange}
{...props}
/>
</FieldBase>
)
}
const buildComponent = props => {
const utils = render(<TestComponent {...props} />)
const input = utils.getByLabelText(props.label)
return {
input,
...utils
}
}
describe('<FieldBase />', () => {
it('Render the component with \'Usuário\' label text', () => {
const { asFragment } = buildComponent({ id: 'user', label: 'Usuário' })
expect(asFragment())
.toMatchSnapshot()
})
it('Find the input by label and types a value in', () => {
const { input } = buildComponent({ id: 'user', label: 'Usuário' })
fireEvent.change(input, { target: { value: 'test' } })
expect(input)
.toHaveProperty('value', 'test')
})
})
|
const UserManager = artifacts.require("UserManager");
const User = artifacts.require("User");
/**
* accounts[0] : admin
* accounts[1] : master
* accounts[2] : user, presidium
* accounts[3] : user
*/
contract("UserManager", accounts => {
it("建立并检索用户合约", () => {
return UserManager.deployed()
.then(instance => {
var addr1 = accounts[2];
instance.newUser(web3.utils.utf8ToHex("小明"), { from: addr1 });
return instance.users.call(addr1);
})
.then(addr => {
return User.at(addr);
})
.then(userInstance => {
return userInstance.name.call();
})
.then(name => {
//bytes10会使用0补全位数,而web3的转换函数不会,所以只能对比utf8值,而不能对比转换后的值
assert.equal(web3.utils.hexToUtf8(name), "小明", "用户合约创建错误");
})
})
it("修改并检索用户message", () => {
return UserManager.deployed()
.then(instance => {
return instance.users.call(accounts[2]);
})
.then(addr => {
return User.at(addr);
})
.then(instance => {
instance.setUserInfo(true, 8618812087780,
1093368800, "xuhaodev@qq.com", web3.utils.utf8ToHex("中国河北衡水"),
[utf82Hex("中文"), utf82Hex("English")], [utf82Hex("唱"), utf82Hex("跳"), utf82Hex("rap")], { from: accounts[2] });
return instance.getUserInfo.call({ from: accounts[2] });
})
.then(info=>{
assert.equal(info._gender, true, "性别错误");
assert.equal(info._phone, 8618812087780, "电话错误");
assert.equal(info._qq, 1093368800, "QQ错误");
assert.equal(info._email, "xuhaodev@qq.com", "email错误");
assert.equal(web3.utils.hexToUtf8(info._location), "中国河北衡水", "地区错误");
let language = ["中文", "English"];
for(var i = 0; i < info._language.length; i++){
assert.equal(web3.utils.hexToUtf8(info._language[i]), language[i], "语言错误");
}
let hobby = ["唱", "跳", "rap"];
for(var i = 0; i < info._hobby.length; i++){
assert.equal(web3.utils.hexToUtf8(info._hobby[i]), hobby[i], "喜好错误");
}
})
})
})
function utf82Hex(str) {
return web3.utils.utf8ToHex(str);
}
function hex2Utf8(hex) {
return web3.utils.hex2Utf8(hex);
}
|
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import AccountsUIWrapper from './AccountsUIWrapper.jsx';
import { Meteor } from 'meteor/meteor';
//import Selectors from './Selectors.jsx'
import { VolunteerDB } from '../api/volunteers.js';
//import VolunteerSendingList from './VolunteerSendingList.jsx'
import DatePicker from 'react-datepicker'
import moment from 'moment'
import BigCalendar from 'react-big-calendar';
require("react-big-calendar/lib/css/react-big-calendar.css")
import { AlertList } from "react-bs-notifier";
//setup calendar
BigCalendar.setLocalizer(
BigCalendar.momentLocalizer(moment)
);
// App component - represents the whole app
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hasDatepickerBeenCreated: false,
startDate: moment(),
selectedOption: "oneNight",
alerts: [{
id: 1,
type: "success",
message: "airbed booked"
}]
};
this.renderDatePicker = this.renderDatePicker.bind(this);
this.handleOptionChange = this.handleOptionChange.bind(this);
this.createDates = this.createDates.bind(this);
this.submitClickHandler = this.submitClickHandler.bind(this)
}
handleOptionChange(changeEvent){
this.setState({
selectedOption: changeEvent.target.value
});
console.log(changeEvent.target.value)
}
handleChangeOfDatePicker(date) {
this.setState({startDate: date});
console.log(date)
}
createDates() {
let dateCounter = new Date()
let endMe = 30
for (let endMe = 0; endMe < 30; endMe ++) {
if (!VolunteerDB.findOne({date:dateCounter})) {
VolunteerDB.insert({date: dateCounter})
}
console.log(dateCounter)
dateCounter.setDate(dateCounter.getDate() + 1)
}
}
submitClickHandler(e) {
console.log("submit!")
CamID = Meteor.user().profile.name
console.log(CamID)
console.log("nights: " + this.state.selectedOption)
console.log(this.state.startDate)
e.preventDefault();
var startDate = new Date(this.state.startDate)
startDate.setHours(0,0,0,0)
this.bookDate(CamID, startDate, this.state.selectedOption)
}
bookDate(CamID, startDate, noDays) {
console.log('adding:' + CamID + startDate + noDays)
var nextDate = new Date(startDate.valueOf());
if (noDays == 'oneNight') {
console.log('only one night!!')
if (VolunteerDB.find({start: startDate.valueOf()}).count() < 2) {
this.insertDate(CamID, startDate)}
else {
alert("Both beds are already booked");
}
}
else {
console.log('two nights!!')
nextDate.setDate(nextDate.getDate() + 1)
console.log(startDate)
if (VolunteerDB.find({start: startDate.valueOf()}).count() < 2 && VolunteerDB.find({start: nextDate.valueOf()}).count() < 2 ) {
this.insertDate(CamID, startDate)
this.insertDate(CamID, nextDate)}
else {
alert("Both beds are already booked");
}
}
}
insertDate(CamID, enterDate) {
if (VolunteerDB.find({start: enterDate.valueOf()}).count() < 2) {
var dayAfter = new Date(enterDate + 1)
var startDate = Number(enterDate.valueOf())
var endDate = Number(dayAfter.valueOf())
console.log(startDate)
Meteor.call('volunteerDB.insert', startDate, endDate);
}
else {
alert("Both beds are already booked");
}
}
renderDatePicker() {
var hasDatepickerBeenCreated = !this.state.hasDatepickerBeenCreated
if (!this.state.hasDatepickerBeenCreated) {
console.log('creating date picker')
return <Datepicker />
this.setState({hasDatepickerBeenCreated: true})
}
}
numberNights(numberNight) {
if (numberNight == 1) {
this.setState({oneNight: true})
}
else {
this.setState({oneNight: false})
}
}
render() {
return (
<div>
<nav className="navbar navbar-inverse navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="#">Catz Air Bed</a>
</div>
<div id="navbar" className="collapse navbar-collapse">
<ul className="nav navbar-nav">
<li className="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li><a id="ravenLogin" href="#">{this.props.currentUser ? <AccountsUIWrapper /> : ''}</a></li>
</ul>
</div>
</div>
</nav>
<div className="container" id="main-content">
<div>
{ this.props.currentUser ?
<div>
<div className="row">
<div className="col-md-4 col-md-offset-4">
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title"> Welcome {Meteor.user().profile.name}:</h3>
</div>
<div className="panel-body">
<label>Start Date:</label>
<form onSubmit={this.handleFormSubmit}>
<DatePicker
selected={this.state.startDate}
onChange={this.handleChangeOfDatePicker.bind(this)}
dateFormat="DD/MM/YYYY"
/>
<div className="radio">
<label>
<input type="radio" value="oneNight"
checked={this.state.selectedOption === 'oneNight'}
onChange={this.handleOptionChange} />
One Night
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="twoNight"
checked={this.state.selectedOption === 'twoNight'}
onChange={this.handleOptionChange} />
Two Nights
</label>
</div>
<button className="btn btn-default" type="submit" onClick={this.submitClickHandler}>Book</button>
</form>
</div>
</div>
</div>
{/*<table className='table table-hover table-striped' >
<thead>
<tr>
<th>Date</th>
<th>Bed 1</th>
<th>Bed 2</th>
</tr>
</thead>
<tbody>
{this.renderVolunteer()}
</tbody>
</table>*/}
</div>
<BigCalendar
events={this.props.volunteerProp}
/*[
{
'title': 'lh511',
'start': new Date(),
'end': new Date(2016, 11, 6, 0, 0, 0),
},
]*/
timeslots={5}
views = {['month']}
defaultDate={new Date()}
/>
</div>
:
<div>
<div className="starter-template">
<h1>Catz Airbed Booking Form</h1>
<p className="lead"><AccountsUIWrapper /><br /> Any questions contact Capucine Brunet CB869</p>
</div>
<div className="navbar navbar-fixed-bottom navbar-default ">
<p className="navbar-text navbar-right">Created By Luke Harries</p>
</div>
</div>
}
</div>
</div>
</div>
)
}
}
App.propTypes = {
volunteerProp: PropTypes.array.isRequired,
currentUser: PropTypes.object,
};
export default createContainer(() => {
return {
volunteerProp: VolunteerDB.find({}).fetch(),
currentUser: Meteor.user(),
};
}, App);
|
import CommunicationLoading from "./Loading";
import BsModal from "./BsModal";
export {
CommunicationLoading,
BsModal,
}
|
import React, { Component } from 'react';
import {
Text,
View,
ListView,
ScrollView,
StyleSheet,
Dimensions,
Platform,
} from 'react-native';
import { Tile, List, ListItem } from 'react-native-elements';
import Communications from 'react-native-communications';
import GiftedSpinner from 'react-native-gifted-spinner';
const { width, height } = Dimensions.get('window');
class UserDetail extends React.Component {
constructor(props){
super(props);
this.state = {};
}
toCall
render() {
const { person_image, name, subTitle, phone, email, skype } = this.props.navigation.state.params;
return (
<ScrollView>
<Tile
imageSrc={person_image}
featured
title={`${name.first} ${name.last}`}
titleStyle={{width, position:'absolute', bottom: (Platform.OS === 'ios') ? 22 : 24, paddingTop: 5, color: '#000', backgroundColor: 'rgba(255,255,255,.5)'}}
caption={subTitle}
captionStyle={{width, position:'absolute', bottom: 0,paddingBottom: 5, color: '#000', backgroundColor: 'rgba(255,255,255,.5)'}}
>
</Tile>
<List>
{
phone ?
<ListItem
title="Phone"
leftIcon={{name: 'phone', type: 'font-awesome', color: '#00897b', size: 20}}
rightTitle={phone}
rightTitleStyle={{color: '#000'}}
hideChevron
onPress={() => {
Communications.phonecall(phone, true);
}}
/>
: null
}
{
email ?
<ListItem
title="Email"
leftIcon={{name: 'envelope', type: 'font-awesome', color: '#00897b', size: 16}}
rightTitle={email}
rightTitleStyle={{color: '#000'}}
hideChevron
onPress={() => {
Communications.email([email],null,null,'','')
}}
/>
: null
}
{
skype ?
<ListItem
title="Skype"
leftIcon={{name: 'skype', type: 'font-awesome', color: '#00897b', size: 18}}
rightTitle={skype}
rightTitleStyle={{color: '#000'}}
hideChevron
onPress={() => {
Communications.phonecall(skype, true);
}}
/>
: null
}
</List>
{/*<List>*/}
{/*<ListItem*/}
{/*title="Username"*/}
{/*rightTitle={login.username}*/}
{/*hideChevron*/}
{/*/>*/}
{/*</List>*/}
{/*<List>*/}
{/*<ListItem*/}
{/*title="Birthday"*/}
{/*rightTitle={dob}*/}
{/*hideChevron*/}
{/*/>*/}
{/*<ListItem*/}
{/*title="City"*/}
{/*rightTitle={location.city}*/}
{/*hideChevron*/}
{/*/>*/}
{/*</List>*/}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
scrollView: {
},
container: {
flex: 1,
marginTop: 20,
},
separator: {
flex: 1,
height: 1,
backgroundColor: '#8E8E8E',
},
});
export default UserDetail;
|
import React from "react";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Checkbox from "@material-ui/core/Checkbox";
import { Box } from "@material-ui/core";
import useStore from "../../../store/todo-store";
import ReactMarkdown from "react-markdown";
import gfm from "remark-gfm";
const useStyles = makeStyles({
root: {
minWidth: 275,
},
completed: {
color: "white",
backgroundColor: "#009688",
},
});
const ToDo = (props) => {
const classes = useStyles();
//const [checked, setChecked] = useState(props.todo.completed);
const completeTodo = useStore((state) => state.completeTodo);
const editTodo = useStore((state) => state.editTodo)
const handleChange = (event) => {
completeTodo(props.todo.id);
};
return (
<Grid item xs={12} sm={6} md={4}>
<Paper className={props.todo.completed ? classes.completed : null}>
<Box
component="div"
display="flex"
flexDirection="row"
alignItems="center"
p={1}
m={1}
>
<Box width="90%" component="div">
<Typography variant="h5" noWrap onClick={() => editTodo(props.todo)}>
{props.todo.title}
</Typography>
</Box>
<Box>
<Checkbox
checked={props.todo.completed}
onChange={handleChange}
color="secondary"
/>
</Box>
</Box>
<Box component="div" p={1} m={1}>
<ReactMarkdown
plugins={[gfm]}
noWrap
children={props.todo.description}
/>
</Box>
{/* <Typography variant="body2" component="p">
{props.todo.description}
</Typography> */}
</Paper>
</Grid>
);
};
export default ToDo;
|
X.define("modules.message.systemBulletin",["model.messageModel"],function (messageModel) {
//初始化视图对象
var view = X.view.newOne({
el: $(".xbn-content"),
url: X.config.message.tpl.systemBulletin
});
//初始化控制器
var ctrl = X.controller.newOne({
view: view
});
ctrl.rendering = function () {
return view.render({}, function () {
ctrl.initPage()
});
};
var schemas = (function(){
var schemas = {
"tabBulletin" :{
searchMeta: {
schema: {
simple:[]
},
search: {
onSearch : function (data) {
return data;
}
},
reset :{
show:false
}
},
gridMeta :{
columns : [],
afterRowRender: function (row, data) {
if (data.content.length > 71) {
$(row.dom).find(".js-content").html(data.content.substr(0, 71) + "...");
}
if(data.status == "0"){
$(row.dom).find(".js-status").html("未读");
}else if(data.status == "1"){
$(row.dom).find(".js-status").css("display","none");
}
$(row.dom).on("click", function (event) {
event.stopPropagation();
event.preventDefault();
var postData ={
messageId: data.messageId,
status: data.status
};
var callback = function(result){
if(result.statusCode ==2000000){
location.href = X.config.receptionUrl.messageUrl+"?id="+data.messageId;
}
};
messageModel.readMessage(postData,callback);
});
},
type : "C",
selector : ".js-message-systenBulletin-tpl"
},
pageInfo : {
pageSize : '10',
totalPages : '10',
pageNo: '1',
smallPapogation: {
isShow: false,
elem: '.js_small_papogation1'
}
},
url : X.config.message.api.listPlatformMessages
}
};
return schemas;
})();
var lists = {};
var activeTabLiInfo;
function initTabPage($elem,schema,tabPage) {
var list = X.controls.getControl("List",$elem,schema);
list.init();
lists[tabPage] = list;
}
ctrl.initPage =function (){
var tabPannel = X.controls.getControl("TabPanel",$('.js_tabPannel1'), {
activeTabInfo: activeTabLiInfo,
beforeChangeTab: function (tabLiInfo, targetLi, index, tabPage) {
activeTabLiInfo = tabLiInfo;
// 刊登状态 不同
var page = $(tabPage);
if(!page.data("hasInited")){
var schema = schemas[tabLiInfo];
if(schema){
initTabPage(page,schema,tabLiInfo);
}
page.data("hasInited",true);
}
// 为了样式效果,把当前选中的前一个加上样式名
targetLi.prev().removeClass('tab_lineNone');
return true;
},
afterChangeTab: function (tabLiInfo, targetLi, index, tabPage) {
activeTabLiInfo = tabLiInfo;
activeTabLi = targetLi;
// 为了样式效果,把当前选中的前一个加上样式名
targetLi.prev().addClass('tab_lineNone');
}
});
};
ctrl.load = function (para) {
ctrl.rendering();
};
return ctrl;
});
|
'use strict';
/* @author Rachel Carbone */
var app = angular.module('editor.controllers', []);
app.controller('ErrorPagesCtrl', ['$rootScope', '$scope', '$state', '$timeout',
function($rootScope, $scope, $state, $timeout) {
$scope.timer = 5;
$timeout(function () {
$scope.goToDashboard();
}, 6000);
($scope.tick = function() {
$timeout(function () {
$scope.timer--;
if($scope.timer > 0) {
$scope.tick();
}
}, 1000);
})();
$scope.goToDashboard = function() {
$state.go('app.dashboard');
};
$scope.isActiveState = function(state) {
return (state === $state.current.name);
};
}]);
|
'use strict';
import angular from 'angular';
import DetectModule from './detect/detect.module';
import DialogboxModule from './dialogbox/dialogbox.module';
import TableModule from './table/table.module';
/**
* @const {String} ComponentsModule
*/
const ComponentsModule = angular
.module('app.components', [
DetectModule,
DialogboxModule,
TableModule
])
.name;
export default ComponentsModule;
|
$(function () {
// ****************************************
// U T I L I T Y F U N C T I O N S
// ****************************************
// Updates the form with data from the response
function update_form_data(res) {
$("#inventory_id").val(res.id);
$("#inventory_name").val(res.name);
$("#inventory_quantity").val(res.quantity.toString());
$("#inventory_status").val(res.status);
}
/// Clears all form fields
function clear_form_data() {
$("#inventory_name").val("");
$("#inventory_quantity").val("");
$("#inventory_status").val("");
}
// Updates the flash message area
function flash_message(message) {
$("#flash_message").empty();
$("#flash_message").append(message);
}
// ****************************************
// Create a inventory
// ****************************************
$("#create-btn").click(function () {
var name = $("#inventory_name").val();
var quantity = parseInt($("#inventory_quantity").val());
var status = $("#inventory_status").val();
var data = {
"name": name,
"quantity": quantity,
"status": status
};
var ajax = $.ajax({
type: "POST",
url: "/inventories",
contentType:"application/json",
data: JSON.stringify(data),
});
ajax.done(function(res){
update_form_data(res)
flash_message("Success")
});
ajax.fail(function(res){
flash_message(res.responseJSON.message)
});
});
// ****************************************
// Update a inventory
// ****************************************
$("#update-btn").click(function () {
var inventory_id = $("#inventory_id").val();
var name = $("#inventory_name").val();
var quantity = parseInt($("#inventory_quantity").val());
var status = $("#inventory_status").val();
var data = {
"name": name,
"quantity": quantity,
"status": status
};
var ajax = $.ajax({
type: "PUT",
url: "/inventories/" + inventory_id,
contentType:"application/json",
data: JSON.stringify(data)
})
ajax.done(function(res){
update_form_data(res)
flash_message("Success")
});
ajax.fail(function(res){
flash_message(res.responseJSON.message)
});
});
// ****************************************
// Retrieve a inventory
// ****************************************
$("#retrieve-btn").click(function () {
var inventory_id = $("#inventory_id").val();
var ajax = $.ajax({
type: "GET",
url: "/inventories/" + inventory_id,
contentType:"application/json",
data: ''
})
ajax.done(function(res){
//alert(res.toSource())
update_form_data(res)
flash_message("Success")
});
ajax.fail(function(res){
clear_form_data()
flash_message(res.responseJSON.message)
});
});
// ****************************************
// Delete a inventory
// ****************************************
$("#delete-btn").click(function () {
var inventory_id = $("#inventory_id").val();
var ajax = $.ajax({
type: "DELETE",
url: "/inventories/" + inventory_id,
contentType:"application/json",
data: '',
})
ajax.done(function(res){
clear_form_data()
flash_message("inventory with ID [" + inventory_id + "] has been Deleted!")
});
ajax.fail(function(res){
flash_message("Server error!")
});
});
// ****************************************
// Clear the form
// ****************************************
$("#clear-btn").click(function () {
$("#inventory_id").val("");
clear_form_data()
});
// ****************************************
// Search for a inventory
// ****************************************
$("#search-btn").click(function () {
var name = $("#inventory_name").val();
var quantity = $("#inventory_quantity").val();
var status = $("#inventory_status").val();
var queryString = ""
if (name) {
queryString += 'name=' + name
}
if (quantity) {
if (queryString.length > 0) {
queryString += '&quantity=' + quantity
} else {
queryString += 'quantity=' + quantity
}
}
if (status) {
if (queryString.length > 0) {
queryString += '&status=' + status
} else {
queryString += 'status=' + status
}
}
var ajax = $.ajax({
type: "GET",
url: "/inventories?" + queryString,
contentType:"application/json",
data: ''
})
ajax.done(function(res){
//alert(res.toSource())
$("#search_results").empty();
$("#search_results").append('<table class="table-striped">');
var header = '<tr>'
header += '<th style="width:10%">ID</th>'
header += '<th style="width:40%">Name</th>'
header += '<th style="width:40%">Quantity</th>'
header += '<th style="width:10%">status</th></tr>'
$("#search_results").append(header);
for(var i = 0; i < res.length; i++) {
inventory = res[i];
var row = "<tr><td>"+inventory.id+"</td><td>"+inventory.name+"</td><td>"+inventory.quantity+"</td><td>"+inventory.status+"</td></tr>";
$("#search_results").append(row);
}
$("#search_results").append('</table>');
flash_message("Success")
});
ajax.fail(function(res){
flash_message(res.responseJSON.message)
});
});
// ****************************************
// List all inventories
// ****************************************
$("#list-btn").click(function () {
var ajax = $.ajax({
type: "GET",
url: "/inventories",
contentType:"application/json",
data: ''
})
ajax.done(function(res){
//alert(res.toSource())
$("#search_results").empty();
$("#search_results").append('<table class="table-striped">');
var header = '<tr>'
header += '<th style="width:10%">ID</th>'
header += '<th style="width:40%">Name</th>'
header += '<th style="width:40%">Quantity</th>'
header += '<th style="width:10%">status</th></tr>'
$("#search_results").append(header);
for(var i = 0; i < res.length; i++) {
inventory = res[i];
var row = "<tr><td>"+inventory.id+"</td><td>"+inventory.name+"</td><td>"+inventory.quantity+"</td><td>"+inventory.status+"</td></tr>";
$("#search_results").append(row);
}
$("#search_results").append('</table>');
flash_message("Success")
});
ajax.fail(function(res){
flash_message(res.responseJSON.message)
});
});
// ****************************************
// Query the quantity of an inventory
// ****************************************
$("#query-btn").click(function () {
var name = $("#inventory_name").val();
var quantity = $("#inventory_quantity").val();
var status = $("#inventory_status").val();
var queryString = ""
if (name) {
queryString += 'name=' + name
}
if (status) {
if (queryString.length > 0) {
queryString += '&status=' + status
} else {
queryString += 'status=' + status
}
}
var ajax = $.ajax({
type: "GET",
url: "/inventories/query?" + queryString,
contentType:"application/json",
data: ''
})
ajax.done(function(res){
//alert(res.toSource())
$("#search_results").empty();
$("#search_results").append('<table class="table-striped">');
var header = '<tr>'
header += '<th style="width:10%">ID</th>'
header += '<th style="width:40%">Name</th>'
header += '<th style="width:40%">Quantity</th>'
header += '<th style="width:10%">status</th></tr>'
$("#search_results").append(header);
for(var i = 0; i < res.length; i++) {
inventory = res[i];
var row = "<tr><td>"+inventory.id+"</td><td>"+inventory.name+"</td><td>"+inventory.quantity+"</td><td>"+inventory.status+"</td></tr>";
$("#search_results").append(row);
}
$("#search_results").append('</table>');
flash_message("Success")
});
ajax.fail(function(res){
flash_message(res.responseJSON.message)
});
});
$("#count-btn").click(function () {
var name = $("#inventory_name").val();
var quantity = $("#inventory_quantity").val();
var status = $("#inventory_status").val();
var queryString = ""
if (name) {
queryString += 'name=' + name
}
var ajax = $.ajax({
type: "GET",
url: "/inventories/count?" + queryString,
contentType:"application/json",
data: ''
})
ajax.done(function(res){
//alert(res.toSource())
$("#search_results").empty();
$("#search_results").append('<table class="table-striped">');
var header = '<tr>'
header += '<th style="width:10%">ID</th>'
header += '<th style="width:40%">Name</th>'
header += '<th style="width:40%">Quantity</th>'
header += '<th style="width:10%">status</th></tr>'
$("#search_results").append(header);
records = res.records
for(var i = 0; i < records.length; i++) {
inventory = records[i];
var row = "<tr><td>"+inventory.id+"</td><td>"+inventory.name+"</td><td>"+inventory.quantity+"</td><td>"+inventory.status+"</td></tr>";
$("#search_results").append(row);
}
$("#search_results").append('</table>');
var total = "<i>Total: "+res.count+'</i>'
$("#search_results").append(total)
flash_message("Success")
});
ajax.fail(function(res){
flash_message(res.responseJSON.message)
});
});
})
|
const logger = require("./src/logger");
const exportLogger = logger();
module.exports = exportLogger;
|
import React from 'react';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import { DialogContent,DialogContentText,Button,DialogActions } from '@material-ui/core';
export default function(props){
const [selectedDate, setSelectedDate] = React.useState(new Date('2014-08-18T21:11:54'));
return(
<Dialog onClose={props.changedeleteDialogState} open={props.deleteDialogState}>
<DialogTitle id="simple-dialog-title">Edit</DialogTitle>
<DialogContent>
<DialogContentText>
Do you really want to deleted ?
</DialogContentText>
<DialogActions>
<Button onClick={props.changedeleteDialogState} color="primary">
No
</Button>
<Button onClick={()=>{props.save()}} color="primary">
Yes
</Button>
</DialogActions>
</DialogContent>
</Dialog>
)
}
|
var _ = require('underscore');
var TransitionBase = require('./transitionbase.js');
var GotoTransition = function(newState) {
TransitionBase.call(this, 'goto');
this.newState = newState;
};
module.exports = GotoTransition;
|
function ex29(arrSpeed) // arrSpeed = Array(speedSlow, speedFast, speedMedium);
{
var exDiv = '#ex29';
var dynamicDiv = '#mainDivDynamic29';
var getParentHeight = $('.games-inner-container').height();
var getParentWidth = $('.games-inner-container').width();
$(exDiv).css('height',getParentHeight+'px');
$(exDiv).css('width',getParentWidth+'px');
var rImages;
var imgPath;
var speedIndex = 0;
var timer;
var pauseFlag = false;
var finishFlag = false;
var speedCounter = 0;
var maxMiliSec = 15000;
var changeRow = 0;
var max_count;
var goTilMax = 1;
var totalImages;
var countdown = 0;
function highLightRow()
{
$('#ex29_'+changeRow+' img:nth-child('+goTilMax+')').show();
if (goTilMax == max_count) {
setTimeout(function(){
goTilMax = 1;
$('#ex29_'+changeRow).css('display','none');
playTick();
changeRow++;
}, arrSpeed[speedIndex]);
}
goTilMax++;
}
function doAnimation()
{
if (pauseFlag)
return;
if (countdown <= totalImages)
{
highLightRow();
checkSpeedChange();
}
else
finishFlag = true;
if (!finishFlag)
{
countdown++;
timer = setTimeout(function(){doAnimation()}, arrSpeed[speedIndex]);
}
else
{
clearTimeout(timer);
//Unbinds click event on pauseClick
$("#cmdpause").unbind('click',pauseClick);
//Unbinds keydown event
$(document).off('keydown');
//Unbinds click event on startAnimation
$("#begin_exercise").unbind('click',startAnimation);
exerciseEnded();
}
}
function pauseClick()
{
var state = $("#cmdpause").val();
togglePause();
if (state == "Pause") {
pauseFlag = true;
clearTimeout(timer);
} else {
pauseFlag = false;
doAnimation();
}
}
function checkSpeedChange()
{
speedCounter += arrSpeed[speedIndex];
var currentTime = maxMiliSec - speedCounter;
if (currentTime <=0 ) {
speedIndex++;
speedCounter = 0;
if (speedIndex > 2) {
finishFlag = true;
return false;
}
}
}
function init()
{
centerMeFromMyParent(exDiv, dynamicDiv);
var mWidth = getParentWidth + .3; //.2 has been added to fill right side area with white bg.
$(dynamicDiv).css('width', mWidth+'px');
$(dynamicDiv).disableSelection();
totalImages = maxMiliSec/arrSpeed[0];
totalImages += maxMiliSec/arrSpeed[1];
totalImages += maxMiliSec/arrSpeed[2];
totalImages = parseInt(totalImages);
max_count = parseInt(getParentWidth / 64);
var totalRows = Math.ceil(totalImages/max_count);
totalRows++;
var str = '';
for (var i=0; i<totalRows; i++)
{
var images = rImages.sort(function() {return 0.5 - Math.random()});
str += '<span id="ex29_'+i+'">';
for (var j=0; j<max_count; j++)
str += '<img src="'+imgPath+images[j]+'" />';
str += '</span>';
}
$(dynamicDiv).html(str);
}
function startAnimation() {
playTick();
hideInstructions();
$(exDiv).show();
//Unbinds keydown event for startAnimation-->$(document).off('keydown', startAnimation);
// Allows for click event to call pauseClick
$("#cmdpause").on('click',pauseClick);
//Allows for all keydown events to call pauseClick
$(document).keydown(function (e) {
if (e.which == 32 || e.which == 13) {
e.preventDefault();
pauseClick();
} else if (e.which == 8) {
e.preventDefault();
}
});
doAnimation();
};
$.ajax({
type: 'POST',
dataType: 'json',
url: api_dir+'exercise-image-list',
data: 'images=32',
success: function(data){
// console.log(data);
rImages = data['images'];
imgPath = data['path'];
init();
showStart();
$("#begin_exercise").bind('click',startAnimation);
//Enables keydown event on startAnimation-->$(document).keydown('space', startAnimation);
}
});
}
|
#!/usr/bin/node
import readlineSync from 'readline-sync';
import { getAnswer } from './functions';
const chalk = require('chalk');
const game = (description, getQuestion, getCorrectAnswer, isValidAnswer) => {
console.log(chalk.yellow('*************************************************'));
console.log(
chalk.yellow('**********',
chalk.cyan('Welcome to the Brain Games!'),
chalk.yellow('**********')));
console.log(chalk.yellow('*************************************************'));
const name = readlineSync.question('May I have your name? ');
const hello = `Hello, ${name}!\n`;
console.log(hello);
console.log(`${description}\n`);
const num = 3;
const iter = (acc) => {
if (acc === num) { return console.log(`\nCongratulations, ${name}!`); }
const question = getQuestion();
const result = getCorrectAnswer(question);
const userAnswer = getAnswer(isValidAnswer, question);
if (userAnswer === result) {
console.log('Correct!');
return iter(acc + 1);
}
console.log(`\n"${userAnswer}" is wrong answer ;(. Correct answer was "${result}".`);
return console.log(`Let's try again, ${name}`);
};
return iter(0);
};
export default game;
|
const hola = (hola = undefined) => {
return `Mi nombre es ${hola}`;
}
hola("kevin");
|
import './App.css';
import Header from './components/Header';
import User from './components/User';
import {useState} from 'react';
function App() {
const [friends , setFriends] = useState(["asdasdsa","asdasd234"]);
return (
<div>
<User name = "orçun" islog = {false}/>
<Header/>
<Header/>
<h2>asdasdsa </h2>
{friends.map((friend, index) => (
<div key ={index}>{friend}</div>
))}
<button onClick={() => setFriends([...friends ,"asdasd"])}> add new </button>
</div>
);
}
export default App
|
import React from 'react';
import { Form, Button } from 'semantic-ui-react';
class EditUserModal extends React.Component {
constructor(props) {
super(props)
this.state = {
user: this.props.user
}
}
handleOnChange = (event) => {
const {id, value} = event.target
this.setState({
user: {...this.state.user, [id]: value}
})
}
render() {
const {name, email} = this.state.user
return (
<Form onChange={this.handleOnChange}>
<Form.Field >
<label>Name</label>
<input value={name} id="name"/>
</Form.Field>
<Form.Field>
<label>Email</label>
<input value={email} id="email"/>
</Form.Field>
<Form.Group >
<Button onClick={() => this.props.handleEditUser(this.state.user)} color="green">
Submit
</Button>
<Button onClick={this.props.handleDeleteUser} color="red">
Delete
</Button>
</Form.Group>
</Form>
)
}
}
export default EditUserModal
|
import React from 'react';
import './index.css';
const Footer = () => {
return (
<div className='footer-wrapper'>
<div className='container'>
<div className='row'>
<div className='col'></div>
<div className='col-5'>
<a href='#header'>
<i className='fa fa-angle-double-up icon'></i>
</a>
</div>
<div className='col'></div>
</div>
<div className='row'>
<div className='col'></div>
<div className='col-md-5 col-sm-12 footer-text'>
<h3>Contact</h3>
<p>
<b>Phone: </b> +972-54-9292103
</p>
<p>
<b>Email: </b>oohana13@gmail.com
</p>
</div>
<div className='col'></div>
</div>
{/*<div className='row social-links'>
<div className='col'></div>
<div className='col-2'>
<a target='_blang' href='https://www.facebook.com/abraham.zilberblat'>
<i className='fa fa-facebook icon'></i>
</a>
</div>
<div className='col-2'>
<a
href='https://www.linkedin.com/in/abraham-zilberblat-2a2b78185/'
target='_blang'
>
<i className='fa fa-linkedin icon'></i>
</a>
</div>
<div className='col-2'>
<a href='https://github.com/AZilberblat' target='_blang'>
<i className='fa fa-github icon'></i>
</a>
</div>
<div className='col'></div>
</div>*/}
</div>
</div>
);
};
export default Footer;
|
import Vue from "vue";
import VueRouter from "vue-router";
import Intro from "../views/Intro";
import About from "../views/About";
import Greeting from "../views/Greeting";
import Stack from "../views/Stack";
import Roadmap from "../views/Roadmap";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "intro",
component: Intro,
},
{
path: "/greeting",
name: "greeting",
component: Greeting,
},
{
path: "/about",
name: "about",
component: About,
},
{
path: "/stack",
name: "stack",
component: Stack,
},
{
path: "/roadmap",
name: "roadmap",
component: Roadmap,
},
];
const router = new VueRouter({
/* mode: "history", */
base: process.env.BASE_URL,
routes,
});
export default router;
|
// выводить ошибки в JSON формате
const { isCelebrateError } = require('celebrate');
const BadRequestError = require('../../errors/400_BadRequestError');
module.exports = (err, req, res, next) => {
if (isCelebrateError(err)) {
const customError = err.details.get('body') || err.details.get('params');
throw new BadRequestError({ message: customError.message.replace(/"/g, '') });
}
return next(err);
};
|
module.exports = [
'You are supah dupah', 'You are beautiful'
];
//write a function that iterates through an array
//and randomly selects an item in the array. use math.ranom()?
|
exports.run = (bot, msg, args) => {
msg.member.voice.channel.join().then(connection => console.log("connected on user : " + msg.author.id)).catch(console.error);
}
|
// However, escaping can be disabled with the |s operator, so use this wth care
{ contents | s }
|
/*
EXERCISE 45:
Using the ES2015 class syntax, create a class called Person with a constructor setting the properties
"name", "weight", and "age", and a default property called "isAlive" set to true
For example:
const myPerson = new Person('Steve',160,35);
//myPerson should be {name: 'Steve', weight: 160, age: 35, isAlive: true}
*/
class Person {}
|
Meteor.publish("transactions", function(options, criteria, searchString){
if (searchString == null || searchString == '')
{
searchString = "";
}
var criteriaMap = {"Account ID":"acctId", "Transaction Code":"tranCode", "Base Currency":"baseCurrency",
"Currency":"currency", "Amount":"amount", "Time Stamp":"timeStamp"};
var field = criteriaMap[criteria];
var doc = {};
if (field == "timeStamp" && searchString != "")
{
searchString = Meteor.call('timeStringFormatter', searchString);
}
else
{
searchString = new RegExp( "^" + searchString, 'i');
}
doc[field] = searchString;
Counts.publish(this, 'numberOfTransactions', Transactions.find(doc), {noReady: true});
var currencies = ["CAD", "USD", "HKD", "SGD" , "AUD", "GBP", "EUR", "YEN", "INR"];
for (var i = 0; i < currencies.length; i++)
{
var currency = currencies[i];
//console.log(currency);
var copyOfDoc = {};
copyOfDoc[field] = searchString;
switch(field)
{
case "currency":
copyOfDoc["baseCurrency"] = currency;
break;
case "baseCurrency":
copyOfDoc["currency"] = currency;
break;
default:
copyOfDoc["currency"] = currency;
}
Counts.publish(this, currencies[i].toString(), Transactions.find(copyOfDoc), {noReady: true});
}
return Transactions.find( doc , options);
});
|
// 个人项目
module.exports = {
text: "项目",
link: "/projects/",
items: [
{ text: "ToDb", link: "https://github.com/xingcxb/todb" },
{ text: "goKit", link: "https://github.com/xingcxb/goKit" },
],
};
|
/** app.js , definition of modules pertaining
to main view in index.html **/
"use strict";
angular.module('musicApp', [])
.controller('MainCtrl',[ '$http',function ($http) { // the array includes a list of dependencies in string format, last argument is function which defines what controller does. controller definition is piped down from module.
//console.log('MainCtrl has been created');
//anything the user needs to see or the HTML needs to use, must be defined on 'this'
var self = this; // due to JS scope funny stuff, its good practice to define self = this in every controller and use self. this could be screwy.
self.fetchData = function() {
$http.get('./music_data.json') // the JSON file CANNOT contain comments for this to work properly
.success(function(data) {
console.log(data);
self.pieces = data;
})
// the return value is necessary to test async
//return $http.get('./music_data.json');
}
self.x = "hi";
self.bye = function() {
self.x = "bye";
}
}]);
/** <script type="text/javascript">
/** $(window).on("load resize ", function() {
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width();
$('.tbl-header').css({'padding-right':scrollWidth});
}).resize();
</script> **/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.