hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4699b465d4aec5854c32c31fbe806955b36f787b | 728 | js | JavaScript | server/helpers/customErrors.js | babadee001/turing--backend | 92aa7d55a24dd54523717105dcfc65d846e6691a | [
"MIT"
] | 1 | 2020-08-07T14:31:41.000Z | 2020-08-07T14:31:41.000Z | server/helpers/customErrors.js | babadee001/turing--backend | 92aa7d55a24dd54523717105dcfc65d846e6691a | [
"MIT"
] | null | null | null | server/helpers/customErrors.js | babadee001/turing--backend | 92aa7d55a24dd54523717105dcfc65d846e6691a | [
"MIT"
] | null | null | null | module.exports = {
noExist(table) {
let code;
const abbreviations = {
department: 'DEP',
category: 'CAT',
product: 'PRO',
attribute: 'ATT',
customer: 'CUS',
};
if (table in abbreviations) {
code = (abbreviations[table]);
}
const error = {
error: {
status: 400,
code: `${code}_02`,
message: `Dont exist ${table} with this ID.`,
field: `${table}_id`,
},
};
return error;
},
customerErrors(code, message, status, field) {
const error = {
error: {
status: `${status}`,
code: `${code}`,
message: `${message}`,
field: `${field}`,
},
};
return error;
},
};
| 19.157895 | 53 | 0.476648 |
4699efe3ede6ffbdfdfb0075d60cb56337d6d57a | 5,299 | js | JavaScript | js/agent/hostDial/tab.js | Skyrul/ULAP | bbefa6e09516e3a36db8f1a84d0d7516e10dbc4d | [
"MIT"
] | null | null | null | js/agent/hostDial/tab.js | Skyrul/ULAP | bbefa6e09516e3a36db8f1a84d0d7516e10dbc4d | [
"MIT"
] | null | null | null | js/agent/hostDial/tab.js | Skyrul/ULAP | bbefa6e09516e3a36db8f1a84d0d7516e10dbc4d | [
"MIT"
] | null | null | null | $( function(){
$(document).ready( function(){
$("#agentStatsTab").on("click", function(){
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/loadAgentStats",
type: "post",
dataType: "json",
data: { "ajax":1 },
beforeSend: function(){
$("#agentStats").html("<h1 class=\"blue center lighter\">Loading agent stats please wait...</h1>");
},
error: function(){
$("#agentStats").html("<h1 class=\"red center lighter\">Error on loading agent stats</h1>");
},
success: function(response) {
if(response.html != "")
{
$("#agentStats").html(response.html);
}
else
{
$("#agentStats").html("<h1 class=\"red center lighter\">Error on loading agent stats</h1>");
}
},
});
});
$(document).on("click", ".data-tab-submit-btn", function(){
var this_button = $(this);
var formData = $("#dataTabForm").serialize() + "&ajax=1";
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/updateDataTab",
type: "post",
dataType: "json",
data: formData,
beforeSend: function(){
this_button.html("Saving please wait...");
},
error: function(){
this_button.html("Database Error <i class=\"fa fa-arrow-right\"></i>");
},
success: function(response) {
alert(response.message);
this_button.html("Save <i class=\"fa fa-arrow-right\"></i>");
},
});
});
$(document).on("change", ".data-tab-dropdown", function(){
var list_id = $(this).val();
var lead_id = $(this).attr("lead_id");
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/ajaxLoadCustomData",
type: "post",
dataType: "json",
data: {
"ajax" : 1,
"list_id" : list_id,
"lead_id" : lead_id,
},
success: function(r){
$(".data-fields-tab").html(r.html);
},
});
});
//tabs on click ajax load scripts
$(document).on("click", "#dataTab", function(){
var tab_content_div = $("#data");
if( tab_content_div.html() == "" )
{
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/loadDataTab",
type: "post",
dataType: "json",
data: { "ajax":1, "lead_id":current_lead_id },
beforeSend: function(){
tab_content_div.html("<h1 class=\"blue center lighter\">Loading data please wait...</h1>");
},
error: function(){
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading data</h1>");
},
success: function(response) {
if(response.html != "")
{
tab_content_div.html(response.html);
}
else
{
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading data</h1>");
}
},
});
}
});
$(document).on("click", "#surveyTab", function(){
var tab_content_div = $("#surveys");
if( tab_content_div.html() == "" )
{
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/loadSurveyTab",
type: "post",
dataType: "json",
data: { "ajax":1, "lead_id":current_lead_id },
beforeSend: function(){
tab_content_div.html("<h1 class=\"blue center lighter\">Loading survey please wait...</h1>");
},
error: function(){
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading survey</h1>");
},
success: function(response) {
if(response.html != "")
{
tab_content_div.html(response.html);
}
else
{
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading survey</h1>");
}
},
});
}
});
$(document).on("click", "#agentStatsTab", function(){
var tab_content_div = $("#agentStats");
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/loadAgentStats",
type: "post",
dataType: "json",
data: { "ajax":1 },
beforeSend: function(){
tab_content_div.html("<h1 class=\"blue center lighter\">Loading agent stats please wait...</h1>");
},
error: function(){
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading agent stats</h1>");
},
success: function(response) {
if(response.html != "")
{
tab_content_div.html(response.html);
}
else
{
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading agent stats</h1>");
}
},
});
});
$(document).on("click", "#scriptTab", function(){
var tab_content_div = $("#script");
if( tab_content_div.html() == "" )
{
$.ajax({
url: yii.urls.absoluteUrl + "/agent/default/loadScriptTab",
type: "post",
dataType: "json",
data: { "ajax":1, "lead_id":current_lead_id },
beforeSend: function(){
tab_content_div.html("<h1 class=\"blue center lighter\">Loading script please wait...</h1>");
},
error: function(){
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading script</h1>");
},
success: function(response) {
if(response.html != "")
{
tab_content_div.html(response.html);
}
else
{
tab_content_div.html("<h1 class=\"red center lighter\">Error on loading script</h1>");
}
},
});
}
});
});
}); | 24.995283 | 104 | 0.552746 |
469a8ae214b9a417da8196a528fb16c1762a6665 | 197 | js | JavaScript | archive_history/backend/models/Comment_20211127172107.js | arione15/arione15-OC-Vue.js-Express-MySQL_P7 | 441434e5cf6995c4864b41047f5a8177c9db1e5e | [
"MIT"
] | null | null | null | archive_history/backend/models/Comment_20211127172107.js | arione15/arione15-OC-Vue.js-Express-MySQL_P7 | 441434e5cf6995c4864b41047f5a8177c9db1e5e | [
"MIT"
] | 1 | 2022-02-04T18:41:41.000Z | 2022-02-04T18:41:41.000Z | archive_history/backend/models/Comment_20211127172108.js | arione15/arione15-OC-Vue.js-Express-MySQL_P7 | 441434e5cf6995c4864b41047f5a8177c9db1e5e | [
"MIT"
] | null | null | null | type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
autoIncrement: true
Record ID
Video ID
User ID
Parent ID(
for nested comments)
Comment
Like status
Date time. | 16.416667 | 35 | 0.741117 |
469a9dc52bc9d775a737e0c15ba8d6ba089906a3 | 7,686 | js | JavaScript | src/jsfb-built/js-file-browser-0.1/examples/calendar/src/dd/DayViewDD.js | limscoder/js-file-browser | b642451248f30bc649a00015da4e85cf10052af8 | [
"MIT"
] | 2 | 2015-06-08T16:39:14.000Z | 2018-09-29T12:16:34.000Z | src/jsfb-built/js-file-browser-0.1/examples/calendar/src/dd/DayViewDD.js | limscoder/js-file-browser | b642451248f30bc649a00015da4e85cf10052af8 | [
"MIT"
] | null | null | null | src/jsfb-built/js-file-browser-0.1/examples/calendar/src/dd/DayViewDD.js | limscoder/js-file-browser | b642451248f30bc649a00015da4e85cf10052af8 | [
"MIT"
] | null | null | null | /*!
* js-file-browser
* Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file.
*
* With components from: Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*
* Internal drag zone implementation for the calendar day and week views.
*/
Ext.calendar.DayViewDragZone = Ext.extend(Ext.calendar.DragZone, {
ddGroup: 'DayViewDD',
resizeSelector: '.ext-evt-rsz',
getDragData: function(e) {
var t = e.getTarget(this.resizeSelector, 2, true),
p,
rec;
if (t) {
p = t.parent(this.eventSelector);
rec = this.view.getEventRecordFromEl(p);
return {
type: 'eventresize',
ddel: p.dom,
eventStart: rec.data[Ext.calendar.EventMappings.StartDate.name],
eventEnd: rec.data[Ext.calendar.EventMappings.EndDate.name],
proxy: this.proxy
};
}
t = e.getTarget(this.eventSelector, 3);
if (t) {
rec = this.view.getEventRecordFromEl(t);
return {
type: 'eventdrag',
ddel: t,
eventStart: rec.data[Ext.calendar.EventMappings.StartDate.name],
eventEnd: rec.data[Ext.calendar.EventMappings.EndDate.name],
proxy: this.proxy
};
}
// If not dragging/resizing an event then we are dragging on
// the calendar to add a new event
t = this.view.getDayAt(e.getPageX(), e.getPageY());
if (t.el) {
return {
type: 'caldrag',
dayInfo: t,
proxy: this.proxy
};
}
return null;
}
});
/*
* Internal drop zone implementation for the calendar day and week views.
*/
Ext.calendar.DayViewDropZone = Ext.extend(Ext.calendar.DropZone, {
ddGroup: 'DayViewDD',
onNodeOver: function(n, dd, e, data) {
var dt,
box,
endDt,
text = this.createText,
curr,
start,
end,
evtEl,
dayCol;
if (data.type == 'caldrag') {
if (!this.dragStartMarker) {
// Since the container can scroll, this gets a little tricky.
// There is no el in the DOM that we can measure by default since
// the box is simply calculated from the original drag start (as opposed
// to dragging or resizing the event where the orig event box is present).
// To work around this we add a placeholder el into the DOM and give it
// the original starting time's box so that we can grab its updated
// box measurements as the underlying container scrolls up or down.
// This placeholder is removed in onNodeDrop.
this.dragStartMarker = n.el.parent().createChild({
style: 'position:absolute;'
});
this.dragStartMarker.setBox(n.timeBox);
this.dragCreateDt = n.date;
}
box = this.dragStartMarker.getBox();
box.height = Math.ceil(Math.abs(e.xy[1] - box.y) / n.timeBox.height) * n.timeBox.height;
if (e.xy[1] < box.y) {
box.height += n.timeBox.height;
box.y = box.y - box.height + n.timeBox.height;
endDt = this.dragCreateDt.add(Date.MINUTE, 30);
}
else {
n.date = n.date.add(Date.MINUTE, 30);
}
this.shim(this.dragCreateDt, box);
curr = Ext.calendar.Date.copyTime(n.date, this.dragCreateDt);
this.dragStartDate = Ext.calendar.Date.min(this.dragCreateDt, curr);
this.dragEndDate = endDt || Ext.calendar.Date.max(this.dragCreateDt, curr);
dt = this.dragStartDate.format('g:ia-') + this.dragEndDate.format('g:ia');
}
else {
evtEl = Ext.get(data.ddel);
dayCol = evtEl.parent().parent();
box = evtEl.getBox();
box.width = dayCol.getWidth();
if (data.type == 'eventdrag') {
if (this.dragOffset === undefined) {
this.dragOffset = n.timeBox.y - box.y;
box.y = n.timeBox.y - this.dragOffset;
}
else {
box.y = n.timeBox.y;
}
dt = n.date.format('n/j g:ia');
box.x = n.el.getLeft();
this.shim(n.date, box);
text = this.moveText;
}
if (data.type == 'eventresize') {
if (!this.resizeDt) {
this.resizeDt = n.date;
}
box.x = dayCol.getLeft();
box.height = Math.ceil(Math.abs(e.xy[1] - box.y) / n.timeBox.height) * n.timeBox.height;
if (e.xy[1] < box.y) {
box.y -= box.height;
}
else {
n.date = n.date.add(Date.MINUTE, 30);
}
this.shim(this.resizeDt, box);
curr = Ext.calendar.Date.copyTime(n.date, this.resizeDt);
start = Ext.calendar.Date.min(data.eventStart, curr);
end = Ext.calendar.Date.max(data.eventStart, curr);
data.resizeDates = {
StartDate: start,
EndDate: end
};
dt = start.format('g:ia-') + end.format('g:ia');
text = this.resizeText;
}
}
data.proxy.updateMsg(String.format(text, dt));
return this.dropAllowed;
},
shim: function(dt, box) {
Ext.each(this.shims,
function(shim) {
if (shim) {
shim.isActive = false;
shim.hide();
}
});
var shim = this.shims[0];
if (!shim) {
shim = this.createShim();
this.shims[0] = shim;
}
shim.isActive = true;
shim.show();
shim.setBox(box);
},
onNodeDrop: function(n, dd, e, data) {
var rec;
if (n && data) {
if (data.type == 'eventdrag') {
rec = this.view.getEventRecordFromEl(data.ddel);
this.view.onEventDrop(rec, n.date);
this.onCalendarDragComplete();
delete this.dragOffset;
return true;
}
if (data.type == 'eventresize') {
rec = this.view.getEventRecordFromEl(data.ddel);
this.view.onEventResize(rec, data.resizeDates);
this.onCalendarDragComplete();
delete this.resizeDt;
return true;
}
if (data.type == 'caldrag') {
Ext.destroy(this.dragStartMarker);
delete this.dragStartMarker;
delete this.dragCreateDt;
this.view.onCalendarEndDrag(this.dragStartDate, this.dragEndDate,
this.onCalendarDragComplete.createDelegate(this));
//shims are NOT cleared here -- they stay visible until the handling
//code calls the onCalendarDragComplete callback which hides them.
return true;
}
}
this.onCalendarDragComplete();
return false;
}
});
| 34.936364 | 108 | 0.504554 |
469b6626bf4f3b6a2f9aef840897507635f4da23 | 2,846 | js | JavaScript | test/browser-pack-source-maps.js | adityavs/babelify | 06facded16eca0886a4d96d19fbf37c0625f6120 | [
"MIT"
] | 1,773 | 2015-02-15T16:47:51.000Z | 2022-03-22T20:26:34.000Z | test/browser-pack-source-maps.js | adityavs/babelify | 06facded16eca0886a4d96d19fbf37c0625f6120 | [
"MIT"
] | 247 | 2015-02-16T21:53:22.000Z | 2021-12-21T01:30:49.000Z | test/browser-pack-source-maps.js | adityavs/babelify | 06facded16eca0886a4d96d19fbf37c0625f6120 | [
"MIT"
] | 154 | 2015-02-16T15:30:07.000Z | 2022-01-12T13:08:24.000Z | var browserify = require('browserify');
var convert = require('convert-source-map');
var path = require('path');
var zipObject = require('lodash.zipobject');
var test = require('tap').test;
var babelify = require('../');
// Validate assumptions about browserify's browser-pack source maps. Without
// intermediate source maps, the source is a relative path from the "basedir".
// When "basedir" is not set, it's `process.cwd()`.
test('browserify source maps (no basedir)', function(t) {
t.plan(14);
// normalize cwd
process.chdir(path.join(__dirname, '..'));
var b = browserify({
entries: [path.join(__dirname, 'bundle/index.js')],
debug: true
});
b.transform(babelify, {
presets: ['@babel/preset-env'],
sourceMaps: false // no intermediate source maps
});
var deps = {};
b.on('dep', function(dep) {
t.ok(path.isAbsolute(dep.file));
deps[dep.file] = dep.source;
});
b.bundle(function (err, src) {
t.error(err);
var sm = convert
.fromSource(src.toString())
.toObject();
// remove the prelude
sm.sources.shift();
sm.sourcesContent.shift();
// source paths are relative to the basedir (cwd if not set)
sm.sources.forEach(function(source) {
t.ok(!path.isAbsolute(source));
var aSource = path.join(__dirname, '..', source);
t.ok(deps.hasOwnProperty(aSource));
});
var smDeps = zipObject(
sm.sources.map(function(x) { return path.join(__dirname, '..', x); }),
sm.sourcesContent
);
t.match(sort(smDeps), sort(deps));
});
});
test('browserify source maps (with basedir)', function(t) {
t.plan(14);
// normalize cwd
process.chdir(path.join(__dirname, '..'));
var b = browserify({
entries: [path.join(__dirname, 'bundle/index.js')],
basedir: __dirname,
debug: true
});
b.transform(babelify, {
presets: ['@babel/preset-env'],
sourceMaps: false // no intermediate source maps
});
var deps = {};
b.on('dep', function(dep) {
t.ok(path.isAbsolute(dep.file));
deps[dep.file] = dep.source;
});
b.bundle(function (err, src) {
t.error(err);
var sm = convert
.fromSource(src.toString())
.toObject();
// remove the prelude
sm.sources.shift();
sm.sourcesContent.shift();
// source paths are relative to the basedir (cwd if not set)
sm.sources.forEach(function(source) {
t.ok(!path.isAbsolute(source));
var aSource = path.join(__dirname, source);
t.ok(deps.hasOwnProperty(aSource));
});
var smDeps = zipObject(
sm.sources.map(function(x) { return path.join(__dirname, x); }),
sm.sourcesContent
);
t.match(sort(smDeps), sort(deps));
});
});
function sort(obj) {
return Object.keys(obj).sort().reduce(function(acc, k) {
acc[k] = obj[k];
return acc;
}, {});
}
| 24.324786 | 78 | 0.618412 |
469b745913c2c561fc7b27e8394b6d8c6acaf804 | 1,774 | js | JavaScript | src/components/Dashboard/Posts/index.js | caritosteph/ReadNews | d2d55d2f5192b30f6fce1e62a52aa98e84d67158 | [
"MIT"
] | null | null | null | src/components/Dashboard/Posts/index.js | caritosteph/ReadNews | d2d55d2f5192b30f6fce1e62a52aa98e84d67158 | [
"MIT"
] | null | null | null | src/components/Dashboard/Posts/index.js | caritosteph/ReadNews | d2d55d2f5192b30f6fce1e62a52aa98e84d67158 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import sortBy from 'sort-by';
import { fetchAllPost } from '../../../actions/posts';
import Grid from 'material-ui/Grid';
import Post from './Post';
import NewPost from '../NewPost';
class Posts extends Component {
state = {
editPost: false,
post: ""
};
componentDidMount = () => {
const { fetchAllPost, category } = this.props;
fetchAllPost(category);
}
componentWillReceiveProps = (nextProps) => {
const { category } = this.props;
if(nextProps.category !== category) {
const { fetchAllPost } = this.props;
fetchAllPost(nextProps.category);
}
}
editPost = (post) => {
this.setState({
editPost: true,
post
})
}
handleCloseEditPost = () => {
this.setState({ editPost: false })
}
render(){
const { posts, sortby } = this.props;
const { editPost, post } = this.state;
return (
<Grid container spacing={8}>
{
posts && posts.sort(sortBy(sortby.sortby)).map(post => (
!post.deleted && <Post
key={post.id}
post={post}
editPost={this.editPost} />
))
}
<NewPost
open={editPost}
handleCloseNewPost={this.handleCloseEditPost}
post={post} />
</Grid>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
posts: state.posts.posts,
sortby: state.posts
}
}
const mapDispatchToProps = ({
fetchAllPost
});
Posts.propTypes = {
posts: PropTypes.array
};
export default connect(mapStateToProps, mapDispatchToProps)(Posts);
| 21.373494 | 67 | 0.563134 |
469b8d48eee2b7e7f5e65be32a92d7c05a75d2e0 | 472 | js | JavaScript | src/core/interceptor.js | IrvingBryant/zy-fetch | 20796a854fefe95653db111295f49c0c3dd50b1e | [
"MIT"
] | 2 | 2018-08-31T08:39:32.000Z | 2018-08-31T08:39:33.000Z | src/core/interceptor.js | IrvingBryant/zy-fetch | 20796a854fefe95653db111295f49c0c3dd50b1e | [
"MIT"
] | null | null | null | src/core/interceptor.js | IrvingBryant/zy-fetch | 20796a854fefe95653db111295f49c0c3dd50b1e | [
"MIT"
] | null | null | null | class Interceptor {
constructor() {
this.handlers = []
}
use(onFulfilled, onRejected) {
this.handlers.push({
onFulfilled,
onRejected
})
return this.handlers.length - 1
}
remove(id) {
if (this.handlers[id]) {
delete this.handlers[id]
this.handlers[id] = null
return true
}
return false
}
forEach(callback, thisArgs) {
this.handlers.forEach(callback, thisArgs)
}
}
export default Interceptor | 16.275862 | 45 | 0.614407 |
469c0e762755007391f5f7518732fef11a49c72e | 910 | js | JavaScript | src/components/Ad.js | actionsflow/actionsflow.github.io | 28d06776c3080e2cd13a182fa6245f1fbc5e11a2 | [
"MIT"
] | null | null | null | src/components/Ad.js | actionsflow/actionsflow.github.io | 28d06776c3080e2cd13a182fa6245f1fbc5e11a2 | [
"MIT"
] | null | null | null | src/components/Ad.js | actionsflow/actionsflow.github.io | 28d06776c3080e2cd13a182fa6245f1fbc5e11a2 | [
"MIT"
] | null | null | null | import React from "react"
const AD = props => {
return (
<section className="cta">
<div align="center">
<h1>Sponsorships</h1>
<br />
<a href="https://meercode.io/?utm_campaign=github_repo&utm_medium=referral&utm_content=actionsflow&utm_source=github">
<div>
<img
src="https://raw.githubusercontent.com/actionsflow/actionsflow/main/docs/assets/meercode-logo.png"
width="192"
alt="Meercode"
/>
</div>
<b>
Meercode is the ultimate monitoring dashboard for your GitHub
Actions.
</b>
<div>
<sup>
It's impossible to improve what you can't measure! Get Real
Insights and Metrics From Your CI usage
</sup>
</div>
</a>
</div>
</section>
)
}
export default AD
| 26.764706 | 126 | 0.525275 |
469c15eddba9e907ea70ba81e694f3093c4f2eee | 3,668 | js | JavaScript | tests/unit/primitives.js | wltn0029/libjass | 6b405e65c1a9b6a82fbf78801d56f0e0b41a559f | [
"Apache-2.0"
] | 151 | 2015-01-04T21:53:43.000Z | 2021-08-01T08:34:36.000Z | tests/unit/primitives.js | wltn0029/libjass | 6b405e65c1a9b6a82fbf78801d56f0e0b41a559f | [
"Apache-2.0"
] | 91 | 2015-01-03T16:55:10.000Z | 2020-07-07T19:10:06.000Z | tests/unit/primitives.js | wltn0029/libjass | 6b405e65c1a9b6a82fbf78801d56f0e0b41a559f | [
"Apache-2.0"
] | 37 | 2015-01-11T12:14:52.000Z | 2022-01-08T19:29:59.000Z | /**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(["intern!tdd", "tests/support/parser-test", "libjass"], function (tdd, parserTest, libjass) {
tdd.suite("Primitives", function () {
tdd.suite("Color", function () {
tdd.test("Starts with &H", parserTest("&H3F171F&", "color", new libjass.parts.Color(31, 23, 63, 1)));
tdd.test("Starts with H", parserTest("&3F171F&", "color", new libjass.parts.Color(31, 23, 63, 1)));
tdd.test("Less than six digits", parserTest("&H71F&", "color", new libjass.parts.Color(31, 7, 0, 1)));
tdd.test("Eight digits", parserTest("&H3F171F00&", "color", new libjass.parts.Color(0, 31, 23, 1)));
tdd.test("Eight digits", parserTest("&H3F171FFF&", "color", new libjass.parts.Color(255, 31, 23, 1)));
tdd.test("More than eight digits", parserTest("&HAAAA3F171F00&", "color", new libjass.parts.Color(255, 255, 255, 1)));
tdd.test("More than eight digits", parserTest("&HAAAA3F171FFF&", "color", new libjass.parts.Color(255, 255, 255, 1)));
});
tdd.suite("Alpha", function () {
tdd.test("Starts with &H", parserTest("&HFF&", "alpha", 0));
tdd.test("Starts with &", parserTest("&FF&", "alpha", 0));
tdd.test("Starts with &H, one digit", parserTest("&HF&", "alpha", 1 - 15 / 255));
tdd.test("Starts with &H, one digit", parserTest("&H0&", "alpha", 1));
tdd.test("Starts with &, one digit", parserTest("&F&", "alpha", 1 - 15 / 255));
tdd.test("Starts with &, one digit", parserTest("&0&", "alpha", 1));
tdd.test("Starts with &H, doesn't end with &", parserTest("&HF&", "alpha", 1 - 15 / 255));
tdd.test("Starts with &H, doesn't end with &", parserTest("&H0&", "alpha", 1));
tdd.test("Starts with &, doesn't end with &", parserTest("&F", "alpha", 1 - 15 / 255));
tdd.test("Starts with &, doesn't end with &", parserTest("&0", "alpha", 1));
tdd.test("Doesn't start with &, doesn't end with &", parserTest("0", "alpha", 1));
tdd.test("Starts with H", parserTest("H0", "alpha", 1));
});
tdd.suite("ColorWithAlpha", function () {
tdd.test("Starts with &H", parserTest("&H00434441", "colorWithAlpha", new libjass.parts.Color(65, 68, 67, 1)));
tdd.test("Starts with &H, non-zero alpha", parserTest("&HF0434441", "colorWithAlpha", new libjass.parts.Color(65, 68, 67, 1 - 240 / 255)));
tdd.test("Starts with &H, zero alpha", parserTest("&HFF434441", "colorWithAlpha", new libjass.parts.Color(65, 68, 67, 0)));
tdd.test("Less than six digits", parserTest("&H71F", "colorWithAlpha", new libjass.parts.Color(31, 7, 0, 1)));
tdd.test("Eight digits", parserTest("&H3F171F00", "colorWithAlpha", new libjass.parts.Color(0, 31, 23, 1 - 63 / 255)));
tdd.test("Eight digits", parserTest("&H3F171FFF", "colorWithAlpha", new libjass.parts.Color(255, 31, 23, 1 - 63 / 255)));
tdd.test("More than eight digits", parserTest("&HAAAA3F171F00", "colorWithAlpha", new libjass.parts.Color(255, 255, 255, 0)));
tdd.test("More than eight digits", parserTest("&HAAAA3F171FFF", "colorWithAlpha", new libjass.parts.Color(255, 255, 255, 0)));
});
});
});
| 43.666667 | 142 | 0.650491 |
469c1e39f7c8f17b54a6afefd549a8d49d197a62 | 5,175 | js | JavaScript | clients/lib/TileLayer.GeoJSON.js | ryanshaw/vector-river-map | 94da4e66e414e5bc5de535ba2d4692df09b13d81 | [
"BSD-3-Clause"
] | 219 | 2015-01-08T01:30:37.000Z | 2021-11-21T16:51:43.000Z | clients/lib/TileLayer.GeoJSON.js | dsconstable/vector-river-map | 94da4e66e414e5bc5de535ba2d4692df09b13d81 | [
"BSD-3-Clause"
] | 5 | 2015-06-02T15:41:35.000Z | 2017-08-22T15:33:54.000Z | clients/lib/TileLayer.GeoJSON.js | dsconstable/vector-river-map | 94da4e66e414e5bc5de535ba2d4692df09b13d81 | [
"BSD-3-Clause"
] | 38 | 2015-01-04T23:38:58.000Z | 2021-01-30T16:46:44.000Z | var statistics = {tiles:[]}; // (nelson): hack in some stats tracking
// Load data tiles using the JQuery ajax function
L.TileLayer.Ajax = L.TileLayer.extend({
_requests: [],
_data: [],
data: function () {
for (var t in this._tiles) {
var tile = this._tiles[t];
if (!tile.processed) {
this._data = this._data.concat(tile.datum);
tile.processed = true;
}
}
return this._data;
},
_addTile: function(tilePoint, container) {
var tile = { datum: null, processed: false };
this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
this._loadTile(tile, tilePoint);
},
// XMLHttpRequest handler; closure over the XHR object, the layer, and the tile
_xhrHandler: function (req, layer, tile) {
return function() {
if (req.readyState != 4) {
return;
}
var s = req.status;
if ((s >= 200 && s < 300) || s == 304) {
statistics.tiles.push({
url: req._url,
size: req.responseText.length,
start: req._startTime,
end: window.performance.now(),
});
tile.datum = JSON.parse(req.responseText);
layer._tileLoaded();
} else {
layer._tileLoaded();
}
}
},
// Load the requested tile via AJAX
_loadTile: function (tile, tilePoint) {
this._adjustTilePoint(tilePoint);
var layer = this;
var req = new XMLHttpRequest();
var url = this.getTileUrl(tilePoint);
req._url = url;
req._startTime = window.performance.now();
this._requests.push(req);
req.onreadystatechange = this._xhrHandler(req, layer, tile);
req.open('GET', url, true);
req.send();
},
_resetCallback: function() {
this._data = [];
L.TileLayer.prototype._resetCallback.apply(this, arguments);
for (var i in this._requests) {
this._requests[i].abort();
}
this._requests = [];
},
_update: function() {
if (this._map._panTransition && this._map._panTransition._inProgress) { return; }
if (this._tilesToLoad < 0) this._tilesToLoad = 0;
L.TileLayer.prototype._update.apply(this, arguments);
}
});
L.TileLayer.GeoJSON = L.TileLayer.Ajax.extend({
_geojson: {"type":"FeatureCollection","features":[]},
initialize: function (url, options, geojsonOptions) {
L.TileLayer.Ajax.prototype.initialize.call(this, url, options);
this.geojsonLayer = new L.GeoJSON(this._geojson, geojsonOptions);
this.geojsonOptions = geojsonOptions;
},
onAdd: function (map) {
this._map = map;
L.TileLayer.Ajax.prototype.onAdd.call(this, map);
this.on('load', this._tilesLoaded);
map.addLayer(this.geojsonLayer);
},
onRemove: function (map) {
map.removeLayer(this.geojsonLayer);
this.off('load', this._tilesLoaded);
L.TileLayer.Ajax.prototype.onRemove.call(this, map);
},
data: function () {
this._geojson.features = [];
if (this.options.unique) {
this._uniqueKeys = {};
}
var tileData = L.TileLayer.Ajax.prototype.data.call(this);
for (var t in tileData) {
var tileDatum = tileData[t];
if (tileDatum && tileDatum.features) {
// deduplicate features by using the string result of the unique function
if (this.options.unique) {
for (var f in tileDatum.features) {
var featureKey = this.options.unique(tileDatum.features[f]);
if (this._uniqueKeys.hasOwnProperty(featureKey)) {
delete tileDatum.features[f];
}
else {
this._uniqueKeys[featureKey] = featureKey;
}
}
}
this._geojson.features =
this._geojson.features.concat(tileDatum.features);
}
}
return this._geojson;
},
_resetCallback: function () {
this._geojson.features = [];
statistics = {tiles:[]};
L.TileLayer.Ajax.prototype._resetCallback.apply(this, arguments);
},
_tilesLoaded: function (evt) {
this._report();
this.geojsonLayer.clearLayers().addData(this.data());
},
_report: function() {
var size = 0, time = 0, start = Infinity, end = 0;
for (var i in statistics.tiles) {
var o = statistics.tiles[i];
size += o.size;
time += (o.end - o.start);
start = Math.min(start, o.start);
end = Math.max(end, o.end);
}
console.log(
Math.round(size/1024) + "kB " +
Math.round(end-start) + "ms " +
statistics.tiles.length + " URLs, " +
Math.round(time) + "ms aggregate",
statistics);
}
});
| 36.443662 | 89 | 0.528309 |
469ca834cecc8d29d8123ff0972f79a1ba0aaaad | 2,431 | js | JavaScript | src/components/footer.js | kuworking/kuworking-theme-four | f68becde05843d2da81c63d54d718bb552d7cdde | [
"MIT"
] | null | null | null | src/components/footer.js | kuworking/kuworking-theme-four | f68becde05843d2da81c63d54d718bb552d7cdde | [
"MIT"
] | null | null | null | src/components/footer.js | kuworking/kuworking-theme-four | f68becde05843d2da81c63d54d718bb552d7cdde | [
"MIT"
] | null | null | null | import React from 'react'
import { Link } from 'gatsby'
import styled from '@emotion/styled'
import { Styled, useThemeUI } from 'theme-ui'
import CookieConsent from 'react-cookie-consent'
import { Text } from 'gatsby-theme-kuworking-core'
export const Footer = ({ basePath }) => {
const { theme } = useThemeUI()
return (
<>
<Expand />
<Foot theme={theme}>
<Legal>
<Styled.a as={Link} aria-label="Mi Historia" to={`${basePath}me`}>
{Text.footer.me}
</Styled.a>
<Separator />
<Styled.a as="a" aria-label="kuworking" href={Text.footer.credits_url}>
{Text.footer.credits}
</Styled.a>
<Separator />
<span>
<Text.footer.date />
</span>
</Legal>
<CookieConsent
onAccept={() => {}}
debug={false}
cookieName="cookies_user_agrees"
hideOnAccept={true}
acceptOnScroll={true}
acceptOnScrollPercentage={10}
buttonText={Text.footer.cookies_agree}
disableStyles={true}
style={{
backgroundColor: '#443f3feb',
bottom: '0px',
position: 'fixed',
width: '100%',
display: 'flex',
padding: '5px',
justifyContent: 'space-around',
color: '#fff',
fontSize: '0.8em',
}}
buttonStyle={{
backgroundColor: '#f7f7f7',
padding: '4px',
color: '#999',
cursor: 'pointer',
fontSize: '0.8em',
borderRadius: '4px',
}}
contentStyle={{}}
>
<Text.footer.cookies />
</CookieConsent>
</Foot>
</>
)
}
const Expand = styled.div`
flex: 1;
`
const Foot = styled.footer`
width: 100%;
z-index: 1;
padding-top: 20px;
padding-bottom: 20px;
margin-top: 50px;
margin-bottom: 20px;
display: flex;
justify-content: center;
letter-spacing: -0.5px;
padding: 3px 3px 10px 3px;
background: ${props => props.theme.colors.cta__div__background};
border-radius: 3px;
`
const Legal = styled.div`
display: flex;
flex-wrap: wrap;
justify-content: center;
`
const q = px => `@media (min-width: ${px}px)`
const Separator = styled.div`
margin: 0px 20px;
border-right: 2px solid #c1c1c1a3;
align-self: center;
${q(600)} {
height: 75%;
}
`
| 23.833333 | 81 | 0.536405 |
469d3364f64ca5c482f6c65e7dfe4ed87517c46c | 148 | js | JavaScript | index.js | sro-boeing-wave-2/hello-world-typescript-problem-hsharathachar | bc3f9ce260b03264b52715b022c434277f3cc5a9 | [
"CC0-1.0"
] | null | null | null | index.js | sro-boeing-wave-2/hello-world-typescript-problem-hsharathachar | bc3f9ce260b03264b52715b022c434277f3cc5a9 | [
"CC0-1.0"
] | null | null | null | index.js | sro-boeing-wave-2/hello-world-typescript-problem-hsharathachar | bc3f9ce260b03264b52715b022c434277f3cc5a9 | [
"CC0-1.0"
] | null | null | null | "use strict";
exports.__esModule = true;
function displayHelloWorld() {
document.getElementById("helloWorldBlock").innerHTML = "Hello World";
}
| 24.666667 | 73 | 0.75 |
469e0a6406ea716ba18de81da863080bf73bdc2f | 373 | js | JavaScript | javaScript/ex-array-includes.js | songseungeun/TIL | d2a42a133998095099df2641b2cb0bc4369dc49b | [
"MIT"
] | null | null | null | javaScript/ex-array-includes.js | songseungeun/TIL | d2a42a133998095099df2641b2cb0bc4369dc49b | [
"MIT"
] | 28 | 2020-08-15T11:48:53.000Z | 2022-02-27T05:38:37.000Z | javaScript/ex-array-includes.js | songseungeun/TIL | d2a42a133998095099df2641b2cb0bc4369dc49b | [
"MIT"
] | null | null | null | const arr = [1, 2, 3];
let result = arr.includes(2);
console.log(result);
result = arr.includes(100);
console.log(result);
result = arr.includes(1, 1);
console.log(result);
result = arr.includes(3, -1);
console.log(result);
// indexOF 메소드를 사용해도 확인 가능하나,
// -1을 비교해야하고, NaN이 포함되어있는지 확인할 수 없다.
console.log([NaN].indexOf(NaN) !== -1);
console.log([NaN].includes(NaN));
| 17.761905 | 39 | 0.664879 |
469e94ed81323e0e85d487af3ef7633c90d4c7f4 | 1,184 | js | JavaScript | public/admin/plugins/ckeditor/config.js | ittranvantruong/menudientu | 093b9f9f105e94563179529235f63d1ea7109050 | [
"MIT"
] | null | null | null | public/admin/plugins/ckeditor/config.js | ittranvantruong/menudientu | 093b9f9f105e94563179529235f63d1ea7109050 | [
"MIT"
] | null | null | null | public/admin/plugins/ckeditor/config.js | ittranvantruong/menudientu | 093b9f9f105e94563179529235f63d1ea7109050 | [
"MIT"
] | null | null | null | /**
* @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see https://ckeditor.com/legal/ckeditor-oss-license
*/
var domain = window.location.protocol +'//'+ window.location.hostname +'/apphoavien';
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.filebrowserBrowseUrl = domain + '/public/plugins/ckfinder/ckfinder.html';
config.filebrowserImageBrowseUrl = domain +'/public/plugins/ckfinder/ckfinder.html?type=Images';
config.filebrowserFlashBrowseUrl = domain +'/public/plugins/ckfinder/ckfinder.html?type=Flash';
config.filebrowserUploadUrl = domain + '/public/plugins/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
config.filebrowserImageUploadUrl = domain +'/public/plugins/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
config.filebrowserFlashUploadUrl = domain +'/public/plugins/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
config.extraPlugins = 'video';
// config.extraPlugins = 'maximize';
};
| 47.36 | 136 | 0.767736 |
469ecb399073fc8300e2e9f6b1c29c62c2cc0b6b | 25,297 | js | JavaScript | interview/assets/js/36.4a72fb12.js | mescalchuan/mescalchuan.github.io | 2006ec912f96bce4b37a07a9915055028476596d | [
"Apache-2.0"
] | null | null | null | interview/assets/js/36.4a72fb12.js | mescalchuan/mescalchuan.github.io | 2006ec912f96bce4b37a07a9915055028476596d | [
"Apache-2.0"
] | 22 | 2020-01-08T07:44:53.000Z | 2022-02-27T03:33:03.000Z | interview/docs/.vuepress/dist/assets/js/36.4a72fb12.js | mescalchuan/mescalchuan.github.io | 2006ec912f96bce4b37a07a9915055028476596d | [
"Apache-2.0"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[36],{440:function(t,s,a){"use strict";a.r(s);var n=a(51),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"前端基础"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#前端基础"}},[t._v("#")]),t._v(" 前端基础")]),t._v(" "),a("h4",{attrs:{id:"同源与跨域"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#同源与跨域"}},[t._v("#")]),t._v(" 同源与跨域")]),t._v(" "),a("p",[t._v("跨域请求是可以发出去的,服务器也能接收并返回结果,只是请求响应response被浏览器阻止了。\n\ufeff\n由于同源策略,跨域的AJAX是不会带上cookie的,如果想带,设置withCredential=true,并要求后台设置白名单。\n\ufeff\n防止CSRF的方法就是将token携带到请求参数中。\n\ufeff\n后台设置Accsee-Control-Allow-Origin允许哪些网站跨域。\n\ufeff\nJSONP的原理:")]),t._v(" "),a("div",{staticClass:"language-js line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("getResult")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\tdocument"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("write")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("data"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v("script src"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"跨域的网站请求路径?callback=getResult"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(">")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("/")]),t._v("script"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(">")]),t._v("\n\ufeff\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//后台")]),t._v("\nresponse"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("writeHead")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token number"}},[t._v("200")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Content-Type"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"text/javascript"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\nresponse"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("send")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("callback"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"(\'"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),a("span",{pre:!0,attrs:{class:"token number"}},[t._v("123")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"\')"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br"),a("span",{staticClass:"line-number"},[t._v("4")]),a("br"),a("span",{staticClass:"line-number"},[t._v("5")]),a("br"),a("span",{staticClass:"line-number"},[t._v("6")]),a("br"),a("span",{staticClass:"line-number"},[t._v("7")]),a("br"),a("span",{staticClass:"line-number"},[t._v("8")]),a("br")])]),a("p",[t._v("JSONP需要将回调写在url中,因此只能支持get请求。\n\ufeff\n跨域的另一中常用方案是让你的后台做为中转层,它去请求跨域网站再返给你。服务器和服务器之间是不存在跨域一说的。")]),t._v(" "),a("h4",{attrs:{id:"上传base64图片"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#上传base64图片"}},[t._v("#")]),t._v(" 上传base64图片")]),t._v(" "),a("div",{staticClass:"language-js line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//b64toBlob的实现请参考书p308页")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("let")]),t._v(" blob "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("b64toBlob")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("base64"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"image/png"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\nformData"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("append")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"fileName"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" blob"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br")])]),a("p"),t._v(" "),a("h4",{attrs:{id:"垂直居中"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#垂直居中"}},[t._v("#")]),t._v(" 垂直居中")]),t._v(" "),a("p",[t._v("想要垂直居中一个比div小的图片,可以:")]),t._v(" "),a("div",{staticClass:"language-css line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-css"}},[a("code",[a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".father")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("text-align")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" center"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".father:before")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("content")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("''")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("vertical-align")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" middle"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n line-height=father.height"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v("//或者\n.father:before")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("content")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("''")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("display")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" inline-block"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("vertical-align")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" middle"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("height")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" 100%"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br"),a("span",{staticClass:"line-number"},[t._v("4")]),a("br"),a("span",{staticClass:"line-number"},[t._v("5")]),a("br"),a("span",{staticClass:"line-number"},[t._v("6")]),a("br"),a("span",{staticClass:"line-number"},[t._v("7")]),a("br"),a("span",{staticClass:"line-number"},[t._v("8")]),a("br"),a("span",{staticClass:"line-number"},[t._v("9")]),a("br"),a("span",{staticClass:"line-number"},[t._v("10")]),a("br"),a("span",{staticClass:"line-number"},[t._v("11")]),a("br"),a("span",{staticClass:"line-number"},[t._v("12")]),a("br"),a("span",{staticClass:"line-number"},[t._v("13")]),a("br"),a("span",{staticClass:"line-number"},[t._v("14")]),a("br"),a("span",{staticClass:"line-number"},[t._v("15")]),a("br")])]),a("p"),t._v(" "),a("h4",{attrs:{id:"左右固定宽度-中间自适应的三栏布局"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#左右固定宽度-中间自适应的三栏布局"}},[t._v("#")]),t._v(" 左右固定宽度,中间自适应的三栏布局")]),t._v(" "),a("div",{staticClass:"language-html line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("100px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("float")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" left")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是左侧"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("100px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("float")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" right")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是右侧"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是中间"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br")])]),a("p"),t._v(" "),a("div",{staticClass:"language-html line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[t._v("//td会自适应沾满tr的剩余空间,但其默认宽度是内容宽,因此设置一个很大的宽度,放心,再怎么大最终都不会超过table并溢出的。\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("100px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("float")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" left")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是左侧"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("100px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("float")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" right")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是右侧"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("disply")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" table-cell"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" 99999px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是中间"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br"),a("span",{staticClass:"line-number"},[t._v("4")]),a("br")])]),a("p"),t._v(" "),a("div",{staticClass:"language-html line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("display")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" flex")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n\t"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("100px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是左侧"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[t._v("flex="),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("grow")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" 1"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是中间"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n\t"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token special-attr"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token value css language-css"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("100px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("我是右侧"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br"),a("span",{staticClass:"line-number"},[t._v("4")]),a("br"),a("span",{staticClass:"line-number"},[t._v("5")]),a("br")])]),a("p"),t._v(" "),a("h4",{attrs:{id:"响应式开发"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#响应式开发"}},[t._v("#")]),t._v(" 响应式开发")]),t._v(" "),a("div",{staticClass:"language-css line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-css"}},[a("code",[a("span",{pre:!0,attrs:{class:"token selector"}},[t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("width")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("calc")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("100% - 20px"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" / 2"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[t._v("1")]),a("br"),a("span",{staticClass:"line-number"},[t._v("2")]),a("br"),a("span",{staticClass:"line-number"},[t._v("3")]),a("br")])]),a("p"),t._v(" "),a("h4",{attrs:{id:"click"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#click"}},[t._v("#")]),t._v(" click")]),t._v(" "),a("p",[t._v("曾经click在移动端会有延迟,这是因为设备要检测你的点击是不是双击,因此增加了延迟。但你添加了"),a("code",[t._v('<meta name="viewport" content="width=device-width">')]),t._v("后就不会有这个问题了。也可以说,现在的移动端开发可以不用考虑click迟钝问题了。\n\ufeff\ntouchstart事件:如果你将click替换成touchstart,那么确实没有延迟,但是当这个dom被滑动时,touchstart也会触发。")]),t._v(" "),a("h4",{attrs:{id:"顺序"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#顺序"}},[t._v("#")]),t._v(" 顺序")]),t._v(" "),a("p",[t._v("touchstart --\x3e touchmove --\x3e touchend --\x3e click")])])}),[],!1,null,null,null);s.default=e.exports}}]); | 25,297 | 25,297 | 0.587105 |
469ecc817850757eafb014a238bfda078be5a60d | 414 | js | JavaScript | stories/index.stories.js | lifechurch/react-draftable | f382d4430a4ea3b2cac79e310fa63e341b62ffff | [
"MIT"
] | 1 | 2022-03-17T11:35:25.000Z | 2022-03-17T11:35:25.000Z | stories/index.stories.js | lifechurch/react-draftable | f382d4430a4ea3b2cac79e310fa63e341b62ffff | [
"MIT"
] | 7 | 2019-05-29T20:04:37.000Z | 2021-05-07T13:24:53.000Z | stories/index.stories.js | lifechurch/react-draftable | f382d4430a4ea3b2cac79e310fa63e341b62ffff | [
"MIT"
] | null | null | null | import React from 'react';
import { storiesOf } from '@storybook/react';
import { Draftable, DraftableState } from '../src';
storiesOf('Draftable', module)
.add('with default config', () => <Draftable />)
.add('with initial state', () => {
const initialState = DraftableState.createFromString('<p>Test <b>bolded</b></p>', 'html');
return (
<Draftable initialState={initialState} />
);
});
| 31.846154 | 94 | 0.640097 |
469fda8443f5531ddc82b6d94df252c9ba849d14 | 16,647 | js | JavaScript | config/flash.js | app-helmet-insure/app-helmet-insure.github.io | 967d6590e235a1f9c8c311a4d7e528bb59712f5b | [
"MIT"
] | 1 | 2021-06-24T08:40:50.000Z | 2021-06-24T08:40:50.000Z | config/flash.js | app-helmet-insure/app-helmet-insure.github.io | 967d6590e235a1f9c8c311a4d7e528bb59712f5b | [
"MIT"
] | null | null | null | config/flash.js | app-helmet-insure/app-helmet-insure.github.io | 967d6590e235a1f9c8c311a4d7e528bb59712f5b | [
"MIT"
] | 2 | 2021-03-30T10:13:44.000Z | 2021-09-01T22:53:19.000Z | import { getTokenPrice } from "~/interface/event.js";
import { fixD } from "~/assets/js/util.js";
import MiningABI from "~/web3/abis/MiningABI.json";
import { Contract } from "ethers-multicall-x";
import {
toWei,
getOnlyMultiCallProvider,
processResult,
fromWei,
} from "~/web3/index.js";
export const PoolList = [
{
Key: "SHIBARGON",
PoolName: "<i>hARGON</i> Pool",
PoolDesc: "By SHIBh-Helmet LPT",
StakeSymbol: "SHIBh-Helmet LPT",
RewardSymbol: "hARGON",
OneLpSymbol: "SHIBh",
StartTime: "2021/07/08 00:00 UTC+8",
FinishTime: "2021/07/15 00:00 UTC+8",
PoolAddress: "0x5A7c52e44D7406ae16C4F3ac1b5cd75BB775954d",
StakeAddress: "0x12fdd0aed56fb61fbf242ac783da600b322f64e6",
RewardAddress: "0x4ce2d9804da7583c02f80fec087aea1d137214eb",
OneLpAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV2",
TotalRewards: 125000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "SHIBh",
AddTokenAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
AddTokenDecimals: 12,
},
RightShowToken: {
AddTokenSymbol: "hARGON",
AddTokenAddress: "0x4ce2d9804da7583c02f80fec087aea1d137214eb",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "SHIBBMXX",
PoolName: "<i>hBMXX</i> Pool",
PoolDesc: "By SHIBh-Helmet LPT",
StakeSymbol: "SHIBh-Helmet LPT",
RewardSymbol: "hBMXX",
OneLpSymbol: "SHIBh",
StartTime: "2021/06/30 00:00 UTC+8",
FinishTime: "2021/07/13 00:00 UTC+8",
PoolAddress: "0xA93f7bAbaf1A0e95dC472eb7cD37C59ed009c728",
StakeAddress: "0x12fdd0aed56fb61fbf242ac783da600b322f64e6",
RewardAddress: "0x6dab495c467c8fb326dc5e792cd7faeb9ecafe44",
OneLpAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV2",
TotalRewards: 3600,
PoolProcess: 13,
LeftShowToken: {
AddTokenSymbol: "SHIBh",
AddTokenAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
AddTokenDecimals: 12,
},
RightShowToken: {
AddTokenSymbol: "hBMXX",
AddTokenAddress: "0x6dab495c467c8fb326dc5e792cd7faeb9ecafe44",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "SHIBBABY",
PoolName: "<i>hBABY</i> Pool",
PoolDesc: "By SHIBh-Helmet LPT",
StakeSymbol: "SHIBh-Helmet LPT",
RewardSymbol: "hBABY",
OneLpSymbol: "SHIBh",
StartTime: "2021/06/25 00:00 UTC+8",
FinishTime: "2021/07/08 00:00 UTC+8",
PoolAddress: "0x475e5A97cA24278E820F93A5423cc1F613658466",
StakeAddress: "0x12fdd0aed56fb61fbf242ac783da600b322f64e6",
RewardAddress: "0x06a954537cdcf6fa57eadf2e3e56e4325b7e9624",
OneLpAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV2",
TotalRewards: 140000,
PoolProcess: 13,
LeftShowToken: {
AddTokenSymbol: "SHIBh",
AddTokenAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
AddTokenDecimals: 12,
},
RightShowToken: {
AddTokenSymbol: "hBABY",
AddTokenAddress: "0x06a954537cdcf6fa57eadf2e3e56e4325b7e9624",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "SHIBMTRG",
PoolName: "<i>hMTRG</i> Pool",
PoolDesc: "By SHIBh-Helmet LPT",
StakeSymbol: "SHIBh-Helmet LPT",
RewardSymbol: "hMTRG",
OneLpSymbol: "SHIBh",
StartTime: "2021/06/24 00:00 UTC+8",
FinishTime: "2021/07/01 00:00 UTC+8",
PoolAddress: "0x784a1507c2D2e90C3842929E06625b0D4e881071",
StakeAddress: "0x12fdd0aed56fb61fbf242ac783da600b322f64e6",
RewardAddress: "0xa561926e81decb74b3d11e14680b3f6d1c5012bd",
OneLpAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV2",
TotalRewards: 8000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "SHIBh",
AddTokenAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
AddTokenDecimals: 12,
},
RightShowToken: {
AddTokenSymbol: "hMTRG",
AddTokenAddress: "0xa561926e81decb74b3d11e14680b3f6d1c5012bd",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "SHIBWINGS",
PoolName: "<i>hWINGS</i> Pool",
PoolDesc: "By SHIBh-Helmet LPT",
StakeSymbol: "SHIBh-Helmet LPT",
RewardSymbol: "hWINGS",
OneLpSymbol: "SHIBh",
StartTime: "2021/06/11 00:00 UTC+8",
FinishTime: "2021/06/25 00:00 UTC+8",
PoolAddress: "0x1CaB756c4B46B44a3012E74F1023ae972c1b1b60",
StakeAddress: "0x12fdd0aed56fb61fbf242ac783da600b322f64e6",
RewardAddress: "0x34508EA9ec327ff3b98A2F10eEDc2950875bf026",
OneLpAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV2",
TotalRewards: 7500,
PoolProcess: 14,
LeftShowToken: {
AddTokenSymbol: "SHIBh",
AddTokenAddress: "0x224b33139a377a62d4BaD3D58cEDb7807AE228eB",
AddTokenDecimals: 12,
},
RightShowToken: {
AddTokenSymbol: "hWINGS",
AddTokenAddress: "0x34508EA9ec327ff3b98A2F10eEDc2950875bf026",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "TPTBURGER",
PoolName: "<i>hxBURGER</i> Pool",
PoolDesc: "By hTPT-Helmet LPT",
StakeSymbol: "hTPT-Helmet LPT",
RewardSymbol: "hxBURGER",
OneLpSymbol: "hTPT",
StartTime: "2021/04/22 14:00 UTC+8",
FinishTime: "2021/05/12 00:00 UTC+8",
PoolAddress: "0x40052013B8c019E999276885467AC156e86Fd1bD",
StakeAddress: "0x413da4890ab12b1a7e01d0bb7fc5cf6cadf5d565",
RewardAddress: "0xCa7597633927A98B800738eD5CD2933a74a80e8c",
OneLpAddress: "0x412B6d4C3ca1F0a9322053490E49Bafb0D57dD7c",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "BURGER",
TotalRewards: 20000,
PoolProcess: 20,
LeftShowToken: {
AddTokenSymbol: "hTPT",
AddTokenAddress: "0x412B6d4C3ca1F0a9322053490E49Bafb0D57dD7c",
AddTokenDecimals: 4,
},
RightShowToken: {
AddTokenSymbol: "hxBURGER",
AddTokenAddress: "0xCa7597633927A98B800738eD5CD2933a74a80e8c",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "DODOTPT",
PoolName: "<i>hTPT</i> Pool",
PoolDesc: "By hDODO-Helmet LPT",
StakeSymbol: "hDODO-Helmet LPT",
RewardSymbol: "hTPT",
OneLpSymbol: "hDODO",
StartTime: "2021/04/06 00:00 UTC+8",
FinishTime: "2021/04/26 00:00 UTC+8",
PoolAddress: "0xe71B586Be2c053E22a44556A7526B02428a943B0",
StakeAddress: "0x762D63a230C4e1EB2673cB5C4FadC5B68b3074c7",
RewardAddress: "0x412B6d4C3ca1F0a9322053490E49Bafb0D57dD7c",
OneLpAddress: "0xfeD2e6A6105E48A781D0808E69460bd5bA32D3D3",
StakeDecimals: 18,
RewardDecimals: 4,
SwapType: "PANCAKEV1",
TotalRewards: 2000000,
PoolProcess: 20,
LeftShowToken: {
AddTokenSymbol: "hDODO",
AddTokenAddress: "0xfeD2e6A6105E48A781D0808E69460bd5bA32D3D3",
AddTokenDecimals: 18,
},
RightShowToken: {
AddTokenSymbol: "hTPT",
AddTokenAddress: "0x412B6d4C3ca1F0a9322053490E49Bafb0D57dD7c",
AddTokenDecimals: 4,
},
APR: "--",
},
{
Key: "MATHTPT",
PoolName: "<i>hDODO</i> Pool",
PoolDesc: "By hMATH-Helmet LPT",
StakeSymbol: "hMATH-Helmet LPT",
RewardSymbol: "hDODO",
OneLpSymbol: "hMATH",
StartTime: "2021/03/24 00:00 UTC+8",
FinishTime: "2021/03/31 12:00 UTC+8",
PoolAddress: "0xc68CB0a3c5Cab3C9521E124Eff97A503c45bE9E4",
StakeAddress: "0xc840de3a061A73467bc98acD9A32aA3a281A380C",
RewardAddress: "0xfeD2e6A6105E48A781D0808E69460bd5bA32D3D3",
OneLpAddress: "0xdD9b5801e8A38ef7A728A42492699521C6A7379b",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV1",
TotalRewards: 40000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "hMATH",
AddTokenAddress: "0xdD9b5801e8A38ef7A728A42492699521C6A7379b",
AddTokenDecimals: 18,
},
RightShowToken: {
AddTokenSymbol: "hTPT",
AddTokenAddress: "0xfeD2e6A6105E48A781D0808E69460bd5bA32D3D3",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "AUTOMATH",
PoolName: "<i>hMATH</i> Pool",
PoolDesc: "By hAUTO-Helmet LPT",
StakeSymbol: "hAUTO-Helmet LPT",
RewardSymbol: "hMATH",
OneLpSymbol: "hAUTO",
StartTime: "2021/03/11 00:00 UTC+8",
FinishTime: "2021/03/18 00:00 UTC+8",
PoolAddress: "0x630179cd153a009b4b864A5A5a3Ac5A0E70804Da",
StakeAddress: "0xB6F84EaD91Fb6d70B8f1E87759E7c95c440DD80C",
RewardAddress: "0xdD9b5801e8A38ef7A728A42492699521C6A7379b",
OneLpAddress: "0xfeF73F4eeE23E78Ee14b6D2B6108359E8fbe6112",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV1",
TotalRewards: 30000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "hAUTO",
AddTokenAddress: "0xfeF73F4eeE23E78Ee14b6D2B6108359E8fbe6112",
AddTokenDecimals: 18,
},
RightShowToken: {
AddTokenSymbol: "hMATH",
AddTokenAddress: "0xdD9b5801e8A38ef7A728A42492699521C6A7379b",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "BNB500AUTO",
PoolName: "<i>hAUTO</i> Pool",
PoolDesc: "By BNB500-Helmet LPT",
StakeSymbol: "BNB500-Helmet LPT",
RewardSymbol: "hAUTO",
OneLpSymbol: "BNB500",
StartTime: "2021/03/02 00:00 UTC+8",
FinishTime: "2021/03/09 00:00 UTC+8",
PoolAddress: "0xe4a5d7cb5A9EbDC4370D0b4EBBd0C1656099b293",
StakeAddress: "0x6A829c3870Ab4ce228Cdf359E6F72295ef472F9d",
RewardAddress: "0xfeF73F4eeE23E78Ee14b6D2B6108359E8fbe6112",
OneLpAddress: "0xe204c4c21c6ed90e37cb06cb94436614f3208d58",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV1",
TotalRewards: 10,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "BNB500",
AddTokenAddress: "0xe204c4c21c6ed90e37cb06cb94436614f3208d58",
AddTokenDecimals: 18,
},
RightShowToken: {
AddTokenSymbol: "hAUTO",
AddTokenAddress: "0xfeF73F4eeE23E78Ee14b6D2B6108359E8fbe6112",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "CTKBNB500",
PoolName: "<i>BNB500</i> Pool",
PoolDesc: "By hCTK-Helmet LPT",
StakeSymbol: "hCTK-Helmet LPT",
RewardSymbol: "BNB500",
OneLpSymbol: "hCTK",
StartTime: "2021/02/22 00:00 UTC+8",
FinishTime: "2021/02/29 00:00 UTC+8",
PoolAddress: "0x6F131e8e5a93ac3Ae71FDdbbE1122cB69AF9Fc71",
StakeAddress: "0x9a6fCD063cA5a9bB31b9f8eE86eCB6476b981280",
RewardAddress: "0xe204c4c21c6ed90e37cb06cb94436614f3208d58",
OneLpAddress: "0x936909e72951A19a5e1d75A109B0D34f06f39838",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV1",
TotalRewards: 1000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "hCTK",
AddTokenAddress: "0x936909e72951A19a5e1d75A109B0D34f06f39838",
AddTokenDecimals: 6,
},
RightShowToken: {
AddTokenSymbol: "BNB500",
AddTokenAddress: "0xe204c4c21c6ed90e37cb06cb94436614f3208d58",
AddTokenDecimals: 18,
},
APR: "--",
},
{
Key: "HCCTCTK",
PoolName: "<i>hCTK</i> Pool",
PoolDesc: "By HCCT-Helmet LPT",
StakeSymbol: "HCCT-Helmet LPT",
RewardSymbol: "hCTK",
OneLpSymbol: "HCCT",
StartTime: "2021/02/21 00:00 UTC+8",
FinishTime: "2021/02/28 00:00 UTC+8",
PoolAddress: "0xaF0e8747FA54b3E000FF1a0F87AF2DB4F1B7Fd87",
StakeAddress: "0xcBbD24DBbF6a487370211bb8B58C3b43C4C32b9E",
RewardAddress: "0x936909e72951A19a5e1d75A109B0D34f06f39838",
OneLpAddress: "0xf1be411556e638790dcdecd5b0f8f6d778f2dfd5",
StakeDecimals: 18,
RewardDecimals: 6,
SwapType: "PANCAKEV1",
TotalRewards: 70000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "HCCT",
AddTokenAddress: "0xf1be411556e638790dcdecd5b0f8f6d778f2dfd5",
AddTokenDecimals: 18,
},
RightShowToken: {
AddTokenSymbol: "hCTK",
AddTokenAddress: "0x936909e72951A19a5e1d75A109B0D34f06f39838",
AddTokenDecimals: 6,
},
APR: "--",
},
{
Key: "LONGHCCT",
PoolName: "<i>HCCT</i> Pool",
PoolDesc: "By LONG-Helmet LPT",
StakeSymbol: "LONG-Helmet LPT",
RewardSymbol: "HCCT",
OneLpSymbol: "LONG",
StartTime: "2021/02/06 00:00 UTC+8",
FinishTime: "2021/02/13 00:00 UTC+8",
PoolAddress: "0xB6ED9f3dCA5CeaaB25F24a377Ed2e47Ecb7dCA5D",
StakeAddress: "0x2ec7FC5A00d4E785821fc8D195291c970d79F0bF",
RewardAddress: "0xf1be411556e638790dcdecd5b0f8f6d778f2dfd5",
OneLpAddress: "0x17934fef9fc93128858e9945261524ab0581612e",
StakeDecimals: 18,
RewardDecimals: 18,
SwapType: "PANCAKEV1",
TotalRewards: 16000,
PoolProcess: 7,
LeftShowToken: {
AddTokenSymbol: "LONG",
AddTokenAddress: "0x17934fef9fc93128858e9945261524ab0581612e",
AddTokenDecimals: 18,
},
RightShowToken: {
AddTokenSymbol: "HCCT",
AddTokenAddress: "0xf1be411556e638790dcdecd5b0f8f6d778f2dfd5",
AddTokenDecimals: 18,
},
APR: "--",
},
];
// Pool Status
// 1 unopen
// 2 ongoing
// 3 expired
export const formatMiningPool = (PoolData) => {
for (let Key = 0; Key < PoolData.length; Key++) {
const ItemPool = PoolData[Key];
const { StartTime, FinishTime } = ItemPool;
const PresentTime = Date.now();
const FixStartTime = new Date(StartTime) * 1;
const FixFinishTime = new Date(FinishTime) * 1;
const PoolStarted = PresentTime > FixStartTime ? true : false;
const PoolFinished = PresentTime > FixFinishTime ? true : false;
if (!PoolStarted) {
ItemPool.Status = 1;
ItemPool.ShowTime = getShowTime(FixStartTime);
}
if (PoolStarted & !PoolFinished) {
ItemPool.Status = 2;
ItemPool.ShowTime = getShowTime(FixFinishTime);
ItemPool.APR = getPoolAPR(ItemPool);
}
if (PoolFinished) {
ItemPool.Status = 3;
ItemPool.ShowTime = "Finished";
}
}
return PoolData;
};
const getShowTime = (time) => {
const now = new Date() * 1;
const dueDate = time;
const DonwTime = dueDate - now;
const day = Math.floor(DonwTime / (24 * 3600000));
const hour = Math.floor((DonwTime - day * 24 * 3600000) / 3600000);
const minute = Math.floor(
(DonwTime - day * 24 * 3600000 - hour * 3600000) / 60000
);
const FixDay = day > 9 ? day : "0" + day;
const FixHour = hour > 9 ? hour : "0" + hour;
const FixMinute = minute > 9 ? minute : "0" + minute;
let template;
if (Number(FixDay) > 0) {
template = `${FixDay}<b>${window.$nuxt.$t(
"Content.DayM"
)}</b><i>/</i>${FixHour}<b>${window.$nuxt.$t("Content.HourM")}</b>`;
} else {
template = `${FixHour}<b>${window.$nuxt.$t(
"Content.HourM"
)}</b><i>/</i>${FixMinute}<b>${window.$nuxt.$t("Content.MinM")}</b>`;
}
return template;
};
const getPoolAPR = async (PoolData) => {
const RewardAddress = PoolData.RewardAddress;
const StakeAddress = PoolData.StakeAddress;
const PoolAddress = PoolData.PoolAddress;
const RewardDecimals = PoolData.RewardDecimals;
const PoolProcess = PoolData.PoolProcess;
const StakeDecimals = PoolData.StakeDecimals;
const TotalRewards = PoolData.TotalRewards;
const HelmetAddress = "0x948d2a81086A075b3130BAc19e4c6DEe1D2E3fE8";
const HelmetDecimals = 18;
const Amount = toWei("1", RewardDecimals);
const Data = await getTokenPrice({
fromTokenAddress: RewardAddress,
toTokenAddress: HelmetAddress,
amount: Amount,
});
if (Data) {
const RewardHelmetPrice = fromWei(Data.data.toTokenAmount);
const PoolContracts = new Contract(PoolAddress, MiningABI);
const StakeContracts = new Contract(StakeAddress, MiningABI);
const HelmetContracts = new Contract(HelmetAddress, MiningABI);
const PromiseList = [
PoolContracts.totalSupply(),
StakeContracts.totalSupply(),
HelmetContracts.balanceOf(StakeAddress),
];
const MulticallProvider = getOnlyMultiCallProvider();
return MulticallProvider.all(PromiseList).then((res) => {
const FixData = processResult(res);
let [TotalStakeVolume, TotalLptVolume, LptHelmetValue] = FixData;
const FixTotalStakeVolume = fromWei(TotalStakeVolume, 18);
const FixTotalLptVolume = fromWei(TotalLptVolume, StakeDecimals);
const FixLptHelmetValue = fromWei(LptHelmetValue, HelmetDecimals);
const Numerator = RewardHelmetPrice * (TotalRewards / PoolProcess) * 365;
const Denominator =
((FixLptHelmetValue * 2) / FixTotalLptVolume) * FixTotalStakeVolume;
const APR = fixD((Numerator / Denominator) * 100, 2);
return (PoolData.APR = APR + "%" || "--");
});
} else {
return "--";
}
};
| 33.360721 | 79 | 0.684207 |
469fde0145c81bd615c163d2ce8e990aa374a2aa | 1,453 | js | JavaScript | src/routes/url.js | Lo-Agency/mojtaba-url-shortener-api | 4333398a3857201fe3a13702d5d24af74eb3c323 | [
"MIT"
] | null | null | null | src/routes/url.js | Lo-Agency/mojtaba-url-shortener-api | 4333398a3857201fe3a13702d5d24af74eb3c323 | [
"MIT"
] | null | null | null | src/routes/url.js | Lo-Agency/mojtaba-url-shortener-api | 4333398a3857201fe3a13702d5d24af74eb3c323 | [
"MIT"
] | null | null | null | const dotenv = require('dotenv'),
{ Logger } = require('@lo-agency/logger'),
validUrl = require('valid-url'),
express = require('express'),
router = express.Router(),
{ getData, insertData } = require('../database/queryBuilder'),
helper = require('../utils/helper')
;
dotenv.config();
const TABLE_NAME = 'urls';
router.post('/shorten', (req, res) => {
const { longUrl } = req.body;
// check long url
if (!validUrl.isUri(longUrl)) {
Logger.warn('Invalid longUrl');
res.status(401).json({ message: 'Invalid longUrl' });
return;
}
// API base url endpoint
const baseUrl = req.protocol + '://' + req.hostname;
//check base url
if (!validUrl.isUri(baseUrl)) {
res.status(401).json({ message: 'Invalid base URL' });
return;
}
//create unique url code
const urlCode = helper.generateID((Math.random() * 1000000000000).toFixed(0));
try {
let url = getData(TABLE_NAME, 'longUrl', longUrl);
if (url.length === 0) {
const shortUrl = `${baseUrl}/${urlCode}`;
const newRecord = {
urlCode,
shortUrl,
longUrl,
createdAt: new Date().toString()
};
res
.status(201)
.json(
getData(
TABLE_NAME,
'id',
insertData(TABLE_NAME, newRecord, Object.keys(newRecord))
.lastInsertRowid
)
);
return;
}
res.status(200).json(url);
} catch (err) {
Logger.error(err.message);
res.status(500).json({ message: 'Server Error' });
}
});
module.exports = router; | 22.015152 | 79 | 0.624226 |
469fef7fb3a29fd55a27f55118d0e07786e9d2d9 | 758 | js | JavaScript | @commitlint/ensure/src/max-line-length.test.js | zbanalagay/commitlint | 7a7562630a33e1cd167243f13d60acd134ba691c | [
"MIT"
] | null | null | null | @commitlint/ensure/src/max-line-length.test.js | zbanalagay/commitlint | 7a7562630a33e1cd167243f13d60acd134ba691c | [
"MIT"
] | null | null | null | @commitlint/ensure/src/max-line-length.test.js | zbanalagay/commitlint | 7a7562630a33e1cd167243f13d60acd134ba691c | [
"MIT"
] | null | null | null | import test from 'ava';
import ensure from './max-line-length';
test('false for no params', t => {
const actual = ensure();
t.is(actual, false);
});
test('true for a against 1', t => {
const actual = ensure('a', 1);
t.is(actual, true);
});
test('false for ab against 0', t => {
const actual = ensure('a', 0);
t.is(actual, false);
});
test('true for a against 2', t => {
const actual = ensure('a', 2);
t.is(actual, true);
});
test('true for ab against 2', t => {
const actual = ensure('ab', 2);
t.is(actual, true);
});
test('false for ab/\nab/\nab 1', t => {
const actual = ensure(
`ab
ab
ab`,
2
);
t.is(actual, true);
});
test('true for ab/\nab/\nab 2', t => {
const actual = ensure(
`ab
ab
ab`,
2
);
t.is(actual, true);
});
| 15.16 | 39 | 0.569921 |
46a0cfd946fa8001f66bed3c1b38f3df4e869f3c | 2,045 | js | JavaScript | webpack/base.js | SHUAXINDIARY/react-nice-avatar | a2510b59a8ca878d512df5b80cd2ad21b5a613a8 | [
"MIT"
] | 467 | 2021-05-30T13:32:09.000Z | 2021-08-08T12:58:09.000Z | webpack/base.js | SHUAXINDIARY/react-nice-avatar | a2510b59a8ca878d512df5b80cd2ad21b5a613a8 | [
"MIT"
] | 18 | 2021-06-02T16:44:22.000Z | 2021-06-28T13:53:51.000Z | webpack/base.js | SHUAXINDIARY/react-nice-avatar | a2510b59a8ca878d512df5b80cd2ad21b5a613a8 | [
"MIT"
] | 38 | 2021-06-02T11:09:18.000Z | 2021-08-06T17:55:25.000Z | const path = require("path");
const autoprefixer = require("autoprefixer");
const tailwindcss = require("tailwindcss");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
context: path.resolve(__dirname, ".."),
resolve: {
modules: [
path.resolve(__dirname, ".."),
path.resolve(__dirname, "../node_modules")
],
extensions: [".tsx", ".ts", ".js"]
},
stats: {
colors: true,
reasons: true,
hash: false,
version: false,
timings: true,
chunks: true,
chunkModules: true,
cached: false,
cachedAssets: false
},
module: {
rules: [
{
test: /\.(j|t)s(x)?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
'@babel/preset-env',
{ targets: { browsers: 'last 2 versions' } },
],
'@babel/preset-typescript',
'@babel/preset-react',
],
plugins: [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-private-methods",
"@babel/plugin-syntax-async-generators",
"@babel/plugin-transform-regenerator",
'react-hot-loader/babel',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[tailwindcss, autoprefixer]
]
}
}
},
"sass-loader"
]
},
{
test: /\.(png|jpg|gif|eot|ttf|woff|woff2|svg)$/,
loader: "file-loader",
options: {
name: "[name].[ext]",
limit: 10000
}
}
]
}
};
| 24.345238 | 64 | 0.458191 |
46a11ffe45cca45f3f261d22bbf89a4c34a8d3f1 | 6,684 | js | JavaScript | index.test.js | luzzif/express-fs | 960e35428ad108f4b86667239ed62f6d93567b63 | [
"MIT"
] | 3 | 2018-12-03T10:48:01.000Z | 2018-12-05T18:35:02.000Z | index.test.js | luzzif/express-fs | 960e35428ad108f4b86667239ed62f6d93567b63 | [
"MIT"
] | 13 | 2019-03-26T18:08:32.000Z | 2019-10-14T12:15:58.000Z | index.test.js | luzzif/express-fs | 960e35428ad108f4b86667239ed62f6d93567b63 | [
"MIT"
] | null | null | null | const { expect } = require("chai");
const glob = require("glob");
const express = require("express");
const {
fsRouter,
getRouteFromFsPath,
getMethodAndPath,
getSanitizedFsPath
} = require(".");
const path = require("path");
const os = require("os");
const { createTree, destroyTree } = require("create-fs-tree");
const sinon = require("sinon");
const proxyquire = require("proxyquire");
const clearModule = require("clear-module");
const handler = () => "handler";
const middleware = () => "middleware";
describe("setup routes", () => {
describe("get sanitized fs path", () => {
it("should return an empty string if a falsy value is given", () => {
expect(getSanitizedFsPath()).to.equal("");
expect(getSanitizedFsPath(null)).to.equal("");
expect(getSanitizedFsPath("")).to.equal("");
});
it("should drop any unneeded prefix", () => {
expect(getSanitizedFsPath(`${__dirname}/api`, __dirname)).to.equal(
"/api"
);
});
it("should drop the 'js' extension, if present", () => {
expect(
getSanitizedFsPath(`${__dirname}/api/get.js`, __dirname)
).to.equal("/api/get");
});
it("should drop the 'index.js', if present", () => {
expect(
getSanitizedFsPath(`${__dirname}/api/get/index.js`, __dirname)
).to.equal("/api/get");
});
it("should drop any leading slash, if present", () => {
expect(getSanitizedFsPath(`${__dirname}/`, __dirname)).to.equal("");
});
});
describe("get route from fs path", () => {
let tmpDir;
afterEach(() => {
clearModule.all();
destroyTree(tmpDir);
});
it("should evaluate a path that directly represents a method", () => {
tmpDir = "./get";
createTree(tmpDir, {
"index.js": `exports.handler = ${handler}; exports.middleware = ${middleware}`
});
const route = getRouteFromFsPath(tmpDir, __dirname);
expect(route.method).to.equal("get");
expect(route.path).to.equal("/");
expect(route.handler()).to.equal("handler");
expect(route.middleware()).to.equal("middleware");
});
it("should evaluate a path that represents an actual route", () => {
tmpDir = `./api`;
createTree(tmpDir, {
get: {
"index.js": `exports.handler = ${handler}; exports.middleware = ${middleware}`
}
});
const route = getRouteFromFsPath(`${tmpDir}/get`, __dirname);
expect(route.method).to.equal("get");
expect(route.path).to.equal("api");
expect(route.handler()).to.equal("handler");
expect(route.middleware()).to.equal("middleware");
});
});
describe("get method and path", () => {
it("should correcly evaluate a direct method", () => {
expect(getMethodAndPath("get")).to.deep.equal({
method: "get",
path: "/"
});
});
it("should correcly evaluate an actual path and method", () => {
expect(getMethodAndPath("api/get")).to.deep.equal({
method: "get",
path: "api"
});
});
});
describe("setup routes", () => {
let tmpDir;
const sandbox = sinon.createSandbox();
const get = sandbox.spy();
const Router = sandbox.spy(() => ({ get }));
const expressFs = proxyquire(".", { express: { Router } });
afterEach(() => {
sandbox.reset();
clearModule.all();
destroyTree(tmpDir);
});
it("should setup a correctly-provided route", () => {
tmpDir = "get";
createTree(tmpDir, {
"index.js": `exports.handler = ${handler}; exports.middleware = ${middleware};`
});
expressFs.fsRouter(__dirname, `${tmpDir}/**/*.js`);
expect(get.callCount).to.equal(1);
const call = get.getCall(0);
expect(call.args).to.have.length(3);
expect(call.args[0]).to.equal("/");
expect(call.args[1]()).to.equal("middleware");
expect(call.args[2]()).to.equal("handler");
});
it("should fail if an invalid method is specified", () => {
tmpDir = "foo";
createTree(tmpDir, {
"index.js": `exports.handler = ${handler}; exports.middleware = ${middleware};`
});
expect(
fsRouter.bind(null, __dirname, `${tmpDir}/**/*.js`)
).to.throw("invalid method foo for route /");
});
it("should fail if no handler method is specified", () => {
tmpDir = "get";
createTree(tmpDir, {
"index.js": `exports.middleware = ${middleware};`
});
expect(
fsRouter.bind(null, __dirname, `${tmpDir}/**/*.js`)
).to.throw("undefined handler for route get@/");
});
it("should provide an empty middleware if none is specified", () => {
tmpDir = "get";
createTree(tmpDir, {
"index.js": `exports.handler = ${handler};`
});
expressFs.fsRouter(__dirname, `${tmpDir}/**/*.js`);
expect(get.callCount).to.equal(1);
const call = get.getCall(0);
expect(call.args).to.have.length(3);
expect(call.args[0]).to.equal("/");
expect(call.args[1]).to.deep.equal([]);
expect(call.args[2]()).to.equal("handler");
});
it("should be verbose if specified", () => {
tmpDir = "get";
createTree(tmpDir, {
"index.js": `exports.handler = ${handler};`
});
const spy = sandbox.spy(console, "log");
fsRouter(__dirname, `${tmpDir}/**/*.js`, { verbose: true });
expect(spy.callCount).to.equal(1);
const call = spy.getCall(0);
expect(call.args).to.have.length(1);
expect(call.args[0]).to.equal(`setup route get@/`);
});
it("should fail when a falsy glob is passed", () => {
expect(fsRouter).to.throw();
});
it("should return a use-chainable function when a truthy glob is passed", () => {
expect(expressFs.fsRouter(__dirname, "foo/bar")).to.deep.equal(
Router()
);
});
});
});
| 35.553191 | 98 | 0.500898 |
46a207bf6af02a349be4e6cf94a01f92f03fa26a | 1,147 | js | JavaScript | src/app.js | 4N1S/btcpayjs | 162c2cbbbaa595b01e47f5bc819fc050c3f000d1 | [
"MIT"
] | null | null | null | src/app.js | 4N1S/btcpayjs | 162c2cbbbaa595b01e47f5bc819fc050c3f000d1 | [
"MIT"
] | null | null | null | src/app.js | 4N1S/btcpayjs | 162c2cbbbaa595b01e47f5bc819fc050c3f000d1 | [
"MIT"
] | null | null | null | import './scss/main.scss';
import btcpay from 'btcpay';
// Aae3kBiFjfHYiMfvh6yFC4drw2i6HjzMT9WRUTHSe2nY
//Ir7WiIEPpDpZYbOUR7QrP07kLi10HRilYWLdobMGhdk
// const keypair = btcpay.crypto.load_keypair(new Buffer.from("Aae3kBiFjfHYiMfvh6yFC4drw2i6HjzMT9WRUTHSe2nY", 'hex'))
// const client = new btcpay.BTCPayClient("https://mainnet.demo.btcpayserver.org/apps/2G7Z7TFyozudWHjdqpWXeS5TfqW8/pos", keypair)
// alert(keypair);
// console.log(keypair);
// // Pair client to server
// client
// .pair_client("wGyfWXF")
// .then(res => console.log(res))
// .catch(err => console.log(err))
const keypair = btcpay.crypto.load_keypair(new Buffer.from("Aae3kBiFjfHYiMfvh6yFC4drw2i6HjzMT9WRUTHSe2nY", 'hex'))
// Recreate client
const client = new btcpay.BTCPayClient("https://mainnet.demo.btcpayserver.org", keypair, {merchant:"merchant"})
console.log(client);
client.get_rates('BTC_USD', "Aae3kBiFjfHYiMfvh6yFC4drw2i6HjzMT9WRUTHSe2nY")
.then(rates => console.log(rates))
.catch(err => console.log(err))
// client.create_invoice({price: 20, currency: 'USD'})
// .then(invoice => console.log(invoice.url))
// .catch(err => console.log(err)) | 32.771429 | 129 | 0.743679 |
46a210ca848e97591a82dcd2ac21a30f2062d65b | 1,075 | js | JavaScript | src/components/LinkButton.js | Webcoda/parkline | 4bde514412828fb8fff3806cc16b0eff5c0c949b | [
"MIT"
] | null | null | null | src/components/LinkButton.js | Webcoda/parkline | 4bde514412828fb8fff3806cc16b0eff5c0c949b | [
"MIT"
] | null | null | null | src/components/LinkButton.js | Webcoda/parkline | 4bde514412828fb8fff3806cc16b0eff5c0c949b | [
"MIT"
] | null | null | null | import React from 'react'
import Link from '@/components/Link'
import './LinkButton.scss'
const LinkButtonInner = ({ children }) => (
<>
{children}
<div
className="absolute inset-0 flex flex-col translate-y-full group-hocus:translate-y-0 transition duration-500 overflow-hidden"
aria-hidden="true"
>
<div
className={`flex-1 py-3 px-7 -translate-y-full group-hocus:translate-y-0 transition duration-500 bg-black text-yellow`}
>
{children}
</div>
</div>
</>
)
const LinkButton = ({
className='',
children,
to,
target,
tag,
...props
}) => {
let _className = `relative overflow-hidden inline-block py-3 px-7 bg-yellow uppercase text-center text-inherit hocus:no-underline transition duration-300 group c-linkbutton ${className}`
const Component = tag;
return tag ? (
<Component {...props} className={_className}>
<LinkButtonInner>{children}</LinkButtonInner>
</Component>
) : (
<Link to={to} target={target} className={_className}>
<LinkButtonInner>{children}</LinkButtonInner>
</Link>
)
}
export default LinkButton;
| 24.431818 | 187 | 0.693023 |
46a25e8c2413b8032b6b1560b0be097112ad1811 | 55 | js | JavaScript | 2/c/1f558.js | moqada/rn-twemoji | c49ce5e83627fa86bdabff9ba15edb157f88c07a | [
"MIT"
] | 8 | 2017-03-15T04:27:47.000Z | 2018-12-03T11:15:23.000Z | 2/n/clock9.js | moqada/rn-twemoji | c49ce5e83627fa86bdabff9ba15edb157f88c07a | [
"MIT"
] | 5 | 2017-06-02T06:29:43.000Z | 2020-04-03T17:48:51.000Z | 2/n/clock9.js | moqada/rn-twemoji | c49ce5e83627fa86bdabff9ba15edb157f88c07a | [
"MIT"
] | null | null | null |
module.exports = require('../../images/2/1f558.png');
| 18.333333 | 53 | 0.636364 |
46a2a3eef4c4d65ac39082045d8adaa5c60a4f07 | 2,237 | js | JavaScript | src/config/index.js | masonwoodford/restqa | c1172414db74330fcecf32d769a190cec5ef8973 | [
"MIT"
] | 45 | 2020-06-20T03:00:32.000Z | 2022-03-17T07:35:08.000Z | src/config/index.js | masonwoodford/restqa | c1172414db74330fcecf32d769a190cec5ef8973 | [
"MIT"
] | 84 | 2020-04-30T02:00:56.000Z | 2022-02-27T23:36:43.000Z | src/config/index.js | masonwoodford/restqa | c1172414db74330fcecf32d769a190cec5ef8973 | [
"MIT"
] | 7 | 2021-06-04T16:13:17.000Z | 2021-12-06T22:39:16.000Z | const fs = require("fs");
const Path = require("path");
const YAML = require("yaml");
const Schema = require("./schema");
function Config({env, configFile}) {
if (!fs.existsSync(configFile)) {
throw new Error(`THE RESTQA CONFIG FILE IS MISSING (${configFile})`);
}
const envVar = {
identify: (value) => value instanceof RegExp,
tag: "!env-var",
resolve(doc, node) {
const {strValue} = node;
return (
process.env[strValue] ||
`${strValue} not found in the environment variable`
);
}
};
const file = fs.readFileSync(configFile, "utf8");
const config = YAML.parse(file, {customTags: [envVar]});
const envs = config.environments.map((env) => env.name);
if (!env) {
env = (config.environments.find((e) => e.default) || {}).name;
}
if (!env && envs.length === 1) {
env = envs[0];
}
env = String(env).toLowerCase();
if (!env || !envs.map((_) => _.toLowerCase()).includes(env)) {
throw new Error(
`THE ENVIRONMENT NEEDS TO BE DEFINED AS (${envs.join(" | ")})`
);
}
config.environment = config.environments.find(
(e) => env === e.name.toLowerCase()
);
delete config.environments;
return Schema.validate(config);
}
Config.locate = function (options) {
let {configFile, path} = options || {};
let fileName = ".restqa.yml";
let filePath = Path.join(process.cwd(), fileName);
let parsed;
if (configFile) {
parsed = Path.parse(configFile);
if (!parsed.dir) {
parsed.dir = process.cwd();
parsed.root = "/";
}
filePath = Path.format(parsed);
}
if (path) {
path = Path.resolve(path);
const isFolder = fs.lstatSync(path).isDirectory();
if (!isFolder) {
throw new ReferenceError(`The path "${path}" is not a folder`);
}
if (configFile && parsed) {
fileName = parsed.base;
}
filePath = Path.join(path, fileName);
}
if (!fs.existsSync(filePath)) {
throw new ReferenceError(
`The configuration file "${filePath}" doesn't exist."`
);
}
return filePath;
};
Config.raw = function (options) {
const {configFile} = options || {};
return YAML.parse(fs.readFileSync(configFile).toString("utf-8"));
};
module.exports = Config;
| 24.053763 | 73 | 0.603487 |
46a30edbc6f085d14da9a94d255acea93c8b723d | 1,320 | js | JavaScript | src/util/getTotp.js | jaskaran-cloud/otp-cli | 5c7a40a7d40d9cf6a03bd9e7ade95b112b9bd8b8 | [
"MIT"
] | 1 | 2019-03-05T18:54:45.000Z | 2019-03-05T18:54:45.000Z | src/util/getTotp.js | jaskaran-cloud/otp-cli | 5c7a40a7d40d9cf6a03bd9e7ade95b112b9bd8b8 | [
"MIT"
] | null | null | null | src/util/getTotp.js | jaskaran-cloud/otp-cli | 5c7a40a7d40d9cf6a03bd9e7ade95b112b9bd8b8 | [
"MIT"
] | null | null | null |
/* global jsSHA, module, require */
var jsSHA = require('./sha');
function dec2hex(s) {
return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
}
function hex2dec(s) {
return parseInt(s, 16);
}
function base32tohex(base32) {
var base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
var bits = '';
var hex = '';
for (var i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, '0');
}
for (var j = 0; j + 4 <= bits.length; j += 4) {
var chunk = bits.substr(j, 4);
hex = hex + parseInt(chunk, 2).toString(16);
}
return hex;
}
function leftpad(str, len, pad) {
if (len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
}
module.exports = function getOtp(mfaSecret) {
var key = base32tohex(mfaSecret);
var epoch = Math.round(new Date().getTime() / 1000.0);
var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
var shaObj = new jsSHA('SHA-1', 'HEX');
shaObj.setHMACKey(key, 'HEX');
shaObj.update(time);
var hmac = shaObj.getHMAC('HEX');
var offset = hex2dec(hmac.substring(hmac.length - 1));
var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
otp = (otp).substr(otp.length - 6, 6);
return otp;
};
| 24.444444 | 77 | 0.607576 |
46a353514a74243d681075a23700f7114e300876 | 2,033 | js | JavaScript | screens/RatingPage.js | yyalexyy/SpotSearch | ee88ef71089398fa75c733c8b0e2dd39236bec39 | [
"CC0-1.0"
] | 1 | 2020-11-24T20:15:07.000Z | 2020-11-24T20:15:07.000Z | screens/RatingPage.js | yyalexyy/SpotSearch | ee88ef71089398fa75c733c8b0e2dd39236bec39 | [
"CC0-1.0"
] | null | null | null | screens/RatingPage.js | yyalexyy/SpotSearch | ee88ef71089398fa75c733c8b0e2dd39236bec39 | [
"CC0-1.0"
] | 1 | 2020-06-12T00:21:07.000Z | 2020-06-12T00:21:07.000Z | import 'react-native-gesture-handler';
import * as React from 'react';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'; // import safe areas to display on screen
import { ScrollView, Button, Image, StyleSheet, Text, TouchableOpacity, View, Animated, Alert } from 'react-native';
//import logo from './assets/logo.png'; //import logo
import { NavigationContainer, DrawerActions } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItemList,
DrawerItem,
} from '@react-navigation/drawer';
/**
* Rating Screen
* @param {*} param0
*/
export const RatingPage = ({ navigation }) => {
return (
<SafeAreaView backgroundColor = '#116466'>
<View style = {styles.topBox}>
<Text style={styles.textColor1}>Any rating preference?</Text>
</View>
<View style={styles.leftBox}>
<Button
color='#9957B8'
title="5 star"
onPress={() => navigation.push('ResultPage')}/>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
textColor1: {
marginLeft: 30,
marginRight: 30,
color: '#9957B8',
fontSize: 25,
alignItems: "center",
textAlign: 'center',
justifyContent: 'center',
marginBottom: 20,
marginTop: 20,
},
leftBox: {
marginTop: 40,
backgroundColor: 'white',
marginLeft: 8,
borderRadius: 10,
width: 145,
height: 143,
},
rightBox: {
marginTop: 40,
backgroundColor: 'white',
marginRight: 8,
borderRadius: 10,
width: 145,
height: 143,
},
topBox: {
marginTop: 10,
backgroundColor: 'white',
borderRadius: 20,
marginLeft: 20,
marginRight: 20,
height: 154,
justifyContent: 'center',
alignItems: 'center',
}
}); | 25.4125 | 123 | 0.585834 |
46a36b6821b1950ce692a32b142cf4a3112b9f07 | 655 | js | JavaScript | day-9/solution.js | larsgw/advent-of-code-2018 | d2bcd3a668718eafc5f610b850a8e541dd75fc35 | [
"MIT"
] | null | null | null | day-9/solution.js | larsgw/advent-of-code-2018 | d2bcd3a668718eafc5f610b850a8e541dd75fc35 | [
"MIT"
] | null | null | null | day-9/solution.js | larsgw/advent-of-code-2018 | d2bcd3a668718eafc5f610b850a8e541dd75fc35 | [
"MIT"
] | null | null | null | const [players, lastMarble] = $0.textContent.match(/\d+/g).map(num => parseInt(num))
function maxScore (players, lastMarble) {
let turn = 0
let marble = 0
let current = 0
let scores = Array(players).fill(0)
let circle = [0]
while (++marble <= lastMarble) {
turn = (turn + 1) % players
if (marble % 23 === 0) {
scores[turn] += marble
current = (current - 7) % circle.length
scores[turn] += circle.splice(current, 1)[0]
} else {
current = (current + 2) % circle.length
circle.splice(current, 0, marble)
}
}
return Math.max(...scores)
}
console.log('star 1:', maxScore(players, lastMarble))
| 24.259259 | 84 | 0.601527 |
46a3b42bda0fd03e1983e2d44f04a642bc7fe13d | 392 | js | JavaScript | src/conf/ListSettings.js | Thirosue/sample-vuejs-front | 19eb0d4d85776714b4f35be8502e3016d9d15829 | [
"MIT"
] | 4 | 2019-03-11T00:54:15.000Z | 2019-07-05T15:58:35.000Z | src/conf/ListSettings.js | Thirosue/sample-vuejs-front | 19eb0d4d85776714b4f35be8502e3016d9d15829 | [
"MIT"
] | 15 | 2018-08-17T09:29:30.000Z | 2022-02-17T20:16:55.000Z | src/conf/ListSettings.js | Thirosue/sample-vuejs-front | 19eb0d4d85776714b4f35be8502e3016d9d15829 | [
"MIT"
] | 3 | 2019-03-09T07:28:22.000Z | 2019-10-01T02:30:07.000Z | const StaffListSettings = [
{
key: 'id', value: 'ID', order: 1, sort: false,
},
{
key: 'firstName', value: '名前', order: 2, sort: true,
},
{
key: 'lastName', value: '苗字', order: 3, sort: false,
},
{
key: 'email', value: 'Email', order: 4, sort: true,
},
{
key: 'tel', value: 'Tel', order: 5, sort: false,
},
];
export default {
StaffListSettings,
};
| 17.818182 | 56 | 0.52551 |
46a47539afbe75d64c0c70dbe9ec7ab403c7235e | 2,107 | js | JavaScript | src/pages/Settings/SettingsEmailPassword/EmailForm.js | walaaayyad/mappypals | 5ad228505b62e21f4e0566b822be3d974b5544f3 | [
"MIT"
] | 69 | 2019-02-19T20:56:31.000Z | 2022-02-15T15:14:15.000Z | src/pages/Settings/SettingsEmailPassword/EmailForm.js | walaaayyad/mappypals | 5ad228505b62e21f4e0566b822be3d974b5544f3 | [
"MIT"
] | 116 | 2019-02-19T07:43:59.000Z | 2020-06-07T02:40:53.000Z | src/pages/Settings/SettingsEmailPassword/EmailForm.js | walaaayyad/mappypals | 5ad228505b62e21f4e0566b822be3d974b5544f3 | [
"MIT"
] | 135 | 2019-02-18T12:36:42.000Z | 2021-07-06T14:29:35.000Z | import React, { Component } from 'react';
import './SettingsEmailPassword.css';
import Button from '../../../components/UI/Button/Button';
class EmailForm extends Component {
state = {
// if user sees current email in input box then
// needs to be derived from web token or props
email: 'testemail@gmail.com',
success: null,
error: null
};
onSubmit = event => {
event.preventDefault();
// fetch made here
};
onChange = event => {
this.setState({ email: event.target.value });
};
render() {
const { email, success, error } = this.state;
let errorMessage;
let successMessage;
if (error) {
errorMessage = (
<span className="form__msg form__msg--err" aria-live="polite">
{error}
</span>
);
}
if (success) {
successMessage = (
<span
className="form__msg form__msg--success"
aria-live="polite"
>
{success}
</span>
);
}
return (
<form onSubmit={this.onSubmit} className="form form--settings">
<div className="form__section">
{errorMessage}
{successMessage}
<label className="form__label form__label--settings">
Email
</label>
<input
className="form__input form__input--settings"
type="text"
onChange={this.onChange}
value={email}
name="email"
required
/>
</div>
<div>
<Button btnType="SettingsEmailPassword" type="submit">
Change Email
</Button>
</div>
</form>
);
}
}
export default EmailForm;
| 29.676056 | 78 | 0.438538 |
46a4823a832d930e8cab0473fd214d781262c83f | 958 | js | JavaScript | packages/medusa-source-shopify/src/services/__mocks__/shopify-client.js | omurilo/medusa | c16df9383c08288f3643fde7aadad1becb2e4c9d | [
"MIT"
] | 9,557 | 2020-04-01T10:46:22.000Z | 2022-03-31T23:26:40.000Z | packages/medusa-source-shopify/src/services/__mocks__/shopify-client.js | omurilo/medusa | c16df9383c08288f3643fde7aadad1becb2e4c9d | [
"MIT"
] | 488 | 2020-03-24T14:42:58.000Z | 2022-03-31T14:41:13.000Z | packages/medusa-source-shopify/src/services/__mocks__/shopify-client.js | omurilo/medusa | c16df9383c08288f3643fde7aadad1becb2e4c9d | [
"MIT"
] | 478 | 2021-03-05T23:16:12.000Z | 2022-03-31T17:19:41.000Z | import { shopifyProducts } from "./test-products"
export const ShopifyClientServiceMock = {
get: jest.fn().mockImplementation((params) => {
if (params.path === "products/ipod") {
return Promise.resolve(shopifyProducts.ipod)
}
if (params.path === "products/new_ipod") {
return Promise.resolve(shopifyProducts.new_ipod)
}
if (params.path === "products/shopify_ipod") {
return Promise.resolve({
body: {
product: shopifyProducts.ipod_update,
},
})
}
if (params.path === "products/shopify_deleted") {
return Promise.resolve({
body: {
product: {
...shopifyProducts.ipod,
variants: shopifyProducts.ipod.variants.slice(1, -1),
},
},
})
}
}),
list: jest.fn().mockImplementation((path, _headers, _query) => {
if (path === "products") {
return Promise.resolve([shopifyProducts.ipod])
}
}),
}
| 27.371429 | 66 | 0.578288 |
46a4a892080467191a6652c4b6a252eb5cd72893 | 506 | js | JavaScript | time-table/client/src/components/Footer.js | starkblaze01/Jenereta | 14b48e9c143a013a22070f24fcc3ad2b4f88164b | [
"MIT"
] | 14 | 2019-01-05T17:20:59.000Z | 2021-11-08T13:28:48.000Z | time-table/client/src/components/Footer.js | starkblaze01/Jenereta | 14b48e9c143a013a22070f24fcc3ad2b4f88164b | [
"MIT"
] | 2 | 2019-01-05T17:18:52.000Z | 2019-09-01T21:40:46.000Z | time-table/client/src/components/Footer.js | starkblaze01/Jenereta | 14b48e9c143a013a22070f24fcc3ad2b4f88164b | [
"MIT"
] | 3 | 2019-01-06T15:07:20.000Z | 2019-09-26T21:53:05.000Z | import React from "react";
function Footer() {
return (
<div className="footer">
<div className="container" style={{display: 'flex', justifyContent:'space-between'}}>
<p></p>
<p>Copyright © {new Date().getFullYear()} <a href="https://github.com/starkblaze01/Jenereta#team-members">CS08</a></p>
<p><a href="https://github.com/starkblaze01/Jenereta"><i class="fa fa-star" aria-hidden="true"></i>Star Me</a></p>
</div>
</div>
);
}
export default Footer;
| 31.625 | 131 | 0.618577 |
46a55967a1baa772f3d9c5ca559f2c29432c6b69 | 2,811 | js | JavaScript | src/firstConsistentlyInteractiveCore.js | lizryzhko/tti-polyfill | e898efb93c8c443ab35b58c8492ef6e242e579fe | [
"Apache-2.0"
] | 258 | 2017-09-20T07:04:17.000Z | 2022-03-08T09:18:15.000Z | src/firstConsistentlyInteractiveCore.js | lizryzhko/tti-polyfill | e898efb93c8c443ab35b58c8492ef6e242e579fe | [
"Apache-2.0"
] | 18 | 2018-03-08T15:53:02.000Z | 2021-02-25T20:41:42.000Z | src/firstConsistentlyInteractiveCore.js | lizryzhko/tti-polyfill | e898efb93c8c443ab35b58c8492ef6e242e579fe | [
"Apache-2.0"
] | 60 | 2017-11-12T14:12:13.000Z | 2022-02-14T03:22:43.000Z | // Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Computes the first consistently interactive value...
* @param {number} searchStart
* @param {number} minValue
* @param {number} lastKnownNetwork2Busy
* @param {number} currentTime
* @param {!Array<{start: (number), end: (number)}>} longTasks
* @return {number|null}
*/
export const computeFirstConsistentlyInteractive =
(searchStart, minValue, lastKnownNetwork2Busy, currentTime, longTasks) => {
// Have not reached network 2-quiet yet.
if ((currentTime - lastKnownNetwork2Busy) < 5000) return null;
const maybeFCI = longTasks.length === 0 ?
searchStart : longTasks[longTasks.length - 1].end;
// Main thread has not been quiet for long enough.
if (currentTime - maybeFCI < 5000) return null;
return Math.max(maybeFCI, minValue);
};
/**
* Computes the time (in milliseconds since requestStart) that the network was
* last known to have >2 requests in-flight.
* @param {!Array<number>} incompleteRequestStarts
* @param {!Array<{start: (number), end: (number)}>} observedResourceRequests
* @return {number}
*/
export const computeLastKnownNetwork2Busy =
(incompleteRequestStarts, observedResourceRequests) => {
if (incompleteRequestStarts.length > 2) return performance.now();
const endpoints = [];
for (const req of observedResourceRequests) {
endpoints.push({
timestamp: req.start,
type: 'requestStart',
});
endpoints.push({
timestamp: req.end,
type: 'requestEnd',
});
}
for (const ts of incompleteRequestStarts) {
endpoints.push({
timestamp: ts,
type: 'requestStart',
});
}
endpoints.sort((a, b) => a.timestamp - b.timestamp);
let currentActive = incompleteRequestStarts.length;
for (let i = endpoints.length - 1; i >= 0; i--) {
const endpoint = endpoints[i];
switch (endpoint.type) {
case 'requestStart':
currentActive--;
break;
case 'requestEnd':
currentActive++;
if (currentActive > 2) {
return endpoint.timestamp;
}
break;
default:
throw Error('Internal Error: This should never happen');
}
}
// If we reach here, we were never network 2-busy.
return 0;
};
| 29.904255 | 79 | 0.676272 |
46a5c5ac778994848db86e0d6348892aafca061f | 2,871 | js | JavaScript | gatsby-config.js | loorely/girls-code-cms | dc8d436ab325bbf128d0905fd03ddc76e862c5e6 | [
"MIT"
] | null | null | null | gatsby-config.js | loorely/girls-code-cms | dc8d436ab325bbf128d0905fd03ddc76e862c5e6 | [
"MIT"
] | null | null | null | gatsby-config.js | loorely/girls-code-cms | dc8d436ab325bbf128d0905fd03ddc76e862c5e6 | [
"MIT"
] | 1 | 2020-04-13T20:17:09.000Z | 2020-04-13T20:17:09.000Z | module.exports = {
siteMetadata: {
title: 'Girls Code - Nosotras Creemos Ellas Hacen',
description:
'Girls Code - Nosotras Creemos Ellas Hacen - Buscamos la inclusión digital de mujeres en las áreas de STEAM en todo Paraguay con espacios de aprendizaje en base a nuestros valores',
},
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: "gatsby-plugin-sass",
options: {
data: '@import "variables.sass";',
includePaths: [
'styles',
],
},
},
{
// keep as first gatsby-source-filesystem plugin for gatsby image support
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/static/img`,
name: 'uploads',
},
},
{
resolve: "gatsby-plugin-web-font-loader",
options: {
custom: {
families: ["geomanistregular","Roboto","Geomanist"],
urls: ["/fonts/fonts.css"],
},
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/img`,
name: 'images',
},
},
'gatsby-plugin-sharp',
'gatsby-transformer-sharp',
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
{
resolve: 'gatsby-remark-relative-images',
options: {
name: 'uploads',
},
},
{
resolve: 'gatsby-remark-images',
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 2048,
},
},
{
resolve: 'gatsby-remark-copy-linked-files',
options: {
destinationDir: 'static',
},
},
],
},
},
{
resolve: 'gatsby-plugin-netlify-cms',
options: {
modulePath: `${__dirname}/src/cms/cms.js`,
},
},
{
resolve: 'gatsby-plugin-purgecss', // purges all unused/unreferenced css rules
options: {
develop: true, // Activates purging in npm run develop
purgeOnly: ['/all.sass'], // applies purging only on the bulma css file
},
}, // must be after other CSS plugins
{
resolve: 'gatsby-plugin-eslint',
options: {
test: /\.js$|\.jsx$/,
exclude: /(node_modules|cache|public)/,
stages: ['develop'],
options: {
emitWarning: true,
failOnError: false
}
}
},
'gatsby-plugin-netlify', // make sure to keep it last in the array
],
}
| 26.831776 | 187 | 0.514107 |
46a5d05a9f91dcb5d9f3081b4670d4c5a7ecbb49 | 2,059 | js | JavaScript | implementation-contributed/v8/mjsunit/compiler/mul-div-52bit.js | katemihalikova/test262 | aaf4402b4ca9923012e61830fba588bf7ceb6027 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | implementation-contributed/v8/mjsunit/compiler/mul-div-52bit.js | katemihalikova/test262 | aaf4402b4ca9923012e61830fba588bf7ceb6027 | [
"BSD-3-Clause"
] | 2,157 | 2015-01-06T05:01:55.000Z | 2022-03-31T17:18:08.000Z | implementation-contributed/v8/mjsunit/compiler/mul-div-52bit.js | katemihalikova/test262 | aaf4402b4ca9923012e61830fba588bf7ceb6027 | [
"BSD-3-Clause"
] | 411 | 2015-01-22T01:40:04.000Z | 2022-03-28T19:19:16.000Z | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax
function mul(a, b) {
const l = a & 0x3ffffff;
const h = b & 0x3ffffff;
return (l * h) >>> 0;
}
function mulAndDiv(a, b) {
const l = a & 0x3ffffff;
const h = b & 0x3ffffff;
const m = l * h;
const rl = m & 0x3ffffff;
const rh = (m / 0x4000000) >>> 0;
return rl | rh;
}
function overflowMul(a, b) {
const l = a | 0;
const h = b | 0;
return (l * h) >>> 0;
}
function overflowDiv(a, b) {
const l = a & 0x3ffffff;
const h = b & 0x3ffffff;
const m = l * h;
return (m / 0x10) >>> 0;
}
function nonPowerOfTwoDiv(a, b) {
const l = a & 0x3ffffff;
const h = b & 0x3ffffff;
const m = l * h;
return (m / 0x4000001) >>> 0;
}
function test(fn, a, b, sets) {
const expected = fn(a, b);
fn(1, 2);
fn(0, 0);
%OptimizeFunctionOnNextCall(fn);
const actual = fn(a, b);
assertEquals(expected, actual);
sets.forEach(function(set, i) {
assertEquals(set.expected, fn(set.a, set.b), fn.name + ', set #' + i);
});
}
test(mul, 0x3ffffff, 0x3ffffff, [
{ a: 0, b: 0, expected: 0 },
{ a: 0xdead, b: 0xbeef, expected: 0xa6144983 },
{ a: 0x1aa1dea, b: 0x2badead, expected: 0x35eb2322 }
]);
test(mulAndDiv, 0x3ffffff, 0x3ffffff, [
{ a: 0, b: 0, expected: 0 },
{ a: 0xdead, b: 0xbeef, expected: 0x21449ab },
{ a: 0x1aa1dea, b: 0x2badead, expected: 0x1ebf32f }
]);
test(overflowMul, 0x4ffffff, 0x4ffffff, [
{ a: 0, b: 0, expected: 0 },
{ a: 0xdead, b: 0xbeef, expected: 0xa6144983 },
{ a: 0x1aa1dea, b: 0x2badead, expected: 0x35eb2322 }
]);
test(overflowDiv, 0x3ffffff, 0x3ffffff, [
{ a: 0, b: 0, expected: 0 },
{ a: 0xdead, b: 0xbeef, expected: 0xa614498 },
{ a: 0x1aa1dea, b: 0x2badead, expected: 0x835eb232 }
]);
test(nonPowerOfTwoDiv, 0x3ffffff, 0x3ffffff, [
{ a: 0, b: 0, expected: 0 },
{ a: 0xdead, b: 0xbeef, expected: 0x29 },
{ a: 0x1aa1dea, b: 0x2badead, expected: 0x122d20d }
]);
| 23.666667 | 74 | 0.609034 |
46a68e1503c167e86d60aabbecf9976641646466 | 5,260 | js | JavaScript | src/assets/MVC/Views/NotificationsPage.js | the-goat7/ZAJIL | f1bca9c95a2336ed028c6adc6f9eb6a3e3eb4d39 | [
"MIT"
] | null | null | null | src/assets/MVC/Views/NotificationsPage.js | the-goat7/ZAJIL | f1bca9c95a2336ed028c6adc6f9eb6a3e3eb4d39 | [
"MIT"
] | null | null | null | src/assets/MVC/Views/NotificationsPage.js | the-goat7/ZAJIL | f1bca9c95a2336ed028c6adc6f9eb6a3e3eb4d39 | [
"MIT"
] | null | null | null | import { createIcon, createPageNav } from '../Helpers';
class NotificationsPage {
constructor() {}
generateMarkup() {
const notificationsPage = `
<div class="page page--inner notificationsPage">
<div class="wrapper">
<header class="pageHeader">
<h2>Notifications</h2>
</header>
<nav class="pageNav">${createPageNav()}</nav>
<aside class="pageBio"></aside>
<main class="pageContent">
<div class="pageContent__container">
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
<div class="notification">
<div class="notification__img">
<img src="./images/avatar.png" />
<span></span>
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cupiditate alias ex doloremque saepe laboriosam eos deserunt dolore? Adipisci quisquam animi error corrupti neque, iure ducimus molestiae amet quidem accusantium.</p>
</div>
</div>
</main>
<footer class="pageFooter">
<div class="footer__container">
<div class="footer__container__buttons">
<button class="btn--large btn--yellow"><span>${createIcon('mute')}</span> Mute</button>
<button class="btn--large btn--yellow"><span>${createIcon('delete')}</span> Delete</button>
</div>
</div>
</footer>
</div>
</div>
`;
return notificationsPage;
}
}
export default new NotificationsPage();
| 51.067961 | 245 | 0.576616 |
46a6f33b960e471cf929f004a2a8a2ac7bf00dca | 4,006 | js | JavaScript | test/specs/version-hooks.spec.js | perry-mitchell/version-bump-prompt | 7a4e16d298f9e62b764b4341e45de2c48ce1316d | [
"MIT"
] | null | null | null | test/specs/version-hooks.spec.js | perry-mitchell/version-bump-prompt | 7a4e16d298f9e62b764b4341e45de2c48ce1316d | [
"MIT"
] | null | null | null | test/specs/version-hooks.spec.js | perry-mitchell/version-bump-prompt | 7a4e16d298f9e62b764b4341e45de2c48ce1316d | [
"MIT"
] | 1 | 2019-06-11T04:27:18.000Z | 2019-06-11T04:27:18.000Z | "use strict";
const cli = require("../fixtures/cli");
const mocks = require("../fixtures/mocks");
const files = require("../fixtures/files");
const check = require("../fixtures/check");
const chai = require("chai");
chai.should();
describe("npm version hooks", () => {
if (process.platform === "win32" && process.env.CI) {
// Spawning NPM fails on Windows due to a bug in NYC (actually in its dependency, spawn-wrap)
// So skip these tests until this bug is fixed: https://github.com/istanbuljs/nyc/issues/760
return;
}
it("should run the preversion script before updating the version number", () => {
files.create("package.json", {
version: "1.0.0",
scripts: {
preversion: "echo hello world",
},
});
let output = cli.exec("--major");
output.stderr.should.be.empty;
output.status.should.equal(0);
output.lines.should.deep.equal([
`${check} Updated package.json to 2.0.0`,
]);
let npm = mocks.npm();
npm.length.should.equal(1);
npm[0].cmd.should.equal("npm run preversion");
npm[0].version.should.equal("1.0.0");
});
it("should run the version script after updating the version number", () => {
files.create("package.json", {
version: "1.0.0",
scripts: {
version: "echo hello world",
},
});
let output = cli.exec("--major");
output.stderr.should.be.empty;
output.status.should.equal(0);
output.lines.should.deep.equal([
`${check} Updated package.json to 2.0.0`,
]);
let npm = mocks.npm();
npm.length.should.equal(1);
npm[0].cmd.should.equal("npm run version");
npm[0].version.should.equal("2.0.0");
});
it("should run the postversion script after updating the version number", () => {
files.create("package.json", {
version: "1.0.0",
scripts: {
postversion: "echo hello world",
},
});
let output = cli.exec("--major");
output.stderr.should.be.empty;
output.status.should.equal(0);
output.lines.should.deep.equal([
`${check} Updated package.json to 2.0.0`,
]);
let npm = mocks.npm();
npm.length.should.equal(1);
npm[0].cmd.should.equal("npm run postversion");
npm[0].version.should.equal("2.0.0");
});
it("should run all the version scripts and git commands in the correct order", () => {
files.create("package.json", {
version: "1.0.0",
scripts: {
preversion: "echo hello world",
version: "echo hello world",
postversion: "echo hello world",
},
});
let output = cli.exec("--major --commit --tag --push");
output.stderr.should.be.empty;
output.status.should.equal(0);
output.lines.should.deep.equal([
`${check} Updated package.json to 2.0.0`,
`${check} Git commit`,
`${check} Git tag`,
`${check} Git push`,
]);
let bin = mocks.all();
bin.length.should.equal(7);
// The preversion script runs before anything
bin[0].cmd.should.equal("npm run preversion");
bin[0].version.should.equal("1.0.0");
// The version script runs after the version has been updated,
bin[1].cmd.should.equal("npm run version");
bin[1].version.should.equal("2.0.0");
// Git commit happens after the version has been updated
bin[2].cmd.should.equal('git commit package.json -m "release v2.0.0"');
bin[2].version.should.equal("2.0.0");
// Git tag happens after the version has been updated
bin[3].cmd.should.equal("git tag -a v2.0.0 -m 2.0.0");
bin[3].version.should.equal("2.0.0");
// The postversion script runs AFTER "git commit" and "git tag", but BEFORE "git push"
bin[4].cmd.should.equal("npm run postversion");
bin[4].version.should.equal("2.0.0");
// Git push happens after everything else
bin[5].cmd.should.equal("git push");
bin[5].version.should.equal("2.0.0");
bin[6].cmd.should.equal("git push --tags");
bin[6].version.should.equal("2.0.0");
});
});
| 27.819444 | 97 | 0.608088 |
46a6ff5bc92285ae4f8bc4f10f24080b5c970bf4 | 57 | js | JavaScript | app/web/store/app/getters.js | Raoul1996/vote | 213386c63b615ae542e11c671c50bb3daae82ff1 | [
"MIT"
] | null | null | null | app/web/store/app/getters.js | Raoul1996/vote | 213386c63b615ae542e11c671c50bb3daae82ff1 | [
"MIT"
] | null | null | null | app/web/store/app/getters.js | Raoul1996/vote | 213386c63b615ae542e11c671c50bb3daae82ff1 | [
"MIT"
] | 1 | 2019-10-28T08:27:02.000Z | 2019-10-28T08:27:02.000Z | 'use strict'
const getters = {}
export default getters | 9.5 | 22 | 0.719298 |
46a714eb7f4f17789da83f72ca568b2f1cb55423 | 633 | js | JavaScript | docs/html/search/enumvalues_c.js | jmpcosta/osapi- | ffd864b6d2ba65cc44e3313de57d52adf93d6412 | [
"MIT"
] | 1 | 2019-03-28T20:40:27.000Z | 2019-03-28T20:40:27.000Z | docs/html/search/enumvalues_c.js | jmpcosta/osapi- | ffd864b6d2ba65cc44e3313de57d52adf93d6412 | [
"MIT"
] | null | null | null | docs/html/search/enumvalues_c.js | jmpcosta/osapi- | ffd864b6d2ba65cc44e3313de57d52adf93d6412 | [
"MIT"
] | null | null | null | var searchData=
[
['unavailable',['unavailable',['../namespaceosapi_1_1process.html#a0a40de8e309519bf16123848d67861b5a7060e0481896e00b3f7d20f1e8e2749a',1,'osapi::process']]],
['unknown',['UNKNOWN',['../namespaceosapi_1_1configuration.html#a134872698cf3e553eef57af4751b33aaa696b031073e74bf2cb98e5ef201d4aa3',1,'osapi::configuration::UNKNOWN()'],['../namespaceosapi_1_1filesystem.html#acb27ca3a4fb070737d33d156cc8b5774aad921d60486366258809553a3db49a4a',1,'osapi::filesystem::unknown()']]],
['unsupported',['unsupported',['../signal_8hh.html#a6088e68d9bfe9f8b952ce9b9c681e182a723c25877a86786664edc4b643c08a6f',1,'signal.hh']]]
];
| 90.428571 | 314 | 0.815166 |
46a77ecb602b3e92d46430687575c2de88c93a27 | 822 | js | JavaScript | www/spf.js | kevinchtsang/cordova-plugin-spf | a6696a28d348ddf5e323bfd8763fdbd452518360 | [
"MIT"
] | null | null | null | www/spf.js | kevinchtsang/cordova-plugin-spf | a6696a28d348ddf5e323bfd8763fdbd452518360 | [
"MIT"
] | null | null | null | www/spf.js | kevinchtsang/cordova-plugin-spf | a6696a28d348ddf5e323bfd8763fdbd452518360 | [
"MIT"
] | null | null | null | /*global cordova, module*/
module.exports = {
requestPermissions: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "SPF", "requestPermissions");
},
startCalibration: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "SPF", "SPFstartCalibration");
},
stopCalibration: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "SPF", "stopCalibration");
},
startMeasurement: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "SPF", "startMeasurement");
},
stopMeasurement: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "SPF", "stopMeasurement");
}
};
| 41.1 | 83 | 0.711679 |
46a800db2652ebccd6d36d7b9671997538c657be | 2,918 | js | JavaScript | src/icons/VectorBezier.js | svgbook/react-icons | 4b8c65e614d6993154412f64a631ba4534da80c6 | [
"MIT"
] | null | null | null | src/icons/VectorBezier.js | svgbook/react-icons | 4b8c65e614d6993154412f64a631ba4534da80c6 | [
"MIT"
] | null | null | null | src/icons/VectorBezier.js | svgbook/react-icons | 4b8c65e614d6993154412f64a631ba4534da80c6 | [
"MIT"
] | null | null | null | import React, { forwardRef, Fragment } from "react";
import IconBase from "../primitives/IconBase";
const renderPath = {};
renderPath["outline"] = (color) => (
<Fragment>
<path fill="none" d="M10.8,9.9a3.61,3.61,0,0,0-3,3.3" />
<path fill="none" d="M13.2,9.9a3.61,3.61,0,0,1,3,3.3" />
<line x1="10.8" y1="9.6" x2="7.2" y2="9.6" />
<line x1="16.8" y1="9.6" x2="13.2" y2="9.6" />
<rect fill="none" x="6.6" y="13.2" width="2.4" height="2.4" rx="0.6" />
<rect fill="none" x="15" y="13.2" width="2.4" height="2.4" rx="0.6" />
<rect fill="none" x="10.8" y="8.4" width="2.4" height="2.4" rx="0.6" />
<circle fill="none" cx="6.6" cy="9.6" r="0.6" />
<circle fill="none" cx="17.4" cy="9.6" r="0.6" />
</Fragment>
);
renderPath["fill"] = () => (
<Fragment>
<path fill="none" d="M10.8,9.9a3.61,3.61,0,0,0-3,3.3" />
<path fill="none" d="M13.2,9.9a3.61,3.61,0,0,1,3,3.3" />
<line x1="10.8" y1="9.6" x2="7.2" y2="9.6" />
<line x1="16.8" y1="9.6" x2="13.2" y2="9.6" />
<rect x="6.6" y="13.2" width="2.4" height="2.4" rx="0.6" />
<rect x="15" y="13.2" width="2.4" height="2.4" rx="0.6" />
<rect x="10.8" y="8.4" width="2.4" height="2.4" rx="0.6" />
<circle cx="6.6" cy="9.6" r="0.6" />
<circle cx="17.4" cy="9.6" r="0.6" />
</Fragment>
);
renderPath["duotone"] = (color) => (
<Fragment>
<path fill="none" d="M10.8,9.9a3.61,3.61,0,0,0-3,3.3" />
<path fill="none" d="M13.2,9.9a3.61,3.61,0,0,1,3,3.3" />
<line x1="10.8" y1="9.6" x2="7.2" y2="9.6" />
<line x1="16.8" y1="9.6" x2="13.2" y2="9.6" />
<rect fillOpacity=".2" x="6.6" y="13.2" width="2.4" height="2.4" rx="0.6" />
<rect fillOpacity=".2" x="15" y="13.2" width="2.4" height="2.4" rx="0.6" />
<rect fillOpacity=".2" x="10.8" y="8.4" width="2.4" height="2.4" rx="0.6" />
<circle fillOpacity=".2" cx="6.6" cy="9.6" r="0.6" />
<circle fillOpacity=".2" cx="17.4" cy="9.6" r="0.6" />
</Fragment>
);
renderPath["color"] = (color, secondaryColor) => (
<Fragment>
<path fill="none" d="M10.8,9.9a3.61,3.61,0,0,0-3,3.3" />
<path fill="none" d="M13.2,9.9a3.61,3.61,0,0,1,3,3.3" />
<line x1="10.8" y1="9.6" x2="7.2" y2="9.6" />
<line x1="16.8" y1="9.6" x2="13.2" y2="9.6" />
<rect
fill={secondaryColor}
x="6.6"
y="13.2"
width="2.4"
height="2.4"
rx="0.6"
/>
<rect
fill={secondaryColor}
x="15"
y="13.2"
width="2.4"
height="2.4"
rx="0.6"
/>
<rect
fill={secondaryColor}
x="10.8"
y="8.4"
width="2.4"
height="2.4"
rx="0.6"
/>
<circle fill={secondaryColor} cx="6.6" cy="9.6" r="0.6" />
<circle fill={secondaryColor} cx="17.4" cy="9.6" r="0.6" />
</Fragment>
);
const VectorBezier = forwardRef((props, ref) => {
return <IconBase ref={ref} {...props} renderPath={renderPath} />;
});
export default VectorBezier;
| 33.159091 | 80 | 0.503084 |
46a880655f591a74ed9b095ede3f0718a1618086 | 5,090 | js | JavaScript | app/javascript/components/Meeting.js | nachosala89/zoom-randomizer | 7a874694e3dcb7b74e39f58dc0c6a5c7d2ed26e0 | [
"MIT"
] | null | null | null | app/javascript/components/Meeting.js | nachosala89/zoom-randomizer | 7a874694e3dcb7b74e39f58dc0c6a5c7d2ed26e0 | [
"MIT"
] | null | null | null | app/javascript/components/Meeting.js | nachosala89/zoom-randomizer | 7a874694e3dcb7b74e39f58dc0c6a5c7d2ed26e0 | [
"MIT"
] | null | null | null | import React, { useEffect, useState } from "react";
import { useParams, Link } from 'react-router-dom';
import Form from 'react-bootstrap/Form';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faX } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';
const Meeting = () => {
const [users, setUsers] = useState([]);
const { id } = useParams();
const [username, setUsername] = useState('');
const onChange = (e) => {
setUsername(e.target.value);
};
const unselected = (arr) => {
return arr.filter((user) => user.selected === 0);
};
const selected = (arr) => {
return arr.filter((user) => user.selected !== 0).sort((a, b) => b.selected - a.selected);
};
const fetchUsers = () => {
axios.get(`http://127.0.0.1:3000/v1/meetings/${id}/users`)
.then((response) => {
setUsers(response.data);
});
}
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
name: username,
meeting_id: id,
};
await axios.post(`http://127.0.0.1:3000/v1/meetings/${id}/users`, data)
.then((response) => {
if (response.status == 200) {
setUsername('');
fetchUsers();
}
});
};
const randomize = async () => {
const arr = unselected(users);
let user = arr[Math.floor(Math.random()*arr.length)];
const selectArr = selected(users);
let last = (selectArr.length === 0) ? 0 : Math.max(...selectArr.map(user => user.selected));
user.selected = last + 1;
await axios.put(`http://127.0.0.1:3000/v1/meetings/${id}/users/${user.id}`, user)
.then((response) => {
if (response.status == 200) {
fetchUsers();
}
});
};
const reset = async () => {
await axios.put(`http://127.0.0.1:3000/v1/meetings/${id}/reset`)
.then((response) => {
if (response.status == 200) {
fetchUsers();
}
});
}
const removeUser = async (userId) => {
await axios.delete(`http://127.0.0.1:3000/v1/meetings/${id}/users/${userId}`)
.then((response) => {
if (response.status == 200) {
fetchUsers();
}
});
}
useEffect( () => {
fetchUsers();
setInterval(() => {
fetchUsers();
}, 5000);
}, []);
const copyURL = () => {
navigator.clipboard.writeText(window.location.href);
}
return (
<div className="container mt-3 mb-5">
<ul>
<li className="text-center">Share this link with your partners.</li>
<li className="d-flex justify-content-center">
<div className="p-1 link-box">
<span>{window.location.href}</span>
<button className="small-btn ms-2" onClick={copyURL}>COPY</button>
</div>
</li>
<li className="text-center">Ask them to add their names. Or you can do it yourself.</li>
</ul>
<div className="row mt-4">
<div className="col-md-3 offset-md-1 participants">
<Form onSubmit={handleSubmit}>
<div className="d-flex">
<Form.Group controlId="username">
<Form.Control name="username" type="text" value={username} onChange={onChange} placeholder="Name" />
</Form.Group>
<button className="small-btn align-self-end" type="submit">
ADD
</button>
</div>
</Form>
{(unselected(users).length === 0)
? <p>No participants to choose.</p>
: <table className="table">
<tbody>
{unselected(users).map((user) => (
<tr key={user.id}>
<td>
<span>{user.name}</span>
</td>
<td>
<FontAwesomeIcon icon={faX} onClick={() => removeUser(user.id)} />
</td>
</tr>
))}
</tbody>
</table>
}
</div>
<div className="col-md-4 d-flex flex-column align-items-center">
<button className="big-button p-4" onClick={randomize}>PICK<br/>RANDOM</button>
{(selected(users).length === 0) ? ''
: <div>
<div className="participants mt-2">Selected:</div>
<p className="current-user text-center">{selected(users)[0].name}</p>
</div>}
</div>
<div className="col-md-4 participants">
{selected(users).length === 0 ? ''
: <button className="small-btn" onClick={reset}>RESET</button>}
{selected(users).slice(1).length === 0 ? ''
: <div>
<span>Previous selected </span>
<ul className="previous-selected">
{selected(users).slice(1).map((user) => (
<li key={user.id}>
<span>{user.name}</span>
</li>
))}
</ul>
</div>
}
</div>
</div>
</div>
);
}
export default Meeting; | 31.419753 | 116 | 0.502947 |
46a8e025ab976e29eec1aef9fc4b2c1ed4868d81 | 1,022 | js | JavaScript | back-end/blog/models/articleCategory.js | hwy2/blog | 5fc0808cc18f90bbce56d6d0713167c0ea93b714 | [
"Apache-2.0"
] | null | null | null | back-end/blog/models/articleCategory.js | hwy2/blog | 5fc0808cc18f90bbce56d6d0713167c0ea93b714 | [
"Apache-2.0"
] | null | null | null | back-end/blog/models/articleCategory.js | hwy2/blog | 5fc0808cc18f90bbce56d6d0713167c0ea93b714 | [
"Apache-2.0"
] | null | null | null | /**
* Article 文章表
* @type {[type]}
*/
var Sequelize = require('sequelize');
var Mysql = require('./mysql');
// console.log("articleCategory文章中间类别表");
var articleCategory = Mysql.define('articleCategory', {
uuid: {
type: Sequelize.UUID,
allowNull: false,
primaryKey: true,
defaultValue: Sequelize.UUIDV1,
}
}, {
freezeTableName: true, // 自定义表名
tableName: 'ArticleCategory',
timestamps: true, // 添加时间戳属性 (updatedAt, createdAt)
createdAt: 'createDate', // 将createdAt字段改个名
updatedAt: 'updateDate', // 将updatedAt字段改个名
indexes: [{ // 索引
type: 'UNIQUE', //UNIQUE、 FULLTEXT 或 SPATIAL之一
method: 'BTREE', //BTREE 或 HASH
unique: true, //唯一 //设置索引是否唯一,设置后会自动触发UNIQUE设置//true:索引列的所有值都只能出现一次,即必须唯一
fields: ['uuid'], //建立索引的字段数组。每个字段可以是一个字段名,sequelize 对象 (如 sequelize.fn),或一个包含:attribute (字段名)、length (创建前缀字符数)、order (列排序方向)、collate (较验的字段集合 (排序))
}],
comment: "ArticleCategory Table", //描述
});
module.exports = articleCategory; | 32.967742 | 156 | 0.648728 |
46a8e73601b0ad5030fbef01209a7149ef51199c | 2,131 | js | JavaScript | prebid/v1.6.0/dist/rtbdemandBidAdapter.js | sortable/prebid-generator | c811e7576bfb794d5850712329f8a906fe68b996 | [
"MIT"
] | null | null | null | prebid/v1.6.0/dist/rtbdemandBidAdapter.js | sortable/prebid-generator | c811e7576bfb794d5850712329f8a906fe68b996 | [
"MIT"
] | null | null | null | prebid/v1.6.0/dist/rtbdemandBidAdapter.js | sortable/prebid-generator | c811e7576bfb794d5850712329f8a906fe68b996 | [
"MIT"
] | null | null | null | pbjsChunk([29],{294:function(e,r,t){t(295),e.exports=t(296)},295:function(e,r,t){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.spec=void 0;var o=(function(e){{if(e&&e.__esModule)return e;var r={};if(null!=e)for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=e[t]);return r.default=e,r}})(t(0)),i=t(1);var a="bidding.rtbdemand.com",n=r.spec={code:"rtbdemand",isBidRequestValid:function(e){return!!(e&&e.params&&e.params.zoneid)},buildRequests:function(e,n){return e.map((function(e){var r=e.params.server||a,t=(function(e){var r={},t=o.parseSizesInput(e)[0];if("string"!=typeof t)return r;var i=t.toUpperCase().split("X"),n=parseInt(i[0],10);n&&(r.width=n);var a=parseInt(i[1],10);a&&(r.height=a);return r})(n.bids[0].sizes),i={from:"hb",v:"1.0",request_id:e.bidderRequestId,imp_id:e.bidId,aff:e.params.zoneid,bid_floor:0<parseFloat(e.params.floor)?e.params.floor:0,charset:document.charSet||document.characterSet,site_domain:document.location.hostname,site_page:window.location.href,subid:"hb",flashver:(function(){var e,r,t;if(navigator.plugins&&0<navigator.plugins.length){e=navigator.plugins;for(var i=0;i<e.length&&!t;i++)-1<(r=e[i]).name.indexOf("Shockwave Flash")&&(t=r.description.split("Shockwave Flash ")[1])}return t||""})(),tmax:n.timeout,hb:"1",name:document.location.hostname,width:t.width,height:t.height,device_width:screen.width,device_height:screen.height,dnt:"yes"==navigator.doNotTrack||"1"==navigator.doNotTrack||"1"==navigator.msDoNotTrack?1:0,secure:"https:"===document.location.protocol,make:navigator.vendor?navigator.vendor:""};return document.referrer&&(i.referrer=document.referrer),{method:"GET",url:"//"+r+"/hb",data:i}}))},interpretResponse:function(e){e=e.body;var t=[];return e&&e.seatbid&&e.seatbid.forEach((function(e){return e.bid.forEach((function(e){var r={requestId:e.impid,creativeId:e.impid,cpm:e.price,width:e.w,height:e.h,ad:e.adm,netRevenue:!0,currency:"USD",ttl:360};t.push(r)}))})),t},getUserSyncs:function(e){if(e.iframeEnabled)return[{type:"iframe",url:"//"+a+"/delivery/matches.php?type=iframe"}]}};(0,i.registerBidder)(n)},296:function(e,r){}},[294]); | 2,131 | 2,131 | 0.72642 |
46a9edc343316f83263ebb00c32332a35f9bca7c | 4,144 | js | JavaScript | skills/sample_conversations.js | andersoncsantos/first-slack-project | acc2395182675cb53be1676c77c33522d72be128 | [
"MIT"
] | null | null | null | skills/sample_conversations.js | andersoncsantos/first-slack-project | acc2395182675cb53be1676c77c33522d72be128 | [
"MIT"
] | null | null | null | skills/sample_conversations.js | andersoncsantos/first-slack-project | acc2395182675cb53be1676c77c33522d72be128 | [
"MIT"
] | null | null | null | /*
WHAT IS THIS?
This module demonstrates simple uses of Botkit's conversation system.
In this example, Botkit hears a keyword, then asks a question. Different paths
through the conversation are chosen based on the user's response.
*/
module.exports = function(controller) {
controller.hears(['color'], 'direct_message,direct_mention', function(bot, message) {
bot.startConversation(message, function(err, convo) {
convo.say('This is an example of using convo.ask with a single callback.');
convo.ask('What is your favorite color?', function(response, convo) {
convo.say('Cool, I like ' + response.text + ' too!');
convo.next();
});
});
});
controller.hears(['cores'], 'direct_message,direct_mention', function(bot, message) {
bot.startConversation(message, function(response, convo) {
//convo.say('calendário?');
convo.ask({
attachments:[
{
title: 'Qual cor?',
callback_id: '123',
attachment_type: 'default',
actions: [
{
"name":'amarelo',
"text": 'Amarelo',
"value": 'Amarelo',
"type": 'button',
},
{
"name":'azul',
"text": 'Azul',
"value": 'azul',
"type": 'button',
}
]
}
]
}, function(response, convo) {
convo.say('Legal, gosto de *' + response.text + '* também!');
convo.next();
});
});
});
controller.hears(['question'], 'direct_message,direct_mention', function(bot, message) {
bot.createConversation(message, function(err, convo) {
// create a path for when a user says YES
convo.addMessage({
text: 'How wonderful.',
},'yes_thread');
// create a path for when a user says NO
// mark the conversation as unsuccessful at the end
convo.addMessage({
text: 'Cheese! It is not for everyone.',
action: 'stop', // this marks the converation as unsuccessful
},'no_thread');
// create a path where neither option was matched
// this message has an action field, which directs botkit to go back to the `default` thread after sending this message.
convo.addMessage({
text: 'Sorry I did not understand. Say `yes` or `no`',
action: 'default',
},'bad_response');
// Create a yes/no question in the default thread...
convo.ask('Do you like cheese?', [
{
pattern: bot.utterances.yes,
callback: function(response, convo) {
convo.gotoThread('yes_thread');
},
},
{
pattern: bot.utterances.no,
callback: function(response, convo) {
convo.gotoThread('no_thread');
},
},
{
default: true,
callback: function(response, convo) {
convo.gotoThread('bad_response');
},
}
]);
convo.activate();
// capture the results of the conversation and see what happened...
convo.on('end', function(convo) {
if (convo.successful()) {
// this still works to send individual replies...
bot.reply(message, 'Let us eat some!');
// and now deliver cheese via tcp/ip...
}
});
});
});
};
| 32.375 | 132 | 0.450531 |
46aa6a4d2e1de483b1098d9a33798b2cad36fcd0 | 1,534 | js | JavaScript | extra/remove-2fa.js | Rongaming7777/uptime-ron | f4fc57c97f2b1ea9969e88bc9cc3bbec32479127 | [
"MIT"
] | null | null | null | extra/remove-2fa.js | Rongaming7777/uptime-ron | f4fc57c97f2b1ea9969e88bc9cc3bbec32479127 | [
"MIT"
] | null | null | null | extra/remove-2fa.js | Rongaming7777/uptime-ron | f4fc57c97f2b1ea9969e88bc9cc3bbec32479127 | [
"MIT"
] | null | null | null | console.log("== Uptime Ron Remove 2FA Tool ==");
console.log("Loading the database");
const Database = require("../server/database");
const { R } = require("redbean-node");
const readline = require("readline");
const TwoFA = require("../server/2fa");
const args = require("args-parser")(process.argv);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const main = async () => {
Database.init(args);
await Database.connect();
try {
// No need to actually reset the password for testing, just make sure no connection problem. It is ok for now.
if (!process.env.TEST_BACKEND) {
const user = await R.findOne("user");
if (! user) {
throw new Error("user not found, have you installed?");
}
console.log("Found user: " + user.username);
let ans = await question("Are you sure want to remove 2FA? [y/N]");
if (ans.toLowerCase() === "y") {
await TwoFA.disable2FA(user.id);
console.log("2FA has been removed successfully.");
}
}
} catch (e) {
console.error("Error: " + e.message);
}
await Database.close();
rl.close();
console.log("Finished.");
};
function question(question) {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer);
});
});
}
if (!process.env.TEST_BACKEND) {
main();
}
module.exports = {
main,
};
| 25.147541 | 118 | 0.568449 |
431b6febb19682cc370442dd8a1dcbc98c16d867 | 350 | js | JavaScript | extern/Halide/osx/share/doc/Halide/struct_d3_d12___t_e_x3_d___r_t_v.js | HiDoYa/webassembly-video-filters | 70bcaaaeb94a763988975aa8e1582ed10c2f2c39 | [
"MIT"
] | 5 | 2021-01-15T03:40:25.000Z | 2021-09-05T22:53:38.000Z | extern/Halide/osx/share/doc/Halide/struct_d3_d12___t_e_x3_d___r_t_v.js | HiDoYa/webassembly-video-filters | 70bcaaaeb94a763988975aa8e1582ed10c2f2c39 | [
"MIT"
] | 1 | 2021-05-05T21:57:46.000Z | 2021-05-05T23:18:06.000Z | extern/Halide/osx/share/doc/Halide/struct_d3_d12___t_e_x3_d___r_t_v.js | HiDoYa/webassembly-video-filters | 70bcaaaeb94a763988975aa8e1582ed10c2f2c39 | [
"MIT"
] | null | null | null | var struct_d3_d12___t_e_x3_d___r_t_v =
[
[ "MipSlice", "struct_d3_d12___t_e_x3_d___r_t_v.html#a5adbc18dc5ec82d18dfa22b5175ceb12", null ],
[ "FirstWSlice", "struct_d3_d12___t_e_x3_d___r_t_v.html#a00a2f8470cd71dfdd568e4fd4c906be8", null ],
[ "WSize", "struct_d3_d12___t_e_x3_d___r_t_v.html#ae578c3a8dd10634bf2cd152768d8e93b", null ]
]; | 58.333333 | 104 | 0.794286 |
431bb7145bf940fb5ebdf27428f7d613bf62a37b | 2,549 | js | JavaScript | src/Popover/events.js | chenwengui/shineout | 250471558aff4a476dfcb45d6cdb9e4645431507 | [
"MIT"
] | 1 | 2021-10-14T00:09:35.000Z | 2021-10-14T00:09:35.000Z | src/Popover/events.js | PatricioPeng/shineout | c676aa79c75894b5585ebfa308d1072d81c2d7c1 | [
"MIT"
] | null | null | null | src/Popover/events.js | PatricioPeng/shineout | c676aa79c75894b5585ebfa308d1072d81c2d7c1 | [
"MIT"
] | null | null | null | import React from 'react'
import ReactDOM from 'react-dom'
import { popoverClass } from '../styles'
import ready from '../utils/dom/ready'
let currentProps = null
const div = document.createElement('div')
div.style.display = 'none'
ready(() => {
document.body.appendChild(div)
})
const arrow = document.createElement('div')
arrow.className = popoverClass('arrow')
div.appendChild(arrow)
const inner = document.createElement('div')
inner.className = popoverClass('content')
div.appendChild(inner)
let timer = null
let currentId
export function hide(delay = 500) {
timer = setTimeout(() => {
div.style.display = 'none'
div.className = ''
currentId = undefined
}, delay)
}
const hide0 = hide.bind(null, 0)
function clickaway(e) {
if (div.contains(e.target)) return
hide(0)
document.removeEventListener('click', clickaway)
}
div.addEventListener('mouseenter', () => {
if (!timer) return
clearTimeout(timer)
document.addEventListener('click', clickaway)
})
div.addEventListener('mouseleave', () => {
clearTimeout(timer)
if (currentProps && currentProps.trigger === 'click') return
hide()
})
export function show(props, id) {
const { position, style, content, background, border, noArrow, type } = props
currentProps = props
// set current id
currentId = id
if (timer) clearTimeout(timer)
div.style.cssText = 'display: none'
Object.keys(style).forEach(k => {
div.style[k] = style[k]
})
if (style.right) div.setAttribute('raw-right', style.right)
if (style.left) div.setAttribute('raw-left', style.left)
div.setAttribute('raw-top', style.top)
div.style.background = background || ''
inner.style.background = background || ''
arrow.style.background = background || ''
div.style.borderColor = border || ''
arrow.style.borderColor = border || ''
const className = popoverClass('_', position, type)
arrow.style.display = noArrow ? 'none' : 'block'
// fix safari
setTimeout(() => {
div.style.display = 'block'
div.className = className
}, 0)
let newContent = typeof content === 'function' ? content(hide0) : content
if (typeof newContent === 'string') newContent = <span className={popoverClass('text')}>{newContent}</span>
ReactDOM.render(newContent, inner)
document.addEventListener('click', clickaway)
}
export function move(id, pos) {
if (id === currentId) {
// eslint-disable-next-line no-return-assign
Object.keys(pos).map(key => (div.style[key] = pos[key]))
}
}
export function isCurrent(id) {
return id === currentId
}
| 24.747573 | 109 | 0.683013 |
431c5420fa490e4cb884f59b399dce8e4c7a267e | 26,085 | js | JavaScript | build/controllers/ProfileController.js | kemijibola/untappedapiv2 | 2fb8f57dbe9d865f7f725e7deccdaa0ef02d75cd | [
"MIT"
] | null | null | null | build/controllers/ProfileController.js | kemijibola/untappedapiv2 | 2fb8f57dbe9d865f7f725e7deccdaa0ef02d75cd | [
"MIT"
] | 7 | 2020-04-13T00:49:55.000Z | 2021-05-09T08:21:35.000Z | build/controllers/ProfileController.js | kemijibola/untappedapiv2 | 2fb8f57dbe9d865f7f725e7deccdaa0ef02d75cd | [
"MIT"
] | null | null | null | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var decorators_1 = require("../decorators");
var ProfileBusiness = require("../app/business/ProfileBusiness");
var error_1 = require("../utils/error");
var auth_1 = require("../middlewares/auth");
var ValidateRequest_1 = require("../middlewares/ValidateRequest");
var _ = __importStar(require("underscore"));
var PermissionConstant_1 = require("../utils/lib/PermissionConstant");
var ProfileController = /** @class */ (function () {
function ProfileController() {
}
ProfileController.prototype.fetch = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var condition, profileBusiness, result, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
condition = {};
if (req.body) {
condition = req.body;
}
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.fetch(condition)];
case 1:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(result.responseCode).json({
message: "Operation successful",
data: result.data,
})];
case 2:
err_1 = _a.sent();
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again.",
}))];
case 3: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.fetchTalents = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
try {
}
catch (err) {
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again.",
}))];
}
return [2 /*return*/];
});
});
};
ProfileController.prototype.fetchUserProfile = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var profileBusiness, result, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.findByUser(req.user)];
case 1:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(result.responseCode).json({
message: "Operation successful",
data: result.data,
})];
case 2:
err_2 = _a.sent();
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again.",
}))];
case 3: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.fetchProfile = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var profileBusiness, result, err_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.fetch({})];
case 1:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(result.responseCode).json({
message: "Operation successful",
data: result.data,
})];
case 2:
err_3 = _a.sent();
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again.",
}))];
case 3: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.create = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var item, profileBusiness, result, err_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
item = req.body;
if (_.has(req.body.userAddress, "address")) {
item.location = req.body.userAddress.address.location;
item.formattedAddres = req.body.userAddress.address.formattedAddres;
}
if (!item.location || !item.formattedAddres) {
return [2 /*return*/, next(new error_1.PlatformError({
code: 400,
message: "Please provide location",
}))];
}
if (item.shortBio) {
if (item.shortBio.trim().length < 80 ||
item.shortBio.trim().length > 2000) {
return [2 /*return*/, next(new error_1.PlatformError({
code: 400,
message: "Short bio length must be greater than 80 and less that 2000",
}))];
}
}
item.user = req.user;
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.create(item)];
case 1:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(result.responseCode).json({
message: "Operation successful",
data: result.data,
})];
case 2:
err_4 = _a.sent();
console.log(err_4);
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again.",
}))];
case 3: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.updateProfile = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var item, id, profileBusiness, result, err_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
item = req.body;
item.user = req.user;
id = req.params.id;
if (_.has(req.body.userAddress, "address")) {
item.location = req.body.userAddress.address.location;
item.formattedAddres = req.body.userAddress.address.formattedAddres;
}
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.patch(id, item)];
case 1:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(result.responseCode).json({
message: "Operation successful",
data: result.data,
})];
case 2:
err_5 = _a.sent();
console.log(err_5);
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again.",
}))];
case 3: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.postTalentLike = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var profileBusiness, talentProfile, userHasLiked, result, err_6;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 4, , 5]);
if (!req.body.userId)
return [2 /*return*/, next(new error_1.PlatformError({
code: 400,
message: "Please provide userId",
}))];
profileBusiness = new ProfileBusiness();
console.log("from controller", req.body.userId);
return [4 /*yield*/, profileBusiness.findByCriteria({
user: req.body.userId,
})];
case 1:
talentProfile = _a.sent();
if (talentProfile.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: talentProfile.responseCode,
message: talentProfile.error,
}))];
}
if (!talentProfile.data) return [3 /*break*/, 3];
userHasLiked = talentProfile.data.tappedBy.filter(function (x) { return x == req.user; })[0];
if (userHasLiked) {
return [2 /*return*/, next(new error_1.PlatformError({
code: 400,
message: "You have already performed Like operation.",
}))];
}
talentProfile.data.tappedBy = talentProfile.data.tappedBy.concat([
req.user,
]);
return [4 /*yield*/, profileBusiness.updateLike(talentProfile.data._id, talentProfile.data)];
case 2:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(200).json({
message: "Operation successful",
data: true,
})];
case 3: return [3 /*break*/, 5];
case 4:
err_6 = _a.sent();
console.log(err_6);
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again later.",
}))];
case 5: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.postTalentUnLike = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var profileBusiness, talentProfile, userHasLiked, result, err_7;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 4, , 5]);
if (!req.body.userId)
return [2 /*return*/, next(new error_1.PlatformError({
code: 400,
message: "Please provide userId",
}))];
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.findByCriteria({
user: req.body.userId,
})];
case 1:
talentProfile = _a.sent();
if (talentProfile.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: talentProfile.responseCode,
message: talentProfile.error,
}))];
}
if (!talentProfile.data) return [3 /*break*/, 3];
userHasLiked = talentProfile.data.tappedBy.filter(function (x) { return x == req.user; })[0];
if (!userHasLiked) {
return [2 /*return*/, next(new error_1.PlatformError({
code: 400,
message: "You have not liked talent",
}))];
}
talentProfile.data.tappedBy = talentProfile.data.tappedBy.filter(function (x) { return x != req.user; });
return [4 /*yield*/, profileBusiness.updateLike(talentProfile.data._id, talentProfile.data)];
case 2:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: result.error,
}))];
}
return [2 /*return*/, res.status(200).json({
message: "Operation successful",
data: true,
})];
case 3: return [3 /*break*/, 5];
case 4:
err_7 = _a.sent();
console.log(err_7);
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured. Please try again later.",
}))];
case 5: return [2 /*return*/];
}
});
});
};
ProfileController.prototype.fetchPendingMedia = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var profileBusiness, result, err_8;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
profileBusiness = new ProfileBusiness();
return [4 /*yield*/, profileBusiness.fetchPendingTalentProfile({
isProfileCompleted: false,
})];
case 1:
result = _a.sent();
if (result.error) {
return [2 /*return*/, next(new error_1.PlatformError({
code: result.responseCode,
message: "Error occured, " + result.error,
}))];
}
return [2 /*return*/, res.status(result.responseCode).json({
message: "Media Operation successful",
data: result.data,
})];
case 2:
err_8 = _a.sent();
return [2 /*return*/, next(new error_1.PlatformError({
code: 500,
message: "Internal Server error occured." + err_8,
}))];
case 3: return [2 /*return*/];
}
});
});
};
__decorate([
decorators_1.use(auth_1.requireAuth),
decorators_1.get("/"),
decorators_1.use(ValidateRequest_1.requestValidator),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "fetch", null);
__decorate([
decorators_1.get("/"),
decorators_1.use(ValidateRequest_1.requestValidator),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "fetchTalents", null);
__decorate([
decorators_1.get("/user"),
decorators_1.use(ValidateRequest_1.requestValidator),
decorators_1.use(auth_1.requireAuth),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "fetchUserProfile", null);
__decorate([
decorators_1.get("/:id"),
decorators_1.use(ValidateRequest_1.requestValidator),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "fetchProfile", null);
__decorate([
decorators_1.use(auth_1.requireAuth),
decorators_1.use(ValidateRequest_1.requestValidator),
decorators_1.post("/"),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "create", null);
__decorate([
decorators_1.use(ValidateRequest_1.requestValidator),
decorators_1.use(auth_1.requireAuth),
decorators_1.put("/:id"),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "updateProfile", null);
__decorate([
decorators_1.post("/talent/like"),
decorators_1.use(ValidateRequest_1.requestValidator),
decorators_1.requestValidators("userId"),
decorators_1.use(auth_1.requireAuth),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "postTalentLike", null);
__decorate([
decorators_1.post("/talent/unLike"),
decorators_1.use(ValidateRequest_1.requestValidator),
decorators_1.requestValidators("userId"),
decorators_1.use(auth_1.requireAuth),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "postTalentUnLike", null);
__decorate([
decorators_1.get("/admin/talents/pending"),
decorators_1.use(auth_1.requireAuth),
decorators_1.use(ValidateRequest_1.requestValidator),
decorators_1.authorize(PermissionConstant_1.canViewTalents),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object, Function]),
__metadata("design:returntype", Promise)
], ProfileController.prototype, "fetchPendingMedia", null);
ProfileController = __decorate([
decorators_1.controller("/v1/profiles")
], ProfileController);
return ProfileController;
}());
exports.ProfileController = ProfileController;
//# sourceMappingURL=ProfileController.js.map | 51.449704 | 169 | 0.446463 |
431c5ac5450d70f81aede34f21a4e76b32ce187b | 70 | js | JavaScript | .history/api/users/users-router_20220227001734.js | lomelo-x/WaterMyPlants-Back-End | ff2e5d0f107852d814d4d6bbd2ec06711ea1a574 | [
"MIT"
] | null | null | null | .history/api/users/users-router_20220227001734.js | lomelo-x/WaterMyPlants-Back-End | ff2e5d0f107852d814d4d6bbd2ec06711ea1a574 | [
"MIT"
] | null | null | null | .history/api/users/users-router_20220227001734.js | lomelo-x/WaterMyPlants-Back-End | ff2e5d0f107852d814d4d6bbd2ec06711ea1a574 | [
"MIT"
] | null | null | null | const router = require('express').Router()
const User = require('./') | 23.333333 | 42 | 0.671429 |
431ce03b5c4510ab9febaea81dbc096672a0d537 | 34,723 | js | JavaScript | microservices/requestApi/test/v2/requests.js | bcgov/OCWA | e0bd0763ed1e3c0acc498cb1689778b4e22a475c | [
"Apache-2.0"
] | 9 | 2018-09-14T18:03:45.000Z | 2021-06-16T16:04:25.000Z | microservices/requestApi/test/v2/requests.js | bcgov/OCWA | e0bd0763ed1e3c0acc498cb1689778b4e22a475c | [
"Apache-2.0"
] | 173 | 2019-01-18T19:25:05.000Z | 2022-01-10T21:15:46.000Z | microservices/requestApi/test/v2/requests.js | bcgov/OCWA | e0bd0763ed1e3c0acc498cb1689778b4e22a475c | [
"Apache-2.0"
] | 3 | 2018-09-24T15:44:39.000Z | 2018-11-24T01:04:37.000Z |
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../../app');
var should = chai.should();
var expect = chai.expect;
var config = require('config');
var jwt = config.get('testJWT');
var adminJwt = config.get('testAdminJWT');
var db = require('../../routes/v2/db/db');
var logger = require('npmlog');
chai.use(chaiHttp);
describe("Requests", function() {
var activeRequestId = '';
var incorrectId = '';
var fileId = 'test_' + Math.random().toString(36) + '.jpeg';
var activeFormId = '';
after(function(done){
db.Request.deleteMany({}, function(err){
var minio = require('minio');
var config = require('config');
var storageConfig = config.get('storageApi');
var Minio = require('minio');
var minioClient = new Minio.Client({
endPoint: storageConfig['uri'],
port: storageConfig['port'],
useSSL: storageConfig['useSSL'],
accessKey: storageConfig['key'],
secretKey: storageConfig['secret']
});
minioClient.removeObject(storageConfig.bucket, fileId, function(err) {
if (err) {
console.log('Unable to remove object', err);
done();
return;
}
done();
})
});
});
before(function(done){
var minio = require('minio');
var config = require('config');
var storageConfig = config.get('storageApi');
var Minio = require('minio');
var minioClient = new Minio.Client({
endPoint: storageConfig['uri'],
port: storageConfig['port'],
useSSL: storageConfig['useSSL'],
accessKey: storageConfig['key'],
secretKey: storageConfig['secret']
});
var Fs = require('fs');
var file = __dirname+'/../file/gov.jpeg';
var fileStream = Fs.createReadStream(file);
minioClient.bucketExists(storageConfig.bucket, function(err, exists) {
if (err) {
return console.log(err)
}
if (!exists) {
minioClient.makeBucket(storageConfig.bucket, 'us-east-1', function(err) {
if (err) {
console.log('Error creating bucket.', err);
done();
}
minioClient.putObject(storageConfig.bucket, fileId, fileStream, function(err, etag) {
done();
});
})
}else{
minioClient.putObject(storageConfig.bucket, fileId, fileStream, function(err, etag) {
done();
});
}
});
});
describe('/GET v2/', function () {
it('it should get unauthorized', function (done) {
chai.request(server)
.get('/v2/')
.end(function (err, res) {
res.should.have.status(401);
done();
});
});
it('it should get file_status_codes', function (done) {
chai.request(server)
.get('/v2/file_status_codes')
.set("Authorization", "Bearer " + jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('0');
res.body.should.have.property('1');
res.body.should.have.property('2');
done();
});
});
it('it should get request_types', function (done) {
chai.request(server)
.get('/v2/request_types')
.set("Authorization", "Bearer " + jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('import');
res.body.should.have.property('export');
done();
});
});
it('it should get all status code mappings', function (done) {
chai.request(server)
.get('/v2/status_codes')
.set("Authorization", "Bearer "+jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('0');
res.body.should.have.property('1');
res.body.should.have.property('2');
res.body.should.have.property('3');
res.body.should.have.property('4');
res.body.should.have.property('5');
res.body.should.have.property('6');
done();
});
});
it('it should get all records (max 100) (currently 6)', function (done) {
chai.request(server)
.get('/v2/')
.set("Authorization", "Bearer "+jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.length.should.be.eql(0);
done();
});
});
});
describe('/POST v2/', function () {
it('it should get unauthorized', function (done) {
chai.request(server)
.post('/v2/')
.end(function (err, res) {
res.should.have.status(401);
done();
});
});
it('it should fail without a name', function (done) {
chai.request(server)
.post('/v2/')
.set("Authorization", "Bearer " + jwt)
.send({
text: "text",
number: 9
})
.end(function (err, res) {
res.should.have.status(500);
res.body.should.be.a('object');
res.body.should.have.property('error');
res.body.error.should.be.a('string');
done();
});
});
it('it should create a request', function (done) {
chai.request(server)
.post('/v2/')
.set("Authorization", "Bearer " + jwt)
.send({
name: "testName",
text: "text",
number: 9
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('result');
res.body.result.should.have.property('_id');
activeRequestId = res.body.result._id;
firstId = res.body.result._id;
incorrectId = activeRequestId.substring(0, activeRequestId.length-1)+"1";
if (incorrectId === activeRequestId){
incorrectId = activeRequestId.substring(0, activeRequestId.length-1)+"2";
}
done();
});
});
});
describe('/GET v2 & v2/requestId', function () {
it('it should get requests', function (done) {
chai.request(server)
.get('/v2?limit=101&page=0&state=0&name=*&id='+activeRequestId)
.set("Authorization", "Bearer " + jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.length.should.be.eql(1);
done();
});
});
it('it should get supervisor requests from internal', function (done) {
chai.request(server)
.get('/v2')
.set("Authorization", "Bearer " + config.get('testSupervisorInternalJWT'))
.end(function (err, res) {
res.should.have.status(200);
res.body.length.should.be.eql(1);
done();
});
});
it('it should get supervisor requests from external', function (done) {
chai.request(server)
.get('/v2')
.set("Authorization", "Bearer " + config.get('testSupervisorExternalJWT'))
.end(function (err, res) {
res.should.have.status(200);
res.body.length.should.be.eql(1);
done();
});
});
it('it should get a specific request', function (done) {
chai.request(server)
.get('/v2/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('_id');
done();
});
});
it('it should get a specific request but without file statuses', function (done) {
chai.request(server)
.get('/v2/' + activeRequestId + "?include_file_status=false")
.set("Authorization", "Bearer " + jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('_id');
res.body.should.not.have.property('fileStatus')
done();
});
});
});
describe('/DELETE /v2/requestId', function() {
it('it should delete a request', function (done) {
chai.request(server)
.delete('/v2/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
it('it should fail to delete an incorrect id', function (done) {
chai.request(server)
.delete('/v2/' + incorrectId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(500);
res.body.should.be.a('object');
res.body.should.have.property('error');
done();
});
});
it('it should fail to delete an invalid id', function (done) {
chai.request(server)
.delete('/v2/1')
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('error');
done();
});
});
});
describe('/PUT /v2/save/requestId', function() {
it('it should create a request', function (done) {
chai.request(server)
.post('/v2/')
.set("Authorization", "Bearer " + jwt)
.send({
name: "testName2",
text: "text",
number: 9
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('result');
res.body.result.should.have.property('_id');
activeRequestId = res.body.result._id;
done();
});
});
it('it should fail to save a with an invalid id', function (done) {
chai.request(server)
.put('/v2/save/1')
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('error');
done();
});
});
it('it should fail to save a request', function (done) {
chai.request(server)
.put('/v2/save/' + incorrectId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('error');
done();
});
});
it('it should save a request', function (done) {
chai.request(server)
.put('/v2/save/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({
files: [fileId]
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
setTimeout(done, 2000);
});
});
it('it should get request file status', function (done) {
chai.request(server)
.get('/v2/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('fileStatus');
var fs = res.body.fileStatus;
// expect(fs[Object.keys(fs)[0]].length).to.equal(2);
// expect(fs[Object.keys(fs)[0]][0]["pass"]).to.equal(true);
// expect(fs[Object.keys(fs)[0]][1]["pass"]).to.equal(true);
// expect(JSON.stringify(res.body, null, 3)).to.equal("");
done();
});
});
it('it should update a v1 request', function (done) {
chai.request(server)
.post('/v1/')
.set("Authorization", "Bearer " + jwt)
.send({
name: "testName",
tags: ["test"],
purpose: "purpose",
phoneNumber: "555-555-5555",
subPopulation: "sub-population",
variableDescriptions: "variable descriptions",
selectionCriteria: "selection criteria",
steps: "steps",
freq: "freq",
confidentiality: "none"
})
.end(function (err, res) {
var intermId = res.body.result._id;
chai.request(server)
.put('/v2/save/' + intermId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
});
});
describe('/PUT /v2/submit/requestId', function() {
it('it should submit a request', function (done) {
chai.request(server)
.put('/v2/submit/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
expect(res.body.error).to.equal(undefined);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
it('it should fail to delete a request that is submitted', function (done) {
chai.request(server)
.delete('/v2/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(403);
res.body.should.be.a('object');
res.body.should.have.property('error');
done();
});
});
});
describe('/PUT /v2/pickup/requestId', function() {
it('it should pickup a request', function (done) {
chai.request(server)
.put('/v2/pickup/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
expect(res.body.error).to.equal(undefined);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
});
describe('/PUT /v2/approve/requestId', function() {
it('it should approve a request', function (done) {
chai.request(server)
.put('/v2/approve/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
expect(res.body.error).to.equal(undefined);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
});
describe('/PUT /v2/cancel/requestId', function() {
it('it should create a request', function (done) {
chai.request(server)
.post('/v2/')
.set("Authorization", "Bearer " + jwt)
.send({
name: "testName3",
text: "text",
number: 9
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('result');
res.body.result.should.have.property('_id');
activeRequestId = res.body.result._id;
done();
});
});
it('it should cancel a request', function (done) {
chai.request(server)
.put('/v2/cancel/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
});
describe('/PUT /v2/deny/requestId', function() {
it('it should create a request', function (done) {
chai.request(server)
.post('/v2/')
.set("Authorization", "Bearer " + jwt)
.send({
name: "testName6",
text: "text",
number: 9
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('result');
res.body.result.should.have.property('_id');
activeRequestId = res.body.result._id;
done();
});
});
it('it should save a request', function (done) {
chai.request(server)
.put('/v2/save/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({
files: [fileId]
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
setTimeout(done, 2000);
});
});
it('it should submit a request', function (done) {
chai.request(server)
.put('/v2/submit/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
expect(res.body.error).to.equal(undefined);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
it('it should pickup a request', function (done) {
chai.request(server)
.put('/v2/pickup/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
expect(res.body.error).to.equal(undefined);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
it('it should deny a request', function (done) {
chai.request(server)
.put('/v2/deny/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
expect(res.body.error).to.equal(undefined);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('result');
done();
});
});
});
describe('CODE Requests', function() {
it('it should create a CODE request', function (done) {
chai.request(server)
.post('/v2/')
.set("Authorization", "Bearer " + jwt)
.send({
name: "testName6",
text: "text",
number: 9,
exportType: "code",
codeDescription: "Whats the code about",
repository: "http://somewhere.com",
externalRepository: "http://somewhere.external.com",
branch: "develop"
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('result');
res.body.result.should.have.property('_id');
res.body.result.should.have.property('mergeRequestStatus');
activeRequestId = res.body.result._id;
done();
});
});
it('it should save a request', function (done) {
chai.request(server)
.put('/v2/save/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
setTimeout(done, 1000);
});
});
it('it should fail submit', function (done) {
chai.request(server)
.put('/v2/submit/' + activeRequestId)
.set("Authorization", "Bearer " + jwt)
.send({})
.end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('error');
expect(res.body.error).to.equal("");
done();
});
});
});
});
describe("Forms", function() {
describe('/GET v2/forms', function () {
it('it should get unauthorized', function (done) {
chai.request(server)
.get('/v2/forms')
.end(function (err, res) {
res.should.have.status(401);
done();
});
});
it('it should get all forms', function (done) {
chai.request(server)
.get('/v2/forms')
.set("Authorization", "Bearer "+jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('0');
res.body[0].should.have.property('_id');
done();
});
});
it('it should get default forms', function (done) {
chai.request(server)
.get('/v2/forms/defaults')
.set("Authorization", "Bearer "+jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('forms');
res.body.forms.should.have.property('internal')
res.body.forms.should.have.property('external')
done();
});
});
it('it should get a specific form', function (done) {
chai.request(server)
.get('/v2/forms/test')
.set("Authorization", "Bearer "+jwt)
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('_id');
done();
});
});
it('it should fail to create a form without admin', function (done) {
chai.request(server)
.post('/v2/forms')
.set("Authorization", "Bearer "+jwt)
.end(function (err, res) {
res.should.have.status(403);
res.body.should.have.property('error');
done();
});
});
it('it should create a form', function (done) {
chai.request(server)
.post('/v2/forms')
.set("Authorization", "Bearer "+adminJwt)
.send({
"title": "testform",
"display": "form",
"type": "form",
"name": "testform",
"path": "testform",
"components": [{
"input": true,
"tableView": true,
"inputType": "text",
"inputMask": "",
"label": "First Name",
"key": "firstName",
"placeholder": "",
"prefix": "",
"suffix": "",
"multiple": false,
"defaultValue": "",
"protected": false,
"unique": false,
"persistent": true,
"validate": {
"required": false,
"minLength": "",
"maxLength": "",
"pattern": "",
"custom": "",
"customPrivate": false
},
"conditional": {
"show": "",
"when": null,
"eq": ""
},
"type": "textfield",
"tags": [],
"lockKey": true,
"isNew": false
}, {
"input": true,
"tableView": true,
"inputType": "text",
"inputMask": "",
"label": "Last Name",
"key": "lastName",
"placeholder": "",
"prefix": "",
"suffix": "",
"multiple": false,
"defaultValue": "",
"protected": false,
"unique": false,
"persistent": true,
"validate": {
"required": false,
"minLength": "",
"maxLength": "",
"pattern": "",
"custom": "",
"customPrivate": false
},
"conditional": {
"show": "",
"when": null,
"eq": ""
},
"type": "textfield",
"tags": [],
"lockKey": true,
"isNew": false
}, {
"input": true,
"tableView": true,
"inputType": "email",
"label": "Email",
"key": "email",
"placeholder": "Enter your email address",
"prefix": "",
"suffix": "",
"defaultValue": "",
"protected": false,
"unique": false,
"persistent": true,
"kickbox": {
"enabled": false
},
"type": "email",
"lockKey": true,
"isNew": false
}, {
"input": true,
"tableView": true,
"inputMask": "(999) 999-9999",
"label": "Phone Number",
"key": "phoneNumber",
"placeholder": "",
"prefix": "",
"suffix": "",
"multiple": false,
"protected": false,
"unique": false,
"persistent": true,
"defaultValue": "",
"validate": {
"required": false
},
"type": "phoneNumber",
"conditional": {
"eq": "",
"when": null,
"show": ""
},
"tags": [],
"lockKey": true,
"isNew": false
}, {
"input": true,
"label": "Submit",
"tableView": false,
"key": "submit",
"size": "md",
"leftIcon": "",
"rightIcon": "",
"block": false,
"action": "submit",
"disableOnInvalid": false,
"theme": "primary",
"type": "button"
}]
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('_id');
activeFormId = res.body._id;
done();
});
});
it('it should fail to update a form with no admin', function (done) {
chai.request(server)
.put('/v2/forms/'+activeFormId)
.set("Authorization", "Bearer "+jwt)
.send({
"title": "testform2",
})
.end(function (err, res) {
res.should.have.status(403);
res.body.should.have.property('error');
done();
});
});
it('it should update a form', function (done) {
chai.request(server)
.put('/v2/forms/'+activeFormId)
.set("Authorization", "Bearer "+adminJwt)
.send({
"title": "testform2",
})
.end(function (err, res) {
res.should.have.status(200);
res.body.should.have.property('_id');
done();
});
});
it('it should fail to delete a form with no admin', function (done) {
chai.request(server)
.delete('/v2/forms/'+activeFormId)
.set("Authorization", "Bearer "+jwt)
.send({})
.end(function (err, res) {
res.should.have.status(403);
res.body.should.have.property('error');
done();
});
});
it('it should delete a form', function (done) {
chai.request(server)
.delete('/v2/forms/testform')
.set("Authorization", "Bearer "+adminJwt)
.send({})
.end(function (err, res) {
res.should.have.status(200);
expect(res.body).to.equal("OK");
done();
});
});
});
});
| 37.78346 | 105 | 0.397316 |
431d1b25aec6dbb85839fa5e81e7ea8542bd2279 | 3,337 | js | JavaScript | components/public/SubHeader.js | NCR-Corporation/ncr-retail-demo | 21d4e05defb94a53a4ac69ca7caa5daf68b6e468 | [
"Apache-2.0"
] | 9 | 2021-01-29T21:31:23.000Z | 2022-02-10T01:55:29.000Z | components/public/SubHeader.js | NCR-Corporation/ncr-retail-demo | 21d4e05defb94a53a4ac69ca7caa5daf68b6e468 | [
"Apache-2.0"
] | 31 | 2021-01-08T16:12:53.000Z | 2021-09-20T12:43:49.000Z | components/public/SubHeader.js | NCR-Corporation/ncr-retail-demo | 21d4e05defb94a53a4ac69ca7caa5daf68b6e468 | [
"Apache-2.0"
] | 3 | 2021-02-06T03:44:13.000Z | 2021-07-27T17:02:19.000Z | import { useState } from 'react';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faStore } from '@fortawesome/free-solid-svg-icons';
import { Container, Collapse, Navbar, NavbarToggler, Nav, NavItem, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
const SubHeader = ({ data, userStore, setIsModalOpen, isLoading, isError }) => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);
return (
<Container className="py-2 bg-white">
<Navbar expand="md" className="p-0 subheader-navbar" light color="faded">
<NavbarToggler onClick={toggle} />
<Collapse isOpen={isOpen} navbar>
{!isError && (
<Nav navbar>
<NavItem>
<Link href="/catalog">
<a className="pl-0 nav-link">All Items</a>
</Link>
</NavItem>
{!isLoading &&
!isError &&
data &&
data.categories &&
data.categories.length > 0 &&
data.categories.map((category) => {
let children = category.children;
delete children['array'];
if (Object.keys(children).length > 0) {
return (
<UncontrolledDropdown nav inNavbar key={category.nodeCode}>
<DropdownToggle nav caret>
{category.title.value}
</DropdownToggle>
<DropdownMenu right>
{/* <Row>
<Col sm={12} md={4}> */}
{Object.keys(children).map((child) => (
<Link key={children[child].nodeCode} href={`/category/${children[child].nodeCode}`}>
<DropdownItem>{children[child].title.value}</DropdownItem>
</Link>
))}
{/* </Col>
</Row> */}
</DropdownMenu>
</UncontrolledDropdown>
);
}
return (
<UncontrolledDropdown nav inNavbar key={category.nodeCode}>
<DropdownToggle nav>
<Link href={`/category/${category.nodeCode}`}>
<a className="text-darker">{category.title.value}</a>
</Link>
</DropdownToggle>
</UncontrolledDropdown>
);
})}
</Nav>
)}
<Nav className="ml-auto" navbar>
<UncontrolledDropdown nav inNavbar>
<DropdownToggle nav caret suppressHydrationWarning>
<FontAwesomeIcon icon={faStore} /> {userStore != undefined ? userStore.siteName : 'Set Store'}
</DropdownToggle>
<DropdownMenu right>
<DropdownItem onClick={() => setIsModalOpen(true)}>Change Store</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</Nav>
</Collapse>
</Navbar>
</Container>
);
};
export default SubHeader;
| 41.7125 | 152 | 0.478274 |
431dfdf8d7c82ce4e550c22b060eebff0205269a | 1,670 | js | JavaScript | packages/cli/src/logger.js | sichangi/carbon | fba393b13012ce3e189568074efa08968dfb9668 | [
"Apache-2.0"
] | 3 | 2018-07-10T18:59:02.000Z | 2019-01-26T16:19:00.000Z | packages/cli/src/logger.js | sichangi/carbon | fba393b13012ce3e189568074efa08968dfb9668 | [
"Apache-2.0"
] | 1 | 2019-12-04T02:46:46.000Z | 2019-12-07T03:33:59.000Z | packages/cli/src/logger.js | sichangi/carbon | fba393b13012ce3e189568074efa08968dfb9668 | [
"Apache-2.0"
] | 1 | 2021-03-10T04:01:44.000Z | 2021-03-10T04:01:44.000Z | /**
* Copyright IBM Corp. 2019, 2019
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
/**
* Create a logger to be used in a handler. This is typically just for
* formatting the output, adding a prefix, and connecting the output with
* box-drawing ASCII characters.
* @returns {object}
*/
function createLogger(command) {
let start;
/**
* Display the given message with a box character. This also includes
* formatting for the logger prefix and box character itself.
* @param {string} boxCharacter
* @param {string?} message
* @returns {void}
*/
function log(boxCharacter, message = '') {
console.log(chalk`{yellow ${command} ▐} {gray ${boxCharacter}} ${message}`);
}
return {
info(message) {
log('┣', chalk.gray(message));
},
start(message) {
start = Date.now();
log('┏', message);
},
stop(message) {
const duration = ((Date.now() - start) / 1000).toFixed(2);
if (message) {
log('┗', message);
} else {
log('┗', chalk`{gray Done in {italic ${duration}s}}`);
}
},
newline() {
log('┃');
},
};
}
/**
* Display the banner in the console, typically at the beginning of a handler
* @returns {void}
*/
function displayBanner() {
console.log(`
_
| |
___ __ _ _ __| |__ ___ _ __
/ __/ _\` | '__| '_ \\ / _ \\| '_ \\
| (_| (_| | | | |_) | (_) | | | |
\\___\\__,_|_| |_.__/ \\___/|_| |_|
`);
}
module.exports = {
createLogger,
displayBanner,
};
| 22.567568 | 80 | 0.567665 |
431e6bbde95205ee878e62942f1702a927e612be | 3,674 | js | JavaScript | tasks/elm/module.js | jigargosar/elm-simple-gtd | bcc437c08b1ba03c376f78ad678493d0a3c914ee | [
"MIT"
] | 24 | 2017-03-23T12:02:07.000Z | 2021-10-22T03:21:58.000Z | tasks/elm/module.js | jigargosar/elm-simple-gtd | bcc437c08b1ba03c376f78ad678493d0a3c914ee | [
"MIT"
] | 4 | 2017-07-05T10:16:37.000Z | 2019-08-08T02:45:36.000Z | tasks/elm/module.js | jigargosar/elm-simple-gtd | bcc437c08b1ba03c376f78ad678493d0a3c914ee | [
"MIT"
] | 2 | 2017-04-02T20:45:05.000Z | 2021-03-19T13:30:36.000Z | import * as _ from "ramda"
import {run} from "runjs"
import assert from "assert"
import fs from "fs"
function parseModuleName(line) {
const match = _.match(/^(?:port )?module ((?:\w|\.)+)/)(line)
if (!match[1]) throw new Error(`Elm module name parse error in line: "${line}"`)
return match[1]
}
// tests
assert.equal("aSomePortMod.a.x", parseModuleName("port module aSomePortMod.a.x e"))
assert.equal("Colors.a.x", parseModuleName("module Colors.a.x e"))
const getParentModuleName =
_.compose(
_.join("."),
_.init,
_.split("."),
)
export function Module(fileName) {
// const lines = _.split("\n")(run("cat " + fileName, {stdio: 'pipe'}))
const lines = _.split("\n")(fs.readFileSync(fileName, {encoding: "UTF-8"}))
const moduleName = parseModuleName(lines[0])
// console.log("moduleName =", moduleName)
const imports = _.compose(
_.map(_.nth(1)),
_.reject(_.isEmpty),
_.map(_.match(/^import ((?:\w|\.)+)/)),
)(lines)
// console.log("imports =", imports)
// console.log(_.take(5, lines))
const parentModuleName = getParentModuleName(moduleName)
return {fileName, moduleName, parentModuleName ,imports, importsCount:_.length(imports)}
}
const addTransitiveDependencies = moduleMap => {
// console.log(moduleMap)
function getImportsOfModule(moduleName) {
const module = moduleMap[moduleName]
return module ? module.imports : []
}
const getTransitiveImports = _.memoize(function (moduleName) {
// console.log(moduleName)
const moduleImports = getImportsOfModule(moduleName)
return _.compose(
_.uniq,
_.sortBy(_.identity),
_.concat(moduleImports),
_.flatten
, _.map(getTransitiveImports),
)(moduleImports)
})
return _.map((module) => {
// const dependencies = _.pick(module.imports)(moduleMap)
const transitiveImports = getTransitiveImports(module.moduleName)
return _.merge(module, {
transitiveImports,
transitiveImportsCount:_.length(transitiveImports),
// dependencies,
// dependenciesCount: _.compose(_.length, _.values)(dependencies)
})
})(moduleMap)
}
function addBackwardDependencies(moduleMap) {
function getBackwardDependencies(moduleName) {
return _.filter(_.compose(
_.contains(moduleName),
_.prop("imports"),
))(moduleMap)
}
const getBackwardImports = _.compose(_.keys,getBackwardDependencies)
const getTransitiveBackwardImports = _.memoize(function (moduleName) {
const dependentModuleNames = _.compose(
_.keys,
getBackwardDependencies,
)(moduleName)
return _.compose(
_.uniq,
_.sortBy(_.identity),
_.flatten,
_.concat(dependentModuleNames),
_.map(getTransitiveBackwardImports)
)(dependentModuleNames)
}
)
return _.map(module => {
// const backwardDependencies = getBackwardDependencies(module.moduleName)
const transitiveBackwardImports = getTransitiveBackwardImports(module.moduleName)
const backwardImports = getBackwardImports(module.moduleName)
return _.merge(module, {
// backwardDependencies,
// backwardDependenciesCount:_.compose(_.length, _.values)(backwardDependencies),
backwardImports,
backwardImportsCount:_.length(backwardImports),
transitiveBackwardImports,
transitiveBackwardImportsCount:_.length(transitiveBackwardImports)
})
})(moduleMap)
}
export function Modules(moduleList) {
const moduleMap = _.zipObj(_.map(_.prop("moduleName"))(moduleList), moduleList)
return addBackwardDependencies(addTransitiveDependencies(moduleMap))
}
| 29.629032 | 90 | 0.67828 |
431f2b6e15e13505492806a52b9c3cac6ebbc1e9 | 466 | js | JavaScript | js/views/aboutDatasetMenu.js | ani4aniket/ucsc-xena-client | 8eff032390c49e17fab892d03591bf6b53bdca3d | [
"Apache-2.0"
] | 60 | 2017-01-18T00:51:24.000Z | 2022-02-16T11:06:08.000Z | js/views/aboutDatasetMenu.js | ani4aniket/ucsc-xena-client | 8eff032390c49e17fab892d03591bf6b53bdca3d | [
"Apache-2.0"
] | 407 | 2016-03-04T23:11:29.000Z | 2022-03-18T07:27:10.000Z | js/views/aboutDatasetMenu.js | ani4aniket/ucsc-xena-client | 8eff032390c49e17fab892d03591bf6b53bdca3d | [
"Apache-2.0"
] | 60 | 2017-03-02T15:19:48.000Z | 2021-01-19T09:39:46.000Z | var React = require('react');
import {MenuItem} from 'react-toolbox/lib/menu';
var {parseDsID} = require('../xenaQuery');
var getAbout = (onClick, dsID, root, text) => {
var [host, dataset] = parseDsID(dsID);
return <MenuItem key='about' onClick={ev => onClick(ev, host, dataset)} caption={text}/>;
};
function aboutDatasetMenu(onClick, dsID, root = '..') {
return dsID ? getAbout(onClick, dsID, root, 'About') : null;
}
module.exports = aboutDatasetMenu;
| 29.125 | 90 | 0.67382 |
4320707c3e64e838515c4d285566efe6d96b28c4 | 3,538 | js | JavaScript | src/components/containers/MainScreen.js | Rogozin-high-school/werewolf_portable | bb2871898381a34166372e78a639281db535f2ed | [
"MIT"
] | 1 | 2020-06-03T10:18:10.000Z | 2020-06-03T10:18:10.000Z | src/components/containers/MainScreen.js | Rogozin-high-school/werewolf_portable | bb2871898381a34166372e78a639281db535f2ed | [
"MIT"
] | 9 | 2021-03-26T22:55:52.000Z | 2021-07-05T08:37:03.000Z | src/components/containers/MainScreen.js | Rogozin-high-school/werewolf_portable | bb2871898381a34166372e78a639281db535f2ed | [
"MIT"
] | 1 | 2021-06-28T12:36:04.000Z | 2021-06-28T12:36:04.000Z | import React, { Component } from "react";
import { connect } from "react-redux";
import { moveTo } from "../../actions/PagesActions";
import * as multiplayer from "../../multiplayer";
import { getNickname } from "../../auth/Profile";
import logo from "../../asset/img/logo.jpg";
class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {
join_loading: false,
join_error: null,
create_loading: false,
create_error: null,
partyId: "",
};
this.updatePartyId = this.updatePartyId.bind(this);
this.joinParty = this.joinParty.bind(this);
this.createParty = this.createParty.bind(this);
this.partyNotFound = this.partyNotFound.bind(this);
this.createPartyError = this.createPartyError.bind(this);
}
updatePartyId(event) {
this.setState({
partyId: event.target.value,
});
}
joinParty() {
if (getNickname() == "") {
this.props.moveTo("profile");
return;
}
this.setState({
join_loading: true,
join_error: null,
});
window.onJoinError = (err) => {
this.setState({
join_loading: false,
join_error: err,
});
};
multiplayer.joinRoom(this.state.partyId);
}
partyNotFound() {
this.setState({
join_loading: false,
join_error: "Party not found",
});
}
createParty() {
if (getNickname() == "") {
this.props.moveTo("profile");
return;
}
this.setState({
create_loading: true,
create_error: null,
});
multiplayer.createRoom();
}
createPartyError() {
this.setState({
create_loading: false,
create_error: "Error creating a party",
});
}
renderError(err) {
if (err) {
return (
<div>
<br />
<div>{err}</div>
<br />
</div>
);
} else {
return (
<div>
<br />
<br />
<br />
</div>
);
}
}
render() {
const { join_loading } = this.state;
return (
<div>
<div style={{ width: "100%", textAlign: "center" }}>
<img src={logo} style={{ height: "30vh" }} />
<div className="ui divider"></div>
<h1>Join a party</h1>
<div className={"ui icon input" + (join_loading ? " loading" : "")}>
<input
type="number"
placeholder="Party ID..."
value={this.state.partyId}
onChange={this.updatePartyId}
/>
<i className="play link icon" onClick={this.joinParty}></i>
</div>
{this.renderError(this.state.join_error)}
or
<h1>Create a party</h1>
<button
className={
"ui button" + (this.state.create_loading ? " loading" : "")
}
onClick={this.createParty}
>
Create new party
</button>
{this.renderError(this.state.create_error)}
</div>
<div
style={{
position: "fixed",
right: 0,
top: 0,
marginTop: ".5em",
fontSize: "2em",
}}
>
<i
className="cog link icon"
onClick={() => this.props.moveTo("profile")}
></i>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
join_loading: state.auth.login,
};
};
export default connect(mapStateToProps, { moveTo })(MainScreen);
| 21.975155 | 78 | 0.510458 |
4320bcd30afe5b41949ffe3530783339e6a0649c | 1,193 | js | JavaScript | server/node_modules/@carbon/icons-react/es/scalpel/20.js | Gelvazio/megahack5 | 66bf43957c1a922099f03ccd3aee891e315f6aaf | [
"MIT"
] | null | null | null | server/node_modules/@carbon/icons-react/es/scalpel/20.js | Gelvazio/megahack5 | 66bf43957c1a922099f03ccd3aee891e315f6aaf | [
"MIT"
] | null | null | null | server/node_modules/@carbon/icons-react/es/scalpel/20.js | Gelvazio/megahack5 | 66bf43957c1a922099f03ccd3aee891e315f6aaf | [
"MIT"
] | null | null | null | /**
* Copyright IBM Corp. 2019, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* Code generated by @carbon/icon-build-helpers. DO NOT EDIT.
*/
import { _ as _objectWithoutProperties, I as Icon, a as _extends } from '../Icon-882b0ed1.js';
import React from 'react';
import '@carbon/icon-helpers';
import 'prop-types';
var _path;
var Scalpel20 = /*#__PURE__*/React.forwardRef(function Scalpel20(_ref, ref) {
var children = _ref.children,
rest = _objectWithoutProperties(_ref, ["children"]);
return /*#__PURE__*/React.createElement(Icon, _extends({
width: 20,
height: 20,
viewBox: "0 0 32 32",
xmlns: "http://www.w3.org/2000/svg",
fill: "currentColor",
ref: ref
}, rest), _path || (_path = /*#__PURE__*/React.createElement("path", {
d: "M28.83,5.17a4.1,4.1,0,0,0-5.66,0L.34,28H9.59a5,5,0,0,0,3.53-1.46L28.83,10.83a4,4,0,0,0,0-5.66ZM12.29,18.88l2.09-2.09,2.83,2.83-2.09,2.09Zm-.58,6.24A3,3,0,0,1,9.59,26H5.17l5.71-5.71,2.83,2.83ZM27.41,9.41l-8.79,8.8-2.83-2.83,8.8-8.79a2,2,0,0,1,2.82,0,2,2,0,0,1,0,2.82Z"
})), children);
});
export default Scalpel20;
| 37.28125 | 275 | 0.663873 |
4320c33857a7f766dd6eddae78f86a959a7addb5 | 1,384 | js | JavaScript | src/templates/home.js | venhrun-petro/test | 7b8e478ee1fb3969eb7917d19173f309e26aa77d | [
"MIT"
] | null | null | null | src/templates/home.js | venhrun-petro/test | 7b8e478ee1fb3969eb7917d19173f309e26aa77d | [
"MIT"
] | null | null | null | src/templates/home.js | venhrun-petro/test | 7b8e478ee1fb3969eb7917d19173f309e26aa77d | [
"MIT"
] | null | null | null | import React from "react"
import PropTypes from "prop-types"
import { graphql } from "gatsby"
import Layout from "~c/layout/layout"
import SEO from "~c/includes/seo"
import Teaser from "~c/sections/Teaser"
import About from "~c/sections/About"
import Slider from "~c/Slider"
import Contact from "~c/sections/Contact"
import useLanguageKey from '~h/useLanguageKey'
import { useDispatch, useSelector } from 'react-redux'
const HomePage = ({
data: {
markdownRemark: {
fields: { langKey },
frontmatter: { metaTitle, metaDescription }
},
},
}) => {
const state = useSelector(props => props);
const dispatch = useDispatch();
useLanguageKey(dispatch, langKey);
return (
<Layout>
<SEO title={metaTitle} description={metaDescription} />
<Teaser />
{/* <Slider />
<About />
<Contact /> */}
</Layout>
)
}
HomePage.propTypes = {
data: PropTypes.shape({
markdownRemark: PropTypes.shape({
frontmatter: PropTypes.object,
}),
}),
}
export default HomePage
export const pageQuery = graphql`
query HomePage($langKey: String!) {
markdownRemark(
fields: { langKey: { eq: $langKey } }
frontmatter: { templateKey: { eq: "home" } }
) {
fields {
langKey
}
frontmatter {
templateKey
metaTitle
metaDescription
}
}
}
`
| 20.352941 | 61 | 0.618497 |
4320e8e0904c27b35a8516ed35d7d5c60197dd64 | 11,567 | js | JavaScript | jquery.input-tags.min.js | lzp9421/jQuery-inputTags | b83fbc5d27a856fe44f0f99e7fb596119fbbf59c | [
"MIT"
] | null | null | null | jquery.input-tags.min.js | lzp9421/jQuery-inputTags | b83fbc5d27a856fe44f0f99e7fb596119fbbf59c | [
"MIT"
] | null | null | null | jquery.input-tags.min.js | lzp9421/jQuery-inputTags | b83fbc5d27a856fe44f0f99e7fb596119fbbf59c | [
"MIT"
] | null | null | null |
!function(a){a.fn.tagEditorInput=function(){var c=" ",f=a(this),g=parseInt(f.css("fontSize")),b=a("<span/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:f.css("fontSize"),fontFamily:f.css("fontFamily"),fontWeight:f.css("fontWeight"),letterSpacing:f.css("letterSpacing"),whiteSpace:"nowrap"}),d=function(){if(c!==(c=f.val())){b.text(c);var e=b.width()+g;20>e&&(e=20),e!=f.width()&&f.width(e)}};return b.insertAfter(f),f.bind("keyup keydown focus",d)};a.fn.tagEditor=function(d,j,h){function e(k){return k.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var g,f=a.extend({},a.fn.tagEditor.defaults,d),b=this;f.dregex=new RegExp("["+f.delimiter.replace("-","-")+"]","g");if(typeof d=="string"){var c=[];b.each(function(){var l=a(this),m=l.data("options"),k=l.next(".tag-editor");if(d=="getTags"){c.push({field:l[0],editor:k,tags:k.data("tags")})}else{if(d=="addTag"){if(m.maxTags&&k.data("tags").length>=m.maxTags){return false}a('<li><div class="tag-editor-spacer"> '+m.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>').appendTo(k).find(".tag-editor-tag").html('<input type="text" maxlength="'+m.maxLength+'">').addClass("active").find("input").val(j).blur();if(!h){k.click()}else{a(".placeholder",k).remove()}}else{if(d=="removeTag"){a(".tag-editor-tag",k).filter(function(){return a(this).text()==j}).closest("li").find(".tag-editor-delete").click();if(!h){k.click()}}else{if(d=="destroy"){l.removeClass("tag-editor-hidden-src").removeData("options").off("focus.tag-editor").next(".tag-editor").remove()}}}}});return d=="getTags"?c:this}if(window.getSelection){a(document).off("keydown.tag-editor").on("keydown.tag-editor",function(p){if(p.which==8||p.which==46||p.ctrlKey&&p.which==88){try{var n=getSelection(),m=document.activeElement.tagName=="BODY"?a(n.getRangeAt(0).startContainer.parentNode).closest(".tag-editor"):0}catch(p){m=0}if(n.rangeCount>0&&m&&m.length){var l=[],o=n.toString().split(m.prev().data("options").dregex);for(i=0;i<o.length;i++){var k=a.trim(o[i]);if(k){l.push(k)}}a(".tag-editor-tag",m).each(function(){if(~a.inArray(a(this).text(),l)){a(this).closest("li").find(".tag-editor-delete").click()}});return false}}})}return b.each(function(){var l=a(this),t=[];var q=a("<ul "+(f.clickDelete?'oncontextmenu="return false;" ':"")+'class="tag-editor"></ul>').insertAfter(l);l.addClass("tag-editor-hidden-src").data("options",f).on("focus.tag-editor",function(){q.click()});q.append('<li style="width:1px"> </li>');var o='<li><div class="tag-editor-spacer"> '+f.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>';function m(){if(f.placeholder&&!t.length&&!a(".deleted, .placeholder, input",q).length){q.append('<li class="placeholder"><div>'+f.placeholder+"</div></li>")}}function s(x){var w=t.toString();t=a(".tag-editor-tag:not(.deleted)",q).map(function(y,z){var A=a.trim(a(this).hasClass("active")?a(this).find("input").val():a(z).text());if(A){return A}}).get();q.data("tags",t);l.val(t.join(f.delimiter[0]));if(!x){if(w!=t.toString()){f.onChange(l,q,t)}}m()}q.click(function(x,w){var A,z=99999,y;if(window.getSelection&&getSelection()!=""){return}if(f.maxTags&&q.data("tags").length>=f.maxTags){q.find("input").blur();return false}g=true;a("input:focus",q).blur();if(!g){return false}g=true;a(".placeholder",q).remove();if(w&&w.length){y="before"}else{a(".tag-editor-tag",q).each(function(){var B=a(this),E=B.offset(),D=E.left,C=E.top;if(x.pageY>=C&&x.pageY<=C+B.height()){if(x.pageX<D){y="before",A=D-x.pageX}else{y="after",A=x.pageX-D-B.width()}if(A<z){z=A,w=B}}})}if(y=="before"){a(o).insertBefore(w.closest("li")).find(".tag-editor-tag").click()}else{if(y=="after"){a(o).insertAfter(w.closest("li")).find(".tag-editor-tag").click()}else{a(o).appendTo(q).find(".tag-editor-tag").click()}}return false});q.on("click",".tag-editor-delete",function(y){if(a(this).prev().hasClass("active")){a(this).closest("li").find("input").caret(-1);return false}var x=a(this).closest("li"),w=x.find(".tag-editor-tag");if(f.beforeTagDelete(l,q,t,w.text())===false){return false}w.addClass("deleted").animate({width:0},f.animateDelete,function(){x.remove();m()});s();return false});if(f.clickDelete){q.on("mousedown",".tag-editor-tag",function(y){if(y.ctrlKey||y.which>1){var x=a(this).closest("li"),w=x.find(".tag-editor-tag");if(f.beforeTagDelete(l,q,t,w.text())===false){return false}w.addClass("deleted").animate({width:0},f.animateDelete,function(){x.remove();m()});s();return false}})}q.on("click",".tag-editor-tag",function(C){if(f.clickDelete&&(C.ctrlKey||C.which>1)){return false}if(!a(this).hasClass("active")){var y=a(this).text();var B=Math.abs((a(this).offset().left-C.pageX)/a(this).width()),x=parseInt(y.length*B),z=a(this).html('<input type="text" maxlength="'+f.maxLength+'" value="'+e(y)+'">').addClass("active").find("input");z.data("old_tag",y).tagEditorInput().focus().caret(x);if(f.autocomplete){var A=a.extend({},f.autocomplete);var w="select" in A?f.autocomplete.select:"";A.select=function(E,D){if(w){w(E,D)}setTimeout(function(){q.trigger("click",[a(".active",q).find("input").closest("li").next("li").find(".tag-editor-tag")])},20)};z.autocomplete(A)}}return false});function k(y){var w=y.closest("li"),C=y.val().replace(/ +/," ").split(f.dregex),B=y.data("old_tag"),x=t.slice(0),D=false,A;for(var z=0;z<C.length;z++){u=a.trim(C[z]).slice(0,f.maxLength);if(f.forceLowercase){u=u.toLowerCase()}A=f.beforeTagSave(l,q,x,B,u);u=A||u;if(A===false||!u){continue}if(f.removeDuplicates&&~a.inArray(u,x)){a(".tag-editor-tag",q).each(function(){if(a(this).text()==u){a(this).closest("li").remove()}})}x.push(u);w.before('<li><div class="tag-editor-spacer"> '+f.delimiter[0]+'</div><div class="tag-editor-tag">'+e(u)+'</div><div class="tag-editor-delete"><i></i></div></li>');if(f.maxTags&&x.length>=f.maxTags){D=true;break}}y.attr("maxlength",f.maxLength).removeData("old_tag").val("");if(D){y.blur()}else{y.focus()}s()}q.on("blur","input",function(z){z.stopPropagation();var x=a(this),y=x.data("old_tag"),w=a.trim(x.val().replace(/ +/," ").replace(f.dregex,f.delimiter[0]));if(!w){if(y&&f.beforeTagDelete(l,q,t,y)===false){x.val(y).focus();g=false;s();return}try{x.closest("li").remove()}catch(z){}if(y){s()}}else{if(w.indexOf(f.delimiter[0])>=0){k(x);return}else{if(w!=y){if(f.forceLowercase){w=w.toLowerCase()}cb_val=f.beforeTagSave(l,q,t,y,w);w=cb_val||w;if(cb_val===false){if(y){x.val(y).focus();g=false;s();return}try{x.closest("li").remove()}catch(z){}if(y){s()}}else{if(f.removeDuplicates){a(".tag-editor-tag:not(.active)",q).each(function(){if(a(this).text()==w){a(this).closest("li").remove()}})}}}}}x.parent().html(e(w)).removeClass("active");if(w!=y){s()}m()});var p;q.on("paste","input",function(w){a(this).removeAttr("maxlength");p=a(this);setTimeout(function(){k(p)},30)});var r;q.on("keypress","input",function(w){if(f.delimiter.indexOf(String.fromCharCode(w.which))>=0){r=a(this);setTimeout(function(){k(r)},20)}});q.on("keydown","input",function(w){var z=a(this);if((w.which==37||!f.autocomplete&&w.which==38)&&!z.caret()||w.which==8&&!z.val()){var y=z.closest("li").prev("li").find(".tag-editor-tag");if(y.length){y.click().find("input").caret(-1)}else{if(z.val()&&!(f.maxTags&&q.data("tags").length>=f.maxTags)){a(o).insertBefore(z.closest("li")).find(".tag-editor-tag").click()}}return false}else{if((w.which==39||!f.autocomplete&&w.which==40)&&(z.caret()==z.val().length)){var x=z.closest("li").next("li").find(".tag-editor-tag");if(x.length){x.click().find("input").caret(0)}else{if(z.val()){q.click()}}return false}else{if(w.which==9){if(w.shiftKey){var y=z.closest("li").prev("li").find(".tag-editor-tag");if(y.length){y.click().find("input").caret(0)}else{if(z.val()&&!(f.maxTags&&q.data("tags").length>=f.maxTags)){a(o).insertBefore(z.closest("li")).find(".tag-editor-tag").click()}else{l.attr("disabled","disabled");setTimeout(function(){l.removeAttr("disabled")},30);return}}return false}else{var x=z.closest("li").next("li").find(".tag-editor-tag");if(x.length){x.click().find("input").caret(0)}else{if(z.val()){q.click()}else{return}}return false}}else{if(w.which==46&&(!a.trim(z.val())||(z.caret()==z.val().length))){var x=z.closest("li").next("li").find(".tag-editor-tag");if(x.length){x.click().find("input").caret(0)}else{if(z.val()){q.click()}}return false}else{if(w.which==13){q.trigger("click",[z.closest("li").next("li").find(".tag-editor-tag")]);if(f.maxTags&&q.data("tags").length>=f.maxTags){q.find("input").blur()}return false}else{if(w.which==36&&!z.caret()){q.find(".tag-editor-tag").first().click()}else{if(w.which==35&&z.caret()==z.val().length){q.find(".tag-editor-tag").last().click()}else{if(w.which==27){z.val(z.data("old_tag")?z.data("old_tag"):"").blur();return false}}}}}}}}});var v=f.initialTags.length?f.initialTags:l.val().split(f.dregex);for(var n=0;n<v.length;n++){if(f.maxTags&&n>=f.maxTags){break}var u=a.trim(v[n].replace(/ +/," "));if(u){if(f.forceLowercase){u=u.toLowerCase()}t.push(u);q.append('<li><div class="tag-editor-spacer"> '+f.delimiter[0]+'</div><div class="tag-editor-tag">'+e(u)+'</div><div class="tag-editor-delete"><i></i></div></li>')}}s(true);if(f.sortable&&a.fn.sortable){q.sortable({distance:5,cancel:".tag-editor-spacer, input",helper:"clone",update:function(){s()}})}})};a.fn.tagEditor.defaults={initialTags:[],maxTags:0,maxLength:50,delimiter:",;",placeholder:"",forceLowercase:true,removeDuplicates:true,clickDelete:false,animateDelete:175,sortable:true,autocomplete:null,onChange:function(){},beforeTagSave:function(){},beforeTagDelete:function(){}};Array.prototype.each=function(f){f=f||Function.K;var b=[];var c=Array.prototype.slice.call(arguments,1);for(var e=0;e<this.length;e++){var d=f.apply(this,[this[e],e].concat(c));if(d!==null){b.push(d)}}return b};Array.prototype.contains=function(c){for(var b=0;b<this.length;b++){if(this[b]===c){return true}}return false};Array.prototype.uniquelize=function(){var c=new Array();for(var b=0;b<this.length;b++){if(!c.contains(this[b])){c.push(this[b])}}return c};Array.complement=function(d,c){return Array.minus(Array.union(d,c),Array.intersect(d,c))};Array.intersect=function(d,c){return d.uniquelize().each(function(b){return c.contains(b)?b:null})};Array.minus=function(d,c){return d.uniquelize().each(function(b){return c.contains(b)?null:b})};Array.union=function(d,c){return d.concat(c).uniquelize()};a.extend({inputTags:function(m,c,e){var h=a("#"+m.inputId);var b=a("#"+m.panelId);var g=m.selectedTags||[];var l=m.allTags||[];var f=m.beforeTagSave;var k=m.beforeTagDelete;delete m.inputId;delete m.panelId;delete m.selectedTags;delete m.allTags;var d=function(r,q,n){var p=r.find("span:contains("+q+")");p.each(function(o,s){if(a(s).text()===q){a(s).siblings('input[type="checkbox"]').prop("checked",n)}})};m.beforeTagSave=function(q,p,o,n,r){n&&d(b,n,false);r&&d(b,r,true);f&&f(q,p,o,r)};m.beforeTagDelete=function(p,o,n,q){d(b,q,false);k&&k(p,o,n,q)};m.initialTags=g=Array.intersect(g,l);h.tagEditor(m,c,e);var j=function(p){var n;for(var q=0;q<p.length;q++){n=p[q];var o=a("<label>").attr("for","label-"+q);var s=a("<input>").attr("type","checkbox").attr("id","label-"+q).css("display","none");var r=a("<span>").addClass("label label-info").text(n);b.append(o.append(s,r))}};j(l);b.find('input[type="checkbox"]').on("change",function(){var n=a(this).siblings("span").text();if(a(this).is(":checked")){h.tagEditor("addTag",n)}else{h.tagEditor("removeTag",n)}})}})}(jQuery); | 5,783.5 | 11,566 | 0.665082 |
43224d5b970ce158481740c5f52dd8a8ff406aaa | 1,971 | js | JavaScript | packages/bundle/src/adaptiveCards/Attachment/AnimationCardAttachment.js | dearbornlavern/BotFramework-WebChat | 18b063ea0f3cbde72b0381777881f1701f0ddb5d | [
"MIT"
] | null | null | null | packages/bundle/src/adaptiveCards/Attachment/AnimationCardAttachment.js | dearbornlavern/BotFramework-WebChat | 18b063ea0f3cbde72b0381777881f1701f0ddb5d | [
"MIT"
] | null | null | null | packages/bundle/src/adaptiveCards/Attachment/AnimationCardAttachment.js | dearbornlavern/BotFramework-WebChat | 18b063ea0f3cbde72b0381777881f1701f0ddb5d | [
"MIT"
] | null | null | null | /* eslint react/no-array-index-key: "off" */
import { Components, connectToWebChat } from 'botframework-webchat-component';
import memoize from 'memoize-one';
import PropTypes from 'prop-types';
import React from 'react';
import { AdaptiveCardBuilder } from './AdaptiveCardBuilder';
import CommonCard from './CommonCard';
const { ImageContent, VideoContent } = Components;
class AnimationCardAttachment extends React.Component {
constructor(props) {
super(props);
this.buildCard = memoize((adaptiveCards, content) => {
const builder = new AdaptiveCardBuilder(adaptiveCards);
(content.images || []).forEach(image => builder.addImage(image.url, null, image.tap));
builder.addCommon(content);
return builder.card;
});
}
render() {
const { adaptiveCards, attachment, attachment: { content: { media = [] } = {} } = {}, styleSet } = this.props;
return (
<div className={styleSet.animationCardAttachment}>
<ul className="media-list">
{media.map(({ profile = '', url }, index) => (
<li key={index}>
{/\.gif$/iu.test(url) ? (
<ImageContent alt={profile} src={url} />
) : (
<VideoContent alt={profile} src={url} />
)}
</li>
))}
</ul>
<CommonCard adaptiveCards={adaptiveCards} attachment={attachment} />
</div>
);
}
}
AnimationCardAttachment.propTypes = {
adaptiveCards: PropTypes.any.isRequired,
attachment: PropTypes.shape({
content: PropTypes.shape({
media: PropTypes.arrayOf(
PropTypes.shape({
profile: PropTypes.string,
url: PropTypes.string.isRequired
})
).isRequired
}).isRequired
}).isRequired,
styleSet: PropTypes.shape({
animationCardAttachment: PropTypes.any.isRequired
}).isRequired
};
export default connectToWebChat(({ styleSet }) => ({ styleSet }))(AnimationCardAttachment);
| 28.985294 | 114 | 0.621512 |
432255fb50fa4faea83ea33dc7a18344cb2d90a1 | 2,418 | js | JavaScript | src/background/WindowBuilder.js | geovannimp/beekeeper-studio | ac991c296d494accc825b59b29fa5a89f50e38e4 | [
"MIT"
] | null | null | null | src/background/WindowBuilder.js | geovannimp/beekeeper-studio | ac991c296d494accc825b59b29fa5a89f50e38e4 | [
"MIT"
] | null | null | null | src/background/WindowBuilder.js | geovannimp/beekeeper-studio | ac991c296d494accc825b59b29fa5a89f50e38e4 | [
"MIT"
] | null | null | null | import _ from 'lodash'
import path from 'path'
import { BrowserWindow } from "electron"
import { createProtocol } from "vue-cli-plugin-electron-builder/lib"
import platformInfo from '../common/platform_info'
import NativeMenuActionHandlers from './NativeMenuActionHandlers'
const windows = []
function getIcon() {
const iconPrefix = platformInfo.environment === 'development' ? 'public' : ''
return path.resolve(path.join(__dirname, '..', `${iconPrefix}/icons/png/512x512.png`))
}
class BeekeeperWindow {
active = true
win = null
actionHandler = null
reloaded = false
get webContents() {
return this.win ? this.win.webContents : null
}
constructor(settings) {
const theme = settings.theme
const showFrame = settings.menuStyle && settings.menuStyle.value == 'native' ? true : false
this.settings = settings
this.actionHandler = new NativeMenuActionHandlers(this.settings)
this.win = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
backgroundColor: theme.value === 'dark' ? "#252525" : '#ffffff',
titleBarStyle: 'hidden',
frame: showFrame,
webPreferences: {
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
},
icon: getIcon()
})
this.win.webContents.zoomLevel = settings.zoomLevel.value || 0
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
this.win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) this.win.webContents.openDevTools();
} else {
createProtocol('app')
// Load the index.html when not in development
this.win.loadURL('app://./index.html')
if (platformInfo.debugEnabled) this.win.webContents.openDevTools();
}
this.initializeCallbacks()
}
initializeCallbacks() {
if (process.env.WEBPACK_DEV_SERVER_URL && platformInfo.isWindows) {
this.win.webContents.on('did-finish-load', this.finishLoadListener.bind(this))
}
this.win.on('closed', () => {
this.win = null
this.active = false
})
}
finishLoadListener() {
if(!this.reloaded) {
this.win.webContents.reload()
}
this.reloaded = true
}
}
export function getActiveWindows() {
return _.filter(windows, 'active')
}
export function buildWindow(settings) {
windows.push(new BeekeeperWindow(settings))
}
| 27.793103 | 95 | 0.677419 |
4322e3a3b511b487c2e89c4d72363a6de02d303a | 7,708 | js | JavaScript | lib/cascader/index.js | wangbaiwang/vant-2.12.25 | 40e7e392acc54e00f50eff329ff473254fb2f1a8 | [
"MIT"
] | null | null | null | lib/cascader/index.js | wangbaiwang/vant-2.12.25 | 40e7e392acc54e00f50eff329ff473254fb2f1a8 | [
"MIT"
] | null | null | null | lib/cascader/index.js | wangbaiwang/vant-2.12.25 | 40e7e392acc54e00f50eff329ff473254fb2f1a8 | [
"MIT"
] | null | null | null | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _utils = require("../utils");
var _tab = _interopRequireDefault(require("../tab"));
var _tabs = _interopRequireDefault(require("../tabs"));
var _icon = _interopRequireDefault(require("../icon"));
var _createNamespace = (0, _utils.createNamespace)('cascader'),
createComponent = _createNamespace[0],
bem = _createNamespace[1],
t = _createNamespace[2];
var _default2 = createComponent({
props: {
title: String,
value: [Number, String],
fieldNames: Object,
placeholder: String,
activeColor: String,
options: {
type: Array,
default: function _default() {
return [];
}
},
closeable: {
type: Boolean,
default: true
}
},
data: function data() {
return {
tabs: [],
activeTab: 0
};
},
computed: {
textKey: function textKey() {
var _this$fieldNames;
return ((_this$fieldNames = this.fieldNames) == null ? void 0 : _this$fieldNames.text) || 'text';
},
valueKey: function valueKey() {
var _this$fieldNames2;
return ((_this$fieldNames2 = this.fieldNames) == null ? void 0 : _this$fieldNames2.value) || 'value';
},
childrenKey: function childrenKey() {
var _this$fieldNames3;
return ((_this$fieldNames3 = this.fieldNames) == null ? void 0 : _this$fieldNames3.children) || 'children';
}
},
watch: {
options: {
deep: true,
handler: 'updateTabs'
},
value: function value(_value) {
var _this = this;
if (_value || _value === 0) {
var values = this.tabs.map(function (tab) {
var _tab$selectedOption;
return (_tab$selectedOption = tab.selectedOption) == null ? void 0 : _tab$selectedOption[_this.valueKey];
});
if (values.indexOf(_value) !== -1) {
return;
}
}
this.updateTabs();
}
},
created: function created() {
this.updateTabs();
},
methods: {
getSelectedOptionsByValue: function getSelectedOptionsByValue(options, value) {
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option[this.valueKey] === value) {
return [option];
}
if (option[this.childrenKey]) {
var selectedOptions = this.getSelectedOptionsByValue(option[this.childrenKey], value);
if (selectedOptions) {
return [option].concat(selectedOptions);
}
}
}
},
updateTabs: function updateTabs() {
var _this2 = this;
if (this.value || this.value === 0) {
var selectedOptions = this.getSelectedOptionsByValue(this.options, this.value);
if (selectedOptions) {
var optionsCursor = this.options;
this.tabs = selectedOptions.map(function (option) {
var tab = {
options: optionsCursor,
selectedOption: option
};
var next = optionsCursor.filter(function (item) {
return item[_this2.valueKey] === option[_this2.valueKey];
});
if (next.length) {
optionsCursor = next[0][_this2.childrenKey];
}
return tab;
});
if (optionsCursor) {
this.tabs.push({
options: optionsCursor,
selectedOption: null
});
}
this.$nextTick(function () {
_this2.activeTab = _this2.tabs.length - 1;
});
return;
}
}
this.tabs = [{
options: this.options,
selectedOption: null
}];
},
onSelect: function onSelect(option, tabIndex) {
var _this3 = this;
this.tabs[tabIndex].selectedOption = option;
if (this.tabs.length > tabIndex + 1) {
this.tabs = this.tabs.slice(0, tabIndex + 1);
}
if (option[this.childrenKey]) {
var nextTab = {
options: option[this.childrenKey],
selectedOption: null
};
if (this.tabs[tabIndex + 1]) {
this.$set(this.tabs, tabIndex + 1, nextTab);
} else {
this.tabs.push(nextTab);
}
this.$nextTick(function () {
_this3.activeTab++;
});
}
var selectedOptions = this.tabs.map(function (tab) {
return tab.selectedOption;
}).filter(function (item) {
return !!item;
});
var eventParams = {
value: option[this.valueKey],
tabIndex: tabIndex,
selectedOptions: selectedOptions
};
this.$emit('input', option[this.valueKey]);
this.$emit('change', eventParams);
if (!option[this.childrenKey]) {
this.$emit('finish', eventParams);
}
},
onClose: function onClose() {
this.$emit('close');
},
renderHeader: function renderHeader() {
var h = this.$createElement;
return h("div", {
"class": bem('header')
}, [h("h2", {
"class": bem('title')
}, [this.slots('title') || this.title]), this.closeable ? h(_icon.default, {
"attrs": {
"name": "cross"
},
"class": bem('close-icon'),
"on": {
"click": this.onClose
}
}) : null]);
},
renderOptions: function renderOptions(options, selectedOption, tabIndex) {
var _this4 = this;
var h = this.$createElement;
var renderOption = function renderOption(option) {
var isSelected = selectedOption && option[_this4.valueKey] === selectedOption[_this4.valueKey];
var Text = _this4.slots('option', {
option: option,
selected: isSelected
}) || h("span", [option[_this4.textKey]]);
return h("li", {
"class": bem('option', {
selected: isSelected
}),
"style": {
color: isSelected ? _this4.activeColor : null
},
"on": {
"click": function click() {
_this4.onSelect(option, tabIndex);
}
}
}, [Text, isSelected ? h(_icon.default, {
"attrs": {
"name": "success"
},
"class": bem('selected-icon')
}) : null]);
};
return h("ul", {
"class": bem('options')
}, [options.map(renderOption)]);
},
renderTab: function renderTab(item, tabIndex) {
var h = this.$createElement;
var options = item.options,
selectedOption = item.selectedOption;
var title = selectedOption ? selectedOption[this.textKey] : this.placeholder || t('select');
return h(_tab.default, {
"attrs": {
"title": title,
"titleClass": bem('tab', {
unselected: !selectedOption
})
}
}, [this.renderOptions(options, selectedOption, tabIndex)]);
},
renderTabs: function renderTabs() {
var _this5 = this;
var h = this.$createElement;
return h(_tabs.default, {
"attrs": {
"animated": true,
"swipeable": true,
"swipeThreshold": 0,
"color": this.activeColor
},
"class": bem('tabs'),
"model": {
value: _this5.activeTab,
callback: function callback($$v) {
_this5.activeTab = $$v;
}
}
}, [this.tabs.map(this.renderTab)]);
}
},
render: function render() {
var h = arguments[0];
return h("div", {
"class": bem()
}, [this.renderHeader(), this.renderTabs()]);
}
});
exports.default = _default2; | 26.67128 | 115 | 0.538012 |
43235b709718191c8a03db9da5d74ccb88f9a5cd | 3,748 | js | JavaScript | index.js | bytedo/five | e92e6e78b79bb2c98e11046547537d55f8b1cbbc | [
"MIT"
] | 2 | 2020-09-25T10:40:21.000Z | 2020-10-01T08:24:45.000Z | index.js | bytedo/five | e92e6e78b79bb2c98e11046547537d55f8b1cbbc | [
"MIT"
] | 2 | 2020-09-29T12:04:26.000Z | 2020-09-30T06:48:35.000Z | index.js | bytedo/five | e92e6e78b79bb2c98e11046547537d55f8b1cbbc | [
"MIT"
] | 1 | 2020-10-01T08:24:27.000Z | 2020-10-01T08:24:27.000Z | /**
* 框架核心
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/28 10:01:47
*/
import 'es.shim' // 加载拓展方法
import http from 'http'
import path from 'path'
import fs from 'iofs'
import Request from '@gm5/request'
import Response from '@gm5/response'
import Views from '@gm5/views'
import { sessionPackage, sessionConnect } from '@gm5/session'
import { jwtPackage, jwtConnect } from '@gm5/jwt'
import config from './config/index.js'
import Routers from './middleware/router.js'
import Cors from './middleware/cors.js'
function hideProperty(host, name, value) {
Object.defineProperty(host, name, {
value: value,
writable: true,
enumerable: false,
configurable: true
})
}
export default class Five {
constructor() {
hideProperty(this, '__FIVE__', config)
hideProperty(this, '__MODULES__', {})
hideProperty(this, '__MIDDLEWARE__', [Cors])
}
__main__() {
var { domain, website, session, jwt } = this.__FIVE__
domain = domain || website
session.domain = session.domain || domain
this.set({ domain, session })
// 安装模板引擎
this.install(Views)
// 将jwt & session中间件提到最前
// 以便用户自定义的中间件可以直接操作session
if (session.enabled) {
this.install(sessionPackage)
this.__MIDDLEWARE__.unshift(sessionConnect)
}
// 开启jwt
if (jwt) {
this.install(jwtPackage)
this.__MIDDLEWARE__.unshift(jwtConnect)
}
// 路由中间件要在最后
this.use(Routers)
}
/*------------------------------------------------------------------------*/
// 注册属性到全局Five对象
set(obj) {
for (let i in obj) {
if (typeof obj[i] === 'object' && !Array.isArray(obj[i])) {
if (!this.__FIVE__[i]) {
this.__FIVE__[i] = obj[i]
} else {
try {
Object.assign(this.__FIVE__[i], obj[i])
} catch (err) {
console.error(err)
}
}
} else {
this.__FIVE__[i] = obj[i]
}
}
return this
}
// 获取全局配置
get(key) {
return this.__FIVE__[key]
}
// 加载中间件
// 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
// 并非原生的request对象和response对象,
// 而是框架内部封装过的,可通过origin属性访问原生的对象
use(fn) {
if (typeof fn === 'function') {
this.__MIDDLEWARE__.push(fn)
return this
}
throw TypeError('argument must be a function')
}
// 注入实例化对象到实例池中
// 与use方法不同的是, 这个会在server创建之前就已经执行
install({ name, install }, args) {
this['$$' + name] = install.call(this, args)
return this
}
// 预加载应用, 缓存以提高性能
preload(dir) {
var list = fs.ls(dir)
if (list) {
list.forEach(item => {
var { name } = path.parse(item)
if (name.startsWith('.')) {
return
}
// 如果是目录,则默认加载index.js, 其他文件不加载
// 交由index.js自行处理, 用于复杂的应用
if (fs.isdir(item)) {
item = path.join(item, './index.js')
}
this.__MODULES__[name] = import(item).catch(err => {
console.error(err)
return { default: null }
})
})
}
return this
}
// 启动http服务
listen(port) {
var _this = this
var server
this.__main__()
server = http.createServer(function(req, res) {
var request = new Request(req, res)
var response = new Response(req, res)
var middleware = _this.__MIDDLEWARE__.concat()
var fn = middleware.shift()
if (response.rendered) {
return
}
response.set('X-Powered-By', 'Five.js')
if (fn) {
;(async function next() {
await fn.call(_this, request, response, function() {
fn = middleware.shift()
if (fn) {
next()
}
})
})()
}
})
server.listen(port || this.get('port'))
return server
}
}
| 21.417143 | 78 | 0.559765 |
4323c59c92ad68f1ed771585c5ff609daeb80760 | 393 | js | JavaScript | app/instance-initializers/ember-toezicht-form-fields-component-initializer.js | lblod/frontend-dynamic-form-builder | dee19ade0bad9441ae515de049db791bff0b3eb4 | [
"MIT"
] | null | null | null | app/instance-initializers/ember-toezicht-form-fields-component-initializer.js | lblod/frontend-dynamic-form-builder | dee19ade0bad9441ae515de049db791bff0b3eb4 | [
"MIT"
] | 2 | 2019-07-05T09:45:38.000Z | 2022-03-18T07:43:37.000Z | app/instance-initializers/ember-toezicht-form-fields-component-initializer.js | lblod/frontend-dynamic-form-builder | dee19ade0bad9441ae515de049db791bff0b3eb4 | [
"MIT"
] | null | null | null | import componentInitializer from '@lblod/ember-toezicht-form-fields/utils/component-initializer';
/**
*
* @param {appInstance} appInstance
* This initializer will give precedence to our local components
* over those from the @lblod/ember-mu-dynamic-forms addon
*
*/
export function initialize( appInstance ) {
componentInitializer( appInstance );
}
export default {
initialize
}; | 26.2 | 97 | 0.755725 |
4324eba8db7ff605ab5b7b386f15e54f40ab7d77 | 908 | js | JavaScript | node_modules/ng-zorro-antd/schematics/ng-update/upgrade-rules/checks/modal-template-rule.js | Bhumikansara/angulatdata | 1578fa6172ba85b5e6f045b2cca7b4c580164129 | [
"MIT"
] | null | null | null | node_modules/ng-zorro-antd/schematics/ng-update/upgrade-rules/checks/modal-template-rule.js | Bhumikansara/angulatdata | 1578fa6172ba85b5e6f045b2cca7b4c580164129 | [
"MIT"
] | null | null | null | node_modules/ng-zorro-antd/schematics/ng-update/upgrade-rules/checks/modal-template-rule.js | Bhumikansara/angulatdata | 1578fa6172ba85b5e6f045b2cca7b4c580164129 | [
"MIT"
] | 1 | 2020-08-19T03:45:16.000Z | 2020-08-19T03:45:16.000Z | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModalTemplateRule = void 0;
const schematics_1 = require("@angular/cdk/schematics");
class ModalTemplateRule extends schematics_1.Migration {
constructor() {
super(...arguments);
this.enabled = this.targetVersion === schematics_1.TargetVersion.V11;
}
visitTemplate(template) {
schematics_1.findInputsOnElementWithTag(template.content, 'nzGetContainer', ['nz-modal'])
.forEach(offset => {
this.failures.push({
filePath: template.filePath,
position: template.getCharacterAndLineOfPosition(offset),
message: `Found deprecated input '[nzGetContainer]'. Please manually remove this input.`
});
});
}
}
exports.ModalTemplateRule = ModalTemplateRule;
//# sourceMappingURL=modal-template-rule.js.map | 41.272727 | 104 | 0.668502 |
4325f709437c4c290b5e1af8b82ecc446ea84c1d | 20,182 | js | JavaScript | client/cards.js | MunchkinsCapstone/Munchkin_RPG | 081ac5c65c915d1133fe6beb611ba62105c68dd7 | [
"MIT"
] | 19 | 2018-07-11T16:05:01.000Z | 2021-12-11T17:35:31.000Z | client/cards.js | MunchkinsCapstone/Munchkin_RPG | 081ac5c65c915d1133fe6beb611ba62105c68dd7 | [
"MIT"
] | 21 | 2018-07-04T15:07:16.000Z | 2018-10-14T22:37:51.000Z | client/cards.js | MunchkinsCapstone/Munchkin_RPG | 081ac5c65c915d1133fe6beb611ba62105c68dd7 | [
"MIT"
] | 9 | 2018-08-10T17:07:27.000Z | 2021-07-01T11:16:57.000Z | const {
Card,
Deck,
Equipment,
Item,
Monster,
Buff,
Spell,
Class,
Race,
Curse,
Charm,
Modifier,
Boost,
shuffle
} = require('./cardLogic');
const monsters = [
new Monster('3,872 Orcs', '3872Orcs.jpeg', 10, 3, (player) => {}),
new Monster('Amazon', 'Amazon.jpeg', 8, 2, (player) => {}),
new Monster('Bigfoot', 'Bigfoot.jpeg', 12, 3, (player) => {
player.lose(player.equipment.head);
}),
new Monster('Bullrog', 'Bullrog.jpeg', 18, 5, (player) => {
player.die();
}),
new Monster('Crabs', 'Crabs.jpeg', 1, 1, (player) => {
player.lose(player.equipment.torso);
player.lose(player.equipment.feet);
}),
new Monster('Drooling Slime', 'DroolingSlime.jpeg', 1, 1, (player) => {
if (player.equipment.feet) {
player.lose(player.equipment.feet);
} else player.levelDown();
}),
new Monster('Face Sucker', 'FaceSucker.jpeg', 8, 2, (player) => {
player.lose(player.equipment.head);
player.levelDown();
}),
new Monster('Floating Nose', 'FloatingNose.jpeg', 10, 3, (player) => {
for (let i = 1; i <= 3; i++) {
player.levelDown();
}
}),
new Monster('Flying Frogs', 'FlyingFrogs.jpeg', 2, 1, (player) => {
for (let i = 1; i <= 2; i++) {
player.levelDown();
}
}),
new Monster('Gazebo', 'Gazebo.jpeg', 8, 2, (player) => {
for (let i = 1; i <= 3; i++) {
player.levelDown();
}
}),
new Monster('Gelatinous Octahedron', 'GelatinousOctahedron.jpeg', 2, 1, (player) => {}),
new Monster('Ghoulfiends', 'Ghoulfiends.jpeg', 8, 2, (player) => {
const lowestLevel = Math.min(...player.game.players.map((player) => player.level));
player.level = lowestLevel;
}),
new Monster('Harpies', 'Harpies.jpeg', 4, 2, (player) => {
for (let i = 1; i <= 2; i++) {
player.levelDown();
}
}),
new Monster('Hippogriff', 'Hippogriff.jpeg', 16, 4, (player) => {}),
new Monster('Insurance Salesman', 'InsuranceSalesman.jpeg', 14, 4, (player) => {}),
new Monster('King Tut', 'KingTut.jpeg', 16, 4, (player) => {
while (player.allEquips.length) {
player.lose(player.allEquips[0]);
}
while (player.hand.length) {
player.lose(player.hand[0]);
}
}),
new Monster('Lame Goblin', 'LameGoblin.jpeg', 1, 1, (player) => {
player.levelDown();
}),
new Monster('Large Angry Chicken', 'LargeAngryChicken.jpeg', 2, 1, (player) => {
player.levelDown();
}),
new Monster('Lawyers', 'Lawyers.jpeg', 6, 2, (player) => {}),
new Monster('Leperchaun', 'Leperchaun.jpeg', 4, 2, (player) => {}),
new Monster('Maul Rat', 'MaulRat.jpeg', 1, 1, (player) => {
player.levelDown();
}),
new Monster('Mr. Bones', 'MrBones.jpeg', 2, 1, (player) => {
for (let i = 1; i <= 2; i++) {
player.levelDown();
}
}),
new Monster('Net Troll', 'NetTroll.jpeg', 10, 3, (player) => {}),
new Monster('Pit Bull', 'PitBull.jpeg', 2, 1, (player) => {
for (let i = 1; i <= 2; i++) {
player.levelDown();
}
}),
new Monster('Platycore', 'Platycore.jpeg', 6, 2, (player) => {}),
new Monster('Plutonium Dragon', 'PlutoniumDragon.jpeg', 20, 5, (player) => {
player.die();
}),
new Monster('Potted Plant', 'PottedPlant.jpeg', 1, 1, (player) => {}),
new Monster('Pukachu', 'Pukachu.jpeg', 6, 2, (player) => {
while (player.hand.length) {
player.lose(player.hand[0]);
}
}),
new Monster('Shrieking Geek', 'ShriekingGeek.jpeg', 6, 2, (player) => {
player.lose(player.race);
player.lose(player.class);
}),
new Monster('Snails On Speed', 'SnailsOnSpeed.jpeg', 4, 2, (player) => {}),
new Monster('Squidzilla', 'Squidzilla.jpeg', 18, 4, (player) => {
player.die();
}),
new Monster('Stoned Golem', 'StonedGolem.jpeg', 14, 4, (player) => {
player.die();
}),
new Monster('Tongue Demon', 'TongueDemon.jpeg', 12, 3, (player) => {
let j = 2;
if (player.race.name === 'Elf') j++;
for (let i = 1; i <= j; i++) {
player.levelDown();
}
}),
new Monster('Undead Horse', 'UndeadHorse.jpeg', 4, 2, (player) => {
for (let i = 1; i <= 2; i++) {
player.levelDown();
}
}),
new Monster('Unspeakably Awful Indescribable Horror', 'UnspeakablyAwfulIndescribableHorror.jpeg', 14, 4, (player) => {
if (player.class && player.class.name === 'Wizard') player.lose(player.class);
else player.die();
}),
new Monster('Wannabe Vampire', 'WannabeVampire.jpeg', 12, 3, (player) => {
for (let i = 1; i <= 3; i++) {
player.levelDown();
}
}),
new Monster('Wight Brothers', 'WightBrothers.jpeg', 16, 4, (player) => {
player.level = 1;
})
];
const modifiers = [
// new Modifier(
// 'Ancient',
// 'Ancient.jpeg',
// (monster) => {
// monster.level += 10;
// },
// (monster) => {
// monster.level -= 10;
// }
// ),
// new Modifier(
// 'Baby',
// 'Baby.jpeg',
// (monster) => {
// monster.shrinkage = Math.min(monster.level - 1, 5);
// monster.level -= monster.shrinkage;
// monster.treasures--;
// },
// (monster) => {
// monster.level += monster.shrinkage;
// monster.treasures++;
// }
// ),
// new Modifier(
// 'Enraged',
// 'Enraged.jpeg',
// (monster) => {
// monster.level += 5;
// },
// (monster) => {
// monster.level -= 5;
// }
// ),
// new Modifier(
// 'Intelligent',
// 'Intelligent.jpeg',
// (monster) => {
// monster.level += 5;
// },
// (monster) => {
// monster.level -= 5;
// }
// )
];
const equipments = [
new Equipment(
'Bad-Ass Bandana',
'BadAssBandana.jpeg',
'head',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
0,
(player) => !player.race
),
new Equipment(
'Boots of Butt-Kicking',
'BootsOfButtKicking.jpeg',
'feet',
(user) => {
user.bonus += 2;
},
(user) => {
user.bonus -= 2;
}
),
new Equipment(
'Boots of Running Really Fast',
'BootsOfRunningReallyFast.jpeg',
'feet',
(user) => {
user.run += 2;
},
(user) => {
user.run -= 2;
}
),
new Equipment(
'Bow With Ribbons',
'BowWithRibbons.jpeg',
'hands',
(user) => {
user.bonus += 4;
},
(user) => {
user.bonus -= 4;
},
2,
(player) => !!player.race && player.race.name === 'Elf'
),
new Equipment(
'Broad Sword',
'BroadSword.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
1,
(player) => player.sex === 'Female'
),
new Equipment(
'Buckler of Swashing',
'BucklerOfSwashing.jpeg',
'hands',
(user) => {
user.bonus += 2;
},
(user) => {
user.bonus -= 2;
},
1
),
new Equipment(
'Chainsaw of Bloody Dismemberment',
'ChainsawOfBloodyDismemberment.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
2
),
new Equipment(
'Cheese Grater of Peace',
'CheeseGraterOfPeace.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
1,
(player) => !!player.class && player.class.name === 'Cleric'
),
new Equipment(
'Cloak of Obscurity',
'CloakOfObscurity.jpeg',
'torso',
(user) => {
user.bonus += 4;
},
(user) => {
user.bonus -= 4;
},
0,
(player) => !!player.class && player.class.name === 'Thief'
),
new Equipment(
'Dagger of Treachery',
'DaggerOfTreachery.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
1,
(player) => !!player.class && player.class.name === 'Thief'
),
new Equipment(
'Eleven-Foot Pole',
'ElevenFootPole.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
2
),
new Equipment(
'Flaming Armor',
'FlamingArmor.jpeg',
'torso',
(user) => {
user.bonus += 2;
},
(user) => {
user.bonus -= 2;
}
),
new Equipment(
"Gentlemen's Club",
'GentlemensClub.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
1,
(player) => player.sex === 'Male'
),
new Equipment(
'Hammer of Kneecapping',
'HammerOfKneecapping.jpeg',
'hands',
(user) => {
user.bonus += 4;
},
(user) => {
user.bonus -= 4;
},
1,
(player) => !!player.race && player.race.name === 'Dwarf'
),
new Equipment(
'Helm of Courage',
'HelmOfCourage.jpeg',
'head',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
}
),
new Equipment(
'Hireling',
'Hireling.jpeg',
'misc',
(user) => {
user.bonus++;
},
(user) => {
user.bonus--;
}
),
new Equipment(
'Horny Helmet',
'HornyHelmet.jpeg',
'head',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
}
),
new Equipment(
'Huge Rock',
'HugeRock.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
2
),
new Equipment(
'Kneepads of Allure',
'KneepadsOfAllure.jpeg',
'misc',
(user) => {
user.allure = true;
},
(user) => {
user.allure = false;
},
0,
(player) => !player.class || player.class.name !== 'Cleric'
),
new Equipment(
'Leather Armor',
'LeatherArmor.jpeg',
'torso',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
}
),
new Equipment(
'Limburger and Anchovy Sandwich',
'LimburgerAndAnchovySandwich.jpeg',
'misc',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
0,
(player) => !!player.race && player.race.name === 'Halfling'
),
new Equipment(
'Mace of Sharpness',
'MaceOfSharpness.jpeg',
'hands',
(user) => {
user.bonus += 4;
},
(user) => {
user.bonus -= 4;
},
1,
(player) => !!player.class && player.class.name === 'Cleric'
),
new Equipment(
'Mithril Armor',
'MithrilArmor.jpeg',
'torso',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
0,
(player) => !player.class || player.class.name !== 'Wizard'
),
new Equipment(
'Pantyhose of Giant Strength',
'PantyhoseOfGiantStrength.jpeg',
'misc',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
0,
(player) => !player.class || player.class.name !== 'Warrior'
),
new Equipment(
'Pointy Hat of Power',
'PointyHatOfPower.jpeg',
'head',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
0,
(player) => !!player.class && player.class.name === 'Wizard'
),
new Equipment(
'Rapier of Unfairness',
'RapierOfUnfairness.jpeg',
'hands',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
1,
(player) => !!player.race && player.race.name === 'Elf'
),
new Equipment(
'Rat on a Stick',
'RatOnAStick.jpeg',
'hands',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
},
1
),
new Equipment(
'Really Impressive Title',
'ReallyImpressiveTitle.jpeg',
'misc',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
}
),
new Equipment(
'Sandals of Protection',
'SandalsOfProtection.jpeg',
'feet',
(user) => {
user.protected = true;
},
(user) => {
user.protected = false;
}
),
new Equipment(
'Shield of Ubiquity',
'ShieldOfUbiquity.jpeg',
'hands',
(user) => {
user.bonus += 4;
},
(user) => {
user.bonus -= 4;
},
1,
(player) => !!player.class && player.class.name === 'Warrior'
),
new Equipment(
'Short Wide Armor',
'ShortWideArmor.jpeg',
'torso',
(user) => {
user.bonus += 3;
},
(user) => {
user.bonus -= 3;
},
0,
(player) => !!player.race && player.race.name === 'Dwarf'
),
new Equipment(
'Singing & Dancing Sword',
'Singing&DancingSword.jpeg',
'misc',
(user) => {
user.bonus += 2;
},
(user) => {
user.bonus -= 2;
},
0,
(player) => !player.class || player.class.name !== 'Thief'
),
new Equipment(
'Slimy Armor',
'SlimyArmor.jpeg',
'torso',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
}
),
new Equipment(
'Sneaky Bastard Sword',
'SneakyBastardSword.jpeg',
'hands',
(user) => {
user.bonus += 2;
},
(user) => {
user.bonus -= 2;
},
1
),
new Equipment(
'Spiky Knees',
'SpikyKnees.jpeg',
'misc',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
}
),
new Equipment(
'Staff of Napalm',
'StaffOfNapalm.jpeg',
'hands',
(user) => {
user.bonus += 5;
},
(user) => {
user.bonus -= 5;
},
1,
(player) => !!player.class && player.class.name === 'Wizard'
),
new Equipment(
'Stepladder',
'Stepladder.jpeg',
'misc',
(user) => {
user.bonus += 1;
},
(user) => {
user.bonus -= 1;
},
0,
(player) => !!player.race && player.race.name === 'Halfling'
),
new Equipment(
'Swiss Army Polearm',
'SwissArmyPolearm.jpeg',
'hands',
(user) => {
user.bonus += 4;
},
(user) => {
user.bonus -= 4;
},
2,
(player) => !player.race
),
new Equipment(
'Tuba of Charm',
'TubaOfCharm.jpeg',
'hands',
(user) => {
user.run += 3;
user.tuba = true;
},
(user) => {
user.run -= 3;
user.tuba = false;
},
1
)
];
const races = [
new Race(
'Dwarf',
'Dwarf1.jpeg',
(player) => {
player.maxInventory = 6;
},
(player) => {
player.maxInventory = 5;
}
),
new Race(
'Dwarf',
'Dwarf2.jpeg',
(player) => {
player.maxInventory = 6;
},
(player) => {
player.maxInventory = 5;
}
),
new Race(
'Dwarf',
'Dwarf3.jpeg',
(player) => {
player.maxInventory = 6;
},
(player) => {
player.maxInventory = 5;
}
),
new Race(
'Elf',
'Elf1.jpeg',
(player) => {
player.run++;
},
(player) => {
player.run--;
}
),
new Race(
'Elf',
'Elf2.jpeg',
(player) => {
player.run++;
},
(player) => {
player.run--;
}
),
new Race(
'Elf',
'Elf3.jpeg',
(player) => {
player.run++;
},
(player) => {
player.run--;
}
),
new Race(
'Halfling',
'Halfling1.jpeg',
(player) => {
//
},
(player) => {
//
}
),
new Race(
'Halfling',
'Halfling2.jpeg',
(player) => {
//
},
(player) => {
//
}
),
new Race(
'Halfling',
'Halfling3.jpeg',
(player) => {
//
},
(player) => {
//
}
)
];
const boosts = [
new Boost('1,000 Gold Pieces', '1000GoldPieces.jpeg'),
new Boost('Boil An Anthill', 'BoilAnAnthill.jpeg'),
new Boost('Bribe GM With Food', 'BribeGMWithFood.jpeg'),
new Boost('Convenient Addition Error', 'ConvenientAdditionError.jpeg'),
new Boost('Invoke Obscure Rules', 'InvokeObscureRules.jpeg'),
new Boost('Kill the Hireling', 'KillTheHireling.jpeg', (player) => player.game && player.game.hireling),
new Boost('Potion of General Studliness', 'PotionOfGeneralStudliness.jpeg'),
new Boost('Whine at the GM', 'WhineAtGM.jpeg', (player) =>
player.game.players.some((otherPlayer) => otherPlayer.level > player.level)
),
new Boost('Mutilate the Bodies', 'MutilateTheBodies.jpeg', (player) => player.game.didKillMonster)
];
const classes = [
new Class('Cleric', 'Cleric1.jpeg', () => {}, () => {}),
new Class('Cleric', 'Cleric2.jpeg', () => {}, () => {}),
new Class('Cleric', 'Cleric3.jpeg', () => {}, () => {}),
new Class('Thief', 'Thief1.jpeg', () => {}, () => {}),
new Class('Thief', 'Thief2.jpeg', () => {}, () => {}),
new Class('Thief', 'Thief3.jpeg', () => {}, () => {}),
new Class('Warrior', 'Warrior1.jpeg', () => {}, () => {}),
new Class('Warrior', 'Warrior2.jpeg', () => {}, () => {}),
new Class('Warrior', 'Warrior3.jpeg', () => {}, () => {}),
new Class('Wizard', 'Wizard1.jpeg', () => {}, () => {}),
new Class('Wizard', 'Wizard2.jpeg', () => {}, () => {}),
new Class('Wizard', 'Wizard3.jpeg', () => {}, () => {})
];
const buffs = [
new Buff('Cotion of Ponfusion', 'CotionOfPonfusion.jpeg', 3),
new Buff('Doppleganger', 'Doppleganger.jpeg', 0, (buffsArray) => (buffsArray.double = true)),
new Buff('Electric Radioactive Acid Potion', 'ElectricRadioactiveAcidPotion.jpeg', 5),
new Buff('Flaming Poison Potion', 'FlamingPoisonPotion.jpeg', 3),
new Buff('Freezing Explosive Potion', 'FreezingExplosivePotion.jpeg', 3),
new Buff('Magic Missile', 'MagicMissile1.jpeg', 5),
new Buff('Magic Missile', 'MagicMissile2.jpeg', 5),
new Buff('Nasty Tasting Sports Drink', 'NastyTastingSportsDrink.jpeg', 2),
new Buff('Potion of Halitosis', 'PotionOfHalitosis.jpeg', 2),
new Buff('Pretty Balloons', 'PrettyBalloons.jpeg', 5),
new Buff('Sleep Potion', 'SleepPotion.jpeg', 2)
// new Buff('Yuppie Water', 'YuppieWater.jpeg', 2)
];
const spells = [
// new Spell('Flask of Glue', 'FlaskOfGlue.jpeg', target => {}),
// new Spell('Friendship Potion', 'FriendshipPotion.jpeg', target => {}),
// new Spell('Hoard', 'Hoard.jpeg', target => {}),
// new Spell('Instant Wall', 'InstantWall.jpeg', target => {}),
// new Spell('Invisibility Potion', 'InvisibilityPotion.jpeg', target => {}),
// new Spell('Loaded Die', 'LoadedDie.jpeg', target => {}),
// new Spell('Magic Lamp', 'MagicLamp.jpeg', target => {}),
// new Spell('Pollymorph Potion', 'PollymorphPotion.jpeg', target => {}),
// new Spell('Steal a Level', 'StealALevel.jpeg', target => {}),
// new Spell('Transferral Potion', 'TransferralPotion.jpeg', target => {}),
// new Spell('Wand of Dowsing', 'WandOfDowsing.jpeg', target => {}),
// new Spell('Wishing Ring', 'WishingRing1.jpeg', target => {}),
// new Spell('Wishing Ring', 'WishingRing2.jpeg', target => {})
];
const curses = [
new Curse('Change Class', 'ChangeClass.jpeg', (player) => {}),
new Curse('Change Race', 'ChangeRace.jpeg', (player) => {}),
new Curse('Change Sex', 'ChangeSex.jpeg', (player) => {
player.sex = player.sex === 'Female' ? 'Male' : 'Female';
}),
// new Curse('Chicken On Your Head', 'ChickenOnYourHead.jpeg', player => {}),
new Curse('Duck of Doom', 'DuckOfDoom.jpeg', (player) => {
player.levelDown();
player.levelDown();
}),
// new Curse('Income Tax', 'IncomeTax.jpeg', player => {}),
// new Curse('Lose 1 Big Item', 'Lose1BigItem.jpeg', player => {}),
// new Curse('Lose 1 Small Item', 'Lose1SmallItem1.jpeg', player => {}),
// new Curse('Lose 1 Small Item', 'Lose1SmallItem2.jpeg', player => {}),
new Curse('Lose a Level', 'LoseALevel1.jpeg', (player) => {
if (player.level > 1) player.levelDown();
}),
new Curse('Lose a Level', 'LoseALevel2.jpeg', (player) => {
if (player.level > 1) player.levelDown();
}),
new Curse('Lose the Armor You Are Wearing', 'LoseArmor.jpeg', (player) => {
player.lose(player.equipment.torso);
}),
new Curse('Lose Your Class', 'LoseClass.jpeg', (player) => {
player.lose(player.class);
}),
new Curse('Lose the Footgear You Are Wearing', 'LoseFootgear.jpeg', (player) => {
player.lose(player.equipment.feet);
}),
new Curse('Lose the Headgear You Are Wearing', 'LoseHeadgear.jpeg', (player) => {
player.lose(player.equipment.head);
}),
new Curse('Lose Your Race', 'LoseRace.jpeg', (player) => {
player.lose(player.race);
}),
// new Curse('Lose Two Cards', 'LoseTwoCards.jpeg', player => {}),
// new Curse('Malign Mirror', 'MalignMirror.jpeg', player => {}),
new Curse('Truly Obnoxious Curse', 'TrulyObnoxiousCurse.jpeg', (player) => {
const bestItem = player.allEquips.reduce((bestItem, currentItem) => {
if (currentItem.bonus > bestItem.bonus) return currentItem;
});
player.lose(bestItem);
})
];
const charms = [
// new Charm('Cheat!', 'Cheat.jpeg'),
// new Charm('Divine Intervention', 'DivineIntervention.jpeg'),
// new Charm('Half-Breed', 'HalfBreed1.jpeg'),
// new Charm('Half-Breed', 'HalfBreed2.jpeg'),
// new Charm('Help Me Out Here!', 'HelpMeOutHere.jpeg'),
// new Charm('Illusion', 'Illusion.jpeg'),
// new Charm('Mate', 'Mate.jpeg'),
// new Charm('Out to Lunch', 'OutToLunch.jpeg'),
// new Charm('Super Munckin', 'SuperMunchkin1.jpeg'),
// new Charm('Super Munckin', 'SuperMunchkin2.jpeg'),
// new Charm('Wandering Monster', 'WanderingMonster1.jpeg'),
// new Charm('Wandering Monster', 'WanderingMonster2.jpeg')
];
const doors = new Deck(monsters.concat(modifiers).concat(races).concat(classes).concat(curses).concat(charms));
const treasures = new Deck(equipments.concat(spells).concat(boosts).concat(buffs));
const decks = {
doors,
treasures
};
const allCards = doors.cards.concat(treasures.cards);
allCardsObj = {};
allCards.forEach((card, index) => {
card.id = index;
allCardsObj[card.id] = card;
});
module.exports = {
Deck,
Race,
Class,
Equipment,
monsters,
equipments,
classes,
races,
spells,
modifiers,
doors,
treasures,
shuffle,
decks,
allCards,
allCardsObj
};
| 21.936957 | 119 | 0.56813 |
4326add8e03a5c621dbee0d5b485b593a745e8f7 | 3,451 | js | JavaScript | web/src/components/Navbar.js | thiagojacinto/omnistack10-devRadar | 44d5776dbc03b6426f95354ffb73d428e7ed0cbd | [
"MIT"
] | null | null | null | web/src/components/Navbar.js | thiagojacinto/omnistack10-devRadar | 44d5776dbc03b6426f95354ffb73d428e7ed0cbd | [
"MIT"
] | 1 | 2020-03-17T23:34:50.000Z | 2020-03-17T23:34:50.000Z | web/src/components/Navbar.js | thiagojacinto/omnistack10-devRadar | 44d5776dbc03b6426f95354ffb73d428e7ed0cbd | [
"MIT"
] | null | null | null | import React from 'react';
import ModalFoundDev from './ModalFoundDev';
export default function Navbar(props) {
function handleDel(event) {
event.preventDefault();
const input = document.querySelector('#delete-input');
// verify if text input is void:
if (!input.value) return alert('Não é possível inserir vazio. Escreva o `usuário do GitHub` de algum desenvolvedor.')
props.removeDev({username: input.value});
console.log(`Username digitado no front: ${input.value}; `);
// clears text input value
input.value = '';
}
return (
<header className="container">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="/">DevRadar</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<div className="navbar-nav">
<a className="nav-item nav-link" href="/">Saiba mais<span className="sr-only">(current)</span></a>
<a className="nav-item nav-link disabled" href="/" tabIndex="-1" aria-disabled="true">Sua empresa</a>
<button className="nav-item nav-link btn btn-outline-secondary" data-toggle="collapse" data-target="#search-by-id" aria-expanded="false" aria-controls="search-by-id">Procurar</button>
<button className="nav-item nav-link btn btn-outline-secondary" data-toggle="collapse" data-target="#delete-by-username" aria-expanded="false" aria-controls="delete-by-username">Remover</button>
<div id="advanced-inputs" className="my-2 my-lg-0">
<form action="" className="form-inline nav-item collapse" id="search-by-id">
<input className="nav-item form-control mr-md-4" type="search" placeholder="ID do Dev" aria-label="search-by-id" id="search-dev" />
<button
className="btn btn-outline-secondary"
data-toggle="modal"
data-target="#foundOrNotDev"
type="button"
onClick={event => props.handleSearchDev(event, document.getElementById('search-dev').value)}
>
Procurar Dev
</button>
</form>
<form action="" className="form-inline nav-item collapse" id="delete-by-username" >
<input
id="delete-input"
className="nav-item form-control mr-md-4"
type="search"
placeholder="Username"
aria-label="delete-by-username"
/>
<button
className="btn btn-outline-danger"
type="button"
onClick={(event) => handleDel(event)}
>
Remover
</button>
</form>
</div>
</div>
</div>
</nav>
{/* Modal conditional rendering */}
{ props.dev && props.dev._id ?
<ModalFoundDev dev={props.dev} closeModal={props.closeModal}/>
: <ModalFoundDev dev={props.dev} closeModal={props.closeModal}/>
}
</header>
);
}
| 41.083333 | 206 | 0.576065 |
4326ca37f144ab35a9bf0724bb968464a538866f | 2,108 | js | JavaScript | Github-Login-Git-Auth/gh-auth.js | nnamdimykel/Github-Login-Git-Auth | be17a1478ae5f09ae20dc4c44637eaf38a0f4be0 | [
"Apache-2.0"
] | 1 | 2018-07-25T09:43:19.000Z | 2018-07-25T09:43:19.000Z | Github-Login-Git-Auth/gh-auth.js | nnamdimykel/Github-Login-Git-Auth | be17a1478ae5f09ae20dc4c44637eaf38a0f4be0 | [
"Apache-2.0"
] | null | null | null | Github-Login-Git-Auth/gh-auth.js | nnamdimykel/Github-Login-Git-Auth | be17a1478ae5f09ae20dc4c44637eaf38a0f4be0 | [
"Apache-2.0"
] | null | null | null | var express = require('express');
var port = process.env.PORT || 5045;
var mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;
var passport = require('passport');
var flash = require('connect-flash');
var expressHbs = require('express-handlebars');
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var app = express();
var uristring = process.env.MONGODB_URI || 'mongodb://127.0.0.1/GH-AUTH';
mongoose.connect(uristring);
require('./config/passport')(passport); // pass passport for configuration
app.engine('.hbs', expressHbs({extname: '.hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', '.hbs');
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser()); // read cookies (needed for auth)
// required for passport
app.use(session({
secret: 'h0jbv7t7ubgdjd8627uf4t7t', // this string of text fit be anything random
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
cookie: { maxAge: 180 * 60 * 1000 }
})); // session secret
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(express.static(path.join(__dirname, '/public')));
app.use(function(req, res, next) {
res.locals.login = req.isAuthenticated(); // global function to check a user's auth state
res.locals.session = req.session; // stores the user's session
next();
});
// routes ======================================================================
require('./routes/index.js')(app, passport);
// launch ======================================================================
app.listen(port);
console.log('your work starts on port ' + port);
| 38.327273 | 90 | 0.657495 |
4327406d18ebd9b7288c21f2d943eada6800b2a8 | 290 | js | JavaScript | node_modules/kefir/src/time-based/interval.js | tishoy/tishoyrobot | 607648790ab7ccc2b778921adfc9aeee7b04de96 | [
"MIT"
] | 520 | 2017-11-08T06:44:00.000Z | 2022-03-28T10:32:20.000Z | node_modules/kefir/src/time-based/interval.js | tishoy/tishoyrobot | 607648790ab7ccc2b778921adfc9aeee7b04de96 | [
"MIT"
] | 68 | 2017-11-05T12:49:30.000Z | 2021-10-30T07:19:43.000Z | node_modules/kefir/src/time-based/interval.js | tishoy/tishoyrobot | 607648790ab7ccc2b778921adfc9aeee7b04de96 | [
"MIT"
] | 32 | 2017-12-06T08:57:55.000Z | 2022-02-09T14:52:23.000Z | import timeBased from '../patterns/time-based'
const S = timeBased({
_name: 'interval',
_init({x}) {
this._x = x
},
_free() {
this._x = null
},
_onTick() {
this._emitValue(this._x)
},
})
export default function interval(wait, x) {
return new S(wait, {x})
}
| 13.181818 | 46 | 0.57931 |
432819b9ee451e555a631171135a94bc6dab4eb6 | 1,459 | js | JavaScript | watermark/index.js | jasony62/tms-koa-jimp | 0e9e66bc7acb6a59e4a7e80055f306420101a5c7 | [
"MIT"
] | null | null | null | watermark/index.js | jasony62/tms-koa-jimp | 0e9e66bc7acb6a59e4a7e80055f306420101a5c7 | [
"MIT"
] | 1 | 2022-03-29T03:49:21.000Z | 2022-03-29T03:49:21.000Z | watermark/index.js | jasony62/tms-koa-jimp | 0e9e66bc7acb6a59e4a7e80055f306420101a5c7 | [
"MIT"
] | null | null | null | const { ResultData, ResultFault } = require('tms-koa')
const { BaseCtrl } = require('tms-koa/lib/controller/fs/base')
const { LocalFS } = require('tms-koa/lib/model/fs/local')
const newTextWatermark = require('../helper/watermark').newTextWatermark
class Main extends BaseCtrl {
constructor(...args) {
super(...args)
}
/**
* 添加文字水印
*/
async text() {
const { image, save } = this.request.query
const localFS = new LocalFS(this.domain, this.bucket)
if (!image || !localFS.existsSync(image))
return new ResultFault('指定的文件不存在')
const fullpath = localFS.fullpath(image)
const textWatermark = await newTextWatermark(fullpath)
/* 保存结果 */
if (save === 'Y')
if (!textWatermark.saver.available)
return new ResultFault(textWatermark.saver.fault)
const watermarks = this.request.body
watermarks.forEach(
({ text, x, y, color, bgColor, width, fontSize, align }) => {
if (typeof text === 'string')
textWatermark.addText(
text,
x,
y,
color,
bgColor,
width,
fontSize,
align
)
}
)
/* 保存结果 */
if (save === 'Y') {
const path = await textWatermark.save(this.bucket)
return new ResultData(path)
} else {
const result = await textWatermark.getBase64Async()
return new ResultData(result)
}
}
}
module.exports = Main
| 24.316667 | 72 | 0.588759 |
4328f20c5fb71daaa4b592dddd12eac2433c5aeb | 235 | js | JavaScript | client/utils.js | scottbot95/stack-chat | bf9542785d19a480cd33f9e4f55ad85510f1f876 | [
"Apache-2.0"
] | null | null | null | client/utils.js | scottbot95/stack-chat | bf9542785d19a480cd33f9e4f55ad85510f1f876 | [
"Apache-2.0"
] | null | null | null | client/utils.js | scottbot95/stack-chat | bf9542785d19a480cd33f9e4f55ad85510f1f876 | [
"Apache-2.0"
] | null | null | null | export const throttle = (func, minTimeout = 0) => {
let lastRun = new Date(0);
return (...args) => {
const now = new Date();
if (now - lastRun >= minTimeout) {
lastRun = now;
return func(...args);
}
};
};
| 21.363636 | 51 | 0.523404 |
4329495556159c06daa01eabf56e11c713c446b0 | 2,023 | js | JavaScript | build/translations/cs.js | adenovan/ckeditor5-build-classic | 6d495e211b194f370f165558e2bc1151b3b654b1 | [
"MIT"
] | null | null | null | build/translations/cs.js | adenovan/ckeditor5-build-classic | 6d495e211b194f370f165558e2bc1151b3b654b1 | [
"MIT"
] | null | null | null | build/translations/cs.js | adenovan/ckeditor5-build-classic | 6d495e211b194f370f165558e2bc1151b3b654b1 | [
"MIT"
] | null | null | null | (function(d){d['cs']=Object.assign(d['cs']||{},{a:"Soubor nelze nahrát:",b:"Panel nástrojů obrázku",c:"Panel nástrojů tabulky",d:"Tučné",e:"Citace",f:"ovládací prvek obrázku",g:"Vložit obrázek nebo soubor",h:"Obrázek v plné velikosti",i:"Postranní obrázek",j:"Obrázek zarovnaný vlevo",k:"Obrázek zarovnaný na střed",l:"Obrázek zarovnaný vpravo",m:"Zvolte nadpis",n:"Nadpis",o:"Kurzíva",p:"Zvětšit odsazení",q:"Zmenšit odsazení",r:"Číslování",s:"Odrážky",t:"Vložit tabulku",u:"Sloupec záhlaví",v:"Vložit sloupec vlevo",w:"Vložit sloupec vpravo",x:"Smazat sloupec",y:"Sloupec",z:"Řádek záhlaví",aa:"Vložit řádek pod",ab:"Vložit řádek před",ac:"Smazat řádek",ad:"Řádek",ae:"Sloučit s buňkou nad",af:"Sloučit s buňkou vpravo",ag:"Sloučit s buňkou pod",ah:"Sloučit s buňkou vlevo",ai:"Rozdělit buňky vertikálně",aj:"Rozdělit buňky horizontálně",ak:"Sloučit buňky",al:"Vložit obrázek",am:"Zadejte popis obrázku",an:"Nahrání selhalo",ao:"ovládací prvek médií",ap:"Vložit média",aq:"URL adresa musí být vyplněna.",ar:"Tato adresa bohužel není podporována.",as:"Odkaz",at:"Změnit alternativní text obrázku",au:"Panel nástrojů ovládacího prvku",av:"Probíhá nahrávání",aw:"Otevřít v nové kartě",ax:"Ke stažení",ay:"Odstranit odkaz",az:"Upravit odkaz",ba:"Otevřít odkaz v nové kartě",bb:"Tento odkaz nemá žádnou URL",bc:"Uložit",bd:"Zrušit",be:"Vložte URL média do vstupního pole.",bf:"Rada: Vložte URL přímo do editoru pro rychlejší vnoření.",bg:"URL adresa",bh:"URL odkazu",bi:"Zpět",bj:"Znovu",bk:"Textový editor",bl:"Rozbalovací panel nástrojů",bm:"%0 z %1",bn:"Předchozí",bo:"Další",bp:"Panel nástrojů editoru",bq:"Zobrazit další položky",br:"Alternativní text",bs:"Textový editor, %0",bt:"Odstavec",bu:"Nadpis 1",bv:"Nadpis 2",bw:"Nadpis 3",bx:"Nadpis 4",by:"Nadpis 5",bz:"Nadpis 6",ca:"Nelze získat URL obrázku se změněnou velikostí.",cb:"Výběr obrázku se změněnou velikostí selhal",cc:"Na současnou pozici nelze vložit obrázek.",cd:"Vložení obrázku selhalo"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={})); | 2,023 | 2,023 | 0.743945 |
43299260dc6464289eb5fe01afe1d3faa87bad18 | 529 | js | JavaScript | data/test/js/43299260dc6464289eb5fe01afe1d3faa87bad18index.services.js | aliostad/deep-learning-lang-detection | d6b031f3ebc690cf2ffd0ae1b08ffa8fb3b38a62 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/test/js/43299260dc6464289eb5fe01afe1d3faa87bad18index.services.js | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/test/js/43299260dc6464289eb5fe01afe1d3faa87bad18index.services.js | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | import params from './index.params';
import UserService from './services/user.service';
import LocaleService from './services/locale.service';
import SessionService from './services/session.service';
import RegistrationService from './services/registration.service';
angular.module('blogAngularExample.services', [])
.value('params', params)
.service('SessionService', SessionService)
.service('RegistrationService', RegistrationService)
.service('UserService', UserService)
.service('LocaleService', LocaleService);
| 37.785714 | 66 | 0.776938 |
4329b3cda87be2e787ca66df93eca219512c41bf | 902 | js | JavaScript | no-parameters-in-call-activity.js | lgaquino/-camunda-modeler-custom-linter-rules | d9f3595814d6e225ffb1fee165594d79a71b9ad6 | [
"MIT"
] | null | null | null | no-parameters-in-call-activity.js | lgaquino/-camunda-modeler-custom-linter-rules | d9f3595814d6e225ffb1fee165594d79a71b9ad6 | [
"MIT"
] | null | null | null | no-parameters-in-call-activity.js | lgaquino/-camunda-modeler-custom-linter-rules | d9f3595814d6e225ffb1fee165594d79a71b9ad6 | [
"MIT"
] | null | null | null | const {
is
} = require('bpmnlint-utils');
/**
* Rule that reports incomplete call activities
*/
module.exports = function() {
function check(node, reporter) {
if (is(node, 'bpmn:CallActivity') && !checkCallActivity(node)){
reporter.report(node.id, 'Input parameters not specified');
}
}
return {
check: check
};
};
// helpers /////////////////////////////
function checkCallActivity(callActivity){
return !!getConnectorInElement(callActivity);
}
function getConnectorInElement(callActivity){
const extensionElements = callActivity.extensionElements || [];
return getInnerElementsByType(extensionElements, "camunda:In");
}
function getInnerElementsByType(extensionElements, innerElementType) {
if(extensionElements.values.length > 0){
const filter = (element) => element.$type === innerElementType;
return extensionElements.values.find(filter);
}
} | 20.044444 | 70 | 0.696231 |
4329db3922cf625dc67ab1e779d37080b0e5b3ce | 3,350 | js | JavaScript | js/apps/system/_admin/aardvark/APP/frontend/js/views/validationView.js | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 1 | 2020-07-30T23:33:02.000Z | 2020-07-30T23:33:02.000Z | js/apps/system/_admin/aardvark/APP/frontend/js/views/validationView.js | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 109 | 2022-01-06T07:05:24.000Z | 2022-03-21T01:39:35.000Z | js/apps/system/_admin/aardvark/APP/frontend/js/views/validationView.js | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 1 | 2016-03-30T14:43:34.000Z | 2016-03-30T14:43:34.000Z | /* jshint browser: true */
/* jshint unused: false */
/* global arangoHelper, Backbone, window, $, templateEngine, document, JSONEditor */
(function () {
'use strict';
window.ValidationView = Backbone.View.extend({
el: '#content',
readOnly: false,
template: templateEngine.createTemplate('validationView.ejs'),
initialize: function (options) {
this.collectionName = options.collectionName;
this.model = this.collection;
},
events: {
"click #saveValidationButton": 'saveValidation'
},
render: function () {
this.breadcrumb();
arangoHelper.buildCollectionSubNav(this.collectionName, 'Schema');
$(this.el).html(this.template.render({}));
this.renderValidationEditor();
this.getValidationProperties();
this.editor.focus();
},
resize: function () {
$('#validationEditor').height($('.centralRow').height() - 300);
},
renderValidationEditor: function () {
var container = document.getElementById('validationEditor');
this.resize();
var options = {
onChange: function () {
},
onModeChange: function (newMode) {
void (newMode);
},
search: true,
mode: 'code',
modes: ['tree', 'code'],
ace: window.ace
};
this.editor = new JSONEditor(container, options);
},
getValidationProperties: function () {
var propCB = (error, data) => {
if (error) {
window.arangoHelper.arangoError("Error", "Could not get collection properties");
} else {
this.editor.set(data.schema);
}
};
this.model.getProperties(propCB);
},
breadcrumb: function () {
$('#subNavigationBar .breadcrumb').html(
'Collection: ' + (this.collectionName.length > 64 ? this.collectionName.substr(0, 64) + "..." : this.collectionName)
);
},
saveValidation: function () {
var saveCallback = function (error, isCoordinator) {
void (isCoordinator);
if (error) {
arangoHelper.arangoError('Error', 'Could not save schema.');
} else {
var newprops = null;
try {
newprops = this.editor.get();
} catch (ex) {
arangoHelper.arangoError('Error', 'Could not save schema: ' + ex);
throw ex;
}
this.model.changeValidation(newprops, (err, data) => {
if (err) {
arangoHelper.arangoError('Error', 'Could not save schema for collection ' + this.model.get('name') + ': ' + data.responseJSON.errorMessage);
} else {
arangoHelper.arangoNotification('Saved schema for collection ' + this.model.get('name') + '.');
}
this.editor.focus();
});
} // if error
}.bind(this);
window.isCoordinator(saveCallback);
},
changeViewToReadOnly: function () {
window.App.validationView.readOnly = true;
$('.breadcrumb').html($('.breadcrumb').html() + ' (read-only)');
// this method disables all write-based functions
$('.modal-body input').prop('disabled', 'true');
$('.modal-body select').prop('disabled', 'true');
$('.modal-footer button').addClass('disabled');
$('.modal-footer button').unbind('click');
}
});
}());
| 30.18018 | 154 | 0.572836 |
432a0cd8cff7f82cd12a6d0e0d15a4552d32eb18 | 9,852 | js | JavaScript | components/FormBlock.js | boratechlife/kos.github.io | 0767a6ce8321918ba322b8a65240ba8e19d4da92 | [
"MIT"
] | null | null | null | components/FormBlock.js | boratechlife/kos.github.io | 0767a6ce8321918ba322b8a65240ba8e19d4da92 | [
"MIT"
] | null | null | null | components/FormBlock.js | boratechlife/kos.github.io | 0767a6ce8321918ba322b8a65240ba8e19d4da92 | [
"MIT"
] | null | null | null | import React from "react"
import Image from "@/components/Image"
import ImageFixed from "next/image"
export default function FormBlock() {
return (
<div className="block-class bg-1">
<div className="grid w-full h-[1000px]">
<Image src="/images/block-bg.jpg" alt />
</div>
<div className="container absolute transform-gpu left-1/2 translate-x-[-50%] translate-y-[-900px]">
<h2 className="text-center decor decor-white">
Let's Get Started
<div className="block mx-auto">
<ImageFixed
src="/images/h-decor-white.png"
height="4px"
width="64px"
alt
/>
</div>
</h2>
<div className="flex flex-wrap lg:flex-nowrap">
<div className="pl-4 pr-4 sm:w-1/2">
<div
className="text-num"
data-animation="fadeInLeft"
data-animation-delay="0s"
>
<div className="text-num-num">
<span>1</span>
</div>
<div className="text-num-info">
<h5 className="text-num-title">Fill out the form</h5>
<p>Tell us who you are and how we can reach you.</p>
</div>
</div>
<div
className="text-num"
data-animation="fadeInRight"
data-animation-delay="0s"
>
<div className="text-num-num">
<span>2</span>
</div>
<div className="text-num-info">
<h5 className="text-num-title">Receive a prompt response</h5>
<p>
A KOS sales specialist WILL REACH OUT TO YOU SHORTLY to get
you signed up and book your service appointment.
</p>
</div>
</div>
<div
className="text-num"
data-animation="fadeInRight"
data-animation-delay="0s"
>
<div className="text-num-num">
<span>3</span>
</div>
<div className="text-num-info">
<h5 className="text-num-title">Get connected</h5>
<p>
One of our professional technicians will perform an on-site,
quick and easy installation to get you set up.
</p>
</div>
</div>
<div
className="text-num last"
data-animation="fadeInLeft"
data-animation-delay="0.8s"
>
<div className="text-num-num">
<span>4</span>
</div>
<div className="text-num-info">
<h5 className="text-num-title">Up and running</h5>
<p>Start enjoying your customized internet package.</p>
</div>
</div>
</div>
<div className="pl-4 pr-4 sm:w-1/2">
<p>
You have choices when it comes to internet. Switching to KOS is
quick and easy to do. Fill in the form below and get connected
today!
</p>
<form
className="index-request-form-js"
id="requestFormSimple"
method="post"
>
<input type="hidden" name="formtype" defaultValue="indexform" />
<div className="successform">
<p>Your message was sent successfully!</p>
</div>
<div className="errorform">
<p>
Something went wrong, try refreshing and submitting the form
again.
</p>
</div>
<input
className="input-custom input-full"
type="text"
name="name"
placeholder="Name:"
/>
<input
className="input-custom input-full"
type="text"
name="phone"
placeholder="Phone:"
/>
<input
className="input-custom input-full"
type="text"
name="email"
placeholder="Email:"
/>
<input
className="input-custom input-full"
type="text"
name="city"
placeholder="City:"
/>
<input
className="input-custom input-full"
type="text"
name="postal"
placeholder="Postal Code:"
/>
<div className="margin10">
<label>
<input
type="checkbox"
name="customer_type_res"
defaultValue="Residential Customer"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
defaultChecked
/>
<span style={{ fontSize: 16, fontWeight: 400 }}>
RESIDENTIAL
</span>
</label>
<label>
<input
type="checkbox"
name="customer_type_bus"
defaultValue="Business Customer"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
<span style={{ fontSize: 16, fontWeight: 400 }}>
BUSINESS
</span>
</label>
</div>
<div name="residential_options" className="margin10">
<label>
<input
type="checkbox"
name="customer_option_dsl"
defaultValue="DSL Information Selected"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
DSL
</label>
<label>
<input
type="checkbox"
name="customer_option_cab"
defaultValue="Cable Information Selected"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
CABLE
</label>
<label>
<input
type="checkbox"
name="customer_option_wir"
defaultValue="Wireless Information Selected"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
WIRELESS
</label>
<label>
<input
type="checkbox"
name="customer_option_voi"
defaultValue="VoIP Information Selected"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
VoIP
</label>
<label>
<input
type="checkbox"
name="customer_option_dia"
defaultValue="Dial Up Information Selected"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
DIAL UP
</label>
<label>
<input
type="checkbox"
name="customer_option_hos"
defaultValue="Hosting Information Selected"
style={{
border: "2px dotted #00f",
background: "#ff0000",
}}
/>
HOSTING
</label>
</div>
<div>
<b>How did you hear about us:</b>
<select className="input-custom input-full" name="how">
<option value>Please select one...</option>
<option value="Current KOS user">Current KOS user</option>
<option value="Family or Friend">Family or Friend</option>
<option value="Radio Ad">Radio Ad</option>
<option value="Print Ad">Print Ad</option>
<option value="Internet Search">Internet Search</option>
<option value="Social Media">Social Media</option>
<option value="Direct Mail">Direct Mail</option>
<option value="Other">Other</option>
</select>
</div>
<textarea
className="input-custom input-full"
type="text"
name="message"
placeholder="Message:"
defaultValue={""}
/>
<button
type="submit"
className="inline-block px-4 py-2 text-base font-normal leading-normal text-center no-underline whitespace-no-wrap align-middle border rounded select-none btn btn-orange"
>
GET STARTED
</button>
</form>
</div>
</div>
</div>
</div>
)
}
| 35.695652 | 186 | 0.40743 |
432a243fa56b3476970411b0a819400ef90e721b | 14,727 | js | JavaScript | ui/file_manager/integration_tests/file_manager/toolbar.js | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ui/file_manager/integration_tests/file_manager/toolbar.js | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ui/file_manager/integration_tests/file_manager/toolbar.js | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {addEntries, ENTRIES, getCaller, pending, repeatUntil, RootPath, sendTestMessage, TestEntryInfo} from '../test_util.js';
import {testcase} from '../testcase.js';
import {remoteCall, setupAndWaitUntilReady} from './background.js';
import {DOWNLOADS_FAKE_TASKS} from './tasks.js';
import {BASIC_FAKE_ENTRY_SET, BASIC_LOCAL_ENTRY_SET} from './test_data.js';
/**
* Tests that the Delete menu item is disabled if no entry is selected.
*/
testcase.toolbarDeleteWithMenuItemNoEntrySelected = async () => {
const contextMenu = '#file-context-menu:not([hidden])';
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS);
// Right click the list without selecting an entry.
chrome.test.assertTrue(
!!await remoteCall.callRemoteTestUtil(
'fakeMouseRightClick', appId, ['list.list']),
'fakeMouseRightClick failed');
// Wait until the context menu is shown.
await remoteCall.waitForElement(appId, contextMenu);
// Assert the menu delete command is disabled.
const deleteDisabled = '[command="#delete"][disabled="disabled"]';
await remoteCall.waitForElement(appId, contextMenu + ' ' + deleteDisabled);
};
/**
* Tests that the toolbar Delete button opens the delete confirm dialog and
* that the dialog cancel button has the focus by default.
*/
testcase.toolbarDeleteButtonOpensDeleteConfirmDialog = async () => {
// Open Files app.
const appId =
await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.desktop]);
// Select My Desktop Background.png
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'selectFile', appId, [ENTRIES.desktop.nameText]));
// Click the toolbar Delete button.
await remoteCall.simulateUiClick(appId, '#delete-button');
// Check: the delete confirm dialog should appear.
await remoteCall.waitForElement(appId, '.cr-dialog-container.shown');
// Check: the dialog 'Cancel' button should be focused by default.
const defaultDialogButton =
await remoteCall.waitForElement(appId, '.cr-dialog-cancel:focus');
chrome.test.assertEq('Cancel', defaultDialogButton.text);
};
/**
* Tests that the toolbar Delete button keeps focus after the delete confirm
* dialog is closed.
*/
testcase.toolbarDeleteButtonKeepFocus = async () => {
// Open Files app.
const appId =
await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.hello], []);
// USB delete never uses trash and always shows the delete dialog.
const USB_VOLUME_QUERY = '#directory-tree [volume-type-icon="removable"]';
// Mount a USB volume.
await sendTestMessage({name: 'mountFakeUsb'});
// Wait for the USB volume to mount.
await remoteCall.waitForElement(appId, USB_VOLUME_QUERY);
// Click to open the USB volume.
chrome.test.assertTrue(
!!await remoteCall.callRemoteTestUtil(
'fakeMouseClick', appId, [USB_VOLUME_QUERY]),
'fakeMouseClick failed');
// Check: the USB files should appear in the file list.
const files = TestEntryInfo.getExpectedRows(BASIC_FAKE_ENTRY_SET);
await remoteCall.waitForFiles(appId, files, {ignoreLastModifiedTime: true});
// Select hello.txt
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'selectFile', appId, [ENTRIES.hello.nameText]));
// Click the toolbar Delete button.
await remoteCall.simulateUiClick(appId, '#delete-button');
// Check: the Delete button should lose focus.
await remoteCall.waitForElementLost(appId, '#delete-button:focus');
// Check: the delete confirm dialog should appear.
await remoteCall.waitForElement(appId, '.cr-dialog-container.shown');
// Check: the dialog 'Cancel' button should be focused by default.
const defaultDialogButton =
await remoteCall.waitForElement(appId, '.cr-dialog-cancel:focus');
chrome.test.assertEq('Cancel', defaultDialogButton.text);
// Click the dialog 'Cancel' button.
await remoteCall.waitAndClickElement(appId, '.cr-dialog-cancel');
// Check: the toolbar Delete button should be focused.
await remoteCall.waitForElement(appId, '#delete-button:focus');
};
/**
* Tests deleting an entry using the toolbar.
*/
testcase.toolbarDeleteEntry = async () => {
const beforeDeletion = TestEntryInfo.getExpectedRows([
ENTRIES.photos,
ENTRIES.hello,
ENTRIES.world,
ENTRIES.desktop,
ENTRIES.beautiful,
]);
const afterDeletion = TestEntryInfo.getExpectedRows([
ENTRIES.photos,
ENTRIES.hello,
ENTRIES.world,
ENTRIES.beautiful,
]);
// Open Files app.
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS);
// Confirm entries in the directory before the deletion.
await remoteCall.waitForFiles(
appId, beforeDeletion, {ignoreLastModifiedTime: true});
// Select My Desktop Background.png
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'selectFile', appId, ['My Desktop Background.png']));
// Click delete button in the toolbar.
if (await sendTestMessage({name: 'isTrashEnabled'}) === 'true') {
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'fakeMouseClick', appId, ['#move-to-trash-button']));
} else {
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'fakeMouseClick', appId, ['#delete-button']));
// Confirm that the confirmation dialog is shown.
await remoteCall.waitForElement(appId, '.cr-dialog-container.shown');
// Press delete button.
chrome.test.assertTrue(
!!await remoteCall.callRemoteTestUtil(
'fakeMouseClick', appId, ['button.cr-dialog-ok']),
'fakeMouseClick failed');
}
// Confirm the file is removed.
await remoteCall.waitForFiles(
appId, afterDeletion, {ignoreLastModifiedTime: true});
};
/**
* Tests that refresh button hides in selection mode.
*
* Non-watchable volumes (other than Recent views) display the refresh
* button so users can refresh the file list content. However this
* button should be hidden when entering the selection mode.
* crbug.com/978383
*/
testcase.toolbarRefreshButtonWithSelection = async () => {
// Open files app.
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS);
// Add files to the DocumentsProvider volume (which is non-watchable)
await addEntries(['documents_provider'], BASIC_LOCAL_ENTRY_SET);
// Wait for the DocumentsProvider volume to mount.
const documentsProviderVolumeQuery =
'[volume-type-icon="documents_provider"]';
await remoteCall.waitAndClickElement(appId, documentsProviderVolumeQuery);
await remoteCall.waitUntilCurrentDirectoryIsChanged(
appId, '/DocumentsProvider');
// Check that refresh button is visible.
await remoteCall.waitForElement(appId, '#refresh-button:not([hidden])');
// Ctrl+A to enter selection mode.
const ctrlA = ['#file-list', 'a', true, false, false];
await remoteCall.fakeKeyDown(appId, ...ctrlA);
// Check that the button should be hidden.
await remoteCall.waitForElement(appId, '#refresh-button[hidden]');
};
/**
* Tests that refresh button is not shown when any of the Recent views
* (or views built on top of them, such as the Media Views) are
* selected.
*/
testcase.toolbarRefreshButtonHiddenInRecents = async () => {
// Open files app.
const appId =
await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.beautiful], []);
// Navigate to Recent.
await remoteCall.waitAndClickElement(
appId, '#directory-tree [entry-label="Recent"]');
await remoteCall.waitUntilCurrentDirectoryIsChanged(appId, '/Recent');
// Check that the button should be hidden.
await remoteCall.waitForElement(appId, '#refresh-button[hidden]');
// Navigate to Images.
await remoteCall.waitAndClickElement(
appId, '#directory-tree [entry-label="Images"]');
await remoteCall.waitUntilCurrentDirectoryIsChanged(appId, '/Images');
// Check that the button should be hidden.
await remoteCall.waitForElement(appId, '#refresh-button[hidden]');
};
/**
* Tests that command Alt+A focus the toolbar.
*/
testcase.toolbarAltACommand = async () => {
// Open files app.
const appId =
await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.beautiful], []);
// Press Alt+A in the File List.
const altA = ['#file-list', 'a', false, false, true];
await remoteCall.fakeKeyDown(appId, ...altA);
// Check that a menu-button should be focused.
const focusedElement =
await remoteCall.callRemoteTestUtil('getActiveElement', appId, []);
const cssClasses = focusedElement.attributes['class'] || '';
chrome.test.assertTrue(cssClasses.includes('menu-button'));
};
/**
* Tests that the menu drop down follows the button if the button moves. This
* happens when the search box is expanded and then collapsed.
*/
testcase.toolbarMultiMenuFollowsButton = async () => {
const entry = ENTRIES.hello;
// Open Files app on Downloads.
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS, [entry], []);
// Override the tasks so the "Open" button becomes a dropdown button.
await remoteCall.callRemoteTestUtil(
'overrideTasks', appId, [DOWNLOADS_FAKE_TASKS]);
// Select an entry in the file list.
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'selectFile', appId, [entry.nameText]));
// Click the toolbar search button.
await remoteCall.waitAndClickElement(appId, '#search-button');
// Wait for the search box to expand.
await remoteCall.waitForElementLost(appId, '#search-wrapper[collapsed]');
// Click the toolbar "Open" dropdown button.
await remoteCall.simulateUiClick(appId, '#tasks');
// Wait for the search box to collapse.
await remoteCall.waitForElement(appId, '#search-wrapper[collapsed]');
// Check that the dropdown menu and "Open" button are aligned.
const caller = getCaller();
await repeatUntil(async () => {
const openButton =
await remoteCall.waitForElementStyles(appId, '#tasks', ['width']);
const menu =
await remoteCall.waitForElementStyles(appId, '#tasks-menu', ['width']);
if (openButton.renderedLeft !== menu.renderedLeft) {
return pending(
caller,
`Waiting for the menu and button to be aligned: ` +
`${openButton.renderedLeft} != ${menu.renderedLeft}`);
}
});
};
/**
* Tests that the sharesheet button is enabled and executable.
*/
testcase.toolbarSharesheetButtonWithSelection = async () => {
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS);
// Fake chrome.fileManagerPrivate.sharesheetHasTargets to return true.
let fakeData = {
'chrome.fileManagerPrivate.sharesheetHasTargets': ['static_fake', [true]],
};
await remoteCall.callRemoteTestUtil('foregroundFake', appId, [fakeData]);
// Fake chrome.fileManagerPrivate.invokeSharesheet.
fakeData = {
'chrome.fileManagerPrivate.invokeSharesheet': ['static_fake', []],
};
await remoteCall.callRemoteTestUtil('foregroundFake', appId, [fakeData]);
const entry = ENTRIES.hello;
// Select an entry in the file list.
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'selectFile', appId, [entry.nameText]));
await remoteCall.waitAndClickElement(
appId, '#sharesheet-button:not([hidden])');
// Check invoke sharesheet is called.
chrome.test.assertEq(
1, await remoteCall.callRemoteTestUtil('staticFakeCounter', appId, [
'chrome.fileManagerPrivate.invokeSharesheet'
]));
// Remove fakes.
const removedCount = await remoteCall.callRemoteTestUtil(
'removeAllForegroundFakes', appId, []);
chrome.test.assertEq(2, removedCount);
};
/**
* Tests that the sharesheet command in context menu is enabled and executable.
*/
testcase.toolbarSharesheetContextMenuWithSelection = async () => {
const contextMenu = '#file-context-menu:not([hidden])';
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS);
// Fake chrome.fileManagerPrivate.sharesheetHasTargets to return true.
let fakeData = {
'chrome.fileManagerPrivate.sharesheetHasTargets': ['static_fake', [true]],
};
await remoteCall.callRemoteTestUtil('foregroundFake', appId, [fakeData]);
// Fake chrome.fileManagerPrivate.invokeSharesheet.
fakeData = {
'chrome.fileManagerPrivate.invokeSharesheet': ['static_fake', []],
};
await remoteCall.callRemoteTestUtil('foregroundFake', appId, [fakeData]);
const entry = ENTRIES.hello;
// Select an entry in the file list.
chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
'selectFile', appId, [entry.nameText]));
chrome.test.assertTrue(!!await remoteCall.waitAndRightClick(
appId, '#file-list .table-row[selected]'));
// Wait until the context menu is shown.
await remoteCall.waitForElement(appId, contextMenu);
// Assert the menu sharesheet command is not hidden.
const sharesheetEnabled =
'[command="#invoke-sharesheet"]:not([hidden]):not([disabled])';
await remoteCall.waitAndClickElement(
appId, contextMenu + ' ' + sharesheetEnabled);
// Check invoke sharesheet is called.
chrome.test.assertEq(
1, await remoteCall.callRemoteTestUtil('staticFakeCounter', appId, [
'chrome.fileManagerPrivate.invokeSharesheet'
]));
// Remove fakes.
const removedCount = await remoteCall.callRemoteTestUtil(
'removeAllForegroundFakes', appId, []);
chrome.test.assertEq(2, removedCount);
};
/**
* Tests that the sharesheet item is hidden if no entry is selected.
*/
testcase.toolbarSharesheetNoEntrySelected = async () => {
const contextMenu = '#file-context-menu:not([hidden])';
const appId = await setupAndWaitUntilReady(RootPath.DOWNLOADS);
// Fake chrome.fileManagerPrivate.sharesheetHasTargets to return true.
const fakeData = {
'chrome.fileManagerPrivate.sharesheetHasTargets': ['static_fake', [true]],
};
await remoteCall.callRemoteTestUtil('foregroundFake', appId, [fakeData]);
// Right click the list without selecting an entry.
chrome.test.assertTrue(
!!await remoteCall.waitAndRightClick(appId, 'list.list'));
// Wait until the context menu is shown.
await remoteCall.waitForElement(appId, contextMenu);
// Assert the menu sharesheet command is disabled.
const sharesheetDisabled =
'[command="#invoke-sharesheet"][hidden][disabled="disabled"]';
await remoteCall.waitForElement(
appId, contextMenu + ' ' + sharesheetDisabled);
await remoteCall.waitForElement(appId, '#sharesheet-button[hidden]');
// Remove fakes.
const removedCount = await remoteCall.callRemoteTestUtil(
'removeAllForegroundFakes', appId, []);
chrome.test.assertEq(1, removedCount);
};
| 35.486747 | 127 | 0.722958 |
432a528351b381187d9c7942deea715a0d3cd4f3 | 3,789 | js | JavaScript | yonoa-fe/webpack.dev.config.js | zyjxh/YON_OA | 5ece2d454b6d7d33df0e2beebaf7bcb49fc4261f | [
"MIT"
] | null | null | null | yonoa-fe/webpack.dev.config.js | zyjxh/YON_OA | 5ece2d454b6d7d33df0e2beebaf7bcb49fc4261f | [
"MIT"
] | null | null | null | yonoa-fe/webpack.dev.config.js | zyjxh/YON_OA | 5ece2d454b6d7d33df0e2beebaf7bcb49fc4261f | [
"MIT"
] | null | null | null | var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
//var ExtractTextPlugin = require("extract-text-webpack-plugin");
const scriptPort = process.env.SCRIPT_PORT || 3004;
let localPath = 'localhost';
if (process.env.IP === 'true') {
//获取本机ip
var os = require('os');
var ifaces = os.networkInterfaces();
var ips = [];
for (var dev in ifaces) {
var alias = 0;
ifaces[dev].forEach(function(details) {
if (details.family == 'IPv4') {
//console.log(dev+(alias?':'+alias:''),details.address);
ips.push(details.address)
++alias;
}
});
}
localPath = ips[1];
}
var origin = [
path.resolve('src/common'),
path.resolve('src/client'),
path.resolve('node_modules/@mdf'),
path.resolve('src/mobile')
];
//let extractCSS = new ExtractTextPlugin('static/styles/default/vendor.css');
//let extractLESS = new ExtractTextPlugin('static/styles/default/index.css');
var config = {
entry: {
// 'basic':[],
// 'index':[],
'index': './src/client',
// 'billing': './src/client/billing',
// 'touch': './src/client/touch'
},
output: {
publicPath: `http://${localPath}:${scriptPort}/`,
path: path.join(__dirname, './'),
filename: 'static/javascripts/[name].js'
},
resolve: {
extensions: [".js", ".jsx"],
},
externals: ['meta-touch'],
module: {
//root: origin,
//modulesDirectories: ['node_modules'],
rules: [{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
include: origin,
query: {
plugins: [
["import", { "style": "css", "libraryName": "antd" }]
],
cacheDirectory: true
}
}, {
test: /\.(jpg|png|gif|ico)$/,
loader: 'url-loader',
options: {
limit: 8192
},
include: [
origin,
path.resolve('node_modules/u8c-components/dist'),
]
}, {
test: /\.less$/,
use: [
{ loader: 'style-loader' }, {
loader: 'css-loader',
options: {
importLoaders: 2,
minimize: true
},
}, {
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
autoprefixer()
]
}
}, {
loader: 'less-loader'
},
],
}, {
test: /\.css$/,
use: [
{ loader: 'style-loader' }, {
loader: 'css-loader',
options: {
importLoaders: 2,
minimize: true
},
}, {
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
autoprefixer()
]
}
},
],
}, {
test: /\.(woff|svg|eot|ttf)\??.*$/,
loader: 'url-loader',
options: {
name: 'fonts/[name].[md5:hash:hex:7].[ext]'
},
//loader: 'url-loader?name=fonts/[name].[md5:hash:hex:7].[ext]',
}]
},
/* postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
],*/
plugins: [
new CaseSensitivePathsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"development"',
'process.env.__CLIENT__': 'true',
}),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./manifest.development.json')
}),
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
headers: {
"Access-Control-Allow-Origin": "*"
},
host: '0.0.0.0',
hot: true,
inline: true,
port: scriptPort,
disableHostCheck: true
},
devtool: 'source-map',
cache: true,
};
module.exports = config
| 22.288235 | 78 | 0.515439 |
432a55e9830aeed40469eaf0bac8f987ccc66fd7 | 2,242 | js | JavaScript | src/components/content/Content.js | Aiso786/formio.js | 91797b79d684d251296b6a6537998c30c01970b9 | [
"MIT"
] | null | null | null | src/components/content/Content.js | Aiso786/formio.js | 91797b79d684d251296b6a6537998c30c01970b9 | [
"MIT"
] | null | null | null | src/components/content/Content.js | Aiso786/formio.js | 91797b79d684d251296b6a6537998c30c01970b9 | [
"MIT"
] | null | null | null | import _ from 'lodash';
import BaseComponent from '../base/Base';
export default class ContentComponent extends BaseComponent {
static schema(...extend) {
return BaseComponent.schema({
label: 'Content',
type: 'content',
key: 'content',
input: false,
html: ''
}, ...extend);
}
static get builderInfo() {
return {
title: 'Content',
group: 'basic',
icon: 'fa fa-html5',
documentation: 'http://help.form.io/userguide/#content-component',
weight: 100,
schema: ContentComponent.schema()
};
}
get defaultSchema() {
return ContentComponent.schema();
}
setHTML() {
this.htmlElement.innerHTML = this.interpolate(this.component.html);
}
build(state = {}) {
const { quill = {} } = state;
this.createElement();
this.htmlElement = this.ce('div', {
id: this.id,
class: `form-group ${this.component.className}`
});
this.htmlElement.component = this;
if (this.options.builder) {
const editorElement = this.ce('div');
this.element.appendChild(editorElement);
this.addQuill(editorElement, this.wysiwygDefault, (element) => {
this.component.html = element.value;
}).then((editor) => {
let contents = quill.contents;
if (_.isString(contents)) {
try {
contents = JSON.parse(contents);
}
catch (err) {
console.warn(err);
}
}
if (_.isObject(contents)) {
editor.setContents(contents);
}
else {
editor.clipboard.dangerouslyPasteHTML(this.component.html);
}
}).catch(err => console.warn(err));
}
else {
this.setHTML();
if (this.component.refreshOnChange) {
this.on('change', () => this.setHTML(), true);
}
}
this.element.appendChild(this.htmlElement);
this.attachLogic();
}
get emptyValue() {
return '';
}
destroy() {
const state = super.destroy();
if (this.quill) {
try {
state.quill = {
contents: JSON.stringify(this.quill.getContents())
};
}
catch (err) {
console.warn(err);
}
}
return state;
}
}
| 22.42 | 72 | 0.557092 |
432a58af2dd1bd25369705a870b8de7e65dc806f | 2,010 | js | JavaScript | ditto/static/flux-chat/js/actions/RouteActionCreators.js | Kvoti/ditto | eb4efb241e54bf679222d14afeb71d9d5441c122 | [
"BSD-3-Clause"
] | null | null | null | ditto/static/flux-chat/js/actions/RouteActionCreators.js | Kvoti/ditto | eb4efb241e54bf679222d14afeb71d9d5441c122 | [
"BSD-3-Clause"
] | 9 | 2015-11-10T15:17:22.000Z | 2015-11-12T11:07:02.000Z | ditto/static/flux-chat/js/actions/RouteActionCreators.js | Kvoti/ditto | eb4efb241e54bf679222d14afeb71d9d5441c122 | [
"BSD-3-Clause"
] | null | null | null | var ChatAppDispatcher = require('../dispatcher/ChatAppDispatcher');
var ChatConstants = require('../constants/ChatConstants');
var ChatWebAPIUtils = require('../utils/ChatWebAPIUtils');
var ChatMessageUtils = require('../utils/ChatMessageUtils');
var ActionTypes = ChatConstants.ActionTypes;
module.exports = {
changeChatroom: function(path) {
var parts = path.split('/');
var roomID = parts[parts.length - 2];
if (roomID !== 'chatroom') {
var roomJID = roomID + '@muc.' + Strophe.getDomainFromJid(chatConf.me); // FIXME
ChatWebAPIUtils.joinChatroom(roomJID);
ChatAppDispatcher.dispatch({
type: ActionTypes.CHANGE_CHATROOM,
roomJID: roomJID,
roomID: roomID
});
}
},
changePrivateChat: function(path) {
path = decodeURIComponent(path);
var parts = path.split('/');
var threadID = parts[parts.length - 2];
var threadType;
if (parts.length === 5) {
var friend = ChatMessageUtils.getMessageOther(threadID);
threadType = parts[parts.length - 3] === 'messages' ? 'message' : 'session'; // FIXME
// TODO only if not already friend
ChatWebAPIUtils.addFriend(friend);
// TODO only if new session
ChatWebAPIUtils.startSession(
threadID,
[
// TODO gah, fix all the places where we do this to get the current user
Strophe.getNodeFromJid(chatConf.me),
friend
]
);
ChatAppDispatcher.dispatch({
type: ActionTypes.CHANGE_PRIVATE_CHAT,
threadType: threadType,
threadID: threadID
});
} else {
threadType = parts[parts.length - 2] === 'messages' ? 'message' : 'session'; // FIXME
ChatAppDispatcher.dispatch({
type: ActionTypes.CHANGE_PRIVATE_CHAT_TYPE,
threadType: threadType
});
}
},
};
| 35.263158 | 98 | 0.580597 |
432b1123d20ab01fbd19117a0e910745f9fe17e9 | 6,398 | js | JavaScript | test/lib/StreamParserTest.js | polem/node-ipp | ef3753a6d8318eb84ce5de881f8f2b98a1dd8089 | [
"MIT"
] | 10 | 2018-06-20T18:42:26.000Z | 2022-02-16T15:44:02.000Z | test/lib/StreamParserTest.js | polem/node-ipp | ef3753a6d8318eb84ce5de881f8f2b98a1dd8089 | [
"MIT"
] | 148 | 2018-02-13T18:06:28.000Z | 2022-03-31T20:57:39.000Z | test/lib/StreamParserTest.js | polem/node-ipp | ef3753a6d8318eb84ce5de881f8f2b98a1dd8089 | [
"MIT"
] | 14 | 2018-07-22T06:55:36.000Z | 2021-12-14T11:23:52.000Z | 'use strict';
const assert = require('assertthat');
const StreamParser = require('../../lib/StreamParser');
const serialize = require('../../lib/serializer');
suite('StreamParser', () => {
test('is a function', (done) => {
assert.that(StreamParser).is.ofType('function');
done();
});
test('returns no attributes and streams no data if ipp message is incomplete', (done) => {
/* eslint-disable line-comment-position */
/* eslint-disable no-inline-comments */
const data = Buffer.from(
'0200' + // version 2.0
'000B' + // Get-Printer-Attributes
'00000001' + // reqid
'01', // operation-attributes-tag
'hex'
);
/* eslint-enable line-comment-position */
/* eslint-enable no-inline-comments */
const streamParser = new StreamParser();
streamParser.once('attributes', () => {
assert.that('the attributes').is.equalTo('should not be emitted');
});
streamParser.once('data', () => {
assert.that('the data stream').is.equalTo('should not emit data');
});
streamParser.once('end', () => {
done();
});
streamParser.write(data);
streamParser.end();
});
test('omits unknown tags', (done) => {
const data = serialize({
operation: 'CUPS-Get-Printers',
'operation-attributes-tag': {
'attributes-charset': 'utf-8',
'attributes-natural-language': 'en',
schrott: 'hugo'
}
});
const streamParser = new StreamParser();
let attrCalled = false;
streamParser.once('attributes', (attr) => {
attrCalled = true;
assert.that(attr['operation-attributes-tag']['attributes-charset']).is.equalTo('utf-8');
assert.that(attr['operation-attributes-tag']['attributes-natural-language']).is.equalTo('en');
assert.that(attr['operation-attributes-tag'].schrott).is.undefined();
});
streamParser.on('data', () => {
assert.that('the data stream').is.equalTo('should not emit data');
});
streamParser.once('end', () => {
assert.that(attrCalled).is.true();
done();
});
streamParser.once('error', (err) => {
done(err);
});
streamParser.write(data);
streamParser.end();
});
test('returns no data if tag is unknown', (done) => {
/* eslint-disable line-comment-position */
/* eslint-disable no-inline-comments */
const data = Buffer.from(
'0200' + // version 2.0
'000B' + // Get-Printer-Attributes
'00000001' + // reqid
'01' + // operation-attributes-tag
// unknown attribute
'1200147072696e7465722d67656f2d6c6f636174696f6e0000',
'hex'
);
/* eslint-enable line-comment-position */
/* eslint-enable no-inline-comments */
const streamParser = new StreamParser();
let dataEmitted = false;
streamParser.once('attributes', () => {
assert.that('the attributes').is.equalTo('should not be emitted');
});
streamParser.on('data', () => {
dataEmitted = true;
});
streamParser.once('end', () => {
assert.that(dataEmitted).is.equalTo(false);
done();
});
streamParser.once('error', (err) => {
assert.that(err.message).is.startingWith('This should not happen.');
});
streamParser.write(data);
streamParser.end();
});
test('returns message and data if send in one chunk', (done) => {
/* eslint-disable line-comment-position */
/* eslint-disable no-inline-comments */
const data = Buffer.from(
'0200' + // version 2.0
'000B' + // Get-Printer-Attributes
'00000001' + // reqid
'01' + // operation-attributes-tag
// blah blah the required bloat of this protocol
'470012617474726962757465732d6368617273657400057574662d3848001b617474726962757465732d6e61747572616c2d6c616e67756167650002656e' +
'03' + // end-of-attributes-tag
'54657374',
'hex'
);
/* eslint-enable line-comment-position */
/* eslint-enable no-inline-comments */
let attributesOk = false;
let dataOk = false;
const streamParser = new StreamParser();
streamParser.once('attributes', (attributes) => {
assert.that(attributes).is.equalTo({
version: '2.0',
operation: 'Get-Printer-Attributes',
id: 1,
'operation-attributes-tag': {
'attributes-charset': 'utf-8',
'attributes-natural-language': 'en'
}
});
attributesOk = true;
});
streamParser.on('data', (chunk) => {
assert.that(chunk.length).is.equalTo(4);
assert.that(chunk.toString('utf8')).is.equalTo('Test');
dataOk = true;
});
streamParser.once('end', () => {
assert.that(attributesOk).is.true();
assert.that(dataOk).is.true();
done();
});
streamParser.write(data);
streamParser.end();
});
test('returns message and data if send in two chunks', (done) => {
/* eslint-disable line-comment-position */
/* eslint-disable no-inline-comments */
const data = Buffer.from(
'0200' + // version 2.0
'000B' + // Get-Printer-Attributes
'00000001' + // reqid
'01' + // operation-attributes-tag
// blah blah the required bloat of this protocol
'470012617474726962757465732d6368617273657400057574662d3848001b617474726962757465732d6e61747572616c2d6c616e67756167650002656e' +
'03', // end-of-attributes-tag
'hex'
);
/* eslint-enable line-comment-position */
/* eslint-enable no-inline-comments */
let attributesOk = false;
let dataOk = false;
const streamParser = new StreamParser();
streamParser.once('attributes', (attributes) => {
assert.that(attributes).is.equalTo({
version: '2.0',
operation: 'Get-Printer-Attributes',
id: 1,
'operation-attributes-tag': {
'attributes-charset': 'utf-8',
'attributes-natural-language': 'en'
}
});
attributesOk = true;
});
streamParser.on('data', (chunk) => {
assert.that(chunk.length).is.equalTo(4);
assert.that(chunk.toString('utf8')).is.equalTo('Test');
dataOk = true;
});
streamParser.once('end', () => {
assert.that(attributesOk).is.true();
assert.that(dataOk).is.true();
done();
});
streamParser.write(data);
streamParser.write(Buffer.from('54657374', 'hex'));
streamParser.end();
});
});
| 30.759615 | 136 | 0.601125 |
432b8ae4771254c3956de9842e3a3304328dce1b | 1,599 | js | JavaScript | src/js/app.js | 125-Ciceksepeti-React-Bootcamp/odev-2-Ogzhnsfgl | 9b00c9fda9fb6fe8217cb053b5220120bdf13af8 | [
"MIT"
] | null | null | null | src/js/app.js | 125-Ciceksepeti-React-Bootcamp/odev-2-Ogzhnsfgl | 9b00c9fda9fb6fe8217cb053b5220120bdf13af8 | [
"MIT"
] | null | null | null | src/js/app.js | 125-Ciceksepeti-React-Bootcamp/odev-2-Ogzhnsfgl | 9b00c9fda9fb6fe8217cb053b5220120bdf13af8 | [
"MIT"
] | null | null | null | import { duckList } from './duck.js';
import { dogList } from './dog.js';
import '../scss/app.scss';
/* Required HTML Elements */
const cardsList = document.querySelector('.cards-list');
/* Merge duckList and DogList */
const animalList = [...dogList, ...duckList];
animalList.map((item, index) => {
const animal = item[`animal${index + 1}`];
/* Create Card Element */
const cards = document.createElement('div');
cards.className = 'card';
/* Check animal type to set paw image */
if (animal.numberOfLegs === 4) {
cards.innerHTML += `
<div class="card-image">
<img src=${animal.image} alt="animal1" />
</div>
<div class="card-body">
<div class="card-body-title">
<p>${animal.name}</p>
</div>
<div class="card-body-text">${animal.age}</div>
</div>
<div class="card-body-paw"><img src="../images/content/dog-paw.png" alt="" /></div>
`;
} else {
cards.innerHTML += `
<div class="card-image">
<img src=${animal.image} alt="animal1" />
</div>
<div class="card-body">
<div class="card-body-title">
<p>${animal.name}</p>
</div>
<div class="card-body-text">${animal.age}</div>
</div>
<div class="card-body-paw"><img src="../images/content/duck-paw.png" alt="" /></div>
`;
}
/* Append card item into cardList */
cardsList.appendChild(cards);
});
| 34.76087 | 100 | 0.50344 |
432cda86b6fc278272bf777d6b1da604ef7bacdc | 1,601 | js | JavaScript | test/index.js | geek/node-style | faf394ddd4be35f7f0490690e9b278149c7c1dd0 | [
"BSD-3-Clause"
] | 6 | 2016-11-30T06:11:49.000Z | 2021-06-08T14:32:15.000Z | test/index.js | geek/node-style | faf394ddd4be35f7f0490690e9b278149c7c1dd0 | [
"BSD-3-Clause"
] | null | null | null | test/index.js | geek/node-style | faf394ddd4be35f7f0490690e9b278149c7c1dd0 | [
"BSD-3-Clause"
] | 1 | 2017-08-29T02:11:50.000Z | 2017-08-29T02:11:50.000Z | 'use strict';
var ChildProcess = require('child_process');
var Path = require('path');
var Code = require('code');
var Fse = require('fs-extra');
var Lab = require('lab');
const lab = exports.lab = Lab.script();
const expect = Code.expect;
const describe = lab.describe;
const it = lab.it;
Code.settings.truncateMessages = false;
Code.settings.comparePrototypes = false;
const fixturesDirectory = Path.join(__dirname, 'fixtures');
const failDirectory = Path.join(fixturesDirectory, 'fail');
const successDirectory = Path.join(fixturesDirectory, 'success');
const tempDirectory = Path.join(process.cwd(), 'test-tmp');
describe('Node Style CLI', function() {
lab.after(function(done) {
Fse.remove(tempDirectory, done);
});
describe('run()', function() {
it('runs binary and reports success', function(done) {
var child = ChildProcess.fork('bin/node-style', ['-w', successDirectory],
{silent: true});
child.once('error', function(err) {
expect(err).to.not.exist();
});
child.once('close', function(code, signal) {
expect(code).to.equal(0);
expect(signal).to.equal(null);
done();
});
});
it('runs binary and reports failures', function(done) {
var child = ChildProcess.fork('bin/node-style', ['-w', failDirectory],
{silent: true});
child.once('error', function(err) {
expect(err).to.not.exist();
});
child.once('close', function(code, signal) {
expect(code).to.equal(1);
expect(signal).to.equal(null);
done();
});
});
});
});
| 27.135593 | 79 | 0.62336 |
432cdd7e2a6d5421ff364bc6a91be2e37625c87f | 87,163 | js | JavaScript | pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/static/js/backform.pgadmin.js | Anillab/One-Minute-Pitch | 123f7b2010d3ae0f031066db1bcfe6eda7a41e84 | [
"MIT"
] | 4 | 2019-10-03T21:58:22.000Z | 2021-02-12T13:33:32.000Z | pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/static/js/backform.pgadmin.js | Anillab/One-Minute-Pitch | 123f7b2010d3ae0f031066db1bcfe6eda7a41e84 | [
"MIT"
] | 4 | 2020-01-22T13:45:12.000Z | 2022-02-10T20:58:09.000Z | pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/static/js/backform.pgadmin.js | Anillab/One-Minute-Pitch | 123f7b2010d3ae0f031066db1bcfe6eda7a41e84 | [
"MIT"
] | 1 | 2021-01-13T09:30:29.000Z | 2021-01-13T09:30:29.000Z | (function(root, factory) {
// Set up Backform appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define([
'sources/gettext', 'underscore', 'underscore.string', 'jquery',
'backbone', 'backform', 'backgrid', 'codemirror', 'spectrum',
'pgadmin.backgrid', 'select2'
],
function(gettext, _, S, $, Backbone, Backform, Backgrid, CodeMirror) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backform.
return factory(root, gettext, _, S, $, Backbone, Backform, Backgrid, CodeMirror);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
var _ = require('underscore') || root._,
$ = root.jQuery || root.$ || root.Zepto || root.ender,
Backbone = require('backbone') || root.Backbone,
Backform = require('backform') || root.Backform,
Backgrid = require('backgrid') || root.Backgrid,
CodeMirror = require('codemirror') || root.CodeMirror,
S = require('underscore.string'),
gettext = require('sources/gettext');
factory(root, gettext, _, S, $, Backbone, Backform, Backgrid, CodeMirror);
// Finally, as a browser global.
} else {
factory(root, root.gettext, root._, root.s, (root.jQuery || root.Zepto || root.ender || root.$), root.Backbone, root.Backform, root.Backgrid, root.CodeMirror);
}
}(this, function(root, gettext, _, S, $, Backbone, Backform, Backgrid, CodeMirror) {
var pgAdmin = (window.pgAdmin = window.pgAdmin || {});
pgAdmin.editableCell = function() {
if (this.attributes && !_.isUndefined(this.attributes.disabled) &&
!_.isNull(this.attributes.disabled)) {
if(_.isFunction(this.attributes.disabled)) {
return !(this.attributes.disabled.apply(this, arguments));
}
if (_.isBoolean(this.attributes.disabled)) {
return !this.attributes.disabled;
}
}
};
// HTML markup global class names. More can be added by individual controls
// using _.extend. Look at RadioControl as an example.
_.extend(Backform, {
controlLabelClassName: "control-label pg-el-sm-3 pg-el-xs-12",
controlsClassName: "pgadmin-controls pg-el-sm-9 pg-el-xs-12",
groupClassName: "pgadmin-control-group form-group pg-el-xs-12",
setGroupClassName: "set-group pg-el-xs-12",
tabClassName: "backform-tab pg-el-xs-12",
setGroupContentClassName: "fieldset-content pg-el-xs-12"
});
var controlMapper = Backform.controlMapper = {
'int': ['uneditable-input', 'numeric', 'integer'],
'text': ['uneditable-input', 'input', 'string'],
'numeric': ['uneditable-input', 'numeric', 'numeric'],
'date': 'datepicker',
'datetime': 'datetimepicker',
'boolean': 'boolean',
'options': ['readonly-option', 'select', Backgrid.Extension.PGSelectCell],
'multiline': ['textarea', 'textarea', 'string'],
'collection': ['sub-node-collection', 'sub-node-collection', 'string'],
'uniqueColCollection': ['unique-col-collection', 'unique-col-collection', 'string'],
'switch' : 'switch',
'select2': 'select2',
'note': 'note',
'color': 'color'
};
var getMappedControl = Backform.getMappedControl = function(type, mode) {
if (type in Backform.controlMapper) {
var m = Backform.controlMapper[type];
if (!_.isArray(m)) {
return m;
}
var idx = 1, len = _.size(m);
switch (mode) {
case 'properties':
idx = 0;
break;
case 'edit':
case 'create':
case 'control':
idx = 1;
break;
case 'cell':
idx = 2;
break;
default:
idx = 0;
break;
}
return m[idx > len ? 0 : idx];
}
return type;
}
var BackformControlInit = Backform.Control.prototype.initialize,
BackformControlRemove = Backform.Control.prototype.remove;
// Override the Backform.Control to allow to track changes in dependencies,
// and rerender the View element
_.extend(Backform.Control.prototype, {
defaults: _.extend(Backform.Control.prototype.defaults, {helpMessage: null}),
initialize: function() {
BackformControlInit.apply(this, arguments);
// Listen to the dependent fields in the model for any change
var deps = this.field.get('deps');
var self = this;
if (deps && _.isArray(deps)) {
_.each(deps, function(d) {
var attrArr = d.split('.');
var name = attrArr.shift();
self.listenTo(self.model, "change:" + name, self.render);
});
}
},
remove: function() {
// Remove the events for the dependent fields in the model
var self = this,
deps = self.field.get('deps');
self.stopListening(self.model, "change:" + name, self.render);
self.stopListening(self.model.errorModel, "change:" + name, self.updateInvalid);
if (deps && _.isArray(deps)) {
_.each(deps, function(d) {
var attrArr = d.split('.');
var name = attrArr.shift();
self.stopListening(self.model, "change:" + name, self.render);
});
}
if (this.cleanup) {
this.cleanup.apply(this);
}
if (BackformControlRemove) {
BackformControlRemove.apply(self, arguments);
} else {
Backbone.View.prototype.remove.apply(self, arguments);
}
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
' <span class="<%=Backform.controlClassName%> uneditable-input" <%=disabled ? "disabled" : ""%>>',
' <%-value%>',
' </span>',
'</div>',
'<% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
'<% } %>',
].join("\n")),
clearInvalid: function() {
this.$el.removeClass(Backform.errorClassName);
this.$el.find(".pgadmin-control-error-message").remove();
return this;
},
updateInvalid: function() {
var self = this,
errorModel = this.model.errorModel;
if (!(errorModel instanceof Backbone.Model)) return this;
this.clearInvalid();
/*
* Find input which have name attribute.
*/
this.$el.find(':input[name]').not('button').each(function(ix, el) {
var attrArr = $(el).attr('name').split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
error = self.keyPathAccessor(errorModel.toJSON(), $(el).attr('name'));
if (_.isEmpty(error)) return;
self.$el.addClass(Backform.errorClassName);
});
},
/*
* Overriding the render function of the control to allow us to eval the
* values properly.
*/
render: function() {
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
// Evaluate the disabled, visible, and required option
_.extend(data, {
disabled: evalF(data.disabled, data, this.model),
visible: evalF(data.visible, data, this.model),
required: evalF(data.required, data, this.model)
});
// Clean up first
this.$el.removeClass(Backform.hiddenClassName);
if (!data.visible)
this.$el.addClass(Backform.hiddenClassName);
this.$el.html(this.template(data)).addClass(field.name);
this.updateInvalid();
return this;
}
});
/*
* Override the input control events in order to reslove the issue related to
* not updating the value sometimes in the input control.
*/
_.extend(
Backform.InputControl.prototype, {
events: {
"change input": "onChange",
"blur input": "onChange",
"keyup input": "onKeyUp",
"focus input": "clearInvalid"
},
onKeyUp: function(ev) {
if (this.key_timeout) {
clearTimeout(this.key_timeout);
}
this.keyup_timeout = setTimeout(function() {
this.onChange(ev);
}.bind(this), 400);
}
});
/*
* Override the textarea control events in order to resolve the issue related
* to not updating the value in model on certain browsers in few situations
* like copy/paste, deletion using backspace.
*
* Reference:
* http://stackoverflow.com/questions/11338592/how-can-i-bind-to-the-change-event-of-a-textarea-in-jquery
*/
_.extend(
Backform.TextareaControl.prototype, {
defaults: _.extend(
Backform.TextareaControl.prototype.defaults,
{rows: 5, helpMessage: null, maxlength: null}
),
events : {
"change textarea": "onChange",
"keyup textarea": "onKeyUp",
"paste textarea": "onChange",
"selectionchange textarea": "onChange",
"focus textarea": "clearInvalid"
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
' <textarea ',
' class="<%=Backform.controlClassName%> <%=extraClasses.join(\' \')%>" name="<%=name%>"',
' <% if (maxlength) { %>',
' maxlength="<%=maxlength%>"',
' <% } %>',
' placeholder="<%-placeholder%>" <%=disabled ? "disabled" : ""%>',
' rows=<%=rows ? rows : ""%>',
' <%=required ? "required" : ""%>><%-value%></textarea>',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>'
].join("\n")),
onKeyUp: function(ev) {
if (this.key_timeout) {
clearTimeout(this.key_timeout);
}
this.keyup_timeout = setTimeout(function() {
this.onChange(ev);
}.bind(this), 400);
}
});
/*
* Overriding the render function of the select control to allow us to use
* options as function, which should return array in the format of
* (label, value) pair.
*/
Backform.SelectControl.prototype.render = function() {
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
// Evaluate the disabled, visible, and required option
_.extend(data, {
disabled: evalF(data.disabled, data, this.model),
visible: evalF(data.visible, data, this.model),
required: evalF(data.required, data, this.model)
});
// Evaluation the options
if (_.isFunction(data.options)) {
try {
data.options = data.options(this)
} catch(e) {
// Do nothing
data.options = []
this.model.trigger('pgadmin-view:transform:error', this.model, this.field, e);
}
}
// Clean up first
this.$el.removeClass(Backform.hiddenClassName);
if (!data.visible)
this.$el.addClass(Backform.hiddenClassName);
this.$el.html(this.template(data)).addClass(field.name);
this.updateInvalid();
return this;
};
_.extend(Backform.SelectControl.prototype.defaults, {helpMessage: null});
var ReadonlyOptionControl = Backform.ReadonlyOptionControl = Backform.SelectControl.extend({
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
'<% for (var i=0; i < options.length; i++) { %>',
' <% var option = options[i]; %>',
' <% if (option.value === rawValue) { %>',
' <span class="<%=Backform.controlClassName%> uneditable-input" disabled><%-option.label%></span>',
' <% } %>',
'<% } %>',
'<% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
'<% } %>',
'</div>'
].join("\n")),
events: {},
getValueFromDOM: function() {
return this.formatter.toRaw(this.$el.find("span").text(), this.model);
}
});
/*
* Override the function 'updateInvalid' of the radio control to resolve an
* issue, which will not render the error block multiple times for each
* options.
*/
_.extend(
Backform.RadioControl.prototype, {
updateInvalid: function() {
var self = this,
errorModel = this.model.errorModel;
if (!(errorModel instanceof Backbone.Model)) return this;
this.clearInvalid();
/*
* Find input which have name attribute.
*/
this.$el.find(':input[name]').not('button').each(function(ix, el) {
var attrArr = $(el).attr('name').split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
error = self.keyPathAccessor(
errorModel.toJSON(), $(el).attr('name')
);
if (_.isEmpty(error)) return;
self.$el.addClass(Backform.errorClassName).find(
'[type="radio"]'
).append(
$("<div></div>").addClass(
'pgadmin-control-error-message pg-el-xs-offset-4 pg-el-xs-8 pg-el-xs-8 help-block'
).text(error));
});
}
});
// Requires the Bootstrap Switch to work.
var SwitchControl = Backform.SwitchControl = Backform.InputControl.extend({
defaults: {
label: "",
options: {
onText: gettext('Yes'),
offText: gettext('No'),
onColor: 'success',
offColor: 'primary',
size: 'small'
},
extraClasses: [],
helpMessage: null
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
' <div class="checkbox">',
' <label>',
' <input type="checkbox" class="<%=extraClasses.join(\' \')%>" name="<%=name%>" <%=value ? "checked=\'checked\'" : ""%> <%=disabled ? "disabled" : ""%> <%=required ? "required" : ""%> />',
' </label>',
' </div>',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>',
].join("\n")),
getValueFromDOM: function() {
return this.formatter.toRaw(
this.$input.prop('checked'),
this.model
);
},
events: {'switchChange.bootstrapSwitch': 'onChange'},
render: function() {
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
},
options = _.defaults({
disabled: evalF(field.disabled, field, this.model)
}, this.field.get('options'), this.defaults.options,
$.fn.bootstrapSwitch.defaults);
Backform.InputControl.prototype.render.apply(this, arguments);
this.$input = this.$el.find("input[type=checkbox]").first();
//Check & set additional properties
this.$input.bootstrapSwitch(
_.extend(options, {'state': rawValue})
);
return this;
}
});
// Backform Dialog view (in bootstrap tabbular form)
// A collection of field models.
var Dialog = Backform.Dialog = Backform.Form.extend({
/* Array of objects having attributes [label, fields] */
schema: undefined,
tagName: "div",
legend: true,
className: function() {
return 'pg-el-sm-12 pg-el-md-12 pg-el-lg-12 pg-el-xs-12';
},
tabPanelClassName: function() {
return Backform.tabClassName;
},
tabIndex: 0,
initialize: function(opts) {
var s = opts.schema;
if (s && _.isArray(s)) {
this.schema = _.each(s, function(o) {
if (o.fields && !(o.fields instanceof Backbone.Collection))
o.fields = new Backform.Fields(o.fields);
o.cId = o.cId || _.uniqueId('pgC_');
o.hId = o.hId || _.uniqueId('pgH_');
o.disabled = o.disabled || false;
o.legend = opts.legend;
});
if (opts.tabPanelClassName && _.isFunction(opts.tabPanelClassName)) {
this.tabPanelClassName = opts.tabPanelClassName;
}
}
this.model.errorModel = opts.errorModel || this.model.errorModel || new Backbone.Model();
this.controls = [];
},
template: {
'header': _.template([
'<li role="presentation" <%=disabled ? "disabled" : ""%>>',
' <a data-toggle="tab" data-tab-index="<%=tabIndex%>" href="#<%=cId%>"',
' id="<%=hId%>" aria-controls="<%=cId%>">',
'<%=label%></a></li>'].join(" ")),
'panel': _.template(
'<div role="tabpanel" class="tab-pane <%=label%> pg-el-sm-12 pg-el-md-12 pg-el-lg-12 pg-el-xs-12 fade" id="<%=cId%>" aria-labelledby="<%=hId%>"></div>'
)},
render: function() {
this.cleanup();
var c = this.$el
.children().first().children('.active')
.first().attr('id'),
m = this.model,
controls = this.controls,
tmpls = this.template,
self = this,
idx=(this.tabIndex * 100),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
this.$el
.empty()
.attr('role', 'tabpanel')
.attr('class', _.result(this, 'tabPanelClassName'));
m.panelEl = this.$el;
var tabHead = $('<ul class="nav nav-tabs" role="tablist"></ul>')
.appendTo(this.$el);
var tabContent = $('<ul class="tab-content pg-el-sm-12 pg-el-md-12 pg-el-lg-12 pg-el-xs-12"></ul>')
.appendTo(this.$el);
_.each(this.schema, function(o) {
idx++;
if (!o.version_compatible || !evalF(o.visible, o, m)) {
return;
}
var el = $((tmpls['panel'])(_.extend(o, {'tabIndex': idx})))
.appendTo(tabContent)
.removeClass('collapse').addClass('collapse'),
h = $((tmpls['header'])(o)).appendTo(tabHead);
o.fields.each(function(f) {
var cntr = new (f.get("control")) ({
field: f,
model: m,
dialog: self,
tabIndex: idx
});
el.append(cntr.render().$el);
controls.push(cntr);
});
tabHead.find('a[data-toggle="tab"]').off(
'shown.bs.tab'
).off('hidden.bs.tab').on(
'hidden.bs.tab', function() {
self.hidden_tab = $(this).data('tabIndex');
}).on('shown.bs.tab', function() {
var self = this;
self.shown_tab = $(self).data('tabIndex');
m.trigger('pg-property-tab-changed', {
'model': m, 'shown': self.shown_tab, 'hidden': self.hidden_tab,
'tab': self
});
});
});
var makeActive = tabHead.find('[id="' + c + '"]').first();
if (makeActive.length == 1) {
makeActive.parent().addClass('active');
tabContent.find('#' + makeActive.attr("aria-controls"))
.addClass('in active');
} else {
tabHead.find('[role="presentation"]').first().addClass('active');
tabContent.find('[role="tabpanel"]').first().addClass('in active');
}
return this;
},
remove: function(opts) {
if (opts && opts.data) {
if (this.model) {
if (this.model.reset) {
this.model.reset({validate: false, silent: true, stop: true});
}
this.model.clear({validate: false, silent: true, stop: true});
delete (this.model);
}
if (this.errorModel) {
this.errorModel.clear({validate: false, silent: true, stop: true});
delete (this.errorModel);
}
}
this.cleanup();
Backform.Form.prototype.remove.apply(this, arguments);
}
});
var Fieldset = Backform.Fieldset = Backform.Dialog.extend({
className: function() {
return 'set-group pg-el-xs-12';
},
tabPanelClassName: function() {
return Backform.tabClassName;
},
fieldsetClass: Backform.setGroupClassName,
legendClass: 'badge',
contentClass: Backform.setGroupContentClassName + ' collapse in',
template: {
'header': _.template([
'<fieldset class="<%=fieldsetClass%>" <%=disabled ? "disabled" : ""%>>',
' <% if (legend != false) { %>',
' <legend class="<%=legendClass%>" <%=collapse ? "data-toggle=\'collapse\'" : ""%> data-target="#<%=cId%>"><%=collapse ? "<span class=\'caret\'></span>" : "" %><%=label%></legend>',
' <% } %>',
'</fieldset>'
].join("\n")),
'content': _.template(
' <div id="<%= cId %>" class="<%=contentClass%>"></div>'
)},
collapse: true,
render: function() {
this.cleanup();
var m = this.model,
$el = this.$el,
tmpl = this.template,
controls = this.controls,
data = {
'className': _.result(this, 'className'),
'fieldsetClass': _.result(this, 'fieldsetClass'),
'legendClass': _.result(this, 'legendClass'),
'contentClass': _.result(this, 'contentClass'),
'collapse': _.result(this, 'collapse')
},
idx=(this.tabIndex * 100),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
this.$el.empty();
_.each(this.schema, function(o) {
idx++;
if (!o.version_compatible || !evalF(o.visible, o, m)) {
return;
}
if (!o.fields)
return;
var d = _.extend({}, data, o),
h = $((tmpl['header'])(d)).appendTo($el),
el = $((tmpl['content'])(d)).appendTo(h);
o.fields.each(function(f) {
var cntr = new (f.get("control")) ({
field: f,
model: m,
tabIndex: idx
});
el.append(cntr.render().$el);
controls.push(cntr);
});
});
return this;
},
getValueFromDOM: function() {
return "";
},
events: {}
});
var generateGridColumnsFromModel = Backform.generateGridColumnsFromModel =
function(node_info, m, type, cols, node) {
var groups = Backform.generateViewSchema(node_info, m, type, node, true, true),
schema = [],
columns = [],
func,
idx = 0;
// Create another array if cols is of type object & store its keys in that array,
// If cols is object then chances that we have custom width class attached with in.
if (_.isNull(cols) || _.isUndefined(cols)) {
func = function(f) {
f.cell_priority = idx;
idx = idx + 1;
// We can also provide custom header cell class in schema itself,
// But we will give priority to extraClass attached in cols
// If headerCell property is already set by cols then skip extraClass property from schema
if (!(f.headerCell) && f.cellHeaderClasses) {
f.headerCell = Backgrid.Extension.CustomHeaderCell;
}
};
} else if (_.isArray(cols)) {
func = function(f) {
f.cell_priority = _.indexOf(cols, f.name);
// We can also provide custom header cell class in schema itself,
// But we will give priority to extraClass attached in cols
// If headerCell property is already set by cols then skip extraClass property from schema
if ((!f.headerCell) && f.cellHeaderClasses) {
f.headerCell = Backgrid.Extension.CustomHeaderCell;
}
};
} else if(_.isObject(cols)) {
var tblCols = Object.keys(cols);
func = function(f) {
var val = (f.name in cols) && cols[f.name];
if (_.isNull(val) || _.isUndefined(val)) {
f.cell_priority = -1;
return;
}
if (_.isObject(val)) {
if ('index' in val) {
f.cell_priority = val['index'];
idx = (idx > val['index']) ? idx + 1 : val['index'];
} else {
var i = _.indexOf(tblCols, f.name);
f.cell_priority = idx = ((i > idx) ? i : idx);
idx = idx + 1;
}
// We can also provide custom header cell class in schema itself,
// But we will give priority to extraClass attached in cols
// If headerCell property is already set by cols then skip extraClass property from schema
if (!f.headerCell) {
if (f.cellHeaderClasses) {
f.headerCell = Backgrid.Extension.CustomHeaderCell;
}
if ('class' in val && _.isString(val['class'])) {
f.headerCell = Backgrid.Extension.CustomHeaderCell;
f.cellHeaderClasses = (f.cellHeaderClasses || '') + ' ' + val['class'];
}
}
}
if (_.isString(val)) {
var i = _.indexOf(tblCols, f.name);
f.cell_priority = idx = ((i > idx) ? i : idx);
idx = idx + 1;
if (!f.headerCell) {
f.headerCell = Backgrid.Extension.CustomHeaderCell;
}
f.cellHeaderClasses = (f.cellHeaderClasses || '') + ' ' + val;
}
};
}
// Prepare columns for backgrid
_.each(groups, function(group, key) {
_.each(group.fields, function(f) {
if (!f.cell) {
return;
}
// Check custom property in cols & if it is present then attach it to current cell
func(f);
if (f.cell_priority != -1) {
columns.push(f);
}
});
schema.push(group);
});
return {
'columns': _.sortBy(columns, function(c) {
return c.cell_priority;
}),
'schema': schema
};
};
var UniqueColCollectionControl = Backform.UniqueColCollectionControl = Backform.Control.extend({
initialize: function() {
Backform.Control.prototype.initialize.apply(this, arguments);
var uniqueCol = this.field.get('uniqueCol') || [],
m = this.field.get('model'),
schema = m.prototype.schema || m.__super__.schema,
columns = [],
self = this;
_.each(schema, function(s) {
columns.push(s.id);
});
// Check if unique columns provided are also in model attributes.
if (uniqueCol.length > _.intersection(columns, uniqueCol).length) {
var errorMsg = "Developer: Unique columns [ "+_.difference(uniqueCol, columns)+" ] not found in collection model [ " + columns +" ]."
alert (errorMsg);
}
var collection = self.collection = self.model.get(self.field.get('name'));
if (!collection) {
collection = self.collection = new (pgAdmin.Browser.Node.Collection)(
null,
{
model: self.field.get('model'),
silent: true,
handler: self.model,
top: self.model.top || self.model,
attrName: self.field.get('name')
});
self.model.set(self.field.get('name'), collection, {silent: true});
}
if (this.field.get('version_compatible')) {
self.listenTo(collection, "add", self.collectionChanged);
self.listenTo(collection, "change", self.collectionChanged);
}
},
cleanup: function() {
this.stopListening(this.collection, "change", this.collectionChanged);
if (this.field.get('version_compatible')) {
this.stopListening(self.collection, "add", this.collectionChanged);
this.stopListening(self.collection, "change", this.collectionChanged);
}
if (this.grid) {
this.grid.remove();
delete this.grid;
}
this.$el.empty();
},
collectionChanged: function(newModel, coll, op) {
var uniqueCol = this.field.get('uniqueCol') || [],
uniqueChangedAttr = [],
self = this;
// Check if changed model attributes are also in unique columns. And then only check for uniqueness.
if (newModel.attributes) {
_.each(uniqueCol, function(col) {
if (_.has(newModel.attributes,col))
{
uniqueChangedAttr.push(col);
}
});
if(uniqueChangedAttr.length == 0) {
return;
}
} else {
return;
}
var collection = this.model.get(this.field.get('name'));
this.stopListening(collection, "change", this.collectionChanged);
// Check if changed attribute's value of new/updated model also exist for another model in collection.
// If duplicate value exists then set the attribute's value of new/updated model to its previous values.
var m = undefined,
oldModel = undefined;
collection.each(function(model) {
if (newModel != model) {
var duplicateAttrValues = []
_.each(uniqueCol, function(attr) {
var attrValue = newModel.get(attr);
if (!_.isUndefined(attrValue) && attrValue == model.get(attr)) {
duplicateAttrValues.push(attrValue)
}
});
if (duplicateAttrValues.length == uniqueCol.length) {
m = newModel;
// Keep reference of model to make it visible in dialog.
oldModel = model;
}
}
});
if (m) {
if (op && op.add) {
// Remove duplicate model.
setTimeout(function() {
collection.remove(m);
}, 0);
} else {
/*
* Set model value to its previous value as its new value is
* conflicting with another model value.
*/
m.set(uniqueChangedAttr[0], m.previous(uniqueChangedAttr[0]));
}
if (oldModel) {
var idx = collection.indexOf(oldModel);
if (idx > -1) {
var newRow = self.grid.body.rows[idx].$el;
newRow.addClass("new");
$(newRow).pgMakeVisible('backform-tab');
setTimeout(function() {
newRow.removeClass("new");
}, 3000);
}
}
}
this.listenTo(collection, "change", this.collectionChanged);
},
render: function() {
// Clean up existing elements
this.undelegateEvents();
this.$el.empty();
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
// Evaluate the disabled, visible, required, canAdd, & canDelete option
_.extend(data, {
disabled: (field.version_compatible &&
evalF.apply(this.field, [data.disabled, data, this.model])
),
visible: evalF.apply(this.field, [data.visible, data, this.model]),
required: evalF.apply(this.field, [data.required, data, this.model]),
canAdd: (field.version_compatible &&
evalF.apply(this.field, [data.canAdd, data, this.model])
),
canAddRow: data.canAddRow,
canDelete: evalF.apply(this.field, [data.canDelete, data, this.model]),
canEdit: evalF.apply(this.field, [data.canEdit, data, this.model])
});
_.extend(data, {add_label: ""});
// This control is not visible, we should remove it.
if (!data.visible) {
return this;
}
this.control_data = _.clone(data);
// Show Backgrid Control
var grid = this.showGridControl(data);
this.$el.html(grid).addClass(field.name);
this.updateInvalid();
this.delegateEvents();
return this;
},
showGridControl: function(data) {
var self = this,
gridHeader = _.template([
'<div class="subnode-header">',
' <label class="control-label pg-el-sm-10"><%-label%></label>',
' <button class="btn-sm btn-default add fa fa-plus" <%=canAdd ? "" : "disabled=\'disabled\'"%>><%-add_label%></button>',
'</div>'].join("\n")),
gridBody = $('<div class="pgadmin-control-group backgrid form-group pg-el-xs-12 object subnode"></div>').append(
gridHeader(data)
);
// Clean up existing grid if any (in case of re-render)
if (self.grid) {
self.grid.remove();
}
if (!(data.subnode)) {
return '';
}
var subnode = data.subnode.schema ? data.subnode : data.subnode.prototype,
gridSchema = Backform.generateGridColumnsFromModel(
data.node_info, subnode, this.field.get('mode'), data.columns
);
// Set visibility of Add button
if (data.mode == 'properties') {
$(gridBody).find("button.add").remove();
}
// Insert Delete Cell into Grid
if (!data.disabled && data.canDelete) {
gridSchema.columns.unshift({
name: "pg-backform-delete", label: "",
cell: Backgrid.Extension.DeleteCell,
editable: false, cell_priority: -1,
canDeleteRow: data.canDeleteRow
});
}
// Insert Edit Cell into Grid
if (data.disabled == false && data.canEdit) {
var editCell = Backgrid.Extension.ObjectCell.extend({
schema: gridSchema.schema
});
gridSchema.columns.unshift({
name: "pg-backform-edit", label: "", cell : editCell,
cell_priority: -2, canEditRow: data.canEditRow
});
}
var collection = this.model.get(data.name);
var cellEditing = function(args) {
var that = this,
cell = args[0];
// Search for any other rows which are open.
this.each(function(m){
// Check if row which we are about to close is not current row.
if (cell.model != m) {
var idx = that.indexOf(m);
if (idx > -1) {
var row = self.grid.body.rows[idx],
editCell = row.$el.find(".subnode-edit-in-process").parent();
// Only close row if it's open.
if (editCell.length > 0){
var event = new Event('click');
editCell[0].dispatchEvent(event);
}
}
}
});
}
// Listen for any row which is about to enter in edit mode.
collection.on( "enteringEditMode", cellEditing, collection);
// Initialize a new Grid instance
var grid = self.grid = new Backgrid.Grid({
columns: gridSchema.columns,
collection: collection,
className: "backgrid table-bordered"
});
// Render subNode grid
var subNodeGrid = self.grid.render().$el;
// Combine Edit and Delete Cell
if (data.canDelete && data.canEdit) {
$(subNodeGrid).find("th.pg-backform-delete").remove();
$(subNodeGrid).find("th.pg-backform-edit").attr("colspan", "2");
}
var $dialog = gridBody.append(subNodeGrid);
// Add button callback
if (!(data.disabled || data.canAdd == false)) {
$dialog.find('button.add').first().click(function(e) {
e.preventDefault();
var canAddRow = _.isFunction(data.canAddRow) ?
data.canAddRow.apply(self, [self.model]) : true;
if (canAddRow) {
// Close any existing expanded row before adding new one.
_.each(self.grid.body.rows, function(row){
var editCell = row.$el.find(".subnode-edit-in-process").parent();
// Only close row if it's open.
if (editCell.length > 0){
var event = new Event('click');
editCell[0].dispatchEvent(event);
}
});
var allowMultipleEmptyRows = !!self.field.get('allowMultipleEmptyRows');
// If allowMultipleEmptyRows is not set or is false then don't allow second new empty row.
// There should be only one empty row.
if (!allowMultipleEmptyRows && collection) {
var isEmpty = false;
collection.each(function(model) {
var modelValues = [];
_.each(model.attributes, function(val, key) {
modelValues.push(val);
})
if(!_.some(modelValues, _.identity)) {
isEmpty = true;
}
});
if(isEmpty) {
return false;
}
}
$(self.grid.body.$el.find($("tr.new"))).removeClass("new")
var m = new (data.model) (null, {
silent: true,
handler: collection,
top: self.model.top || self.model,
collection: collection,
node_info: self.model.node_info
});
collection.add(m);
var idx = collection.indexOf(m),
newRow = self.grid.body.rows[idx].$el;
newRow.addClass("new");
$(newRow).pgMakeVisible('backform-tab');
return false;
}
});
}
return $dialog;
},
clearInvalid: function() {
this.$el.removeClass("subnode-error");
this.$el.find(".pgadmin-control-error-message").remove();
return this;
},
updateInvalid: function() {
var self = this,
errorModel = this.model.errorModel;
if (!(errorModel instanceof Backbone.Model)) return this;
this.clearInvalid();
this.$el.find('.subnode-body').each(function(ix, el) {
var error = self.keyPathAccessor(errorModel.toJSON(), self.field.get('name'));
if (_.isEmpty(error)) return;
self.$el.addClass("subnode-error").append(
$("<div></div>").addClass('pgadmin-control-error-message pg-el-xs-offset-4 pg-el-xs-8 help-block').text(error)
);
});
}
});
var SubNodeCollectionControl = Backform.SubNodeCollectionControl = Backform.Control.extend({
row: Backgrid.Row,
render: function() {
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
// Evaluate the disabled, visible, required, canAdd, cannEdit & canDelete option
_.extend(data, {
disabled: evalF(data.disabled, data, this.model),
visible: evalF(data.visible, data, this.model),
required: evalF(data.required, data, this.model),
canAdd: evalF(data.canAdd, data, this.model),
canAddRow: data.canAddRow,
canEdit: evalF(data.canEdit, data, this.model),
canDelete: evalF(data.canDelete, data, this.model)
});
// Show Backgrid Control
var grid = (data.subnode == undefined) ? "" : this.showGridControl(data);
// Clean up first
this.$el.removeClass(Backform.hiddenClassName);
if (!data.visible)
this.$el.addClass(Backform.hiddenClassName);
this.$el.html(grid).addClass(field.name);
this.updateInvalid();
return this;
},
updateInvalid: function() {
var self = this;
var errorModel = this.model.errorModel;
if (!(errorModel instanceof Backbone.Model)) return this;
this.clearInvalid();
var attrArr = self.field.get('name').split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
error = self.keyPathAccessor(errorModel.toJSON(), path);
if (_.isEmpty(error)) return;
self.$el.addClass('subnode-error').append(
$("<div></div>").addClass('pgadmin-control-error-message pg-el-xs-offset-4 pg-el-xs-8 help-block').text(error)
);
},
cleanup: function() {
// Clean up existing grid if any (in case of re-render)
if (this.grid) {
this.grid.remove();
}
if (this.collection) {
this.collection.off( "enteringEditMode");
}
},
clearInvalid: function() {
this.$el.removeClass('subnode-error');
this.$el.find(".pgadmin-control-error-message").remove();
return this;
},
showGridControl: function(data) {
var self = this,
gridHeader = ["<div class='subnode-header'>",
" <label class='control-label pg-el-sm-10'>" + data.label + "</label>" ,
" <button class='btn-sm btn-default add fa fa-plus'></button>",
"</div>"].join("\n"),
gridBody = $("<div class='pgadmin-control-group backgrid form-group pg-el-xs-12 object subnode'></div>").append(gridHeader);
var subnode = data.subnode.schema ? data.subnode : data.subnode.prototype,
gridSchema = Backform.generateGridColumnsFromModel(
data.node_info, subnode, this.field.get('mode'), data.columns, data.schema_node
),
pgBrowser = window.pgAdmin.Browser;
// Clean up existing grid if any (in case of re-render)
if (self.grid) {
self.grid.remove();
}
// Set visibility of Add button
if (data.disabled || data.canAdd == false) {
$(gridBody).find("button.add").remove();
}
// Insert Delete Cell into Grid
if (data.disabled == false && data.canDelete) {
gridSchema.columns.unshift({
name: "pg-backform-delete", label: "",
cell: Backgrid.Extension.DeleteCell,
editable: false, cell_priority: -1,
canDeleteRow: data.canDeleteRow,
customDeleteMsg: data.customDeleteMsg,
customDeleteTitle: data.customDeleteTitle
});
}
// Insert Edit Cell into Grid
if (data.disabled == false && data.canEdit) {
var editCell = Backgrid.Extension.ObjectCell.extend({
schema: gridSchema.schema
}),
canEdit = self.field.has('canEdit') &&
self.field.get('canEdit') || true;
gridSchema.columns.unshift({
name: "pg-backform-edit", label: "", cell : editCell,
cell_priority: -2, editable: canEdit,
canEditRow: data.canEditRow
});
}
var collection = self.model.get(data.name);
if (!collection) {
collection = new (pgBrowser.Node.Collection)(null, {
handler: self.model.handler || self.model,
model: data.model, top: self.model.top || self.model,
silent: true
});
self.model.set(data.name, collection, {silent: true});
}
var cellEditing = function(args) {
var self = this,
cell = args[0];
// Search for any other rows which are open.
this.each(function(m){
// Check if row which we are about to close is not current row.
if (cell.model != m) {
var idx = self.indexOf(m);
if (idx > -1) {
var row = grid.body.rows[idx],
editCell = row.$el.find(".subnode-edit-in-process").parent();
// Only close row if it's open.
if (editCell.length > 0){
var event = new Event('click');
editCell[0].dispatchEvent(event);
}
}
}
});
}
// Listen for any row which is about to enter in edit mode.
collection.on( "enteringEditMode", cellEditing, collection);
// Initialize a new Grid instance
var grid = self.grid = new Backgrid.Grid({
columns: gridSchema.columns,
collection: collection,
row: this.row,
className: "backgrid table-bordered"
});
// Render subNode grid
var subNodeGrid = grid.render().$el;
// Combine Edit and Delete Cell
if (data.canDelete && data.canEdit) {
$(subNodeGrid).find("th.pg-backform-delete").remove();
$(subNodeGrid).find("th.pg-backform-edit").attr("colspan", "2");
}
var $dialog = gridBody.append(subNodeGrid);
// Add button callback
$dialog.find('button.add').click(function(e) {
e.preventDefault();
var canAddRow = _.isFunction(data.canAddRow) ?
data.canAddRow.apply(self, [self.model]) : true;
if (canAddRow) {
// Close any existing expanded row before adding new one.
_.each(grid.body.rows, function(row){
var editCell = row.$el.find(".subnode-edit-in-process").parent();
// Only close row if it's open.
if (editCell.length > 0){
var event = new Event('click');
editCell[0].dispatchEvent(event);
}
});
grid.insertRow({});
var newRow = $(grid.body.rows[collection.length - 1].$el);
newRow.attr("class", "new").click(function(e) {
$(this).attr("class", "editable");
});
$(newRow).pgMakeVisible('backform-tab');
return false;
}
});
return $dialog;
}
});
/*
* SQL Tab Control for showing the modified SQL for the node with the
* property 'hasSQL' is set to true.
*
* When the user clicks on the SQL tab, we will send the modified data to the
* server and fetch the SQL for it.
*/
var SqlTabControl = Backform.SqlTabControl = Backform.Control.extend({
defaults: {
label: "",
controlsClassName: "pgadmin-controls pg-el-sm-12 SQL",
extraClasses: [],
helpMessage: null
},
template: _.template([
'<div class="<%=controlsClassName%>">',
' <textarea class="<%=Backform.controlClassName%> <%=extraClasses.join(\' \')%>" name="<%=name%>" placeholder="<%-placeholder%>" <%=disabled ? "disabled" : ""%> <%=required ? "required" : ""%>><%-value%></textarea>',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>'
].join("\n")),
/*
* Initialize the SQL Tab control properly
*/
initialize: function(o) {
Backform.Control.prototype.initialize.apply(this, arguments);
// Save the required information for using it later.
this.dialog = o.dialog;
this.tabIndex = o.tabIndex;
_.bindAll(this, 'onTabChange', 'onPanelResized');
},
getValueFromDOM: function() {
return this.formatter.toRaw(this.$el.find("textarea").val(), this.model);
},
render: function() {
if (this.sqlCtrl) {
this.sqlCtrl.toTextArea();
delete this.sqlCtrl;
this.sqlCtrl = null;
this.$el.empty();
this.model.off('pg-property-tab-changed', this.onTabChange, this);
this.model.off('pg-browser-resized', this.onPanelResized, this);
}
// Use the Backform Control's render function
Backform.Control.prototype.render.apply(this, arguments);
this.sqlCtrl = CodeMirror.fromTextArea(
(this.$el.find("textarea")[0]), {
lineNumbers: true,
lineWrapping: true,
mode: "text/x-pgsql",
readOnly: true,
extraKeys: pgAdmin.Browser.editor_shortcut_keys,
tabSize: pgAdmin.Browser.editor_options.tabSize,
lineWrapping: pgAdmin.Browser.editor_options.wrapCode,
autoCloseBrackets: pgAdmin.Browser.editor_options.insert_pair_brackets,
matchBrackets: pgAdmin.Browser.editor_options.brace_matching
});
/*
* We will listen to the tab change event to check, if the SQL tab has
* been clicked or, not.
*/
this.model.on('pg-property-tab-changed', this.onTabChange, this);
this.model.on('pg-browser-resized', this.onPanelResized, this);
return this;
},
onTabChange: function(obj) {
// Fetch the information only if the SQL tab is visible at the moment.
if (this.dialog && obj.shown == this.tabIndex) {
// We will send a request to the sever only if something has changed
// in a model and also it does not contain any error.
if(this.model.sessChanged()) {
if (_.size(this.model.errorModel.attributes) == 0) {
var self = this,
node = self.field.get('schema_node'),
msql_url = node.generate_url.apply(
node, [
null, 'msql', this.field.get('node_data'), !self.model.isNew(),
this.field.get('node_info')
]);
// Fetching the modified SQL
self.model.trigger('pgadmin-view:msql:fetching', self.method, node);
$.ajax({
url: msql_url,
type: 'GET',
cache: false,
data: self.model.toJSON(true, 'GET'),
dataType: "json",
contentType: "application/json"
}).done(function(res) {
self.sqlCtrl.clearHistory();
self.sqlCtrl.setValue(res.data);
}).fail(function() {
self.model.trigger('pgadmin-view:msql:error', self.method, node, arguments);
}).always(function() {
self.model.trigger('pgadmin-view:msql:fetched', self.method, node, arguments);
});
} else {
this.sqlCtrl.clearHistory();
this.sqlCtrl.setValue('-- ' + gettext('Definition incomplete.'));
}
} else {
this.sqlCtrl.clearHistory();
this.sqlCtrl.setValue('-- ' + gettext('Nothing changed.'));
}
this.sqlCtrl.refresh.apply(this.sqlCtrl);
}
},
onPanelResized: function(o) {
if (o && o.container) {
var $tabContent = o.container.find(
'.backform-tab > .tab-content'
).first(),
$sqlPane = $tabContent.find(
'div[role=tabpanel].tab-pane.SQL'
);
if ($sqlPane.hasClass('active')) {
$sqlPane.find('.CodeMirror').css(
'cssText',
'height: ' + ($tabContent.height() + 8) + 'px !important;'
)
}
}
},
remove: function() {
if (this.sqlCtrl) {
this.sqlCtrl.toTextArea();
delete this.sqlCtrl;
this.sqlCtrl = null;
this.$el.empty();
}
this.model.off('pg-property-tab-changed', this.onTabChange, this);
this.model.off('pg-browser-resized', this.onPanelResized, this);
Backform.Control.__super__.remove.apply(this, arguments);
}
});
/*
* Numeric input Control functionality just like backgrid
*/
var NumericControl = Backform.NumericControl = Backform.InputControl.extend({
defaults: {
type: "number",
label: "",
min: undefined,
max: undefined,
maxlength: 255,
extraClasses: [],
helpMessage: null
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
' <input type="<%=type%>" class="<%=Backform.controlClassName%> <%=extraClasses.join(\' \')%>" name="<%=name%>" min="<%=min%>" max="<%=max%>"maxlength="<%=maxlength%>" value="<%-value%>" placeholder="<%-placeholder%>" <%=disabled ? "disabled" : ""%> <%=required ? "required" : ""%> />',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>'
].join("\n"))
});
///////
// Generate a schema (as group members) based on the model's schema
//
// It will be used by the grid, properties, and dialog view generation
// functions.
var generateViewSchema = Backform.generateViewSchema = function(
node_info, Model, mode, node, treeData, noSQL, subschema
) {
var proto = (Model && Model.prototype) || Model,
schema = subschema || (proto && proto.schema),
pgBrowser = window.pgAdmin.Browser, fields = [],
groupInfo = {};
// 'schema' has the information about how to generate the form.
if (schema && _.isArray(schema)) {
var evalASFunc = evalASFunc = function(prop) {
return ((prop && proto[prop] &&
typeof proto[prop] == "function") ? proto[prop] : prop);
};
var groups = {},
server_info = node_info && ('server' in node_info) &&
pgBrowser.serverInfo && pgBrowser.serverInfo[node_info.server._id],
in_catalog = node_info && ('catalog' in node_info);
_.each(schema, function(s) {
// Do we understand - what control, we're creating
// here?
if (s.type == 'group') {
var ver_in_limit = (_.isUndefined(server_info) ? true :
((_.isUndefined(s.server_type) ? true :
(server_info.type in s.server_type)) &&
(_.isUndefined(s.min_version) ? true :
(server_info.version >= s.min_version)) &&
(_.isUndefined(s.max_version) ? true :
(server_info.version <= s.max_version)))),
visible = true;
if (s.mode && _.isObject(s.mode))
visible = (_.indexOf(s.mode, mode) > -1);
if (visible)
visible = evalASFunc(s.visible);
groupInfo[s.id] = {
label: s.label || s.id,
version_compatible: ver_in_limit,
visible: visible
};
return;
}
if (!s.mode || (s && s.mode && _.isObject(s.mode) &&
_.indexOf(s.mode, mode) != -1)) {
// Each field is kept in specified group, or in
// 'General' category.
var group = s.group || gettext('General'),
control = s.control || Backform.getMappedControl(s.type, mode),
cell = s.cell || Backform.getMappedControl(s.type, 'cell');
if (control == null) {
return;
}
// Generate the empty group list (if not exists)
groups[group] = (groups[group] || []);
var ver_in_limit = (_.isUndefined(server_info) ? true :
((_.isUndefined(s.server_type) ? true :
(server_info.type in s.server_type)) &&
(_.isUndefined(s.min_version) ? true :
(server_info.version >= s.min_version)) &&
(_.isUndefined(s.max_version) ? true :
(server_info.version <= s.max_version)))),
disabled = ((mode == 'properties') || !ver_in_limit || in_catalog),
schema_node = (s.node && _.isString(s.node) &&
s.node in pgBrowser.Nodes && pgBrowser.Nodes[s.node]) || node;
var o = _.extend(_.clone(s), {
name: s.id,
// This can be disabled in some cases (if not hidden)
disabled: (disabled ? true : evalASFunc(s.disabled)),
editable: _.isUndefined(s.editable) ?
pgAdmin.editableCell : evalASFunc(s.editable),
subnode: ((_.isString(s.model) && s.model in pgBrowser.Nodes) ?
pgBrowser.Nodes[s.model].model : s.model),
canAdd: (disabled ? false : evalASFunc(s.canAdd)),
canAddRow: (disabled ? false : evalASFunc(s.canAddRow)),
canEdit: (disabled ? false : evalASFunc(s.canEdit)),
canDelete: (disabled ? false : evalASFunc(s.canDelete)),
canEditRow: (disabled ? false : evalASFunc(s.canEditRow)),
canDeleteRow: (disabled ? false : evalASFunc(s.canDeleteRow)),
transform: evalASFunc(s.transform),
mode: mode,
control: control,
cell: cell,
node_info: node_info,
schema_node: schema_node,
// Do we need to show this control in this mode?
visible: evalASFunc(s.visible),
node: node,
node_data: treeData,
version_compatible: ver_in_limit
});
delete o.id;
// Temporarily store in dictionary format for
// utilizing it later.
groups[group].push(o);
if (s.type == 'nested') {
delete o.name;
delete o.cell;
o.schema = Backform.generateViewSchema(
node_info, Model, mode, node, treeData, true, s.schema
);
o.control = o.control || 'tab';
}
}
});
// Do we have fields to genreate controls, which we
// understand?
if (_.isEmpty(groups)) {
return null;
}
if (!noSQL && node && node.hasSQL && (mode == 'create' || mode == 'edit')) {
groups[gettext('SQL')] = [{
name: 'sql',
visible: true,
disabled: false,
type: 'text',
control: 'sql-tab',
node_info: node_info,
schema_node: node,
node_data: treeData
}];
}
// Create an array from the dictionary with proper required
// structure.
_.each(groups, function(val, key) {
fields.push(
_.extend(
_.defaults(
groupInfo[key] || {label: key},
{version_compatible: true, visible: true}
), {fields: val})
);
});
}
return fields;
};
var Select2Formatter = function() {};
_.extend(Select2Formatter.prototype, {
fromRaw: function(rawData, model) {
return encodeURIComponent(rawData);
},
toRaw: function(formattedData, model) {
if (_.isArray(formattedData)) {
return _.map(formattedData, decodeURIComponent);
} else {
if(!_.isNull(formattedData) && !_.isUndefined(formattedData)) {
return decodeURIComponent(formattedData);
} else {
return null;
}
}
}
});
/*
* Backform Select2 control.
*/
var Select2Control = Backform.Select2Control = Backform.SelectControl.extend({
defaults: _.extend({}, Backform.SelectControl.prototype.defaults, {
select2: {
first_empty: true,
multiple: false,
emptyOptions: false
}
}),
formatter: Select2Formatter,
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
' <select class="<%=Backform.controlClassName%> <%=extraClasses.join(\' \')%>"',
' name="<%=name%>" value="<%-value%>" <%=disabled ? "disabled" : ""%>',
' <%=required ? "required" : ""%><%= select2.multiple ? " multiple>" : ">" %>',
' <%=select2.first_empty ? " <option></option>" : ""%>',
' <% for (var i=0; i < options.length; i++) {%>',
' <% var option = options[i]; %>',
' <option ',
' <% if (option.image) { %> data-image=<%=option.image%> <%}%>',
' value=<%- formatter.fromRaw(option.value) %>',
' <% if (option.selected) {%>selected="selected"<%} else {%>',
' <% if (!select2.multiple && option.value === rawValue) {%>selected="selected"<%}%>',
' <% if (select2.multiple && rawValue && rawValue.indexOf(option.value) != -1){%>selected="selected" data-index="rawValue.indexOf(option.value)"<%}%>',
' <%}%>',
' <%= disabled ? "disabled" : ""%>><%-option.label%></option>',
' <%}%>',
' </select>',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>'
].join("\n")),
render: function() {
if(this.$sel && this.$sel.select2 &&
this.$sel.select2.hasOwnProperty('destroy')) {
this.$sel.select2('destroy');
}
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
data.select2 = data.select2 || {};
_.defaults(data.select2, this.defaults.select2, {
first_empty: true,
multiple: false,
emptyOptions: false
});
// Evaluate the disabled, visible, and required option
_.extend(data, {
disabled: evalF(data.disabled, data, this.model),
visible: evalF(data.visible, data, this.model),
required: evalF(data.required, data, this.model)
});
// Evaluation the options
if (_.isFunction(data.options)) {
try {
data.options = data.options(this)
} catch(e) {
// Do nothing
data.options = []
this.model.trigger(
'pgadmin-view:transform:error', this.model, this.field, e
);
}
}
// Clean up first
this.$el.removeClass(Backform.hiddenClassName);
if (!data.visible)
this.$el.addClass(Backform.hiddenClassName);
this.$el.html(this.template(data)).addClass(field.name);
var select2Opts = _.extend({
disabled: data.disabled
}, field.select2, {
options: (this.field.get('options') || this.defaults.options)
});
// If disabled then no need to show placeholder
if(data.disabled || data.mode === 'properties') {
select2Opts['placeholder'] = '';
}
/*
* Add empty option as Select2 requires any empty '<option><option>' for
* some of its functionality to work and initialize select2 control.
*/
if (data.select2.tags && data.select2.emptyOptions) {
select2Opts.data = data.rawValue;
}
this.$sel = this.$el.find("select").select2(select2Opts);
// Add or remove tags from select2 control
if (data.select2.tags && data.select2.emptyOptions) {
this.$sel.val(data.rawValue);
this.$sel.trigger('change.select2');
this.$sel.on('select2:unselect', function(evt) {
$(this).find('option[value="'+evt.params.data.text.replace("'","\\'").replace('"','\\"')+'"]').remove();
$(this).trigger('change.select2');
if ($(this).val() == null) {
$(this).empty();
}
});
}
// Select the highlighted item on Tab press.
if (this.$sel) {
this.$sel.data('select2').on("keypress", function(ev) {
var self = this;
// keycode 9 is for TAB key
if (ev.which === 9 && self.isOpen()) {
ev.preventDefault();
self.trigger('results:select', {});
}
});
}
this.updateInvalid();
return this;
},
getValueFromDOM: function() {
var val = Backform.SelectControl.prototype.getValueFromDOM.apply(
this, arguments
),
select2Opts = _.extend({}, this.field.get("select2") || this.defaults.select2);
if (select2Opts.multiple && val == null) {
return [];
}
return val;
}
});
var FieldsetControl = Backform.FieldsetControl = Backform.Fieldset.extend({
initialize: function(opts) {
Backform.Control.prototype.initialize.apply(
this, arguments
);
Backform.Dialog.prototype.initialize.apply(
this, [{schema: opts.field.get('schema')}]
);
this.dialog = opts.dialog;
this.tabIndex = opts.tabIndex;
// Listen to the dependent fields in the model for any change
var deps = this.field.get('deps');
var self = this;
if (deps && _.isArray(deps)) {
_.each(deps, function(d) {
var attrArr = d.split('.'),
name = attrArr.shift();
self.listenTo(self.model, "change:" + name, self.render);
});
}
},
// Render using Backform.Fieldset (only if this control is visible)
orig_render: Backform.Fieldset.prototype.render,
render: function() {
var field = _.defaults(this.field.toJSON(), this.defaults),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
if (!field.version_compatible ||
!evalF(field.visible, field, this.model)) {
this.cleanup();
this.$el.empty()
} else {
this.orig_render.apply(this, arguments);
}
return this;
},
formatter: function() {},
cleanup: function() {
Backform.Fieldset.prototype.cleanup.apply(this);
},
remove: function() {
Backform.Control.prototype.remove.apply(this, arguments);
Backform.Dialog.prototype.remove.apply(this, arguments);
},
className: function() {
return 'set-group';
},
tabPanelClassName: function() {
return Backform.tabClassName;
},
fieldsetClass: 'inline-fieldset',
legendClass: '',
contentClass: '',
collapse: false
});
// Backform Tab Control (in bootstrap tabbular)
// A collection of field models.
var TabControl = Backform.TabControl = Backform.FieldsetControl.extend({
tagName: "div",
className: 'inline-tab-panel',
tabPanelClassName: 'inline-tab-panel',
initialize: function(opts) {
Backform.FieldsetControl.prototype.initialize.apply(
this, arguments
);
this.tabIndex = (opts.tabIndex || parseInt(Math.random() * 1000)) + 1;
},
// Render using Backform.Dialog (tabular UI) (only if this control is
// visible).
orig_render: Backform.Dialog.prototype.render,
template: Backform.Dialog.prototype.template
});
// Backform Tab Control (in bootstrap tabbular)
// A collection of field models.
var PlainFieldsetControl = Backform.PlainFieldsetControl = Backform.FieldsetControl.extend({
initialize: function(opts) {
Backform.FieldsetControl.prototype.initialize.apply(
this, arguments
);
},
template: {
'header': _.template([
'<fieldset class="<%=fieldsetClass%>" <%=disabled ? "disabled" : ""%>>',
' <% if (legend != false) { %>',
' <legend class="<%=legendClass%>" <%=collapse ? "data-toggle=\'collapse\'" : ""%> data-target="#<%=cId%>"><%=collapse ? "<span class=\'caret\'></span>" : "" %></legend>',
' <% } %>',
'</fieldset>'
].join("\n")),
'content': _.template(
' <div id="<%= cId %>" class="<%=contentClass%>"></div>'
)},
fieldsetClass: 'inline-fieldset-without-border',
legend: false,
});
/*
* Control For Code Mirror SQL text area.
*/
var SqlFieldControl = Backform.SqlFieldControl = Backform.TextareaControl.extend({
defaults: {
label: "",
extraClasses: [], // Add default control height
helpMessage: null,
maxlength: 4096,
rows: undefined
},
// Customize template to add new styles
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%> sql_field_layout <%=extraClasses.join(\' \')%>">',
' <textarea ',
' class="<%=Backform.controlClassName%> " name="<%=name%>"',
' maxlength="<%=maxlength%>" placeholder="<%-placeholder%>" <%=disabled ? "disabled" : ""%>',
' rows=<%=rows%>',
' <%=required ? "required" : ""%>><%-value%></textarea>',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>'
].join("\n")),
/*
* Initialize the SQL Field control properly
*/
initialize: function(o) {
Backform.TextareaControl.prototype.initialize.apply(this, arguments);
this.sqlCtrl = null;
_.bindAll(this, 'onFocus', 'onBlur', 'refreshTextArea');
},
getValueFromDOM: function() {
return this.sqlCtrl.getValue();
},
render: function() {
// Clean up the existing sql control
if (this.sqlCtrl) {
this.model.off('pg-property-tab-changed', this.refreshTextArea, this);
this.sqlCtrl.off('focus', this.onFocus);
this.sqlCtrl.off('blur', this.onBlur);
this.sqlCtrl.toTextArea();
delete this.sqlCtrl;
this.sqlCtrl = null;
this.$el.empty();
}
// Use the Backform TextareaControl's render function
Backform.TextareaControl.prototype.render.apply(this, arguments);
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
// Evaluate the disabled, visible option
var isDisabled = evalF(data.disabled, data, this.model),
isVisible = evalF(data.visible, data, this.model),
self = this;
self.sqlCtrl = CodeMirror.fromTextArea(
(self.$el.find("textarea")[0]), {
lineNumbers: true,
mode: "text/x-pgsql",
extraKeys: pgAdmin.Browser.editor_shortcut_keys,
indentWithTabs: pgAdmin.Browser.editor_options.indent_with_tabs,
indentUnit: pgAdmin.Browser.editor_options.tabSize,
tabSize: pgAdmin.Browser.editor_options.tabSize,
lineWrapping: pgAdmin.Browser.editor_options.wrapCode,
autoCloseBrackets: pgAdmin.Browser.editor_options.insert_pair_brackets,
matchBrackets: pgAdmin.Browser.editor_options.brace_matching
});
// Disable editor
if (isDisabled) {
self.sqlCtrl.setOption("readOnly", "nocursor");
var cm = self.sqlCtrl.getWrapperElement();
if (cm) {
cm.className += ' cm_disabled';
}
}
if (!isVisible)
self.$el.addClass(Backform.hiddenClassName);
// There is an issue with the Code Mirror SQL.
//
// It does not initialize the code mirror object completely when the
// referenced textarea is hidden (not visible), hence - we need to
// refresh the code mirror object on 'pg-property-tab-changed' event to
// make it work properly.
self.model.on('pg-property-tab-changed', this.refreshTextArea, this);
this.sqlCtrl.on('focus', this.onFocus);
this.sqlCtrl.on('blur', this.onBlur);
var self = this;
// Refresh SQL Field to refresh the control lazily after it renders
setTimeout(function() {
self.refreshTextArea.apply(self);
}, 0);
return self;
},
onFocus: function() {
var $ctrl = this.$el.find('.pgadmin-controls').first();
if (!$ctrl.hasClass('focused'))
$ctrl.addClass('focused');
},
onBlur: function() {
this.$el.find('.pgadmin-controls').first().removeClass('focused');
},
refreshTextArea: function() {
if (this.sqlCtrl) {
this.sqlCtrl.refresh();
}
},
remove: function() {
// Clean up the sql control
if (this.sqlCtrl) {
this.sqlCtrl.off('focus', this.onFocus);
this.sqlCtrl.off('blur', this.onBlur);
delete this.sqlCtrl;
this.sqlCtrl = null;
this.$el.empty();
}
this.model.off("pg-property-tab-changed", this.refreshTextArea, this);
Backform.TextareaControl.prototype.remove.apply(this, arguments);
}
});
// We will use this control just as a annotate in Backform
var NoteControl = Backform.NoteControl = Backform.Control.extend({
defaults: {
label: gettext("Note"),
text: '',
extraClasses: [],
noteClass: 'backform_control_notes'
},
template: _.template([
'<div class="<%=noteClass%> pg-el-xs-12 <%=extraClasses.join(\' \')%>">',
'<label class="control-label"><%=label%>:</label>',
'<span><%=text%></span></div>'
].join("\n"))
});
/*
* Input File Control: This control is used with Storage Manager Dialog,
* It allows user to perform following operations:
* - Select File
* - Select Folder
* - Create File
* - Opening Storage Manager Dialog itself.
*/
var FileControl = Backform.FileControl = Backform.InputControl.extend({
defaults: {
type: "text",
label: "",
min: undefined,
max: undefined,
maxlength: 255,
extraClasses: [],
dialog_title: '',
btn_primary: '',
helpMessage: null,
dialog_type: 'select_file'
},
initialize: function(){
Backform.InputControl.prototype.initialize.apply(this, arguments);
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
'<div class="file_selection_ctrl form-control">',
'<input type="<%=type%>" class="browse_file_input form-control <%=extraClasses.join(\' \')%>" name="<%=name%>" min="<%=min%>" max="<%=max%>"maxlength="<%=maxlength%>" value="<%-value%>" placeholder="<%-placeholder%>" <%=disabled ? "disabled" : ""%> <%=required ? "required" : ""%> />',
'<button class="btn fa fa-ellipsis-h select_item pull-right" <%=disabled ? "disabled" : ""%> ></button>',
'<% if (helpMessage && helpMessage.length) { %>',
'<span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
'<% } %>',
'</div>',
'</div>'
].join("\n")),
events: function() {
// Inherit all default events of InputControl
return _.extend({}, Backform.InputControl.prototype.events, {
"click .select_item": "onSelect"
});
},
onSelect: function(ev) {
var dialog_type = this.field.get('dialog_type'),
supp_types = this.field.get('supp_types'),
btn_primary = this.field.get('btn_primary'),
dialog_title = this.field.get('dialog_title'),
params = {
supported_types: supp_types,
dialog_type: dialog_type,
dialog_title: dialog_title,
btn_primary: btn_primary
};
pgAdmin.FileManager.init();
pgAdmin.FileManager.show_dialog(params);
// Listen click events of Storage Manager dialog buttons
this.listen_file_dlg_events();
},
storage_dlg_hander: function(value) {
var field = _.defaults(this.field.toJSON(), this.defaults),
attrArr = this.field.get("name").split('.'),
name = attrArr.shift();
this.remove_file_dlg_event_listeners();
// Set selected value into the model
this.model.set(name, decodeURI(value));
},
storage_close_dlg_hander: function() {
this.remove_file_dlg_event_listeners();
},
listen_file_dlg_events: function() {
pgAdmin.Browser.Events.on('pgadmin-storage:finish_btn:'+this.field.get('dialog_type'), this.storage_dlg_hander, this);
pgAdmin.Browser.Events.on('pgadmin-storage:cancel_btn:'+this.field.get('dialog_type'), this.storage_close_dlg_hander, this);
},
remove_file_dlg_event_listeners: function() {
pgAdmin.Browser.Events.off('pgadmin-storage:finish_btn:'+this.field.get('dialog_type'), this.storage_dlg_hander, this);
pgAdmin.Browser.Events.off('pgadmin-storage:cancel_btn:'+this.field.get('dialog_type'), this.storage_close_dlg_hander, this);
},
clearInvalid: function() {
Backform.InputControl.prototype.clearInvalid.apply(this, arguments);
this.$el.removeClass("pgadmin-file-has-error");
return this;
},
updateInvalid: function() {
Backform.InputControl.prototype.updateInvalid.apply(this, arguments);
// Introduce a new class to fix the error icon placement on the control
this.$el.addClass("pgadmin-file-has-error");
}
});
var DatetimepickerControl = Backform.DatetimepickerControl =
Backform.InputControl.extend({
defaults: {
type: "text",
label: "",
options: {
format: "YYYY-MM-DD HH:mm:ss Z",
showClear: true,
showTodayButton: true,
toolbarPlacement: 'top',
widgetPositioning: {
horizontal: 'auto',
vertical: 'bottom'
},
},
placeholder: "YYYY-MM-DD HH:mm:ss Z",
extraClasses: [],
helpMessage: null
},
events: {
"blur input": "onChange",
"change input": "onChange",
"changeDate input": "onChange",
"focus input": "clearInvalid",
'db.change': "onChange",
'click': 'openPicker'
},
openPicker: function() {
if (this.has_datepicker) {
this.$el.find("input").datetimepicker('show');
}
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="input-group <%=Backform.controlsClassName%>">',
' <input type="text" class="<%=Backform.controlClassName%> <%=extraClasses.join(\' \')%>" name="<%=name%>" value="<%-value%>" placeholder="<%-placeholder%>" <%=disabled ? "disabled" : ""%> <%=required ? "required" : ""%> />',
' <span class="input-group-addon">',
' <span class="fa fa-calendar"></span>',
' </span>',
'</div>',
'<% if (helpMessage && helpMessage.length) { %>',
' <div class="<%=Backform.controlsClassName%>">',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' </div>',
'<% } %>'
].join("\n")),
render: function() {
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, m) {
return (_.isFunction(f) ? !!f(m) : !!f);
};
// Evaluate the disabled, visible, and required option
_.extend(data, {
disabled: evalF(data.disabled, this.model),
visible: evalF(data.visible, this.model),
required: evalF(data.required, this.model)
});
if (!data.disabled) {
data.placeholder = data.placeholder || this.defaults.placeholder;
}
// Clean up first
if (this.has_datepicker)
this.$el.find("input").datetimepicker('destroy');
this.$el.empty();
this.$el.removeClass(Backform.hiddenClassName);
this.$el.html(this.template(data)).addClass(field.name);
if (!data.visible) {
this.has_datepicker = false;
this.$el.addClass(Backform.hiddenClassName);
} else {
this.has_datepicker = true;
var self = this;
this.$el.find("input").first().datetimepicker(
_.extend({
keyBinds: {
enter: function(widget) {
var picker = this;
if (widget) {
setTimeout(function() {
picker.toggle();
self.$el.find('input').first().blur();
}, 10);
} else {
setTimeout(function() { picker.toggle(); }, 10);
}
},
tab: function(widget) {
if (!widget) {
// blur the input
setTimeout(
function() { self.$el.find('input').first().blur(); }, 10
);
}
},
escape: function(widget) {
if (widget) {
var picker = this;
setTimeout(function() {
picker.toggle();
self.$el.find('input').first().blur();
}, 10);
}
}
}
}, this.defaults.options, this.field.get("options"),
{'date': data.value})
);
}
this.updateInvalid();
return this;
},
clearInvalid: function() {
Backform.InputControl.prototype.clearInvalid.apply(this, arguments);
this.$el.removeClass("pgadmin-datepicker-has-error");
return this;
},
updateInvalid: function() {
Backform.InputControl.prototype.updateInvalid.apply(this, arguments);
// Introduce a new class to fix the error icon placement on the control
this.$el.addClass("pgadmin-datepicker-has-error");
},
cleanup: function() {
if (this.has_datepicker)
this.$el.find("input").datetimepicker('destroy');
this.$el.empty();
}
});
// Color Picker control
var ColorControl = Backform.ColorControl = Backform.InputControl.extend({
defaults: {
label: "",
extraClasses: [],
helpMessage: null,
showButtons: false,
showPalette: true,
allowEmpty: true,
colorFormat: "hex",
defaultColor: ""
},
template: _.template([
'<label class="<%=Backform.controlLabelClassName%>"><%=label%></label>',
'<div class="<%=Backform.controlsClassName%>">',
' <input class="<%=Backform.controlClassName%> <%=extraClasses.join(\' \')%>" name="<%=name%>" value="<%-value%>" <%=disabled ? "disabled" : ""%> <%=required ? "required" : ""%> />',
' <% if (helpMessage && helpMessage.length) { %>',
' <span class="<%=Backform.helpMessageClassName%>"><%=helpMessage%></span>',
' <% } %>',
'</div>'
].join("\n")),
render: function() {
// Clear first
if(this.$picker && this.$picker.hasOwnProperty('destroy')) {
this.$picker('destroy');
}
var field = _.defaults(this.field.toJSON(), this.defaults),
attributes = this.model.toJSON(),
attrArr = field.name.split('.'),
name = attrArr.shift(),
path = attrArr.join('.'),
rawValue = this.keyPathAccessor(attributes[name], path),
data = _.extend(field, {
rawValue: rawValue,
value: this.formatter.fromRaw(rawValue, this.model),
attributes: attributes,
formatter: this.formatter
}),
evalF = function(f, d, m) {
return (_.isFunction(f) ? !!f.apply(d, [m]) : !!f);
};
// Evaluate the disabled, visible, and required option
_.extend(data, {
disabled: evalF(data.disabled, data, this.model),
visible: evalF(data.visible, data, this.model),
required: evalF(data.required, data, this.model)
});
// Clean up first
this.$el.empty();
if (!data.visible)
this.$el.addClass(Backform.hiddenClassname);
this.$el.html(this.template(data)).addClass(field.name);
// Creating default Color picker
this.$picker = this.$el.find("input").spectrum({
allowEmpty: data.allowEmpty,
preferredFormat: data.colorFormat,
disabled: data.disabled,
hideAfterPaletteSelect:true,
clickoutFiresChange: true,
showButtons: data.showButtons,
showPaletteOnly: data.showPalette,
togglePaletteOnly: data.showPalette,
togglePaletteMoreText: gettext('More'),
togglePaletteLessText: gettext('Less'),
color: data.value || data.defaultColor,
// Predefined palette colors
palette: [
["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
]
});
this.updateInvalid();
return this;
}
});
return Backform;
}));
| 35.245855 | 295 | 0.554192 |
432cf70f5a1f73b97599e56c7fe6804ef41f25f2 | 2,902 | js | JavaScript | public/js-minified/draft.js | cmd3BOT/Luminosity | 92ac3f65f621a5ed74ff627db16b45ebebd81a78 | [
"MIT"
] | 19 | 2021-04-28T20:23:54.000Z | 2021-11-08T11:41:31.000Z | public/js-minified/draft.js | cmd3BOT/Luminosity | 92ac3f65f621a5ed74ff627db16b45ebebd81a78 | [
"MIT"
] | 2 | 2021-04-30T10:12:04.000Z | 2021-08-10T18:36:54.000Z | public/js-minified/draft.js | cmd3BOT/Luminosity | 92ac3f65f621a5ed74ff627db16b45ebebd81a78 | [
"MIT"
] | 1 | 2021-08-07T07:53:50.000Z | 2021-08-07T07:53:50.000Z | import{newTokenData,URL,isJson,clipboardCopy}from"./script.js";let title,tagline,content;const saveBtn=document.querySelector("#save-changes"),draftId=document.querySelector("[name='draft_id']").value,toast=document.getElementById("draft-update-toast"),toastBody=toast.querySelector(".toast-body");function updateVars(){title=document.querySelector("#title").value,tagline=document.querySelector("#tagline").value,content=document.querySelector(".ql-editor").innerHTML}function changeSaveBtnState(){let e=title,t=tagline,n=content;updateVars(),e==title&&t==tagline&&n==content||(saveBtn.classList.add("btn-info"),saveBtn.classList.remove("btn-success"),saveBtn.innerText="Save Changes")}function updateDraft(){updateVars();const e=newTokenData({title:title,tagline:tagline,content:content,draft_id:draftId});toastBody.innerHTML='Saving Changes <i class="fas fa-circle-notch fa-spin"></i>';let t=new bootstrap.Toast(toast,{delay:15e3});t.show(),fetch(`${URL}/ajax/write/update-draft`,{method:"POST",body:e}).then(e=>e.text()).then(e=>{if(isJson(e)){let t=JSON.parse(e);200===t.status?(toastBody.innerHTML="Saved Changes",saveBtn.classList.remove("btn-info"),saveBtn.classList.add("btn-success"),saveBtn.innerText="Saved",updateVars()):(delete t.status,toastBody.innerHTML=`${t[Object.keys(t)[0]]}`)}setTimeout(function(){t.hide()},2e3)})}setTimeout(function(){updateVars(),window.setInterval(changeSaveBtnState,1e3)},2e3),document.querySelector("#rename").addEventListener("click",function(){let e=prompt("Enter new draft name: ")??" ";const t=newTokenData({new_name:e,draft_id:draftId});toastBody.innerHTML="Changing Name";let n=new bootstrap.Toast(toast,{delay:5e3});n.show(),fetch(`${URL}/ajax/write/rename-draft`,{method:"POST",body:t}).then(e=>e.text()).then(t=>{if(isJson(t)){let n=JSON.parse(t);200===n.status?(toastBody.innerHTML="Renamed Draft",document.querySelector("#draft_name").innerText=e):(delete n.status,toastBody.innerHTML=`${n[Object.keys(n)[0]]}`)}setTimeout(function(){n.hide()},3e3)})}),document.querySelector("#delete").addEventListener("click",function(){let e=prompt("Enter username to delete draft: ")??" ";const t=newTokenData({username:e,draft_id:draftId});toastBody.innerHTML="Delete";let n=new bootstrap.Toast(toast,{delay:5e3});n.show(),fetch(`${URL}/ajax/write/delete-draft`,{method:"POST",body:t}).then(e=>e.text()).then(e=>{if(isJson(e)){let t=JSON.parse(e);200===t.status?location.replace(`${URL}/write/drafts`):(delete t.status,toastBody.innerHTML=`${t[Object.keys(t)[0]]}`)}setTimeout(function(){n.hide()},3e3)})}),saveBtn.addEventListener("click",updateDraft),document.addEventListener("keydown",e=>{e.ctrlKey&&"s"===e.key&&(e.preventDefault(),updateDraft())}),document.querySelector("#copy-link").addEventListener("click",function(){clipboardCopy(`${URL}/write/draft/${draftId}`),toastBody.innerHTML="Copied Link",new bootstrap.Toast(toast,{delay:2e3}).show()}) | 2,902 | 2,902 | 0.749139 |
432e3ea3fd6f69b3026a56bc89c30fb484cdce3f | 3,431 | js | JavaScript | pie-time/dist/script.js | programmerkm/piclock | 5dfd6feda81cec5ecdedae855360e998a96fd112 | [
"MIT"
] | null | null | null | pie-time/dist/script.js | programmerkm/piclock | 5dfd6feda81cec5ecdedae855360e998a96fd112 | [
"MIT"
] | null | null | null | pie-time/dist/script.js | programmerkm/piclock | 5dfd6feda81cec5ecdedae855360e998a96fd112 | [
"MIT"
] | null | null | null | var c = document.getElementById('canv');
var $ = c.getContext('2d');
var ang = 0;
var secondsColor = 'hsla(180, 85%, 5%, .7)';
var minutesColor = 'hsla(180, 95%, 15%, 1)';
var hoursColor = 'hsla(180, 75%, 25%, 1)';
var currentHr;
var currentMin;
var currentSec;
var currentMillisec;
var t = setInterval( 'updateTime()', 50 );
function updateTime(){
var currentDate = new Date();
var g = $.createRadialGradient(250,250,.5,250,250,250);
g.addColorStop(0, 'hsla(180, 55%, 8%, 1)');
g.addColorStop(1, 'hsla(180, 95%, 15%, 1)');
$.fillStyle = g;
$.fillRect( 0, 0, c.width, c.height );
currentSec = currentDate.getSeconds();
currentMillisec = currentDate.getMilliseconds();
currentMin = currentDate.getMinutes();
currentHr = currentDate.getHours();
if(currentHr == 0){ //if midnight (00 hours) hour = 12
currentHr=12;
}
else if (currentHr >= 13 ){ //convert military hours at and over 1300 (1pm) to regular hours by subtracting 12.
currentHr -=12;
}
drawSeconds();
drawMinutes();
drawHours();
var realTime = currentHr + ':' + numPad0( currentMin ) + ':' + numPad0( currentSec );
/*Here is the selected option of creating the text within the pie canvas elemenet */
var textPosX = 250 - ( $.measureText(realTime).width / 2 );
$.shadowColor = 'hsla(180, 100%, 5%, 1)';
$.shadowBlur = 100;
$.shadowOffsetX = 12;
$.shadowOffsetY = 0;
$.fillStyle = 'hsla(255,255%,255%,.7)';
$.font = "bold 1.6em 'Noto Serif', serif";
$.fillText( realTime, textPosX, c.height/2+50);
/* OR using a div to display the time (#time) where I pre-styled text with a long shadow using css...can't decide which I like better - but since this is a canvas demo....; (comment out the above text settings and uncomment the below)
document.getElementById('time').innerHTML = realTime;
*/
}
function drawSeconds(){
ang = 0.006 * ( ( currentSec * 1000 ) + currentMillisec );
$.fillStyle = secondsColor;
$.beginPath();
$.moveTo( 250, 250 );
$.lineTo( 250, 50 );
$.arc( 250, 250, 200, calcDeg( 0 ), calcDeg( ang ), false );
$.lineTo( 250, 250 );
$.shadowColor = 'hsla(180, 45%, 5%, .4)';
$.shadowBlur =15;
$.shadowOffsetX = 15;
$.shadowOffsetY = 15;
$.fill();
}
function drawMinutes(){
ang = 0.0001 * ( ( currentMin * 60 * 1000 ) + ( currentSec * 1000 ) + currentMillisec );
$.fillStyle = minutesColor;
$.beginPath();
$.moveTo( 250, 250 );
$.lineTo( 250, 100 );
$.arc( 250, 250, 150, calcDeg( 0 ), calcDeg( ang ), false );
$.lineTo( 250, 250 );
$.shadowColor = 'hsla(180, 25%, 5%, .4)';
$.shadowBlur =15;
$.shadowOffsetX = 15;
$.shadowOffsetY = 15;
$.fill();
}
function drawHours(){
ang = 0.000008333 * ( ( currentHr * 60 * 60 * 1000 ) + ( currentMin * 60 * 1000 ) + ( currentSec * 1000 ) + currentMillisec );
if( ang > 360 ){
ang -= 360;
}
$.fillStyle = hoursColor;
$.beginPath();
$.moveTo( 250, 250 );
$.lineTo( 250, 150 );
$.arc( 250, 250, 100, calcDeg( 0 ), calcDeg( ang ), false );
$.lineTo( 250, 250 );
$.shadowColor = 'hsla(180, 45%, 5%, .4)';
$.shadowBlur =15;
$.shadowOffsetX = 15;
$.shadowOffsetY = 15;
$.fill();
}
function calcDeg( deg ){
return (Math.PI/180) * (deg - 90);
}
//handle zeros for minutes and seconds
function numPad0( str ){
var cStr = str.toString();
if( cStr.length < 2 ){
str = 0 + cStr;
}
return str;
}
window.addEventListener('resize', function(){
c.width = 500;
c.height = 500;
});
| 29.577586 | 237 | 0.620519 |
432e6ae37ca27b913feee3bad282da1c1f69f604 | 1,874 | js | JavaScript | src/mixins/inputHelper.js | znck/bootstrap-for-vue | dae9ee46fc7f1393613e8ff81ac9c2c2e80c0731 | [
"MIT"
] | 76 | 2017-02-16T08:43:26.000Z | 2020-10-14T18:02:17.000Z | src/mixins/inputHelper.js | znck/bootstrap-for-vue | dae9ee46fc7f1393613e8ff81ac9c2c2e80c0731 | [
"MIT"
] | 2 | 2017-03-17T15:45:49.000Z | 2017-03-28T10:54:14.000Z | src/mixins/inputHelper.js | znck/bootstrap-for-vue | dae9ee46fc7f1393613e8ff81ac9c2c2e80c0731 | [
"MIT"
] | 12 | 2017-03-09T14:28:21.000Z | 2021-03-19T05:53:34.000Z | import { ErrorBag } from '../utils'
export default {
inject: ['form'],
props: {
value: { required: true },
title: { type: String, default: null },
subtitle: { type: String, default: null },
name: { type: String, default: null },
inputName: { type: String, default: null },
errors: {
validator (errors) {
return !errors || errors instanceof ErrorBag
},
default: null
},
inputClass: String,
placeholder: String,
autofill: [String, Boolean],
autocomplete: [String, Boolean],
autofocus: [Boolean],
min: {},
max: {}
},
data: () => ({
expression: null,
required: null
}),
computed: {
id () {
return `text${this._uid}`
},
nameKey () {
const inputName = this.inputName
const expression = this.expression
if (inputName) return inputName
return expression
},
feedback () {
const errors = this.errors
const form = this.form
const name = this.nameKey
if (errors) {
return errors.get(name)
}
if (form && form.errors) {
return form.errors.get(name)
}
return null
}
},
methods: {
/**
* Mirror attributes from root element.
*
* @return {void}
*/
updateAttributes () {
if (!this.$vnode || !this.$vnode.data || !this.$vnode.data.attrs) return
this.required = this.$vnode.data.attrs.hasOwnProperty('required')
}
},
mounted () {
const model = this.$vnode.data.model
if (model) {
this.expression = model.expression.split('.').pop()
}
this.updateAttributes()
if (this.autofocus !== false) {
this.$nextTick(() => {
const el = this.$el.querySelector('[autofocus]')
if (el) el.focus()
})
}
},
beforeUpdate () {
this.updateAttributes()
}
}
| 18.929293 | 78 | 0.546958 |
432eb548a37dce3459bdb83d0188620bc1b69132 | 1,712 | js | JavaScript | public/assets/demo/custom/components/base/dropdown.js | UNICEFLebanonInnovation/measuring-wellbeing | 6e233aee9e5c51189dbf55a1d37a068aba8787df | [
"MIT"
] | null | null | null | public/assets/demo/custom/components/base/dropdown.js | UNICEFLebanonInnovation/measuring-wellbeing | 6e233aee9e5c51189dbf55a1d37a068aba8787df | [
"MIT"
] | null | null | null | public/assets/demo/custom/components/base/dropdown.js | UNICEFLebanonInnovation/measuring-wellbeing | 6e233aee9e5c51189dbf55a1d37a068aba8787df | [
"MIT"
] | null | null | null | //== Class definition
var DropdownDemo = function () {
//== Private functions
// basic demo
var demo1 = function () {
var output = $('#m_dropdown_api_output');
var dropdown1 = new mDropdown('m_dropdown_api_1');
var dropdown2 = new mDropdown('m_dropdown_api_2');
dropdown1.on('afterShow', function(dropdown) {
output.append('<p>Dropdown 1: afterShow event fired</p>');
});
dropdown1.on('beforeShow', function(dropdown) {
output.append('<p>Dropdown 1: beforeShow event fired</p>');
});
dropdown1.on('afterHide', function(dropdown) {
output.append('<p>Dropdown 1: afterHide event fired</p>');
});
dropdown1.on('beforeHide', function(dropdown) {
output.append('<p>Dropdown 1: beforeHide event fired</p>');
});
dropdown2.on('afterShow', function(dropdown) {
output.append('<p>Dropdown 2: afterShow event fired</p>');
});
dropdown2.on('beforeShow', function(dropdown) {
output.append('<p>Dropdown 2: beforeShow event fired</p>');
});
dropdown2.on('afterHide', function(dropdown) {
output.append('<p>Dropdown 2: afterHide event fired</p>');
});
dropdown2.on('beforeHide', function(dropdown) {
output.append('<p>Dropdown 2: beforeHide event fired</p>');
});
}
return {
// public functions
init: function() {
demo1();
}
};
}();
jQuery(document).ready(function() {
DropdownDemo.init();
}); | 34.24 | 73 | 0.526869 |
432eb648b912af82dceea24b214d062f0097302f | 3,372 | js | JavaScript | packages/tools/sugar/src/shared/function/getArgsNames.js | Coffeekraken/coffeekraken | 110ed7912affde64ecad1d19681ca6909a244239 | [
"MIT"
] | null | null | null | packages/tools/sugar/src/shared/function/getArgsNames.js | Coffeekraken/coffeekraken | 110ed7912affde64ecad1d19681ca6909a244239 | [
"MIT"
] | 57 | 2020-06-25T15:29:02.000Z | 2021-08-14T16:45:06.000Z | packages/tools/sugar/src/shared/function/getArgsNames.js | Coffeekraken/coffeekraken | 110ed7912affde64ecad1d19681ca6909a244239 | [
"MIT"
] | 2 | 2020-03-04T09:55:42.000Z | 2020-12-18T04:15:33.000Z | // @ts-nocheck
/**
* @name getArgsNames
* @namespace shared.function
* @type Function
* @platform js
* @platform ts
* @platform node
* @status beta
*
* Get the arguments names of the passed function. Return an array of the arguments names
*
* @param {Function} func The function reference of which get the arguments names
* @return {Array} An array of arguments names
*
* @todo interface
* @todo doc
* @todo move this into the "function" folder
*
* @example js
* import getArgsNames from '@coffeekraken/sugar/shared/function/getArgsNames';
* function hello(world, coco, plop) { }
* getArgsNames(hello); // => ['world', 'coco', 'plop']
*
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://olivierbossel.com)
*/
function getArgsNames(func) {
// String representaation of the function code
let str = func.toString();
// Remove comments of the form /* ... */
// Removing comments of the form //
// Remove body of the function { ... }
// removing '=>' if func is arrow function
str = str
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\/\/(.)*/g, '')
.replace(/{[\s\S]*}/, '')
.replace(/=>/g, '')
.trim();
// Start parameter names after first '('
const start = str.indexOf('(') + 1;
// End parameter names is just before last ')'
const end = str.length - 1;
const result = str.substring(start, end).split(', ');
const params = [];
result.forEach((element) => {
// Removing any default value
element = element.replace(/=[\s\S]*/g, '').trim();
if (element.length > 0)
params.push(element);
});
return params;
}
export default getArgsNames;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2V0QXJnc05hbWVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZ2V0QXJnc05hbWVzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWM7QUFFZDs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztHQXlCRztBQUNILFNBQVMsWUFBWSxDQUFDLElBQUk7SUFDeEIsOENBQThDO0lBQzlDLElBQUksR0FBRyxHQUFHLElBQUksQ0FBQyxRQUFRLEVBQUUsQ0FBQztJQUMxQix3Q0FBd0M7SUFDeEMsbUNBQW1DO0lBQ25DLHNDQUFzQztJQUN0QywwQ0FBMEM7SUFDMUMsR0FBRyxHQUFHLEdBQUc7U0FDTixPQUFPLENBQUMsbUJBQW1CLEVBQUUsRUFBRSxDQUFDO1NBQ2hDLE9BQU8sQ0FBQyxXQUFXLEVBQUUsRUFBRSxDQUFDO1NBQ3hCLE9BQU8sQ0FBQyxXQUFXLEVBQUUsRUFBRSxDQUFDO1NBQ3hCLE9BQU8sQ0FBQyxLQUFLLEVBQUUsRUFBRSxDQUFDO1NBQ2xCLElBQUksRUFBRSxDQUFDO0lBRVYsd0NBQXdDO0lBQ3hDLE1BQU0sS0FBSyxHQUFHLEdBQUcsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFDO0lBRW5DLDhDQUE4QztJQUM5QyxNQUFNLEdBQUcsR0FBRyxHQUFHLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztJQUUzQixNQUFNLE1BQU0sR0FBRyxHQUFHLENBQUMsU0FBUyxDQUFDLEtBQUssRUFBRSxHQUFHLENBQUMsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7SUFFckQsTUFBTSxNQUFNLEdBQUcsRUFBRSxDQUFDO0lBRWxCLE1BQU0sQ0FBQyxPQUFPLENBQUMsQ0FBQyxPQUFPLEVBQUUsRUFBRTtRQUN6Qiw2QkFBNkI7UUFDN0IsT0FBTyxHQUFHLE9BQU8sQ0FBQyxPQUFPLENBQUMsV0FBVyxFQUFFLEVBQUUsQ0FBQyxDQUFDLElBQUksRUFBRSxDQUFDO1FBRWxELElBQUksT0FBTyxDQUFDLE1BQU0sR0FBRyxDQUFDO1lBQUUsTUFBTSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsQ0FBQztJQUMvQyxDQUFDLENBQUMsQ0FBQztJQUVILE9BQU8sTUFBTSxDQUFDO0FBQ2hCLENBQUM7QUFDRCxlQUFlLFlBQVksQ0FBQyJ9 | 60.214286 | 1,414 | 0.724199 |
432f09b1dfac8c81fa1945b064288f82a89e03df | 118 | js | JavaScript | test/fixtures/transformation/es6-computed-property-names/this/expected.js | Dashed/6to5 | e7cbbefc111ff83d0f8bbd67e59d690c76cb72ea | [
"MIT"
] | 1 | 2019-05-14T15:37:43.000Z | 2019-05-14T15:37:43.000Z | test/fixtures/transformation/es6-computed-property-names/this/expected.js | Dashed/6to5 | e7cbbefc111ff83d0f8bbd67e59d690c76cb72ea | [
"MIT"
] | null | null | null | test/fixtures/transformation/es6-computed-property-names/this/expected.js | Dashed/6to5 | e7cbbefc111ff83d0f8bbd67e59d690c76cb72ea | [
"MIT"
] | null | null | null | "use strict";
var _this = this;
var obj = (function (_obj) {
_obj["x" + _this.foo] = "heh";
return _obj;
})({});
| 14.75 | 32 | 0.550847 |
433002f56ce38960e1c2a3533384b5cd1eda160a | 829 | js | JavaScript | src/documents/inbox/iris-documents-inbox.js | akhellas/synapse-iris | 9f195ba414a865a5c0d0d61648e163b480ff8fef | [
"MIT"
] | null | null | null | src/documents/inbox/iris-documents-inbox.js | akhellas/synapse-iris | 9f195ba414a865a5c0d0d61648e163b480ff8fef | [
"MIT"
] | null | null | null | src/documents/inbox/iris-documents-inbox.js | akhellas/synapse-iris | 9f195ba414a865a5c0d0d61648e163b480ff8fef | [
"MIT"
] | null | null | null | let tmpl = document.createElement('template');
tmpl.innerHTML = `
<style>:host { ... }</style> <!-- look ma, scoped styles -->
<b>I'm in shadow dom!</b>
<slot></slot>
`;
class IrisDocumentsInbox extends HTMLElement {
static get observedAttributes() {
return ['test'];
}
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(tmpl.content.cloneNode(true));
}
connectedCallback() {
console.log('IDI', 'connected');
this.innerHTML = "<b>iris-documents-inbox</b>";
}
disconnectedCallback() {
console.log('IDI', 'disconnected');
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log('IDI', 'attributeChanged', attrName, oldVal, newVal);
}
}
customElements.define('iris-documents-inbox', IrisDocumentsInbox);
| 22.405405 | 69 | 0.658625 |
43317abdb0ac63f8f54ac22b5d22486620274577 | 930 | js | JavaScript | tests/js/EntityTest.js | Sanwuthree/away3d-core-ts | 02a4b5f0a16914f8f74259a23252756d8ccf359d | [
"Apache-2.0"
] | null | null | null | tests/js/EntityTest.js | Sanwuthree/away3d-core-ts | 02a4b5f0a16914f8f74259a23252756d8ccf359d | [
"Apache-2.0"
] | null | null | null | tests/js/EntityTest.js | Sanwuthree/away3d-core-ts | 02a4b5f0a16914f8f74259a23252756d8ccf359d | [
"Apache-2.0"
] | 1 | 2018-11-18T18:00:42.000Z | 2018-11-18T18:00:42.000Z | ///<reference path="../../../build/Away3D.next.d.ts" />
//<reference path="../../../src/Away3D.ts" />
var tests;
(function (tests) {
(function (entities) {
var EntityTest = (function () {
// private entity : away.entities.Entity;
function EntityTest() {
// this.entity = new away.entities.Entity();
// this.entity.x = 10;
// this.entity.y = 10;
// this.entity.z = 10;
//
// this.entity.getIgnoreTransform();
//
// console.log( this.entity );
}
return EntityTest;
})();
entities.EntityTest = EntityTest;
})(tests.entities || (tests.entities = {}));
var entities = tests.entities;
})(tests || (tests = {}));
//# sourceMappingURL=EntityTest.js.map
| 37.2 | 71 | 0.446237 |
433199f67f80284b63f5d3b9e0661f200e8961f2 | 1,975 | js | JavaScript | src/props/igCurrencyEditor.js | IgniteUI/igniteui-react-wrappers | 1088bdb2179868ee6426d09fbedb2efc166dc3d2 | [
"MIT"
] | 18 | 2019-08-19T11:36:49.000Z | 2022-02-12T12:31:18.000Z | src/props/igCurrencyEditor.js | IgniteUI/igniteui-react-wrappers | 1088bdb2179868ee6426d09fbedb2efc166dc3d2 | [
"MIT"
] | 14 | 2019-03-11T08:57:48.000Z | 2022-03-02T11:08:00.000Z | src/props/igCurrencyEditor.js | IgniteUI/igniteui-react-wrappers | 1088bdb2179868ee6426d09fbedb2efc166dc3d2 | [
"MIT"
] | null | null | null | $.ig.react.propTypes.igCurrencyEditor = {
id: PropTypes.string.isRequired,
positivePattern: PropTypes.string,
currencySymbol: PropTypes.string,
listItems: PropTypes.array,
negativeSign: PropTypes.string,
negativePattern: PropTypes.string,
decimalSeparator: PropTypes.string,
groupSeparator: PropTypes.string,
groups: PropTypes.array,
maxDecimals: PropTypes.number,
minDecimals: PropTypes.number,
roundDecimals: PropTypes.bool,
textAlign: PropTypes.oneOf([
"left",
"right",
"center"
]),
dataMode: PropTypes.oneOf([
"double",
"float",
"long",
"ulong",
"int",
"uint",
"short",
"ushort",
"sbyte",
"byte"
]),
minValue: PropTypes.number,
maxValue: PropTypes.number,
allowNullValue: PropTypes.bool,
spinDelta: PropTypes.number,
scientificFormat: PropTypes.oneOf([
"E",
"e",
"E+",
"e+"
]),
spinWrapAround: PropTypes.bool,
isLimitedToListValues: PropTypes.bool,
value: PropTypes.object,
buttonType: PropTypes.oneOf([
"dropdown",
"clear",
"spin"
]),
listWidth: PropTypes.number,
listItemHoverDuration: PropTypes.number,
dropDownAttachedToBody: PropTypes.bool,
dropDownAnimationDuration: PropTypes.number,
visibleItemsCount: PropTypes.number,
placeHolder: PropTypes.string,
selectionOnFocus: PropTypes.oneOf([
"selectAll",
"atStart",
"atEnd",
"browserDefault"
]),
revertIfNotValid: PropTypes.bool,
preventSubmitOnEnter: PropTypes.bool,
dropDownOrientation: PropTypes.oneOf([
"auto",
"bottom",
"top"
]),
dropDownOnReadOnly: PropTypes.bool,
suppressNotifications: PropTypes.bool,
suppressKeyboard: PropTypes.bool,
width: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
height: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
tabIndex: PropTypes.number,
nullValue: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
inputName: PropTypes.string,
readOnly: PropTypes.bool,
disabled: PropTypes.bool,
validatorOptions: PropTypes.object
}
| 22.191011 | 45 | 0.739241 |
4331cc491853fe7726d6b164414bdf1f1107f582 | 13,972 | js | JavaScript | backend/dist/docker/docker-events.service.js | drumfreak/dockermon-app | be4aff5f5f270687d4b50f492b833f9896501a39 | [
"MIT"
] | null | null | null | backend/dist/docker/docker-events.service.js | drumfreak/dockermon-app | be4aff5f5f270687d4b50f492b833f9896501a39 | [
"MIT"
] | null | null | null | backend/dist/docker/docker-events.service.js | drumfreak/dockermon-app | be4aff5f5f270687d4b50f492b833f9896501a39 | [
"MIT"
] | null | null | null | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var DockerEventsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DockerEventsService = void 0;
const common_1 = require("@nestjs/common");
const axios_1 = require("@nestjs/axios");
const util_1 = require("util");
const child_process_1 = require("child_process");
const rxjs_1 = require("rxjs");
const stream_1 = require("stream");
const docker_service_1 = require("./docker.service");
const events_gateway_1 = require("../events/events.gateway");
const docker_hosts_service_1 = require("../docker-hosts/docker-hosts.service");
const activity_logs_service_1 = require("../activity-logs/activity-logs.service");
let DockerEventsService = DockerEventsService_1 = class DockerEventsService {
constructor(http, dockerService, eventsGateway, hostService, activityLogService) {
this.http = http;
this.dockerService = dockerService;
this.eventsGateway = eventsGateway;
this.hostService = hostService;
this.activityLogService = activityLogService;
this.logger = new common_1.Logger(DockerEventsService_1.name);
this.exec = (0, util_1.promisify)(child_process_1.exec);
this.dockerHubUrl = 'http://hub.docker.com/v2/';
this.dockerEventObservables = [rxjs_1.Subscription];
this.dockerEventStreams = [];
this.inoutStream = new stream_1.Transform({
transform(chunk, encoding, callback) {
this.push(chunk);
callback();
},
});
}
async dockerEvents() {
this.logger.log('Connecting to http events');
const f = await this.hostService.getHosts({ active: true });
if ((f === null || f === void 0 ? void 0 : f.status) === 'success') {
f.data.forEach((host) => {
const inoutStream = new stream_1.Transform({
transform(chunk, encoding, callback) {
this.push(chunk);
callback();
},
});
if (process.env.DOCKERMON_CURRENT_ENV === 'dev' && (host.ipAddress === 'localhost' || host.ipAddress === '127.0.0.1')) {
host.ipAddress = process.env.DOCKERMON_WORKER_HOST_ADDRESS;
}
const url = host.connectionType + '://' + host.ipAddress + ':' + host.port;
const dockerEventObservable = this.http
.get(url + '/events', {
responseType: 'stream',
timeout: 0,
})
.subscribe((res) => {
res.data.pipe(inoutStream);
});
inoutStream.on('data', (chunk) => {
const decoder = new TextDecoder('utf-8');
const data = decoder.decode(chunk);
let parsedData;
try {
parsedData = JSON.parse(data);
}
catch (err) {
console.warn('dockerEvents could not parse JSON data from event', err.message);
parsedData = data;
}
this.handleEvent(parsedData, host.id);
});
this.dockerEventObservables.push(dockerEventObservable);
this.dockerEventStreams.push(inoutStream);
});
}
}
subscribeDockerEvents() {
this.dockerEvents();
}
handleEvent(event, hostId) {
switch (event.Type) {
case 'container':
this.handleContainerEvent(event, hostId);
break;
case 'volume':
this.handleVolumeEvent(event, hostId);
break;
case 'image':
this.handleImageEvent(event, hostId);
break;
case 'network':
this.handleNetworkEvent(event, hostId);
break;
}
}
unsubscribeDockerEvents() {
if (this.dockerEventObservables.length > 0) {
this.dockerEventObservables.foreach((observable) => {
observable.unsubscribe();
});
this.dockerEventObservable.unsubscribe();
}
}
async handleContainerEvent(event, hostId) {
const container = { containerId: event.Actor.ID.substring(0, 12), containerLongId: event.Actor.ID, hostId: hostId };
const action = event.Action;
const excluded = ['top'];
switch (event.Action) {
default:
if (!excluded.includes(event.Action)) {
this.logger.log('Container Event');
}
else {
return;
}
if (event.Action === 'create') {
await this.dockerService.dockerUsage(hostId);
}
setTimeout(async () => {
const c = await this.dockerService.inspectContainer(container);
this.eventsGateway.dockerReceiver({
type: 'container',
action,
event,
hostId: hostId,
data: c,
});
if (!excluded.includes(event.Action)) {
const activityLog = {
container: c.id,
host: hostId,
contentType: 'containers',
action: event.Action,
notes: 'dockerEventsReceiver',
contentName: c.name,
dockerId: event.Actor.ID,
contentId: c.id,
data: event,
createdAt: new Date(event.time),
containerSnapshotAfter: c,
};
try {
this.activityLogService.save(activityLog);
}
catch (error) {
console.log('Activity Log Container Event Failed', error);
}
}
}, 500);
break;
}
}
async handleVolumeEvent(event, hostId) {
const volume = { volumeId: event.Actor.ID, hostId: hostId };
const action = event.Action;
switch (event.Action) {
default:
switch (event.status) {
case 'delete':
this.eventsGateway.dockerReceiver({
type: 'volume',
action,
event,
hostId: hostId,
data: null,
});
break;
default:
setTimeout(async () => {
const c = await this.dockerService.inspectVolume(volume);
this.eventsGateway.dockerReceiver({
type: 'volume',
action,
event,
hostId: hostId,
data: c,
});
try {
const activityLog = {
volume: c.id,
host: hostId,
contentType: 'volumes',
action: event.Action,
notes: 'dockerEventsReceiver',
dockerId: event.Actor.ID,
contentName: c.name,
contentId: c.id,
data: event,
createdAt: new Date(event.time),
};
this.activityLogService.save(activityLog);
}
catch (error) {
console.log('Activity Log Volume Event Failed', error);
}
}, 500);
break;
}
break;
}
}
async handleImageEvent(event, hostId) {
const image = { imageId: event.Actor.ID, hostId: hostId };
const action = event.Action;
switch (event.Action) {
default:
switch (event.status) {
case 'delete':
this.eventsGateway.dockerReceiver({
type: 'image',
action,
event,
hostId: hostId,
data: null,
});
break;
default:
setTimeout(async () => {
const c = await this.dockerService.inspectImage(image);
this.eventsGateway.dockerReceiver({
type: 'image',
action,
event,
hostId: hostId,
data: c,
});
try {
const activityLog = {
image: c.id,
host: hostId,
contentType: 'images',
action: event.Action,
contentName: c.name,
contentId: c.id,
notes: 'dockerEventsReceiver',
dockerId: event.Actor.ID,
data: event,
createdAt: new Date(event.time),
};
this.activityLogService.save(activityLog);
}
catch (error) {
console.log('Activity Log Image Event Failed', error);
}
}, 500);
break;
}
break;
}
}
async handleNetworkEvent(event, hostId) {
const network = { networkId: event.Actor.ID, hostId: hostId };
const action = event.Action;
switch (event.Action) {
default:
switch (event.status) {
case 'delete':
this.eventsGateway.dockerReceiver({
type: 'network',
action,
event,
hostId: hostId,
data: null,
});
break;
default:
setTimeout(async () => {
const c = await this.dockerService.inspectNetwork(network);
this.eventsGateway.dockerReceiver({
type: 'network',
action,
event,
hostId: hostId,
data: c,
});
const activityLog = {
network: c.id,
host: hostId,
contentType: 'networks',
action: event.Action,
contentName: c.name,
contentId: c.id,
dockerId: event.Actor.ID,
notes: 'dockerEventsReceiver',
createdAt: new Date(event.time),
data: event,
};
try {
this.activityLogService.save(activityLog);
}
catch (error) {
console.log('Activity Log Network Event Failed', error);
}
}, 500);
break;
}
break;
}
}
};
DockerEventsService = DockerEventsService_1 = __decorate([
(0, common_1.Injectable)(),
__metadata("design:paramtypes", [axios_1.HttpService,
docker_service_1.DockerService,
events_gateway_1.EventsGateway,
docker_hosts_service_1.DockerHostsService,
activity_logs_service_1.ActivityLogService])
], DockerEventsService);
exports.DockerEventsService = DockerEventsService;
//# sourceMappingURL=docker-events.service.js.map | 44.07571 | 150 | 0.419768 |
4332282ef68051486e0eb60bff5d24752a487dae | 5,267 | js | JavaScript | src/app/sop/filter_ops.tags.test.js | yuan-kuan/zasa | 05cfe702e3d131744ccd4b7fdf18eb50a8ae315a | [
"MIT"
] | null | null | null | src/app/sop/filter_ops.tags.test.js | yuan-kuan/zasa | 05cfe702e3d131744ccd4b7fdf18eb50a8ae315a | [
"MIT"
] | 2 | 2021-11-25T11:28:41.000Z | 2022-02-17T07:33:57.000Z | src/app/sop/filter_ops.tags.test.js | yuan-kuan/zasa | 05cfe702e3d131744ccd4b7fdf18eb50a8ae315a | [
"MIT"
] | null | null | null | import * as R from 'ramda';
import { createTestHelper } from 'test/utils';
import * as free from 'fp/free';
import * as item_ops from './item_ops';
import * as filter_ops from './filter_ops';
import * as tag_ops from "./tag_ops";
describe('Need memory KV', () => {
const testHelper = createTestHelper(false, true);
let interpret;
beforeEach(() => {
interpret = testHelper.setup();
});
test('Getting no saved filter? no problem', async () => {
const result = await interpret(
free.bimap(
(arr) => `No saved filter ${arr.length}`,
R.identity,
filter_ops.getSavedTagFilter()
)
);
expect(result).toBe('No saved filter 0');
});
test('Adding filter tags', async () => {
const result = await interpret(
free.sequence([
filter_ops.addFilterTag('A'),
filter_ops.addFilterTag('B'),
filter_ops.addFilterTag('C'),
filter_ops.getSavedTagFilter()
])
.map(R.last)
);
expect(result).toHaveLength(3);
expect(result).toEqual(['A', 'B', 'C']);
});
test('Removing filter tags', async () => {
const result = await interpret(
free.sequence([
filter_ops.addFilterTag('A'),
filter_ops.addFilterTag('B'),
filter_ops.addFilterTag('C'),
filter_ops.removeFilterTag('B'),
filter_ops.getSavedTagFilter()
])
.map(R.last)
);
expect(result).toHaveLength(2);
expect(result).toEqual(['A', 'C']);
});
});
describe('Need Filter Design Doc', () => {
const testHelper = createTestHelper(true, true);
let interpret;
beforeEach(() => {
interpret = testHelper.setup();
return interpret(filter_ops.setup());
});
test('Get all tags ever added to any existing items', async () => {
const result = await interpret(
free
.sequence([
item_ops.create('test item 1', null),
item_ops.create('test item 2', null),
])
.chain(([itemId1, itemId2]) =>
free.sequence([
tag_ops.add(itemId1, 'A'),
tag_ops.add(itemId1, 'B'),
tag_ops.add(itemId2, 'B'), // Overlap is fine
tag_ops.add(itemId2, 'C'),
filter_ops.getAllTags()
])
)
.map(R.last)
);
expect(result).toHaveLength(3);
expect(result).toEqual(['A', 'B', 'C']);
});
test('Tag will be gone as soon as no item had it', async () => {
const result = await interpret(
free
.sequence([
item_ops.create('test item 1', null),
item_ops.create('test item 2', null),
])
.chain(([itemId1, itemId2]) =>
free.sequence([
tag_ops.add(itemId1, 'A'),
tag_ops.add(itemId1, 'B'),
tag_ops.add(itemId2, 'B'), // Overlap is fine
tag_ops.add(itemId2, 'C'),
tag_ops.remove(itemId1, 'B'),
tag_ops.remove(itemId2, 'B'),
filter_ops.getAllTags()
])
)
.map(R.last)
);
expect(result).toHaveLength(2);
expect(result).toEqual(['A', 'C']);
});
test('Filter items with only the selected tag', async () => {
const result = await interpret(
free
.sequence([
item_ops.create('apple', null),
item_ops.create('ferrari', null),
item_ops.create('sky', null),
item_ops.create('grass', null),
])
.chain(([itemIdApple, itemIdFerrari, itemIdSky, itemIdGrass]) =>
free.sequence([
tag_ops.add(itemIdApple, 'fruit'),
tag_ops.add(itemIdApple, 'red'),
tag_ops.add(itemIdFerrari, 'red'), // Overlap is fine
tag_ops.add(itemIdFerrari, 'car'),
tag_ops.add(itemIdSky, 'blue'),
tag_ops.add(itemIdSky, 'natural'),
tag_ops.add(itemIdGrass, 'natural'),
tag_ops.add(itemIdGrass, 'green'),
filter_ops.getItemsWithTags(['red'])
])
)
.map(R.last)
);
expect(result).toHaveLength(2);
expect(result[0]).toHaveProperty('name', 'apple');
expect(result[1]).toHaveProperty('name', 'ferrari');
});
test('Filter items with all selected tags', async () => {
const result = await interpret(
free
.sequence([
item_ops.create('apple', null),
item_ops.create('ferrari', null),
item_ops.create('sky', null),
item_ops.create('grass', null),
])
.chain(([itemIdApple, itemIdFerrari, itemIdSky, itemIdGrass]) =>
free.sequence([
tag_ops.add(itemIdApple, 'fruit'),
tag_ops.add(itemIdApple, 'red'),
tag_ops.add(itemIdFerrari, 'red'),
tag_ops.add(itemIdFerrari, 'car'),
tag_ops.add(itemIdSky, 'blue'),
tag_ops.add(itemIdSky, 'natural'),
tag_ops.add(itemIdGrass, 'natural'),
tag_ops.add(itemIdGrass, 'green'),
filter_ops.getItemsWithTags(['fruit', 'natural'])
])
)
.map(R.last)
);
expect(result).toHaveLength(3);
expect(result[0]).toHaveProperty('name', 'apple');
expect(result[1]).toHaveProperty('name', 'grass');
expect(result[2]).toHaveProperty('name', 'sky');
});
})
| 29.261111 | 72 | 0.553256 |
4332419f7050169278dd37ae78af6f6b301c313b | 316 | js | JavaScript | src/store/index.js | taikongfeizhu/webpack-dll-demo | ca85bf6432fc3d59c33c37617e6c004a326660f7 | [
"MIT"
] | 107 | 2016-12-20T07:56:17.000Z | 2021-05-10T04:30:51.000Z | src/store/index.js | laihaojing/webpack-dll-demo | ca85bf6432fc3d59c33c37617e6c004a326660f7 | [
"MIT"
] | 2 | 2017-12-08T06:13:27.000Z | 2018-07-21T15:45:22.000Z | src/store/index.js | laihaojing/webpack-dll-demo | ca85bf6432fc3d59c33c37617e6c004a326660f7 | [
"MIT"
] | 31 | 2017-01-07T07:22:48.000Z | 2021-03-10T16:58:12.000Z | import { injectReducer } from './reducers';
import { injectSagas } from './sagas';
export const injectStore = (store, key, modules) => {
const reducer = modules.default;
const sagas = modules.sagas;
injectReducer(store, { key, reducer });
injectSagas(store, { key, sagas });
};
export default injectStore;
| 26.333333 | 53 | 0.689873 |
433290542149bfc9146c18a4ca7b07daa1bd4b22 | 1,653 | js | JavaScript | source/javascripts/mapper/main.js | voxmedia/mapper | b9bb8c751d8e07422eb564fcace8cbd83150f7b6 | [
"BSD-3-Clause"
] | 51 | 2015-04-17T17:15:33.000Z | 2021-11-23T16:49:22.000Z | source/javascripts/mapper/main.js | voxmedia/mapper | b9bb8c751d8e07422eb564fcace8cbd83150f7b6 | [
"BSD-3-Clause"
] | 2 | 2015-02-09T16:23:10.000Z | 2015-04-17T15:03:41.000Z | source/javascripts/mapper/main.js | gmac/mapper | b9bb8c751d8e07422eb564fcace8cbd83150f7b6 | [
"BSD-3-Clause"
] | 9 | 2015-04-17T18:12:55.000Z | 2020-11-10T13:34:23.000Z | var Mapper = {
models: {},
views: {},
init: function() {
this.settings = new this.models.Settings();
this.data = new this.models.Data();
this.fills = new this.models.Styles();
this.strokes = new this.models.Styles();
var editorMain = new this.views.EditorMainView();
var editorSettings = new this.views.MapSettingsView({
model: this.settings
});
var editorBaseView = new this.views.EditorStyleBaseView({
model: this.settings
});
var editorFillView = new this.views.EditorStyleListView({
el: '#editor-style-fill',
collection: this.fills,
model: this.settings,
type: 'fill'
});
var editorStrokeView = new this.views.EditorStyleListView({
el: '#editor-style-stroke',
collection: this.strokes,
model: this.settings,
type: 'stroke'
});
var editorData = new this.views.EditorDataView({
collection: this.data,
model: this.settings
});
this.mapPreview = new this.views.MapRenderView({
settings: this.settings,
fills: this.fills,
strokes: this.strokes,
data: this.data
});
this.fills.reset([
{value: 50, color: '#6d98a8', label: 'Reads Vox'},
{value: 100, color: '#fa4b2a', label: 'Reads Verge'}
]);
window.onbeforeunload = function() {
//return "You are about to exit this layout.";
};
},
getRenderConfig: function(opts) {
var config = this.settings.toJSON();
config.fills = this.fills.toJSON();
config.strokes = this.strokes.toJSON();
if (opts && opts.rows) config.rows = this.data.toJSON();
return config;
}
}; | 25.828125 | 63 | 0.61464 |
43332c7f6e218ed1fb3f234f11accde04b3d566b | 1,989 | js | JavaScript | packages/gasket-plugin-nextjs/lib/config.js | SNYKabbott/gasket | 3dd65ea2e2344d505d1987ece5bc573fe3cecf23 | [
"MIT"
] | 93 | 2019-12-11T13:30:32.000Z | 2022-03-31T17:41:43.000Z | packages/gasket-plugin-nextjs/lib/config.js | SNYKabbott/gasket | 3dd65ea2e2344d505d1987ece5bc573fe3cecf23 | [
"MIT"
] | 74 | 2019-12-12T16:15:55.000Z | 2022-03-23T19:19:00.000Z | packages/gasket-plugin-nextjs/lib/config.js | SNYKabbott/gasket | 3dd65ea2e2344d505d1987ece5bc573fe3cecf23 | [
"MIT"
] | 48 | 2019-12-12T18:15:51.000Z | 2022-02-24T16:48:05.000Z | const { initWebpack } = require('@gasket/plugin-webpack');
/**
* Bring forward configuration from intl plugin to config for next.
*
* @param {Gasket} gasket - The gasket API
* @param {object} config - Configuration to pass to Nextjs
* @private
*/
function forwardIntlConfig(gasket, config) {
const { logger } = gasket;
const { intl: intlConfig = {} } = gasket.config;
if (intlConfig.nextRouting === false) {
return;
}
// make a copy of i18n for mutating
const i18n = { ...(config.i18n || {}) };
if (intlConfig.locales) {
if (i18n.locales) {
logger.warning('Gasket config has both `intl.locales` (preferred) and `nextConfig.i18n.locales`');
}
i18n.locales = intlConfig.locales;
if (i18n.defaultLocale) {
logger.warning('Gasket config has both `intl.defaultLocale` (preferred) and `nextConfig.i18n.defaultLocale`');
}
i18n.defaultLocale = intlConfig.defaultLocale;
config.i18n = i18n;
}
}
/**
* Small helper function that creates nextjs configuration from the gasket
* configuration.
*
* @param {Gasket} gasket The gasket API.
* @param {Boolean} includeWebpackConfig `true` to generate webpack config
* @returns {Promise<Object>} The configuration data for Nextjs
* @private
*/
function createConfig(gasket, includeWebpackConfig = true) {
const { nextConfig = {} } = gasket.config;
const config = {
poweredByHeader: false,
...nextConfig
};
forwardIntlConfig(gasket, config);
if (includeWebpackConfig) {
const { webpack: existingWebpack } = config;
//
// Add webpack property to nextConfig and wrap existing
//
config.webpack = function webpack(webpackConfig, data) {
if (typeof existingWebpack === 'function') {
webpackConfig = existingWebpack(webpackConfig, data);
}
return initWebpack(gasket, webpackConfig, data);
};
}
return gasket.execWaterfall('nextConfig', config);
}
module.exports = {
createConfig
};
| 26.878378 | 116 | 0.668678 |
43337800cd83e8db19357cd5fc3caa1a83c17370 | 989 | js | JavaScript | src/reducers/pokemonReducer.js | BotCode95/pokemonWithRedux | 650d6f7da958b416d8da542860f3ce651c6f85bc | [
"MIT"
] | null | null | null | src/reducers/pokemonReducer.js | BotCode95/pokemonWithRedux | 650d6f7da958b416d8da542860f3ce651c6f85bc | [
"MIT"
] | null | null | null | src/reducers/pokemonReducer.js | BotCode95/pokemonWithRedux | 650d6f7da958b416d8da542860f3ce651c6f85bc | [
"MIT"
] | null | null | null | import { SET_POKEMONS, SET_ERROR, CLEAR_ERROR, TOGGLE_LOADER, SET_FAVORITE } from '../actions/type';
const initialState = {
list: [],
error: '',
loading: true,
};
export const pokemonReducer = (state = initialState, action) => {
switch (action.type) {
case SET_POKEMONS:
return { ...state, list: action.payload };
case SET_ERROR:
return { ...state, error: action.payload.message };
case CLEAR_ERROR:
return { ...state, error: '' };
case TOGGLE_LOADER:
return { ...state, loading: !state.loading };
case SET_FAVORITE:
const newPokemonList = [...state.list]
const currentPokemonIndex = newPokemonList.findIndex((poke) => poke.id === action.payload)
if(currentPokemonIndex >= 0) {
newPokemonList[currentPokemonIndex].favorite = !newPokemonList[currentPokemonIndex].favorite;
}
return {
...state,
list: newPokemonList
}
default:
return state;
}
}; | 31.903226 | 103 | 0.62184 |
433415df881bd5b67ed9e8532c387423e741b853 | 420 | js | JavaScript | src/main.js | bryanjhickey/bjh | 4f69e116eb5ce746842d286a5eec501b9bbae5bc | [
"MIT"
] | null | null | null | src/main.js | bryanjhickey/bjh | 4f69e116eb5ce746842d286a5eec501b9bbae5bc | [
"MIT"
] | 2 | 2021-03-09T12:45:35.000Z | 2021-05-10T03:09:26.000Z | src/main.js | bryanjhickey/bjh-vue | 4f69e116eb5ce746842d286a5eec501b9bbae5bc | [
"MIT"
] | null | null | null | import DefaultLayout from '~/layouts/Default.vue'
export default function (Vue, { head }) {
Vue.component('Layout', DefaultLayout)
// Add an external CSS file
head.link.push({
rel: 'stylesheet',
href: 'https://fonts.googleapis.com/css?family=Mali:700|Nunito'
}),
// Add a meta tag
head.meta.push({
name: "p:domain_verify",
content: "32b98802270ed243841884e2ca3a9709"
})
} | 24.705882 | 68 | 0.65 |