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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b24ad7e770b396ee28d35de61935454e7f2da2a | 196 | js | JavaScript | _scripts/webpack.config.js | bumplzz69/unifi-slackbot | 3aee8d6e99e69157dede7efe1cd5a8eb53d975a8 | [
"MIT"
] | 7 | 2017-06-30T12:45:48.000Z | 2020-10-26T03:46:36.000Z | _scripts/webpack.config.js | glenndehaan/slack-bot-basis | c13a7416ad97d40366a031acbbd5dd0c6c3baf43 | [
"MIT"
] | null | null | null | _scripts/webpack.config.js | glenndehaan/slack-bot-basis | c13a7416ad97d40366a031acbbd5dd0c6c3baf43 | [
"MIT"
] | 2 | 2019-04-29T20:10:08.000Z | 2020-06-21T11:37:10.000Z | const webpack = require('webpack');
module.exports = {
watchOptions: {
poll: true
},
entry: `${__dirname}/../public/js/main.js`,
stats: {
colors: true,
}
};
| 14 | 47 | 0.520408 |
8b24cd2149fe5a1cef816705147ab26941c9b24b | 3,059 | js | JavaScript | micro/helpers.js | mzch/web-file-uploader | baeb9d8a7474ff399dd91f65b458779435385b4f | [
"MIT"
] | 38 | 2020-07-09T16:54:04.000Z | 2022-01-26T16:25:25.000Z | micro/helpers.js | mzch/web-file-uploader | baeb9d8a7474ff399dd91f65b458779435385b4f | [
"MIT"
] | 46 | 2019-05-04T20:26:02.000Z | 2021-09-01T05:31:33.000Z | micro/helpers.js | mzch/web-file-uploader | baeb9d8a7474ff399dd91f65b458779435385b4f | [
"MIT"
] | 9 | 2020-09-17T20:16:19.000Z | 2022-01-13T20:46:10.000Z | const toArray = require('stream-to-array')
const mongoose = require('mongoose')
const config = require('@femto-apps/config')
const memoize = require('memoizee')
const fetch = require('node-fetch')
const Types = require('../types')
const Item = require('../modules/Item')
const Short = require('../modules/Short')
const Store = require('../modules/Store')
let connectedToMongoose = false
module.exports.connectToMongoose = () => {
if (connectedToMongoose) return
mongoose.connect(config.get('mongo.uri') + config.get('mongo.db'), {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
connectedToMongoose = true
}
module.exports.bustCache = async (short) => {
return fetch(`http://localhost:${config.get('cluster.getClusterPort')}/buster?short=${short}`)
.then(res => res.json())
}
module.exports.getTypeFromStore = async (store, metadata) => {
const bytes = (await toArray(await store.getStream({ end: 2048, start: 0 })))[0]
const { data } = await Types.detect(store, bytes, metadata)
return data
}
module.exports.createUrlItem = async (url, { expiry, user }) => {
const item = await Item.create({
name: {
// req.body.text is only used in uploader v2
original: url,
},
metadata: {
filetype: 'url',
expiresAt: expiry
},
user
})
const shortWord = await Short.generate({ keyLength: 4 })
const short = await Short.createReference(shortWord, item.item)
await item.setCanonical(short)
return { item, short }
}
module.exports.createItem = async (storage, { expiry, mimetype, encoding, filename, user }) => {
const extension = filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
const store = await Store.create(storage)
const type = await module.exports.getTypeFromStore(store, { mimetype, encoding })
const item = await Item.create({
name: {
original: filename,
extension: extension,
filename: filename.replace(/\.[^/.]+$/, '')
},
metadata: {
expiresAt: expiry,
createdAt: new Date(),
updatedAt: new Date(),
size: storage.size,
...type
},
references: {
storage: store.store
},
user
})
const shortWord = await Short.generate({ keyLength: 4 })
const short = await Short.createReference(shortWord, item.item)
await item.setCanonical(short)
return { item, store, short }
}
module.exports.getItem = async (name) => {
const short = await Short.get(name.split('.')[0])
if (short === null) {
return undefined
}
const item = new Item(short.item)
const type = Types.match(item)
return type
}
module.exports.cachedGetItem = memoize(module.exports.getItem, {
primitive: true,
length: 1,
resolvers: [String],
promise: true,
maxAge: 1000 * 60 * 60,
preFetch: false
}) | 27.558559 | 98 | 0.609676 |
8b26c449acff0c07f040ad8236a0417c39031fb1 | 1,173 | js | JavaScript | react-disqus.js | rajzshkr/react-disqus | 6d0badbcc7738f53a51301692382219e5a717cba | [
"MIT"
] | 3 | 2016-09-17T00:25:20.000Z | 2017-01-12T19:17:10.000Z | react-disqus.js | rajasekarm/react-disqus | 6d0badbcc7738f53a51301692382219e5a717cba | [
"MIT"
] | 5 | 2016-10-27T04:59:30.000Z | 2017-08-30T05:09:15.000Z | react-disqus.js | rajasekarm/react-disqus | 6d0badbcc7738f53a51301692382219e5a717cba | [
"MIT"
] | 4 | 2016-09-17T20:29:35.000Z | 2017-02-06T22:45:21.000Z | import React from 'react';
class ReactDisqus extends React.Component{
componentDidMount() {
this.embedDisqus();
}
render() {
return(
<div>
<div id="disqus_thread">
<noscript>
<span>
Please enable JavaScript to view the
<a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a>
</span>
</noscript>
</div>
</div>
)
}
embedDisqus() {
var disqus_config = function () {
this.page.url = this.props.pageurl;
this.page.identifier = this.props.identifier;
};
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + this.props.shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
}
ReactDisqus.propTypes = {
shortname: React.PropTypes.string.isRequired,
pageurl: React.PropTypes.string,
identifier: React.PropTypes.string,
}
ReactDisqus.defaultProps = {
shortname: null,
pageurl: window.location.href,
identifier: null
};
export default ReactDisqus;
| 26.066667 | 108 | 0.628303 |
8b273ba190cd6ff48bfbcb4ce6f9888e000391af | 8,049 | js | JavaScript | routes/api-old/role.js | kumaresanb/evolvus-platform-server | 9158fc5975fe2a19de7c24ff501b491b3f8bf2f8 | [
"MIT"
] | null | null | null | routes/api-old/role.js | kumaresanb/evolvus-platform-server | 9158fc5975fe2a19de7c24ff501b491b3f8bf2f8 | [
"MIT"
] | 3 | 2020-09-04T14:46:24.000Z | 2022-02-12T04:32:57.000Z | routes/api-old/role.js | Evolvus/evolvus-platform-server | 3fa8424113b42a1d03fabd2c6cf92f5a845468be | [
"MIT"
] | 1 | 2021-05-13T16:34:59.000Z | 2021-05-13T16:34:59.000Z | const debug = require("debug")("evolvus-platform-server:routes:api:role");
const _ = require("lodash");
const role = require("evolvus-role");
const application = require("evolvus-application");
const roleAttributes = ["tenantId", "roleName", "applicationCode", "description", "activationStatus", "processingStatus", "associatedUsers", "createdBy", "createdDate", "menuGroup", "lastUpdatedDate"];
const headerAttributes = ["tenantid", "entityid", "accesslevel"];
module.exports = (router) => {
router.route("/role")
.post((req, res, next) => {
try {
let body = _.pick(req.body, roleAttributes);
let header = _.pick(req.headers, headerAttributes);
body.tenantId = header.tenantid;
body.entityCode = header.entityid;
body.accessLevel = header.accesslevel;
body.processingStatus = "PENDING_AUTHORIZATION";
body.associatedUsers = 5;
body.createdBy = "SYSTEM";
body.createdDate = new Date().toISOString();
body.lastUpdatedDate = body.createdDate;
Promise.all([application.getOne({
applicationCode: body.applicationCode
}), role.getOne("roleName", body.roleName)])
.then((result) => {
if (_.isEmpty(result[0])) {
throw new Error(`No Application with ${body.applicationCode} found`);
}
if (!_.isEmpty(result[1])) {
throw new Error(`RoleName ${body.roleName} already exists`);
}
role.save(body).then((obj) => {
res.json({
savedRoleObject: obj,
message: `New role ${body.roleName.toUpperCase()} has been added successfully for the application ${body.applicationCode} and sent for the supervisor authorization.`
});
}).catch((e) => {
res.status(400).json({
error: e.toString(),
message: `Unable to add new role ${body.roleName}. Due to ${e.message}`
});
});
}).catch((e) => {
res.status(400).json({
error: e.toString(),
message: `Unable to add new role ${body.roleName}. Due to ${e.message}`
});
});
} catch (e) {
res.status(400).json({
error: e.toString(),
message: `Unable to add new role ${body.roleName}. Due to ${e.message}`
});
}
});
router.route('/role')
.get((req, res, next) => {
try {
let header = _.pick(req.headers, headerAttributes);
let pageNo = +req.query.pageNo;
let pageSize = +req.query.pageSize;
role.getAll(header.tenantid, header.entityid, header.accesslevel, pageSize, pageNo)
.then((result) => {
let totalNoOfRecords;
let data;
let pageObject = {};
pageObject.totalNoOfRecords = result.length;
let totalNoOfPages = Math.ceil(pageObject.totalNoOfRecords / pageSize);
pageObject.totalNoOfPages = totalNoOfPages;
pageObject.data = result;
res.json(pageObject);
}).catch((e) => {
res.status(400).json({
error: e.toString()
});
});
} catch (e) {
res.status(400).json({
error: e.toString()
});
}
});
router.route("/role/:id")
.put((req, res, next) => {
try {
let body = _.pick(req.body.roleData, roleAttributes);
body.lastUpdatedDate = new Date().toISOString();
body.updatedBy = "SYSTEM";
body.processingStatus = "PENDING_AUTHORIZATION";
Promise.all([application.getOne({
applicationCode: body.applicationCode
}), role.getOne("roleName", body.roleName)])
.then((result) => {
if (_.isEmpty(result[0])) {
throw new Error(`No Application with ${body.applicationCode} found`);
}
if ((!_.isEmpty(result[1])) && (result[1]._id != req.params.id)) {
throw new Error(`RoleName ${body.roleName} already exists`);
}
role.update(req.params.id, body).then((updatedRole) => {
res.json({
updatedRoleObject: updatedRole,
message: `${body.roleName} role has been modified successfully for the application ${body.applicationCode} and sent for the supervisor authorization.`
});
}).catch((e) => {
res.status(400).json({
error: e.toString(),
message: `Unable to modify role ${body.roleName}. Due to ${e.message}`
});
});
}).catch((e) => {
res.status(400).json({
error: e.toString(),
message: `Unable to modify role ${body.roleName}. Due to ${e.message}`
});
});
} catch (e) {
res.status(400).json({
error: e.toString(),
message: `Unable to modify role ${body.roleName}. Due to ${e.message}`
});
}
});
router.route('/role/find')
.get((req, res, next) => {
try {
let roleName = req.query.roleName;
role.getOne("roleName", roleName).then((role) => {
res.json(role);
}).catch((e) => {
res.status(400).json({
error: e.toString()
});
});
} catch (e) {
res.status(400).json({
error: e.toString()
});
}
});
router.route("/role/delete/:id")
.put((req, res, next) => {
try {
let body = _.pick(req.body.roleData, roleAttributes);
Promise.all([application.getOne("applicationCode", body.applicationCode), role.getOne("roleName", body.roleName)])
.then((result) => {
if (_.isEmpty(result[0])) {
throw new Error(`No Application with ${body.applicationCode} found`);
}
if ((!_.isEmpty(result[1])) && (result[1]._id != req.params.id)) {
throw new Error(`RoleName ${body.roleName} already exists`);
}
let updated = {
deletedFlag: "1"
};
role.update(req.params.id, updated).then((updatedRole) => {
res.json(updatedRole);
}).catch((e) => {
res.status(400).json({
error: e.toString()
});
});
}).catch((e) => {
res.status(400).json({
error: e.toString()
});
});
} catch (e) {
res.status(400).json({
error: e
});
}
});
router.route('/role/filter')
.get((req, res, next) => {
try {
let header = _.pick(req.headers, headerAttributes);
let countQuery = {};
countQuery.processingStatus = req.query.processingStatus;
countQuery.activationStatus = req.query.activationStatus;
countQuery.applicationCode = req.query.applicationCode;
let filterQuery = {};
filterQuery.processingStatus = req.query.processingStatus;
filterQuery.activationStatus = req.query.activationStatus;
filterQuery.applicationCode = req.query.applicationCode;
let pageNo = +req.query.pageNo;
let pageSize = +req.query.pageSize;
Promise.all([role.filterByRoleDetails(filterQuery, pageSize, pageNo), role.getRoleCounts(countQuery)])
.then((result) => {
let totalNoOfRecords;
let data;
let pageObject = {};
let totalNoOfPages = Math.ceil(result[1] / pageSize);
pageObject.totalNoOfPages = totalNoOfPages;
pageObject.totalNoOfRecords = result[1];
pageObject.data = result[0];
res.json(pageObject);
}).catch((e) => {
res.status(400).json({
error: e.toString()
});
});
} catch (e) {
res.status(400).send(JSON.stringify({
error: e.toString()
}));
}
});
}; | 37.263889 | 201 | 0.528513 |
8b28312f010321a51a5e7727e58c40fa0fa789b1 | 512 | js | JavaScript | node_modules/rxjs/dist/esm5/internal/operators/switchScan.js | vikusss/sub4.3 | 006301051ed052c8105b7da592bd2ae59d695920 | [
"MIT"
] | 30 | 2021-11-29T17:38:12.000Z | 2022-02-11T21:59:22.000Z | node_modules/rxjs/dist/esm5/internal/operators/switchScan.js | vikusss/sub4.3 | 006301051ed052c8105b7da592bd2ae59d695920 | [
"MIT"
] | 95 | 2022-02-04T19:40:09.000Z | 2022-03-31T20:24:11.000Z | node_modules/rxjs/dist/esm5/internal/operators/switchScan.js | vikusss/sub4.3 | 006301051ed052c8105b7da592bd2ae59d695920 | [
"MIT"
] | 4 | 2021-04-22T14:14:01.000Z | 2022-03-31T01:56:15.000Z | import { switchMap } from './switchMap';
import { operate } from '../util/lift';
export function switchScan(accumulator, seed) {
return operate(function (source, subscriber) {
var state = seed;
switchMap(function (value, index) { return accumulator(state, value, index); }, function (_, innerValue) { return ((state = innerValue), innerValue); })(source).subscribe(subscriber);
return function () {
state = null;
};
});
}
//# sourceMappingURL=switchScan.js.map | 42.666667 | 191 | 0.642578 |
8b2840cadbaef1b176f5c9ebc98d0b889db9e796 | 4,617 | js | JavaScript | miniprogram/lib/fc-api.js | ynu/szyd-wxapp | 6ca46291cf5bbe2279395ac4b18d1e1942e63dde | [
"MIT"
] | 6 | 2018-05-18T21:49:01.000Z | 2020-10-27T11:21:28.000Z | miniprogram/lib/fc-api.js | ynu/szyd-wxapp | 6ca46291cf5bbe2279395ac4b18d1e1942e63dde | [
"MIT"
] | 17 | 2019-05-08T00:35:49.000Z | 2020-07-23T12:33:09.000Z | miniprogram/lib/fc-api.js | ynu/szyd-wxapp | 6ca46291cf5bbe2279395ac4b18d1e1942e63dde | [
"MIT"
] | 7 | 2019-04-08T02:43:14.000Z | 2020-08-26T01:49:35.000Z | /**
* version: 1.0.2
* FC虚拟化平台API
*/
class FcApi {
// 获取所有虚拟机
allvm() {
return this.vmCount().then(allvm => {
let vm = [];
let vmall = [];
for (let offset = 0; offset < allvm; offset += 100) {
vm.push(this.vms({
siteId: this.siteId,
limit: 100,
offset: offset
}));
}
return Promise.all(vm).then(vms => {
for (let vm of vms) {
vmall = vmall.concat(vm.list);
}
return vmall || {};
});
});
}
// 查询指定集群虚拟机
SelectVmForClusters(clusterName) {
return this.allvm().then(vms => {
var newvms = [];
for (let vm of vms) {
if (vm.clusterName == clusterName) {
newvms.push(vm);
}
}
return newvms;
});
}
// 查询指定主机虚拟机
SelectVmForHost(hostName) {
return this.allvm().then(vms => {
var newvms = [];
for (let vm of vms) {
if (vm.hostName == hostName) {
newvms.push(vm);
}
}
return newvms;
});
}
// 查询指定集群主机
SelectHostForClusters(clusterName) {
return this.hosts().then(hosts => {
var newhost = [];
for (let host of hosts.list) {
if (host.clusterName == clusterName) {
newhost.push(host);
}
}
return newhost;
});
}
// 按规则合并集群主机虚拟机
setlist() {
return Promise.all([this.allvm(), this.clusters(), this.hosts()]).then(([allvm, clusters, hosts]) => {
for (let cluster of clusters) {
cluster.hostcount = 0;
for (let host of hosts.list) {
cluster.vmcount = 0;
cluster.vmstartcount = 0;
if (cluster.name == host.clusterName) {
cluster.hostcount += 1;
}
for (let vm of allvm) {
if (cluster.name == vm.clusterName) {
cluster.vmcount += 1;
if (vm.status == "running") {
cluster.vmstartcount += 1;
}
}
}
}
}
return clusters;
});
}
// 筛选关闭的虚拟机
ShutdownVm(vms) {
var down = [];
var start = [];
for (let vm of vms) {
if (vm.status == "stopped") {
down.push(vm);
} else {
start.push(vm);
}
}
return {
start,
down
};
}
//通过云函数获取指定的虚拟机信息
vms(options = {}) {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'fcApiVms',
data: {
siteIdOptions: options.siteId,
limit: options.limit,
offset: options.offset
}
}).then(res => {
resolve(res.result.result || {});
}).catch(err => reject(err))
})
}
//获取虚拟机总数量
vmCount() {
const db = wx.cloud.database();
return db.collection('kvs').where({
_id: "index:fc-vms-count"
}).get().then((res) => {
return res.data[0].value || 0;
})
}
//通过云函数获取集群
clusters(options = {}) {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'fcApiClusters',
data: {
siteIdOption: options.siteId
}
}).then(res => {
resolve(res.result.result || []);
}).catch(err => reject(err))
})
}
//通过云数据库调用获取集群数量
clustersCount() {
const db = wx.cloud.database();
return db.collection('kvs').where({
_id: "index:fc-clusters-count"
}).get().then((res) => {
return res.data[0].value || 0;
})
}
//通过云函数获取主机信息
hosts(options = {}) {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'fcApiHosts',
data: {
siteIdOption: options.siteId,
limit: options.limit,
offset: options.offset
}
}).then(res => {
resolve(res.result.result || {})
}).catch(err => reject(err))
})
}
//获取主机数量
hostCount() {
const db = wx.cloud.database();
return db.collection('kvs').where({
_id: "index:fc-hosts-count"
}).get().then((res) => {
return res.data[0].value || 0;
})
}
//计算正在运行的虚拟机的数量
runningVmCount() {
const db = wx.cloud.database();
return db.collection('kvs').where({
_id: "index:fc-running-vms-count"
}).get().then((res) => {
return res.data[0].value || 0;
})
}
//查询虚拟机详细信息
vmDetails(vmId) {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'fcApiVmDetails',
data: {
vmId: vmId
}
}).then(res => {
resolve(res.result.result || {});
}).catch(err => reject(err))
})
}
}
module.exports = FcApi; | 21.881517 | 106 | 0.49426 |
8b29f4c2aa0a708dfa16ebeefbfcd313ac922550 | 1,240 | js | JavaScript | example/itinerary_example.js | samuelkitazume/graph-engine | e9c12ae8d144ced1358f51515396c1e58f770582 | [
"MIT"
] | 1 | 2019-05-27T14:44:48.000Z | 2019-05-27T14:44:48.000Z | example/itinerary_example.js | samuelkitazume/graph-engine | e9c12ae8d144ced1358f51515396c1e58f770582 | [
"MIT"
] | 1 | 2020-07-17T01:45:17.000Z | 2020-07-17T01:45:17.000Z | example/itinerary_example.js | samuelkitazume/graph-engine | e9c12ae8d144ced1358f51515396c1e58f770582 | [
"MIT"
] | null | null | null | const railway = (name, trigger, bullet, destination) => Object.assign({}, { name, trigger, bullet, destination })
const station = (name, railways, initial=false) => Object.assign({}, { name, railways, initial })
const example = {
name: 'example of itinerary',
description: 'Lorem ipsum dolor sit amet',
railways: [
railway('railway1', 'trigger1', 'bullet1', 'station2'),
railway('railway2', 'trigger2', 'bullet2', 'station3'),
railway('railway3', 'trigger3', 'bullet3', 'station4'),
railway('railway4', 'trigger4', 'bullet4', 'station5'),
railway('railway5', 'trigger5', 'bullet5', 'station6'),
railway('railway6', 'trigger6', 'bullet6', 'station7'),
railway('railway7', 'trigger7', 'bullet7', 'station7'),
railway('railway8', 'trigger8', 'bullet8', 'station8'),
railway('railway9', 'trigger9', 'bullet9', 'station8'),
],
stations: [
station('station1', ['railway1', 'railway2'], true),
station('station2', ['railway3', 'railway4']),
station('station3', ['railway5']),
station('station4', ['railway6']),
station('station5', ['railway7']),
station('station6', ['railway9']),
station('station7', ['railway8']),
station('station8'),
]
}
module.exports = example | 41.333333 | 113 | 0.635484 |
8b29f91d04061c6b823ba136e4d37a9cfc22f80f | 1,230 | js | JavaScript | Commands/register/y-info.js | Aello1/Aello-Register-v12 | 78b9a78b5712bdaefd477a91fcf59f97ce49f918 | [
"MIT"
] | 1 | 2021-11-15T18:02:53.000Z | 2021-11-15T18:02:53.000Z | Commands/register/y-info.js | Aello1/Aello-Register-v12 | 78b9a78b5712bdaefd477a91fcf59f97ce49f918 | [
"MIT"
] | null | null | null | Commands/register/y-info.js | Aello1/Aello-Register-v12 | 78b9a78b5712bdaefd477a91fcf59f97ce49f918 | [
"MIT"
] | null | null | null | const { DiscordAPIError } = require('discord.js')
const Discord = require('discord.js')
const db = require('quick.db')
const Config = require('../../Config.json')
exports.run = async (client, message, args) => {
if (!message.member.hasPermission('ADMINISTRATOR') && !message.member.roles.cache.has(Config.Kayitci) && !message.member.roles.cache.has(Config.Parnerci)) return;
let m;
if(message.mentions.members.first()) m = message.mentions.members.first()
if(!message.mentions.members.first()) m = message.member;
let kayit = db.get(`yetkili.kayit.${m.id}`)
let erkek = db.get(`yetkili.erkek.kayit.${m.id}`)
let kadin = db.get(`yetkili.kadin.kayit.${m.id}`)
message.channel.send(new Discord.MessageEmbed().setTitle(`${m.displayName} Yetki İstatistikleri`).setColor(m.displayHexColor).setFooter(message.guild.name, 'https://media.discordapp.net/attachments/634781972970995714/816007004527001640/AELLO_GNG_1.png')
.setDescription(`
Toplam Üye Kaydı: **${kayit ? kayit : '0'}**
Toplam Erkek Üye Kaydı: **${erkek ? erkek : '0'}**
Toplam Kadın Üye Kaydı: **${kadin ? kadin : '0'}**`))
}
exports.conf = {
aliases: ['yti','yinfo', 'y-info'],
permLevel: 0
};
exports.help = {
name: 'yetkili-info',
}; | 42.413793 | 254 | 0.688618 |
8b2a201113ae70ba3d0048d89530594d014a8e6a | 673 | js | JavaScript | apps/app/components/associate/index.js | DesignWorldsCollabs/mindseum | 4948409f568bc244027835e878bbbe0aabdf2122 | [
"Apache-2.0"
] | null | null | null | apps/app/components/associate/index.js | DesignWorldsCollabs/mindseum | 4948409f568bc244027835e878bbbe0aabdf2122 | [
"Apache-2.0"
] | null | null | null | apps/app/components/associate/index.js | DesignWorldsCollabs/mindseum | 4948409f568bc244027835e878bbbe0aabdf2122 | [
"Apache-2.0"
] | null | null | null | module.exports = Associate
function Associate() {}
Associate.prototype.name = 'associate';
Associate.prototype.view = __dirname;
Associate.prototype.init = function () {
this.model.ref('offset', this.model.scope('_page.offset'));
this.model.ref('clippings', this.model.scope('_page.clippings'));
this.model.start('count', 'clippings', countClippings);
function countClippings(clippings) {
return (clippings || []).length;
}
}
Associate.prototype.prevOffset = function (offset) {
offset--;
if (-1 < offset) return offset+'';
}
Associate.prototype.nextOffset = function (offset) {
offset++;
if (offset < this.model.get('count')) return offset+'';
}
| 26.92 | 67 | 0.699851 |
8b2af94748b8a4f563123ff73370a66090de95e7 | 4,251 | js | JavaScript | test/oracle/apatite-oracle-test-case.js | apatitejs/apatite | 6613eef86821843cd705647aa48178a2338e0e82 | [
"MIT"
] | 3 | 2016-07-02T08:03:32.000Z | 2019-03-31T20:35:05.000Z | test/oracle/apatite-oracle-test-case.js | apatitejs/apatite | 6613eef86821843cd705647aa48178a2338e0e82 | [
"MIT"
] | 42 | 2016-08-24T06:33:29.000Z | 2021-09-02T12:34:19.000Z | test/oracle/apatite-oracle-test-case.js | apatitejs/apatite | 6613eef86821843cd705647aa48178a2338e0e82 | [
"MIT"
] | 2 | 2017-04-19T06:34:46.000Z | 2017-04-20T10:08:50.000Z | var ApatiteDialectTestCaseAbstract = require('../apatite-dialect-test-case-abstract.js')
var ApatiteOracleTestUtil = require('./apatite-oracle-test-util')
var util = new ApatiteOracleTestUtil()
var ApatiteOracleDialect = require('../../lib/database/oracle/apatite-oracle-dialect.js')
class ApatiteOracleTestCase extends ApatiteDialectTestCaseAbstract {
constructor() {
super(util)
}
testDMLExecution(onTestPerformed) {
var self = this
this.doDMLExecutionTests(() => {
self.doFailedSQLTests(() => {
self.doConnResultSetFailTests(() => {
self.apatiteSession.existsDBTable('DEPT', (existsErr, result) => {
self.assertNullOrUndefined(existsErr, null, 'Table Existence Check: No error should occur when checking for table existence.')
self.assertEqual(result.rows.length, 1, null, 'Table Existence Check: Since table DEPT exists, the result rows length should be 1.')
self.apatiteSession.existsDBTableColumn('DEPT', 'NAME', (colExistsErr, colResult) => {
self.assertNullOrUndefined(colExistsErr, null, 'Table Column Existence Check: No error should occur when checking for table column existence.')
self.assertEqual(colResult.rows.length, 1, null, 'Table Column Existence Check: Since column NAME exists in table DEPT, the result rows length should be 1.')
onTestPerformed()
})
})
})
})
})
}
doConnResultSetFailTests(onTestPerformed) {
if (!this.existsDialectModule())
return onTestPerformed()
var self = this
var session = this.apatiteSession
var resultSet = new ApatiteOracleDialect().getApatiteResultSet({resultSet: {
getRows: function(recSetSize, onFetched) {
onFetched(new Error('Failed to get rows.'))
},
close: function(onClosed) {
onClosed(null)
}
}})
var sqlOptions = { isApatiteDirectSql: true, resultSet: true }
var onExecuted = function(err, result) {
self.assertEqual(err.message, 'Failed to get rows.')
session.connection.testResultSet = null
self.doResultSetTests(onTestPerformed)
}
session.connection.testResultSet = resultSet
session.connection.executeSQLString('select * from DEPT', [], onExecuted, sqlOptions)
}
doResultSetTests(onTestPerformed) {
var self = this
var resultSet = new ApatiteOracleDialect().getApatiteResultSet({rows: []});
resultSet.fetchRecords(function(err, rows) {
self.assertNullOrUndefined(err)
self.assertEqual(rows.length, 0);
resultSet.closeResultSet(function(closeErr) {
self.assertNullOrUndefined(closeErr)
self.doResultSetFailTests(onTestPerformed)
})
})
}
doResultSetFailTests(onTestPerformed) {
var self = this
var resultSet = new ApatiteOracleDialect().getApatiteResultSet({resultSet: {
getRows: function(recSetSize, onFetched) {
onFetched(new Error('Failed to get rows.'))
},
close: function(onClosed) {
onClosed(null)
}
}})
resultSet.fetchAllRows(function(err, rows) {
self.assertEqual(err.message, 'Failed to get rows.')
self.doResultSetCloseFailTests(onTestPerformed)
})
}
doResultSetCloseFailTests(onTestPerformed) {
var self = this
var resultSet = new ApatiteOracleDialect().getApatiteResultSet({resultSet: {
getRows: function(recSetSize, onFetched) {
onFetched(null, [])
},
close: function(onClosed) {
onClosed(new Error('Failed to close result set.'))
}
}})
resultSet.fetchAllRows(function(err, rows) {
self.assertEqual(err.message, 'Failed to close result set.')
onTestPerformed()
})
}
}
module.exports = ApatiteOracleTestCase | 42.939394 | 185 | 0.602446 |
8b2b2b36bdb9b24cf9c47af46d20155760c06c20 | 1,281 | js | JavaScript | service.controller.hue/controller/DeviceController.js | Thajudheen/home-automation | d61b85026ebecf5f57dbabe554816de242c47ba0 | [
"MIT"
] | null | null | null | service.controller.hue/controller/DeviceController.js | Thajudheen/home-automation | d61b85026ebecf5f57dbabe554816de242c47ba0 | [
"MIT"
] | 3 | 2020-07-16T12:11:02.000Z | 2021-05-07T21:12:41.000Z | service.controller.hue/controller/DeviceController.js | Thajudheen/home-automation | d61b85026ebecf5f57dbabe554816de242c47ba0 | [
"MIT"
] | null | null | null | class DeviceController {
constructor(express, lightService) {
this.lightService = lightService;
// Middleware
express.use("/device/:deviceId", this.loadDevice.bind(this));
// Routes
express.get("/device/:deviceId", this.readDevice.bind(this));
express.patch("/device/:deviceId", this.updateDevice.bind(this));
}
/** Middleware to load the device and update its state */
loadDevice(req, res, next) {
req.device = this.lightService.findById(req.params.deviceId);
if (!req.device) {
res.status(404);
res.json({ message: "Device not found" });
return;
}
next();
}
/** Retrieve a device's current state */
readDevice(req, res) {
res.json({ data: req.device });
}
/** Update a device. Only properties that are set will be updated. */
async updateDevice(req, res, next) {
let err = req.device.validate(req.body);
if (err !== undefined) {
res.status(422);
res.json({ message: `Invalid state: ${err}` });
return;
}
const state = req.device.transform(req.body);
try {
await this.lightService.applyState(req.device, state);
res.json({ data: req.device });
} catch (err) {
next(err);
}
}
}
exports = module.exports = DeviceController;
| 24.634615 | 71 | 0.62139 |
8b2cbcd29cd0d1b15831d1257c7a6416e742f40c | 102 | js | JavaScript | components/Layout/index.js | whydnxx/whydn.dev | 5e5d8545a36569185c4c45bb20d22d39cc683349 | [
"MIT"
] | 2 | 2021-02-12T15:30:14.000Z | 2021-02-20T15:32:25.000Z | components/Layout/index.js | whydnxx/whydn.dev | 5e5d8545a36569185c4c45bb20d22d39cc683349 | [
"MIT"
] | 14 | 2021-02-08T18:19:07.000Z | 2021-02-25T17:49:23.000Z | components/Layout/index.js | whydnxx/whydn.dev | 5e5d8545a36569185c4c45bb20d22d39cc683349 | [
"MIT"
] | null | null | null | export * from "./Layout.Landing";
export * from "./Layout.Blog";
export * from "./Layout.BlogDetail";
| 25.5 | 36 | 0.676471 |
8b2dc2ed686e79f4ef9dae991a500e38156b8dec | 828 | js | JavaScript | src/layouts/CoreLayout/CoreLayout.js | oneUSeP/freqs | 3fdf75a3b603061bc29a53e165470e58e703f289 | [
"MIT"
] | null | null | null | src/layouts/CoreLayout/CoreLayout.js | oneUSeP/freqs | 3fdf75a3b603061bc29a53e165470e58e703f289 | [
"MIT"
] | null | null | null | src/layouts/CoreLayout/CoreLayout.js | oneUSeP/freqs | 3fdf75a3b603061bc29a53e165470e58e703f289 | [
"MIT"
] | null | null | null | import React from 'react'
import Header from '../../components/Header'
import classes from './CoreLayout.scss'
import '../../styles/core.scss'
import Alert from 'react-s-alert'
import 'react-s-alert/dist/s-alert-default.css'
import 'react-s-alert/dist/s-alert-css-effects/scale.css'
import 'react-select/dist/react-select.css'
import LoadingBar from 'react-redux-loading-bar'
export const CoreLayout = ({ children }) => (
<div className='container text-center'>
{/* <Header /> */}
<LoadingBar style={{position: 'fixed', top: 0, left: 0, backgroundColor: '#009dc7', zIndex: 9999, height: 5}} />
<div className={classes.mainContainer}>
{children}
<Alert stack={{limit: 3}} />
</div>
</div>
)
CoreLayout.propTypes = {
children: React.PropTypes.element.isRequired
}
export default CoreLayout
| 27.6 | 116 | 0.688406 |
8b2ed933509015dddcbb60386db8c62b05224dc5 | 271 | js | JavaScript | src/customTheme.js | ryangillman/baseball-superstars-deckbuilder | f2aa480fc18c3175e2b113cf81e1f4db409c2a26 | [
"MIT"
] | null | null | null | src/customTheme.js | ryangillman/baseball-superstars-deckbuilder | f2aa480fc18c3175e2b113cf81e1f4db409c2a26 | [
"MIT"
] | 6 | 2020-09-12T11:53:28.000Z | 2021-12-07T10:21:08.000Z | src/customTheme.js | ryangillman/baseball-superstars-deckbuilder | f2aa480fc18c3175e2b113cf81e1f4db409c2a26 | [
"MIT"
] | 5 | 2020-09-15T05:57:16.000Z | 2022-03-31T19:15:43.000Z | import { theme } from '@chakra-ui/core';
const customTheme = {
...theme,
colors: {
...theme.colors,
rarity: {
UR: '#FFAB17',
SSR: '#ff4242',
SR: '#4B1C86',
R: '#1927D0',
N: '#65CF24',
},
},
};
export default customTheme;
| 15.055556 | 40 | 0.494465 |
8b2f7f37fdf844abbcf38e54d1dee22f911f9faa | 330 | js | JavaScript | lib/getPriceWithTax.js | UK090483/meetFrida | 65f0977f8de7b7cf705bd47208424b510f8e8660 | [
"RSA-MD"
] | null | null | null | lib/getPriceWithTax.js | UK090483/meetFrida | 65f0977f8de7b7cf705bd47208424b510f8e8660 | [
"RSA-MD"
] | 1 | 2020-07-21T12:48:04.000Z | 2021-04-05T16:30:45.000Z | lib/getPriceWithTax.js | UK090483/meetFrida | 65f0977f8de7b7cf705bd47208424b510f8e8660 | [
"RSA-MD"
] | null | null | null | function getPriceWithTax(price) {
if (!price) {
return ""
}
// const withTax = (price / 84) * 100
const withTax = price * 1.16
const roundTen = Math.ceil(withTax / 10) * 10
// console.log(`Preis: ${price}/ mitMwSt: ${withTax}/ gerundet: ${roundTen}`)
return roundTen
}
exports.getPriceWithTax = getPriceWithTax
| 25.384615 | 79 | 0.654545 |
8b2fb08a83e5cb3b4abcc74555035a3ca1a7f942 | 3,039 | js | JavaScript | components/Flex/index.js | linyingzhen/btnew | 213c16401850c88a0b7f49b82b0f66c7c9863144 | [
"Apache-2.0"
] | null | null | null | components/Flex/index.js | linyingzhen/btnew | 213c16401850c88a0b7f49b82b0f66c7c9863144 | [
"Apache-2.0"
] | null | null | null | components/Flex/index.js | linyingzhen/btnew | 213c16401850c88a0b7f49b82b0f66c7c9863144 | [
"Apache-2.0"
] | null | null | null | /**
* const prefixCls = 'style-903220';
* const images = '/static/images/components/Flex';
* @Author: czy0729
* @Date: 2018-07-11 11:40:38
* @Last Modified by: czy0729
* @Last Modified time: 2018-10-29 00:09:31
* @Path m.benting.com.cn /components/Flex/index.js
*/
import React from 'react';
import classNames from 'classnames';
import Link from '../Link';
const prefixCls = 'am-flexbox';
const Flex = props => {
const {
direction,
wrap,
justify,
align = 'center',
alignContent,
href,
as,
login,
prefetch,
className,
children,
style,
...restProps
} = props;
const wrapCls = classNames(prefixCls, className, {
[`${prefixCls}-dir-row`]: direction === 'row',
[`${prefixCls}-dir-row-reverse`]: direction === 'row-reverse',
[`${prefixCls}-dir-column`]: direction === 'column',
[`${prefixCls}-dir-column-reverse`]: direction === 'column-reverse',
[`${prefixCls}-nowrap`]: wrap === 'nowrap',
[`${prefixCls}-wrap`]: wrap === 'wrap',
[`${prefixCls}-wrap-reverse`]: wrap === 'wrap-reverse',
[`${prefixCls}-justify-start`]: justify === 'start',
[`${prefixCls}-justify-end`]: justify === 'end',
[`${prefixCls}-justify-center`]: justify === 'center',
[`${prefixCls}-justify-between`]: justify === 'between',
[`${prefixCls}-justify-around`]: justify === 'around',
[`${prefixCls}-align-start`]: align === 'start',
[`${prefixCls}-align-center`]: align === 'center',
[`${prefixCls}-align-end`]: align === 'end',
[`${prefixCls}-align-baseline`]: align === 'baseline',
[`${prefixCls}-align-stretch`]: align === 'stretch',
[`${prefixCls}-align-content-start`]: alignContent === 'start',
[`${prefixCls}-align-content-end`]: alignContent === 'end',
[`${prefixCls}-align-content-center`]: alignContent === 'center',
[`${prefixCls}-align-content-between`]: alignContent === 'between',
[`${prefixCls}-align-content-around`]: alignContent === 'around',
[`${prefixCls}-align-content-stretch`]: alignContent === 'stretch'
});
if (href) {
return (
<Link
className={wrapCls}
href={href}
as={as}
login={login}
prefetch={prefetch}
flex
style={style}
{...restProps}
>
{children}
</Link>
);
}
return (
<div className={wrapCls} style={style} {...restProps}>
{children}
</div>
);
};
Flex.Item = props => {
const {
href,
as,
login,
prefetch,
children,
className,
style,
...restProps
} = props;
const wrapCls = classNames(`${prefixCls}-item`, className);
if (href) {
return (
<Link
className={wrapCls}
href={href}
as={as}
login={login}
prefetch={prefetch}
style={style}
block
{...restProps}
>
{children}
</Link>
);
}
return (
<div className={wrapCls} style={style} {...restProps}>
{children}
</div>
);
};
export default Flex;
| 24.312 | 72 | 0.560053 |
8b2fff390a441e419fe8a53839f79f9acdf0cc83 | 262 | js | JavaScript | config/helpers/root.js | pramod2work/simple-calculator | e0f0f5ef1205790ddd88cb8c02b681767bb795bf | [
"MIT"
] | null | null | null | config/helpers/root.js | pramod2work/simple-calculator | e0f0f5ef1205790ddd88cb8c02b681767bb795bf | [
"MIT"
] | 4 | 2021-08-16T07:15:10.000Z | 2022-02-27T12:24:36.000Z | config/helpers/root.js | kspramod/pacman | 77a60cd02156b790650dd138ad87c22de23bbf3c | [
"MIT"
] | 1 | 2019-06-13T00:04:43.000Z | 2019-06-13T00:04:43.000Z | const path = require('path')
/**
* @param {string} pathString input path string
* @returns {string} PathString path string relative to the root folder resolved with provided parameters
*/
exports.root = path.join.bind(path, path.resolve(__dirname, '../..'))
| 32.75 | 105 | 0.721374 |
8b310914f689dd30309db1f167e86ee2e848ee12 | 2,110 | js | JavaScript | client/src/App.js | hannahtesfay/conundrum | e5eecda9d37e575aeda6200025732cb66c1f39e1 | [
"MIT"
] | null | null | null | client/src/App.js | hannahtesfay/conundrum | e5eecda9d37e575aeda6200025732cb66c1f39e1 | [
"MIT"
] | null | null | null | client/src/App.js | hannahtesfay/conundrum | e5eecda9d37e575aeda6200025732cb66c1f39e1 | [
"MIT"
] | null | null | null | import React from 'react';
import { Switch, withRouter, Route } from 'react-router-dom';
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import { Container } from 'semantic-ui-react'
import styled from 'styled-components'
import { useDarkMode } from './components/dark-mode/useDarkMode'
import { ThemeProvider } from "styled-components";
import { GlobalStyles } from "./components/dark-mode/globalStyles";
import { lightTheme, darkTheme } from "./components/dark-mode/Themes"
import Home from './pages/Home'
import Login from './pages/Login'
import Register from './pages/Register'
import MenuBar from './components/MenuBar'
import SinglePost from './pages/SinglePost'
import { AuthProvider } from './context/auth'
import AuthRoute from './utilities/AuthRoute'
import 'semantic-ui-css/semantic.min.css';
import './App.css';
function App({ location }) {
const [theme] = useDarkMode();
const themeMode = theme === 'light' ? lightTheme : darkTheme;
return (
<ThemeProvider theme={themeMode}>
<GlobalStyles/>
<AuthProvider>
<Wrapper>
<Container style={{margin: 40}}>
<MenuBar/>
<TransitionGroup>
<CSSTransition key={location.key} timeout={{ enter: 300, exit: 300 }} classNames={'fade'}>
<Switch location={location}>
<Route exact path="/" component={Home}/>
<AuthRoute exact path="/login" component={Login}/>
<AuthRoute exact path="/register" component={Register}/>
<Route exact path="/posts/:postId" component={SinglePost}/>
</Switch>
</CSSTransition>
</TransitionGroup>
</Container>
</Wrapper>
</AuthProvider>
</ThemeProvider>
);
}
const Wrapper = styled.div`
.fade-enter {
opacity: 0.01;
}
.fade-enter.fade-enter-active {
opacity: 1;
transition: opacity 300ms ease-in;
}
.fade-exit {
opacity: 1;
}
.fade-exit.fade-exit-active {
opacity: 0.01;
transition: opacity 300ms ease-in;
}
`;
export default withRouter(App);
| 28.90411 | 104 | 0.63981 |
8b325c794c0170e1fd75d1277373099b1d28d7e4 | 280 | js | JavaScript | _/Chapter05/05-09-using-promise-for-simple-interfaces/worker.js | paullewallencom/ecmascript-978-1-7886-2817-4 | cce0a7ff305c8d206bef6315d8352b7fceabe2be | [
"Apache-2.0"
] | 21 | 2018-03-30T19:32:23.000Z | 2021-11-08T13:12:14.000Z | _/Chapter05/05-09-using-promise-for-simple-interfaces/worker.js | paullewallencom/ecmascript-978-1-7886-2817-4 | cce0a7ff305c8d206bef6315d8352b7fceabe2be | [
"Apache-2.0"
] | null | null | null | _/Chapter05/05-09-using-promise-for-simple-interfaces/worker.js | paullewallencom/ecmascript-978-1-7886-2817-4 | cce0a7ff305c8d206bef6315d8352b7fceabe2be | [
"Apache-2.0"
] | 6 | 2018-07-16T13:06:55.000Z | 2020-10-01T21:56:34.000Z | const global = this;
global.onmessage = (message) => {
const { data } = message;
switch (data.type) {
case 'calculate-sum':
const sum = data.array.reduce((acc, number) => acc + number, 0);
global.postMessage({ type: 'sum', result: sum });
break;
}
}
| 21.538462 | 70 | 0.582143 |
8b325d23f5a6da5bc0afea9a92b3e36c80141ba1 | 600 | js | JavaScript | server/models/Parent.js | Balanced02/schoolMS | 82871b97378d0d73c8fba0102d9cea206295435a | [
"MIT"
] | 1 | 2021-12-30T14:23:07.000Z | 2021-12-30T14:23:07.000Z | server/models/Parent.js | Balanced02/schoolMS | 82871b97378d0d73c8fba0102d9cea206295435a | [
"MIT"
] | 2 | 2022-01-22T09:13:48.000Z | 2022-02-10T19:22:12.000Z | server/models/Parent.js | Balanced02/schoolMS | 82871b97378d0d73c8fba0102d9cea206295435a | [
"MIT"
] | 3 | 2018-08-23T19:34:08.000Z | 2019-10-24T12:44:59.000Z | import mongoose from 'mongoose';
import uuid from 'uuid/v4';
let ParentSchema = new mongoose.Schema({
sid: {
type: String,
unique: true,
required: true,
default: uuid,
},
schoolId: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
phoneNumber: {
type: String,
required: true,
},
occupation: {
type: String,
required: true,
},
officeAddress: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
});
export default mongoose.model('Parent', ParentSchema);
| 15.384615 | 54 | 0.588333 |
8b32d42b3a2b86566be9e82a0b190cc38d890548 | 967 | js | JavaScript | src/components/Dashboard/Health/HealthItem.js | knowncitizen/web-ui-components | 9b70da17541de6e21d007a705a03dbf267b7a675 | [
"Apache-2.0"
] | null | null | null | src/components/Dashboard/Health/HealthItem.js | knowncitizen/web-ui-components | 9b70da17541de6e21d007a705a03dbf267b7a675 | [
"Apache-2.0"
] | null | null | null | src/components/Dashboard/Health/HealthItem.js | knowncitizen/web-ui-components | 9b70da17541de6e21d007a705a03dbf267b7a675 | [
"Apache-2.0"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
import { Icon } from 'patternfly-react';
import { InlineLoading } from '../../Loading';
export const HealthItem = ({ icon, classname, message, isLoading, LoadingComponent }) => {
const description = isLoading ? <LoadingComponent /> : message;
return (
<div className="kubevirt-dashboard-health__icon">
<Icon
type="fa"
size="2x"
name={icon}
className={`kubevirt-health__icon kubevirt-dashboard-health__icon--${classname}`}
/>
<span className="kubevirt-health__text">{description}</span>
</div>
);
};
HealthItem.defaultProps = {
LoadingComponent: InlineLoading,
isLoading: false,
};
HealthItem.propTypes = {
message: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
classname: PropTypes.string.isRequired,
LoadingComponent: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
isLoading: PropTypes.bool,
};
| 28.441176 | 90 | 0.693899 |
8b346a5c46bc345f16b2b6ff5266b660005d4829 | 7,794 | js | JavaScript | _src/chapter_6/novius-os/novius-os/static/admin/vendor/wijmo/js/Base/jquery.wijmo.widget.min.js | paullewallencom/fuelphp-978-1-7839-8540-1 | 9ea1193049d42bbeff3be45a5d15819bc8276474 | [
"Apache-2.0"
] | null | null | null | _src/chapter_6/novius-os/novius-os/static/admin/vendor/wijmo/js/Base/jquery.wijmo.widget.min.js | paullewallencom/fuelphp-978-1-7839-8540-1 | 9ea1193049d42bbeff3be45a5d15819bc8276474 | [
"Apache-2.0"
] | null | null | null | _src/chapter_6/novius-os/novius-os/static/admin/vendor/wijmo/js/Base/jquery.wijmo.widget.min.js | paullewallencom/fuelphp-978-1-7839-8540-1 | 9ea1193049d42bbeff3be45a5d15819bc8276474 | [
"Apache-2.0"
] | null | null | null | var __extends=this.__extends||function(e,t){function n(){this.constructor=e}n.prototype=t.prototype,e.prototype=new n},wijmo;(function(e){var t=jQuery,n=function(){function e(){}return e.autoMobilize=!0,e.wijCSS={widget:"ui-widget",overlay:"ui-widget-overlay",content:"ui-widget-content",header:"ui-widget-header",stateDisabled:"ui-state-disabled",stateFocus:"ui-state-focus",stateActive:"ui-state-active",stateDefault:"ui-state-default",stateHighlight:"ui-state-highlight",stateHover:"ui-state-hover",stateChecked:"ui-state-checked",stateError:"ui-state-error",getState:function(e){return e=e.charAt(0).toUpperCase()+e.substr(1),t.wijmo.wijCSS["state"+e]},icon:"ui-icon",iconCheck:"ui-icon-check",iconRadioOn:"ui-icon-radio-on",iconRadioOff:"ui-icon-radio-off",iconClose:"ui-icon-close",iconArrow4Diag:"ui-icon-arrow-4-diag",iconNewWin:"ui-icon-newwin",iconVGripSolid:"ui-icon-grip-solid-vertical",iconHGripSolid:"ui-icon-grip-solid-horizontal",iconPlay:"ui-icon-play",iconPause:"ui-icon-pause",iconStop:"ui-icon-stop",iconArrowUp:"ui-icon-triangle-1-n",iconArrowRight:"ui-icon-triangle-1-e",iconArrowDown:"ui-icon-triangle-1-s",iconArrowLeft:"ui-icon-triangle-1-w",iconArrowRightDown:"ui-icon-triangle-1-se",iconArrowThickDown:"ui-icon-arrowthick-1-s glyphicon glyphicon-arrow-down",iconArrowThickUp:"ui-icon-arrowthick-1-n glyphicon glyphicon-arrow-up",iconCaratUp:"ui-icon-carat-1-n",iconCaratRight:"ui-icon-carat-1-e",iconCaratDown:"ui-icon-carat-1-s",iconCaratLeft:"ui-icon-carat-1-w",iconClock:"ui-icon-clock glyphicon glyphicon-time",iconPencil:"ui-icon-pencil glyphicon glyphicon-pencil",iconSeekFirst:"ui-icon-seek-first",iconSeekEnd:"ui-icon-seek-end",iconSeekNext:"ui-icon-seek-next",iconSeekPrev:"ui-icon-seek-prev",iconPrint:"ui-icon-print",iconDisk:"ui-icon-disk",iconSeekStart:"ui-icon-seek-start",iconFullScreen:"ui-icon-newwin",iconContinousView:"ui-icon-carat-2-n-s",iconZoomIn:"ui-icon-zoomin",iconZoomOut:"ui-icon-zoomout",iconBookmark:"ui-icon-bookmark",iconSearch:"ui-icon-search",iconImage:"ui-icon-image",inputSpinnerLeft:"ui-input-spinner-left",inputSpinnerRight:"ui-input-spinner-right",inputTriggerLeft:"ui-input-trigger-left",inputTriggerRight:"ui-input-trigger-right",inputSpinnerTriggerLeft:"ui-input-spinner-trigger-left",inputSpinnerTriggerRight:"ui-input-spinner-trigger-right",cornerAll:"ui-corner-all",cornerLeft:"ui-corner-left",cornerRight:"ui-corner-right",cornerBottom:"ui-corner-bottom",cornerBL:"ui-corner-bl",cornerBR:"ui-corner-br",cornerTop:"ui-corner-top",cornerTL:"ui-corner-tl",cornerTR:"ui-corner-tr",helperClearFix:"ui-helper-clearfix",helperReset:"ui-helper-reset",helperHidden:"ui-helper-hidden",priorityPrimary:"ui-priority-primary",prioritySecondary:"ui-priority-secondary",button:"ui-button",buttonText:"ui-button-text",buttonTextOnly:"ui-button-text-only",tabs:"ui-tabs",tabsTop:"ui-tabs-top",tabsBottom:"ui-tabs-bottom",tabsLeft:"ui-tabs-left",tabsRight:"ui-tabs-right",tabsLoading:"ui-tabs-loading",tabsActive:"ui-tabs-active",tabsPanel:"ui-tabs-panel",tabsNav:"ui-tabs-nav",tabsHide:"ui-tabs-hide",tabsCollapsible:"ui-tabs-collapsible",activeMenuitem:"ui-active-menuitem"},e.wijMobileCSS={content:"ui-content",header:"ui-header",overlay:"ui-overlay",stateDisabled:"ui-state-disabled",stateFocus:"ui-focus",stateActive:"ui-btn-active",stateDefault:"ui-btn ui-btn-a",icon:"ui-icon ui-btn-icon-notext",iconArrowUp:"ui-icon-carat-u",iconArrowRight:"ui-icon-carat-r",iconArrowDown:"ui-icon-carat-d",iconArrowLeft:"ui-icon-carat-l",iconArrowRightDown:"ui-icon-carat-d",iconSeekFirst:"ui-icon-carat-l",iconSeekEnd:"ui-icon-carat-r",iconSeekNext:"ui-icon-carat-r",iconSeekPrev:"ui-icon-carat-l",iconClose:"ui-icon-delete",iconStop:"ui-icon-grid",iconCheck:"ui-icon-check"},e.wijMobileThemePrefix=["ui-bar","ui-body","ui-overlay","ui-btn"],e.registerWidget=function(n,r,i,s){var o="wijmo."+n,u;typeof i=="function"&&(u=i,i=null);if(i===null||i===undefined)i=t.extend(!0,{},r),r=t.wijmo.widget;i.options=i.options||{},i.options.initSelector=i.options.initSelector||":jqmData(role='"+n+"')",i.initSelector=i.initSelector==null?i.options.initSelector:i.initSelector+i.options.initSelector,t.mobile&&i.options&&i.options.wijMobileCSS&&(i.options.wijCSS=i.options.wijCSS||{},t.extend(i.options.wijCSS,i.options.wijMobileCSS)),t.widget(o,r,i),u&&u.call()},e.addThemeToMobileCSS=function(r,i){t.each(i,function(n,s){typeof s=="string"?t.each(e.wijMobileThemePrefix,function(e,t){var o=new RegExp("\\b"+t);o.test(s)&&(i[n]=s+" "+t+"-"+r)}):e.addThemeToMobileCSS(r,s)})},e}();t.wijmo=n;var r=function(){function e(){}return e.prototype.destroy=function(){},e.prototype._setOption=function(e,t){},e.prototype._create=function(){},e.prototype._init=function(){},e.prototype.widget=function(){return this.element},e}();e.JQueryUIWidget=r,r.prototype.options={wijCSS:t.wijmo.wijCSS},r.prototype.destroy=function(){t.Widget.prototype.destroy.apply(this,arguments)},r.prototype._setOption=function(e,n){t.Widget.prototype._setOption.apply(this,arguments)},r.prototype._create=function(){t.Widget.prototype._create.apply(this,arguments)},r.prototype._init=function(){t.Widget.prototype._init.apply(this,arguments)};var i=function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t}(r);e.JQueryMobileWidget=i,t(window.document).trigger("wijmoinit");var s=function(e){function n(){e.apply(this,arguments),this._widgetCreated=!1}return __extends(n,e),n.prototype._baseWidget=function(){return this._isMobile?t.mobile.widget:t.Widget},n.prototype._createWidget=function(e,n){this._widgetCreated=!0,this._syncEventPrefix&&(this.widgetEventPrefix=this.widgetName),window.wijmoApplyWijTouchUtilEvents&&(t=window.wijmoApplyWijTouchUtilEvents(t)),this._baseWidget().prototype._createWidget.apply(this,arguments)},n.prototype._create=function(){this._baseWidget().prototype._create.apply(this,arguments)},n.prototype._init=function(){this._baseWidget().prototype._init.apply(this,arguments)},n.prototype.destroy=function(){this._baseWidget().prototype.destroy.apply(this,arguments)},n.prototype._setOption=function(e,t){this._baseWidget().prototype._setOption.apply(this,arguments),e==="disabled"&&t&&this._isMobile&&this.element.removeClass("ui-state-disabled").addClass(this.options.wijCSS.stateDisabled)},n}(i);e.wijmoWidget=s,s.prototype._syncEventPrefix=!0,s.prototype._isMobile=!1,t.mobile!=null&&t.wijmo.autoMobilize===!0?(t.extend(!0,s.prototype.options.wijCSS,t.wijmo.wijMobileCSS),s.prototype._isMobile=!0,s.prototype.options=t.extend(!0,{},s.prototype.options,s.prototype._baseWidget().prototype.options),s.prototype._getCreateOptions=function(){var e=this.element,n,r=r=function(e){if(typeof e=="undefined")return{};if(e===null)return{};var n=/(?:(?:\{[\n\r\t\s]*(.+?)\s*\:[\n\r\t\s]*)|(?:,[\n\r\t\s]*(.+?)\s*\:[\n\r\t\s]*))('(.*?[^\\])')?/gi,r=/\[.*?(?=[\]\[])|[\]\[].*?(?=[\]])/gi,i=e.replace(n,function(e,t,n,r){var i,s=/[\n\r\t\s]*['"]?([^\{,\s]+?)['"]?\s*:[\n\r\t\s]*/i,o=/\:[\n\r\t\s]*(?:'(.*)')?/i;return i=e.replace(s,'"$1":'),r?i.replace(o,':"$1"'):i}).replace(r,function(e){var t=/'(.*?[^\\])'/g;return e.replace(t,'"$1"')});return t.parseJSON(i)},i=r(e.attr("data-"+t.mobile.nsNormalize("options"))),s;return n=t.mobile.widget.prototype._getCreateOptions.apply(this,arguments),s=t.extend(!0,{},this.options.wijCSS),this.theme=this.options.theme!==undefined?this.options.theme:this.element.jqmData("theme"),this.theme&&t.wijmo.addThemeToMobileCSS(this.theme,s),t.extend(n,{wijCSS:s},i)},t.widget("wijmo.widget",t.mobile.widget,s.prototype),t(document).on("pageshow",function(e,n){if(e.target==null)return;var r=t(e.target);r.wijTriggerVisibility&&r.wijTriggerVisibility()})):(s.prototype.options=t.extend(!0,{},s.prototype.options,s.prototype._baseWidget().prototype.options),t.widget("wijmo.widget",s.prototype))})(wijmo||(wijmo={})); | 7,794 | 7,794 | 0.756864 |
8b34e0e1f3e33f40b300852022d9ee58e25f7a55 | 5,408 | js | JavaScript | assets/js/Components/RepLogApp.js | vmilkovic/lift-stuff | 7fd9a1b79ee55b682df88f781c5c5f7c461e6866 | [
"MIT"
] | null | null | null | assets/js/Components/RepLogApp.js | vmilkovic/lift-stuff | 7fd9a1b79ee55b682df88f781c5c5f7c461e6866 | [
"MIT"
] | null | null | null | assets/js/Components/RepLogApp.js | vmilkovic/lift-stuff | 7fd9a1b79ee55b682df88f781c5c5f7c461e6866 | [
"MIT"
] | null | null | null | 'use strict';
import Helper from './RepLogAppHelper';
import $ from 'jquery';
import Swal from 'sweetalert2';
import 'sweetalert2/dist/sweetalert2.css';
import Routing from './Routing';
import random from 'lodash/random';
let HelperInstance = new WeakMap();
class RepLogApp {
constructor($wrapper, initialRepLogs){
this.$wrapper = $wrapper;
this.repLogs = [];
HelperInstance.set(this, new Helper(this.repLogs));
for(let repLog of initialRepLogs){
this._addRow(repLog);
}
this._clearForm();
this.$wrapper.on(
'click',
'.js-delete-rep-log',
this.handleRepLogDelete.bind(this)
);
this.$wrapper.on(
'click',
'tbody tr',
this.handleRowClick.bind(this)
);
this.$wrapper.on(
'submit',
RepLogApp._selectors.newRepForm,
this.handleNewFormSubmit.bind(this)
);
};
static get _selectors() {
return {
newRepForm: '.js-new-rep-log-form'
}
}
updateTotalWeightLifted(){
this.$wrapper.find('.js-total-weight').html(HelperInstance.get(this).getTotalWeightString());
}
handleRepLogDelete(e){
e.preventDefault();
const $link = $(e.currentTarget);
Swal.fire({
title: 'Delete this log???',
html: 'What? Did you not actually lift this?',
showCancelButton: true
}).then(
(result) => {
if(result.isConfirmed){
this._deleteRepLog($link);
} else {
console.log('canceled');
}
}
);
}
_deleteRepLog($link){
$link.addClass('text-danger');
$link.find('.fa')
.removeClass('fa-trash')
.addClass('fa-spinner')
.addClass('fa-spin');
const deleteUrl = $link.data('url');
const $row = $link.closest('tr');
$.ajax({
url: deleteUrl,
method: 'DELETE',
}).then(() => {
$row.fadeOut('normal', () => {
this.repLogs.splice($row.data('key'), 1);
$row.remove();
this.updateTotalWeightLifted();
});
});
}
handleRowClick(){
console.log('row clicked');
}
handleNewFormSubmit(e){
e.preventDefault();
const $form = $(e.currentTarget);
const formData = {};
for(let fieldData of $form.serializeArray()){
formData[fieldData.name] = fieldData.value;
}
this._saveRepLog(formData)
.then((data) => {
this._clearForm();
this._addRow(data);
}).catch((errorData) => {
this._mapErrorsToForm(errorData);
});
}
_saveRepLog(data) {
return new Promise((resolve, reject) => {
const url = Routing.generate('rep_log_new');
$.ajax({
url,
method: 'POST',
data: JSON.stringify(data),
}).then((data, textStatus, jqXHR) => {
$.ajax({
url: jqXHR.getResponseHeader('Location')
}).then((data) => {
resolve(data);
});
}).catch((jqXHR) => {
const errorData = JSON.parse(jqXHR.responseText).errors;
reject(errorData);
});
});
}
_mapErrorsToForm(errorData) {
const $form = this.$wrapper.find(RepLogApp._selectors.newRepForm);
this._removeFormErrors();
for(let element of $form.find(':input')){
const fieldName = $(element).attr('name');
const $wrapper = $(element).closest('.form-group');
if(!errorData[fieldName]){
return;
}
const $error = $('<span class="js-field-error help-block"></span>');
$error.html(errorData[fieldName]);
$wrapper.append($error);
$wrapper.addClass('has-error');
};
}
_removeFormErrors(){
const $form = this.$wrapper.find(RepLogApp._selectors.newRepForm);
$form.find('.js-field-error').remove();
$form.find('.form-group').removeClass('has-error');
}
_clearForm(){
this._removeFormErrors();
const $form = this.$wrapper.find(RepLogApp._selectors.newRepForm);
$form[0].reset();
$form.find('[name="reps"]').val(random(1, 10))
}
_addRow(repLog){
this.repLogs.push(repLog);
const html = rowTemplate(repLog);
const $row = $($.parseHTML(html));
$row.data('key', this.repLogs.length - 1);
this.$wrapper.find('tbody').append($row);
this.updateTotalWeightLifted();
}
}
const rowTemplate = (repLog) => `
<tr data-weight="${repLog.totalWeightLifted}">
<td>${repLog.itemLabel}</td>
<td>${repLog.reps}</td>
<td>${repLog.totalWeightLifted}</td>
<td>
<a href="#"
class="js-delete-rep-log"
data-url="${repLog.links._self}"
>
<span class="fa fa-trash">
</span>
</a>
</td>
</tr>`;
export default RepLogApp;
| 26.772277 | 101 | 0.495377 |
8b3751d643f2695e11aee528ef9d842287e4eae4 | 3,744 | js | JavaScript | index.js | daskeyboard/daskeyboard-applet--dasping | ea59fa7f6dfab0c796250492ddb18e4946ab04b7 | [
"MIT"
] | 1 | 2020-01-03T19:36:47.000Z | 2020-01-03T19:36:47.000Z | index.js | daskeyboard/daskeyboard-applet--dasping | ea59fa7f6dfab0c796250492ddb18e4946ab04b7 | [
"MIT"
] | 2 | 2020-01-06T20:50:27.000Z | 2021-06-23T14:31:45.000Z | index.js | daskeyboard/daskeyboard-applet--dasping | ea59fa7f6dfab0c796250492ddb18e4946ab04b7 | [
"MIT"
] | 1 | 2020-01-06T15:42:52.000Z | 2020-01-06T15:42:52.000Z | const q = require("daskeyboard-applet");
const { execSync } = require("child_process");
const { logger } = q;
const pingCountArg = process.platform === "win32" ? "-n" : "-c";
const timeRe = / time=(\d+\.?\d*)\s?ms/gi;
function buildColorSteps({
colorGood,
colorBad,
midSteps,
pingThreshold,
stepGap
}) {
const totalSteps = midSteps + 2;
const colorGoodRGB = hexToRGB(colorGood);
const colorBadRGB = hexToRGB(colorBad);
const stepPercentagesReversed = [0].concat(
new Array(totalSteps - 1)
.fill(1 / (totalSteps - 1))
.map((n, i) => (i + 1) * n * 2)
);
const stepPercentages = stepPercentagesReversed.slice().reverse();
const colorSteps = new Array(totalSteps)
.fill(0)
.map((_, i) =>
rgbToHex(
new Array(3)
.fill(0)
.map((_, x) =>
mergeColorPiece(
colorGoodRGB[x],
colorBadRGB[x],
stepPercentages[i],
stepPercentagesReversed[i]
)
)
)
);
// Assign color step to a predicate
return colorSteps.map((hex, i) => {
let predicate = time => time <= pingThreshold + stepGap * i;
if (i + 1 === totalSteps) {
predicate = time => time > pingThreshold + stepGap * (i - 1);
}
return [hex, predicate];
});
}
function mergeColorPiece(color1, color2, percentage1, percentage2) {
return Math.round((color1 * percentage1 + color2 * percentage2) / 2);
}
function hexToRGB(color) {
return color
.substr(1)
.split("")
.reduce((acc, cur, i) => {
if (i % 2) {
acc[acc.length - 1] += cur;
} else {
acc.push(cur);
}
return acc;
}, [])
.map(n => parseInt(n, 16));
}
function rgbToHex(color) {
return (
"#" +
color
.map(n =>
Number(n)
.toString(16)
.padStart(2, "0")
)
.join("")
);
}
class DasPing extends q.DesktopApp {
constructor() {
super();
this.config = {
colorGood: "#00FF00",
colorBad: "#FF0000",
colorFail: "#FF00FF",
...this.config,
midSteps: parseInt(this.config.midSteps, 10) || 3,
pingThreshold: parseInt(this.config.pingThreshold, 10) || 300,
pollingInterval: parseInt(this.config.pollingInterval, 10) || 60000,
stepGap: parseInt(this.config.stepGap, 10) || 100
};
this.colorSteps = buildColorSteps(this.config);
this.pollingInterval = this.config.pollingInterval;
logger.info("DasPing applet initialized");
}
async run() {
const { address } = this.config;
try {
const output = execSync(`ping ${address} ${pingCountArg} 1`).toString();
var [, time] = timeRe.exec(output);
// Reset exec index for next call
timeRe.lastIndex = 0;
logger.info(output);
} catch (error) {
logger.error(`An error occurred while pinging ${address}: ${error}`);
}
return this.buildSignal(time);
}
buildSignal(time) {
let { address, colorFail: color } = this.config;
const addStr = `URL: ${address}`;
const dateStr = `Last Checked: ${new Date().toLocaleString()}`;
let message = `${addStr}; Time: No Response; Color: ${color}; ${dateStr}`;
if (time) {
// For five steps between Green and Red:
// <=300 <=400 <=500 <=600 >600
// [ '#00ff00', '#40bf00', '#808000', '#bf4000', '#ff0000' ]
[color] = this.colorSteps.find(([, predicate]) => predicate(time));
message = `${addStr}; Time: ${time}ms; Color: ${color}; ${dateStr}`;
}
logger.info(message);
return new q.Signal({
points: [[new q.Point(color)]],
name: "Das Ping",
message
});
}
}
module.exports = { DasPing };
new DasPing();
| 24.794702 | 78 | 0.563835 |
8b38beaac93e8bfd4dbe592ae8b1ed2a3f456c1a | 2,031 | js | JavaScript | tests/unit/views/AboutApp.test.js | TheJaredWilcurt/karngdarbo | a545db63dea7c16e1c2c67edd62c713fba151798 | [
"MIT"
] | 11 | 2018-10-02T21:10:20.000Z | 2021-10-05T07:21:44.000Z | tests/unit/views/AboutApp.test.js | TheJaredWilcurt/karngdarbo | a545db63dea7c16e1c2c67edd62c713fba151798 | [
"MIT"
] | 3 | 2019-07-20T13:26:13.000Z | 2021-11-21T16:53:34.000Z | tests/unit/views/AboutApp.test.js | TheJaredWilcurt/karngdarbo | a545db63dea7c16e1c2c67edd62c713fba151798 | [
"MIT"
] | 1 | 2020-05-22T02:24:34.000Z | 2020-05-22T02:24:34.000Z | import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex, { Store } from 'vuex';
import AboutApp from '@/views/AboutApp.vue';
import mutations from '@/store/mutations.js';
describe('AboutApp.vue', () => {
let store;
let localVue;
beforeEach(() => {
localVue = createLocalVue();
localVue.use(Vuex);
store = new Store({
state: {
appError: ''
},
getters: {},
mutations,
actions: {}
});
});
describe('Created', () => {
beforeEach(() => {
global.nw.require = jest.fn(function (moduleName) {
if (moduleName === 'child_process') {
return {
exec: function (command, callback) {
if (command === 'git --version') {
callback(null, 'git version 0.0.0.windows.0 ');
}
}
};
}
return require(moduleName);
});
});
test('Default snapshot', () => {
const wrapper = shallowMount(AboutApp);
expect(wrapper.html())
.toMatchSnapshot();
});
});
describe('External link', () => {
beforeEach(() => {
global.nw.require = require;
});
test('Click link', () => {
const wrapper = shallowMount(AboutApp);
wrapper.find({ ref: 'testExternalLink' }).trigger('click');
expect(nw.Shell.openExternal)
.toHaveBeenCalledWith('http://TheJaredWilcurt.com');
});
});
describe('Error handling', () => {
beforeEach(() => {
global.nw.require = jest.fn((moduleName) => {
if (moduleName === 'child_process') {
return {
exec: jest.fn((command, callback) => {
callback('There was an error.');
})
};
} else {
return;
}
});
});
test('git version', () => {
const wrapper = shallowMount(AboutApp, {
store,
localVue
});
expect(wrapper.vm.$store.state.appError)
.toEqual('There was an error.');
});
});
});
| 22.318681 | 65 | 0.504677 |
8b3c1538b4c546a14921b1b13a118b9b60690ba5 | 1,107 | js | JavaScript | src/js/app.js | cemulate/project-euler-208 | e8408edbc49451a50b6b17dfd081630d307f4fd4 | [
"MIT"
] | 2 | 2018-04-15T22:50:51.000Z | 2019-11-26T21:40:53.000Z | src/js/app.js | cemulate/project-euler-208 | e8408edbc49451a50b6b17dfd081630d307f4fd4 | [
"MIT"
] | null | null | null | src/js/app.js | cemulate/project-euler-208 | e8408edbc49451a50b6b17dfd081630d307f4fd4 | [
"MIT"
] | 2 | 2019-11-26T21:41:34.000Z | 2019-11-26T21:44:10.000Z | import {CoordinateSystem} from './coordinatesystem.js'
import {Robot} from './robot.js'
$(document).ready(() => {
var [WIDTH, HEIGHT] = [$(window).width(), $(window).height() - $(".top-bar").outerHeight()];
$("#canvas").width(WIDTH);
$("#canvas").height(HEIGHT);
$("#canvas").attr("width", WIDTH);
$("#canvas").attr("height", HEIGHT);
paper.setup($("#canvas").get(0));
var cs = new CoordinateSystem(WIDTH, HEIGHT);
cs.autoSetFromWidth(50);
cs.calculateTransformation();
let t = cs.transform;
paper.project.activeLayer.transformContent = false;
paper.project.activeLayer.matrix = new paper.Matrix(t.sx, 0, 0, t.sy, t.tx, t.ty);
var r = new Robot(paper.project.activeLayer);
var keyboard = new paper.Tool();
keyboard.onKeyDown = (event) => {
if (event.key == 'left') {
r.move("L");
} else if (event.key == 'right') {
r.move("R");
}
};
var hash = window.location.hash ? window.location.hash.substring(1) : null;
if (hash != null) {
hash.split("").map(x => r.move(x));
}
});
| 27.675 | 96 | 0.574526 |
8b3c161b4c5fa236ecf70aefbad5b54d1c210dc8 | 202 | js | JavaScript | src/js/highlight.js | kbyyd24/LoveIt | 29ad41568d72f2f39ccaddc2ccd2a2379ea56fa2 | [
"MIT"
] | null | null | null | src/js/highlight.js | kbyyd24/LoveIt | 29ad41568d72f2f39ccaddc2ccd2a2379ea56fa2 | [
"MIT"
] | null | null | null | src/js/highlight.js | kbyyd24/LoveIt | 29ad41568d72f2f39ccaddc2ccd2a2379ea56fa2 | [
"MIT"
] | null | null | null | if (!hljs.initHighlighting.called) {
hljs.initHighlighting.called = true;
[].slice.call(document.querySelectorAll('pre.highlight > code')).forEach(function (el) {
hljs.highlightBlock(el)
})
}
| 28.857143 | 90 | 0.712871 |
8b3c40bf7fcdce9f42a3b0e80e6eaf298151cfcd | 171 | js | JavaScript | src/components/layout/index.js | MountsoftWeb/Ink-app | 078a198bfb9430e3bdb1bf17da7d6427ca71c8a9 | [
"MIT"
] | 1 | 2019-04-04T13:45:15.000Z | 2019-04-04T13:45:15.000Z | src/components/layout/index.js | MountsoftWeb/Ink-app | 078a198bfb9430e3bdb1bf17da7d6427ca71c8a9 | [
"MIT"
] | null | null | null | src/components/layout/index.js | MountsoftWeb/Ink-app | 078a198bfb9430e3bdb1bf17da7d6427ca71c8a9 | [
"MIT"
] | null | null | null | import Layout from './Layout.vue'
import Header from './Header.vue'
import Footer from './Footer.vue'
Layout.Header = Header
Layout.Footer = Footer
export default Layout | 21.375 | 33 | 0.760234 |
8b3d129609b97c4a8a55daae9a1ca1be13e71883 | 2,117 | js | JavaScript | src/components/Information&Profile/Information/About.js | necheporenko/react-validbook | 84511f2b0351a16919512289bee932b364915f0a | [
"MIT"
] | null | null | null | src/components/Information&Profile/Information/About.js | necheporenko/react-validbook | 84511f2b0351a16919512289bee932b364915f0a | [
"MIT"
] | null | null | null | src/components/Information&Profile/Information/About.js | necheporenko/react-validbook | 84511f2b0351a16919512289bee932b364915f0a | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import InformationMenu from './InformationMenu';
import InformationFooter from './InformationFooter';
import './index.scss';
class About extends Component {
render() {
return (
<div className="additional-wrap">
<InformationMenu />
<div className="additional-content">
<div className="additional-title">About</div>
<div className="information-wrap-content">
<h2 style={{'padding-top': '0'}}>Validbook is a universal platform for cooperation.</h2>
<p>
It consists of 3 main parts. <br/>
§ A universal log – an effective tool to organize information and learn about something or someone.<br/>
§ A universal communication platform, that can be used for any type of communication either social-, interest- or work-related.<br/>
§ A tool to create, store and exchange indestructible tokens-documents. Tokens behave similarly to real-world, physical paper documents. They can be stored, exchanged, collected. Tokens can be destroyed only by their current owner.<br/>
</p>
<hr className="additional-hr"/>
<p>Validbook is an open source, open governance, user controlled, not-for-profit, social enterprise. It is funded through debt and its own operational income.</p>
<hr className="additional-hr" style={{'margin-bottom': '0'}}/>
<h2>Validbook mission is to enhance cooperation, by making it more transparent and reliable.</h2>
<p>Transparency of cooperation is improved by Validbook books, that can be used to organize information and make observable and unobservable qualities of subjects and objects of cooperation clearer and more understandable.</p>
<p>Reliability of cooperation is improved by Validbook tokens (smart documents), that can be used to decrease reliance on trust when needed and make cooperation more certain and unfailing.</p>
</div>
<InformationFooter />
</div>
</div>
);
}
}
export default About;
| 48.113636 | 250 | 0.675012 |
8b3dadeea3a3c8da25ec5e29f0d3086796dac5b2 | 589 | js | JavaScript | src/routes/index.js | Tatuck/docker-web-management | 4198015df4336c4a220ef175caf3e43a6ba2c69b | [
"MIT"
] | null | null | null | src/routes/index.js | Tatuck/docker-web-management | 4198015df4336c4a220ef175caf3e43a6ba2c69b | [
"MIT"
] | null | null | null | src/routes/index.js | Tatuck/docker-web-management | 4198015df4336c4a220ef175caf3e43a6ba2c69b | [
"MIT"
] | null | null | null | var express = require('express')
var Docker = require('dockerode');
var docker = new Docker();
var app = express.Router()
app.get('/', function(req, res){
docker.listContainers(function(err, containers){
if(err){
throw err;
}
res.render('index', {'all':false,'containers':containers});
});
})
app.get('/all', function(req, res){
docker.listContainers({all:true}, function(err, containers){
if(err){
throw err;
}
res.render('index', {'all':true, 'containers':containers});
});
})
module.exports= app | 24.541667 | 67 | 0.582343 |
8b3eec1cbbd36028a10d4cdf09eaae324f3aa461 | 317 | js | JavaScript | node_modules/tailwindcss/jit/corePlugins/wordBreak.js | mickaelamimba/Round-game | cafc3c0545194177ba4cff58d67bf65cc5e5da11 | [
"MIT"
] | 2,397 | 2021-03-15T16:52:49.000Z | 2022-03-29T09:24:28.000Z | jit/corePlugins/wordBreak.js | infohojin/tailwindcss | e5c41bb779c45004cc7c5c84752bde132dcf7f55 | [
"MIT"
] | 178 | 2021-03-15T17:36:14.000Z | 2021-04-05T19:43:02.000Z | jit/corePlugins/wordBreak.js | infohojin/tailwindcss | e5c41bb779c45004cc7c5c84752bde132dcf7f55 | [
"MIT"
] | 56 | 2021-03-15T17:16:12.000Z | 2022-03-16T14:40:45.000Z | const { createSimpleStaticUtilityPlugin } = require('../pluginUtils')
module.exports = createSimpleStaticUtilityPlugin({
'.break-normal': {
'overflow-wrap': 'normal',
'word-break': 'normal',
},
'.break-words': {
'overflow-wrap': 'break-word',
},
'.break-all': { 'word-break': 'break-all' },
})
| 24.384615 | 69 | 0.624606 |
8b3f29a1f0db5537ac63b8313d4906c602074473 | 556 | js | JavaScript | Dashboard-master/src/Redux/Reducers/MainReducer.js | Daniel-TheProgrammer/Admin-Dashboard | 57f7970fb08428bb60380be6726f45cdddaa9a1e | [
"Apache-2.0"
] | 6 | 2021-02-28T04:51:06.000Z | 2021-07-02T16:31:47.000Z | Dashboard-master/src/Redux/Reducers/MainReducer.js | Daniel-TheProgrammer/Admin-Dashboard | 57f7970fb08428bb60380be6726f45cdddaa9a1e | [
"Apache-2.0"
] | null | null | null | Dashboard-master/src/Redux/Reducers/MainReducer.js | Daniel-TheProgrammer/Admin-Dashboard | 57f7970fb08428bb60380be6726f45cdddaa9a1e | [
"Apache-2.0"
] | null | null | null | const initialState = {
loggedInStatus: localStorage[('isLogged')] === 'true'
};
const mainReducer = (currentState = initialState, action) => {
switch(action.type) {
case 'USER_LOGIN':
localStorage.setItem('isLogged', true);
return {...currentState, loggedInStatus: true};
case 'USER_LOGOUT':
localStorage.setItem('isLogged', false);
return {...currentState, loggedInStatus: false};
default:
return {...currentState};
}
}
export default mainReducer;
| 27.8 | 64 | 0.595324 |
8b3fbe272b39e8943096b15fdd0fd56ad6ad9074 | 722 | js | JavaScript | js/user-info.js | coder-begin/yfunfun | 7aff8cd3af3eb1bcb07868b39d401e138ee03bda | [
"MIT"
] | null | null | null | js/user-info.js | coder-begin/yfunfun | 7aff8cd3af3eb1bcb07868b39d401e138ee03bda | [
"MIT"
] | null | null | null | js/user-info.js | coder-begin/yfunfun | 7aff8cd3af3eb1bcb07868b39d401e138ee03bda | [
"MIT"
] | null | null | null | /**
* Created by rulersex on 2017/2/22.
*/
$(function(){
initInfo();
});
function initInfo(){
$.ajax({
type:"GET",
dataType:"json",
url:"../php/user-info.php",
success:function(data){
$("#userName").text(data["userName"]);
$("#createTime").text(data["createTime"]);
$("#userIntroduce").text(data["descripe"]);
$("#userRealName").text(data["realName"]);
$("#userSex").text(data["sex"]);
$("#userSexLove").text(data["sexLove"]);
$("#userAddress").text(data["address"]);
$("#userBirthday").text(data["birthday"]);
$("#userHobbies").text(data["hobbies"]);
}
});
} | 26.740741 | 55 | 0.484765 |
8b3fc3cf1d1a94f3d495c04babe6ab18a5b4b425 | 2,338 | js | JavaScript | src/util/util.js | kkltmoyu/Clm | 3c98b3530837ffd8887332f3e0495cb703be965a | [
"MIT"
] | null | null | null | src/util/util.js | kkltmoyu/Clm | 3c98b3530837ffd8887332f3e0495cb703be965a | [
"MIT"
] | null | null | null | src/util/util.js | kkltmoyu/Clm | 3c98b3530837ffd8887332f3e0495cb703be965a | [
"MIT"
] | null | null | null | import _ from 'lodash'
import React, {
syncStorage
} from 'react-native';
let utils = {
}
utils.mapBottomIcons = (routeName, state) => {
let iconName = ''
if (routeName === 'Home') {
iconName = `ios-information-circle${state ? '' : '-outline'}`;
} else if (routeName === 'Order') {
iconName = `ios-options${state ? '' : '-outline'}`;
}
return iconName
}
//构造request请求
utils.makeRequest = (config) => {
//url可根据环境配置或者config传入
const basicUrl = 'http://172.30.113.47:3333'
let url = basicUrl + '/' + config.url;
const defaults = {
method: 'GET',
// body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
// credentials: 'same-origin', // include, same-origin, *omit
headers: {
'content-type': 'application/json'
},
mode: 'cors', // no-cors, cors, *same-origin
// redirect: 'follow', // manual, *follow, error
// referrer: 'no-referrer', // *client, no-referrer
};
const request = _.merge(defaults, config);
// const ax = this.$axios(request);
// return ax;
delete request['url']
return fetch(url, request)
}
utils.makeFetch = (config) => {
return fetch('http://api.map.baidu.com/place/v2/suggestion?query=天®ion=北京市&city_limit=true&output=json&ak=WrXbRe8gO1bFqqMUwj6PHgcnBQBO6Lpj')
.then(response => response.json())
.then(responseJson => {
return responseJson.movies;
})
.catch(error => {
console.error(error);
});
}
/*-----------AsyncStorage部分-----------start*/
utils.getItem = (key) => {
return AsyncStorage.getItem(key).then((value) => {
const jsonValue = JSON.parse(value);
return jsonValue;
});
}
utils.saveItem = (key, value) => {
return AsyncStorage.setItem(key, JSON.stringify(value));
}
utils.updateItem = (key, value) => {
return DeviceStorage.get(key).then((item) => {
value = typeof value === 'string' ? value : Object.assign({}, item, value);
return AsyncStorage.setItem(key, JSON.stringify(value));
});
}
utils.deleteItem = (key) => {
return AsyncStorage.removeItem(key);
}
/*-----------AsyncStorage部分-----------end*/
export default utils
| 29.225 | 147 | 0.585115 |
8b400724b5924031f1690f6578bcdb24145593b7 | 1,130 | js | JavaScript | src/js/popup.js | masungwon/should-i-eat-there | 26626502f1e5589513c16c9b446a25b15e430738 | [
"MIT"
] | null | null | null | src/js/popup.js | masungwon/should-i-eat-there | 26626502f1e5589513c16c9b446a25b15e430738 | [
"MIT"
] | null | null | null | src/js/popup.js | masungwon/should-i-eat-there | 26626502f1e5589513c16c9b446a25b15e430738 | [
"MIT"
] | null | null | null | /**
* customizes the browser
* this content script is invoked inside of <script> tags in popup.html
* (see popup.html file in build directory)
*
* To see console.logs added in this file,
* open the popup in the UI, right click the element
* and click "inspect."
*/
import { getInspectionData } from "./api.js";
import { getFromStoragePromisified } from "./utils.js";
popup();
async function popup() {
try {
const data = await getFromStoragePromisified(["restaurant_name"]);
const response = await getInspectionData(data.restaurant_name);
const grade = getGrade(response);
addToPage(grade);
} catch (error) {
console.error(error);
}
}
function getGrade(response) {
let grade = "N/A";
const is_grade_available = response.length && response[0].grade;
if (is_grade_available) {
grade = response[0].grade;
}
return grade;
}
function addToPage(data) {
let container = document.getElementById("inspectionResult");
const h1 = document.createElement("h1");
const inspectionResult = document.createTextNode(data);
h1.appendChild(inspectionResult);
container.appendChild(h1);
}
| 26.27907 | 71 | 0.70885 |
8b40340b5fb4c0408a174c6bb3eb017b2fb09212 | 1,312 | js | JavaScript | app/routes/role.route.js | RobertSomodi/RAW_SERVER_2 | ec0f6c9cc1ea2edeee000271d51b7e63f4f62fcb | [
"MIT"
] | null | null | null | app/routes/role.route.js | RobertSomodi/RAW_SERVER_2 | ec0f6c9cc1ea2edeee000271d51b7e63f4f62fcb | [
"MIT"
] | 2 | 2020-07-17T02:33:51.000Z | 2021-05-08T22:03:55.000Z | app/routes/role.route.js | RobertSomodi/RAW_SERVER_2 | ec0f6c9cc1ea2edeee000271d51b7e63f4f62fcb | [
"MIT"
] | null | null | null | const roleService = require('../services/role.service');
const schema = require('../schema/roleValidationSchema.json')
const iValidator = require('../../common/iValidator');
function init(router) {
router.route('/role')
.post(addRole);
router.route('/role/:id')
.get(getRoleById)
.delete(deleteRole)
}
function getRoleById(req,res) {
let reqData = req.params;
var json_format = iValidator.json_schema(schema.getSchema,reqData,"role");
if (json_format.valid == false) {
return res.status(422).send(json_format.errorMessage);
}
roleService.getRoleById(reqData.id).then((data) => {
res.send(data);
}).catch((err) => {
res.send(err);
});
}
function addRole(req,res) {
var roleData=req.body;
//Validating the input entity
var json_format = iValidator.json_schema(schema.postSchema, roleData, "role");
if (json_format.valid == false) {
return res.status(422).send(json_format.errorMessage);
}
roleService.addRole(roleData).then((data) => {
res.json(data);
}).catch((err) => {
res.json(err);
});
}
function deleteRole(req,res) {
var delId = req.params.id;
roleService.deleteRole(delId).then((data)=>{
res.json(data);
}).catch((err)=>{
res.json(err);
});
}
module.exports.init = init;
| 21.16129 | 81 | 0.643293 |
8b409fc22170709fd3e749bb41c611abdb5784ed | 2,458 | js | JavaScript | client/src/components/MarkerSearch.js | christykusuma/wanderlust | e279a62d4df6bdfebe7d564b289775b3d30e8d8f | [
"MIT"
] | null | null | null | client/src/components/MarkerSearch.js | christykusuma/wanderlust | e279a62d4df6bdfebe7d564b289775b3d30e8d8f | [
"MIT"
] | null | null | null | client/src/components/MarkerSearch.js | christykusuma/wanderlust | e279a62d4df6bdfebe7d564b289775b3d30e8d8f | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { searchMarker } from '../actions/index';
import { bindActionCreators } from 'redux';
import '../css/markersearch.css';
class MarkerSearch extends Component {
componentDidMount() {
this.props.searchMarker(this.props.match.params.id);
}
renderBusinesses() {
return this.props.search.map((business) => {
console.log(business);
return (
<div className="search-results">
<div className="left-col">
<img className="search-img" src={`${business.image_url}`} alt="search" />
</div>
<div className="right-col">
<div className="search-list card"
key={business.id} >
<div className="card-content">
<span className="card-title"><a href={business.url} target="_blank">{business.name}</a></span>
</div>
</div>
<div className="search-info card">
<div className="card-content">
<ul>
<li> Rating: {business.rating}/5</li>
<li> Phone number: {business.phone}</li>
<li>Price: {business.price} </li>
<li>Category: {business.categories[0].title}</li>
<li>Address: {business.location.address1}, {business.location.address2}, {business.location.city}, {business.location.country}</li>
</ul>
</div>
</div>
</div>
</div>
);
});
}
render() {
if (!this.props.search) {
return <h5></h5>
}
return (
<div className="marker-search">
<h3>Search Results</h3>
{this.renderBusinesses()}
</div>
);
}
}
function mapStateToProps(state) {
return {
search: state.activeSearch,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators( {
searchMarker,
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(MarkerSearch);
| 32.342105 | 163 | 0.465826 |
8b4157fa3c6b1524145e5e0027b3916eb74a8f81 | 20,813 | js | JavaScript | src/components/program/gogoGenarators/index.js | bankkooo/gogotest2 | ee03f26c4f282507a5ec69d74343dc4c094d5a0a | [
"MIT"
] | 1 | 2020-03-30T18:43:11.000Z | 2020-03-30T18:43:11.000Z | src/components/program/gogoGenarators/index.js | thapakorn613/remote-gogo-program | fd48df1cbc26b0d5893ccef34cb46411f2a223f4 | [
"MIT"
] | null | null | null | src/components/program/gogoGenarators/index.js | thapakorn613/remote-gogo-program | fd48df1cbc26b0d5893ccef34cb46411f2a223f4 | [
"MIT"
] | 1 | 2020-03-02T11:11:06.000Z | 2020-03-02T11:11:06.000Z | // module.exports =
export default function (Blockly) {
Blockly.GogoCode = new Blockly.Generator('GogoCode')
/**
* List of illegal variable names.
* This is not intended to be a security feature. Blockly is 100% client-side,
* so bypassing this list is trivial. This is intended to prevent users from
* accidentally clobbering a built-in object or function.
* @private
*/
Blockly.GogoCode.addReservedWords(
'Blockly,' + // In case JS is evaled in the current window.
// https://developer.mozilla.org/en/GogoCode/Reference/Reserved_Words
'break,case,catch,continue,debugger,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with,' +
'class,enum,export,extends,import,super,implements,interface,let,package,private,protected,public,static,yield,' +
'const,null,true,false,' +
// https://developer.mozilla.org/en/GogoCode/Reference/Global_Objects
'Array,ArrayBuffer,Boolean,Date,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Error,eval,EvalError,Float32Array,Float64Array,Function,Infinity,Int16Array,Int32Array,Int8Array,isFinite,isNaN,Iterator,JSON,Math,NaN,Number,Object,parseFloat,parseInt,RangeError,ReferenceError,RegExp,StopIteration,String,SyntaxError,TypeError,Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray,undefined,uneval,URIError,' +
// https://developer.mozilla.org/en/DOM/window
'applicationCache,closed,Components,content,_content,controllers,crypto,defaultStatus,dialogArguments,directories,document,frameElement,frames,fullScreen,globalStorage,history,innerHeight,innerWidth,length,location,locationbar,localStorage,menubar,messageManager,mozAnimationStartTime,mozInnerScreenX,mozInnerScreenY,mozPaintCount,name,navigator,opener,outerHeight,outerWidth,pageXOffset,pageYOffset,parent,performance,personalbar,pkcs11,returnValue,screen,screenX,screenY,scrollbars,scrollMaxX,scrollMaxY,scrollX,scrollY,self,sessionStorage,sidebar,status,statusbar,toolbar,top,URL,window,' +
'addEventListener,alert,atob,back,blur,btoa,captureEvents,clearImmediate,clearInterval,clearTimeout,close,confirm,disableExternalCapture,dispatchEvent,dump,enableExternalCapture,escape,find,focus,forward,GeckoActiveXObject,getAttention,getAttentionWithCycleCount,getComputedStyle,getSelection,home,matchMedia,maximize,minimize,moveBy,moveTo,mozRequestAnimationFrame,open,openDialog,postMessage,print,prompt,QueryInterface,releaseEvents,removeEventListener,resizeBy,resizeTo,restore,routeEvent,scroll,scrollBy,scrollByLines,scrollByPages,scrollTo,setCursor,setImmediate,setInterval,setResizable,setTimeout,showModalDialog,sizeToContent,stop,unescape,updateCommands,XPCNativeWrapper,XPCSafeJSObjectWrapper,' +
'onabort,onbeforeunload,onblur,onchange,onclick,onclose,oncontextmenu,ondevicemotion,ondeviceorientation,ondragdrop,onerror,onfocus,onhashchange,onkeydown,onkeypress,onkeyup,onload,onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmozbeforepaint,onpaint,onpopstate,onreset,onresize,onscroll,onselect,onsubmit,onunload,onpageshow,onpagehide,' +
'Image,Option,Worker,' +
// https://developer.mozilla.org/en/Gecko_DOM_Reference
'Event,Range,File,FileReader,Blob,BlobBuilder,' +
'Attr,CDATASection,CharacterData,Comment,console,DocumentFragment,DocumentType,DomConfiguration,DOMError,DOMErrorHandler,DOMException,DOMImplementation,DOMImplementationList,DOMImplementationRegistry,DOMImplementationSource,DOMLocator,DOMObject,DOMString,DOMStringList,DOMTimeStamp,DOMUserData,Entity,EntityReference,MediaQueryList,MediaQueryListListener,NameList,NamedNodeMap,Node,NodeFilter,NodeIterator,NodeList,Notation,Plugin,PluginArray,ProcessingInstruction,SharedWorker,Text,TimeRanges,Treewalker,TypeInfo,UserDataHandler,Worker,WorkerGlobalScope,' +
'HTMLDocument,HTMLElement,HTMLAnchorElement,HTMLAppletElement,HTMLAudioElement,HTMLAreaElement,HTMLBaseElement,HTMLBaseFontElement,HTMLBodyElement,HTMLBRElement,HTMLButtonElement,HTMLCanvasElement,HTMLDirectoryElement,HTMLDivElement,HTMLDListElement,HTMLEmbedElement,HTMLFieldSetElement,HTMLFontElement,HTMLFormElement,HTMLFrameElement,HTMLFrameSetElement,HTMLHeadElement,HTMLHeadingElement,HTMLHtmlElement,HTMLHRElement,HTMLIFrameElement,HTMLImageElement,HTMLInputElement,HTMLKeygenElement,HTMLLabelElement,HTMLLIElement,HTMLLinkElement,HTMLMapElement,HTMLMenuElement,HTMLMetaElement,HTMLModElement,HTMLObjectElement,HTMLOListElement,HTMLOptGroupElement,HTMLOptionElement,HTMLOutputElement,HTMLParagraphElement,HTMLParamElement,HTMLPreElement,HTMLQuoteElement,HTMLScriptElement,HTMLSelectElement,HTMLSourceElement,HTMLSpanElement,HTMLStyleElement,HTMLTableElement,HTMLTableCaptionElement,HTMLTableCellElement,HTMLTableDataCellElement,HTMLTableHeaderCellElement,HTMLTableColElement,HTMLTableRowElement,HTMLTableSectionElement,HTMLTextAreaElement,HTMLTimeElement,HTMLTitleElement,HTMLTrackElement,HTMLUListElement,HTMLUnknownElement,HTMLVideoElement,' +
'HTMLCanvasElement,CanvasRenderingContext2D,CanvasGradient,CanvasPattern,TextMetrics,ImageData,CanvasPixelArray,HTMLAudioElement,HTMLVideoElement,NotifyAudioAvailableEvent,HTMLCollection,HTMLAllCollection,HTMLFormControlsCollection,HTMLOptionsCollection,HTMLPropertiesCollection,DOMTokenList,DOMSettableTokenList,DOMStringMap,RadioNodeList,' +
'SVGDocument,SVGElement,SVGAElement,SVGAltGlyphElement,SVGAltGlyphDefElement,SVGAltGlyphItemElement,SVGAnimationElement,SVGAnimateElement,SVGAnimateColorElement,SVGAnimateMotionElement,SVGAnimateTransformElement,SVGSetElement,SVGCircleElement,SVGClipPathElement,SVGColorProfileElement,SVGCursorElement,SVGDefsElement,SVGDescElement,SVGEllipseElement,SVGFilterElement,SVGFilterPrimitiveStandardAttributes,SVGFEBlendElement,SVGFEColorMatrixElement,SVGFEComponentTransferElement,SVGFECompositeElement,SVGFEConvolveMatrixElement,SVGFEDiffuseLightingElement,SVGFEDisplacementMapElement,SVGFEDistantLightElement,SVGFEFloodElement,SVGFEGaussianBlurElement,SVGFEImageElement,SVGFEMergeElement,SVGFEMergeNodeElement,SVGFEMorphologyElement,SVGFEOffsetElement,SVGFEPointLightElement,SVGFESpecularLightingElement,SVGFESpotLightElement,SVGFETileElement,SVGFETurbulenceElement,SVGComponentTransferFunctionElement,SVGFEFuncRElement,SVGFEFuncGElement,SVGFEFuncBElement,SVGFEFuncAElement,SVGFontElement,SVGFontFaceElement,SVGFontFaceFormatElement,SVGFontFaceNameElement,SVGFontFaceSrcElement,SVGFontFaceUriElement,SVGForeignObjectElement,SVGGElement,SVGGlyphElement,SVGGlyphRefElement,SVGGradientElement,SVGLinearGradientElement,SVGRadialGradientElement,SVGHKernElement,SVGImageElement,SVGLineElement,SVGMarkerElement,SVGMaskElement,SVGMetadataElement,SVGMissingGlyphElement,SVGMPathElement,SVGPathElement,SVGPatternElement,SVGPolylineElement,SVGPolygonElement,SVGRectElement,SVGScriptElement,SVGStopElement,SVGStyleElement,SVGSVGElement,SVGSwitchElement,SVGSymbolElement,SVGTextElement,SVGTextPathElement,SVGTitleElement,SVGTRefElement,SVGTSpanElement,SVGUseElement,SVGViewElement,SVGVKernElement,' +
'SVGAngle,SVGColor,SVGICCColor,SVGElementInstance,SVGElementInstanceList,SVGLength,SVGLengthList,SVGMatrix,SVGNumber,SVGNumberList,SVGPaint,SVGPoint,SVGPointList,SVGPreserveAspectRatio,SVGRect,SVGStringList,SVGTransform,SVGTransformList,' +
'SVGAnimatedAngle,SVGAnimatedBoolean,SVGAnimatedEnumeration,SVGAnimatedInteger,SVGAnimatedLength,SVGAnimatedLengthList,SVGAnimatedNumber,SVGAnimatedNumberList,SVGAnimatedPreserveAspectRatio,SVGAnimatedRect,SVGAnimatedString,SVGAnimatedTransformList,' +
'SVGPathSegList,SVGPathSeg,SVGPathSegArcAbs,SVGPathSegArcRel,SVGPathSegClosePath,SVGPathSegCurvetoCubicAbs,SVGPathSegCurvetoCubicRel,SVGPathSegCurvetoCubicSmoothAbs,SVGPathSegCurvetoCubicSmoothRel,SVGPathSegCurvetoQuadraticAbs,SVGPathSegCurvetoQuadraticRel,SVGPathSegCurvetoQuadraticSmoothAbs,SVGPathSegCurvetoQuadraticSmoothRel,SVGPathSegLinetoAbs,SVGPathSegLinetoHorizontalAbs,SVGPathSegLinetoHorizontalRel,SVGPathSegLinetoRel,SVGPathSegLinetoVerticalAbs,SVGPathSegLinetoVerticalRel,SVGPathSegMovetoAbs,SVGPathSegMovetoRel,ElementTimeControl,TimeEvent,SVGAnimatedPathData,' +
'SVGAnimatedPoints,SVGColorProfileRule,SVGCSSRule,SVGExternalResourcesRequired,SVGFitToViewBox,SVGLangSpace,SVGLocatable,SVGRenderingIntent,SVGStylable,SVGTests,SVGTextContentElement,SVGTextPositioningElement,SVGTransformable,SVGUnitTypes,SVGURIReference,SVGViewSpec,SVGZoomAndPan' +
'False,None,True,and,as,assert,break,class,continue,def,del,elif,else,' +
'except,exec,finally,for,from,global,if,import,in,is,lambda,nonlocal,not,' +
'or,pass,print,raise,return,try,while,with,yield,' +
// https://docs.python.org/3/library/constants.html
// https://docs.python.org/2/library/constants.html
'NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,' +
// >>> print(','.join(sorted(dir(__builtins__))))
// https://docs.python.org/3/library/functions.html
// https://docs.python.org/2/library/functions.html
'ArithmeticError,AssertionError,AttributeError,BaseException,' +
'BlockingIOError,BrokenPipeError,BufferError,BytesWarning,' +
'ChildProcessError,ConnectionAbortedError,ConnectionError,' +
'ConnectionRefusedError,ConnectionResetError,DeprecationWarning,EOFError,' +
'Ellipsis,EnvironmentError,Exception,FileExistsError,FileNotFoundError,' +
'FloatingPointError,FutureWarning,GeneratorExit,IOError,ImportError,' +
'ImportWarning,IndentationError,IndexError,InterruptedError,' +
'IsADirectoryError,KeyError,KeyboardInterrupt,LookupError,MemoryError,' +
'ModuleNotFoundError,NameError,NotADirectoryError,NotImplemented,' +
'NotImplementedError,OSError,OverflowError,PendingDeprecationWarning,' +
'PermissionError,ProcessLookupError,RecursionError,ReferenceError,' +
'ResourceWarning,RuntimeError,RuntimeWarning,StandardError,' +
'StopAsyncIteration,StopIteration,SyntaxError,SyntaxWarning,SystemError,' +
'SystemExit,TabError,TimeoutError,TypeError,UnboundLocalError,' +
'UnicodeDecodeError,UnicodeEncodeError,UnicodeError,' +
'UnicodeTranslateError,UnicodeWarning,UserWarning,ValueError,Warning,' +
'ZeroDivisionError,_,__build_class__,__debug__,__doc__,__import__,' +
'__loader__,__name__,__package__,__spec__,abs,all,any,apply,ascii,' +
'basestring,bin,bool,buffer,bytearray,bytes,callable,chr,classmethod,cmp,' +
'coerce,compile,complex,copyright,credits,delattr,dict,dir,divmod,' +
'enumerate,eval,exec,execfile,exit,file,filter,float,format,frozenset,' +
'getattr,globals,hasattr,hash,help,hex,id,input,int,intern,isinstance,' +
'issubclass,iter,len,license,list,locals,long,map,max,memoryview,min,' +
'next,object,oct,open,ord,pow,print,property,quit,range,raw_input,reduce,' +
'reload,repr,reversed,round,set,setattr,slice,sorted,staticmethod,str,' +
'sum,super,tuple,type,unichr,unicode,vars,xrange,zip,' +
'main,to,end,ifstatechange,not,and,or,beep,forever,repeat,waituntil,' +
'sensor1,sensor2,sensor3,sensor4,sensor5,sensor6,sensor7,sensor8,' +
'on,off,onfor,cw,ccw,rd,setpower,seth,lt,rt,wait,timer,resett,' +
'settickrate,tickcount,cleartick,ir,show,' +
'seconds,minutes,hours,dow,day,month,year,' +
'setpos,cls,play,nexttrack,prevtrack,gototrack,erasetracks,' +
'i2cwrite,i2cread,')
/**
* Order of operation ENUMs.
* https://developer.mozilla.org/en/GogoCode/Reference/Operators/Operator_Precedence
*/
Blockly.GogoCode.ORDER_ATOMIC = 0 // 0 "" ...
Blockly.GogoCode.ORDER_MEMBER = 1 // . []
Blockly.GogoCode.ORDER_NEW = 1 // new
Blockly.GogoCode.ORDER_FUNCTION_CALL = 2 // ()
Blockly.GogoCode.ORDER_INCREMENT = 3 // ++
Blockly.GogoCode.ORDER_DECREMENT = 3 // --
Blockly.GogoCode.ORDER_LOGICAL_NOT = 4 // !
Blockly.GogoCode.ORDER_BITWISE_NOT = 4 // ~
Blockly.GogoCode.ORDER_UNARY_PLUS = 4 // +
Blockly.GogoCode.ORDER_UNARY_NEGATION = 4 // -
Blockly.GogoCode.ORDER_TYPEOF = 4 // typeof
Blockly.GogoCode.ORDER_VOID = 4 // void
Blockly.GogoCode.ORDER_DELETE = 4 // delete
Blockly.GogoCode.ORDER_MULTIPLICATION = 5 // *
Blockly.GogoCode.ORDER_DIVISION = 5 // /
Blockly.GogoCode.ORDER_MODULUS = 5 // %
Blockly.GogoCode.ORDER_ADDITION = 6 // +
Blockly.GogoCode.ORDER_SUBTRACTION = 6 // -
Blockly.GogoCode.ORDER_BITWISE_SHIFT = 7 // << >> >>>
Blockly.GogoCode.ORDER_RELATIONAL = 8 // < <= > >=
Blockly.GogoCode.ORDER_IN = 8 // in
Blockly.GogoCode.ORDER_INSTANCEOF = 8 // instanceof
Blockly.GogoCode.ORDER_EQUALITY = 9 // == != === !==
Blockly.GogoCode.ORDER_BITWISE_AND = 10 // &
Blockly.GogoCode.ORDER_BITWISE_XOR = 11 // ^
Blockly.GogoCode.ORDER_BITWISE_OR = 12 // |
Blockly.GogoCode.ORDER_LOGICAL_AND = 13 // &&
Blockly.GogoCode.ORDER_LOGICAL_OR = 14 // ||
Blockly.GogoCode.ORDER_CONDITIONAL = 15 // ?:
Blockly.GogoCode.ORDER_ASSIGNMENT = 16 // = += -= *= /= %= <<= >>= ...
Blockly.GogoCode.ORDER_COMMA = 17 // ,
Blockly.GogoCode.ORDER_NONE = 99 // (...)
// /**
// * Arbitrary code to inject into locations that risk causing infinite loops.
// * Any instances of '%1' will be replaced by the block ID that failed.
// * E.g. ' checkTimeout(%1);\n'
// * @type ?string
// */
Blockly.GogoCode.INFINITE_LOOP_TRAP = null
/**
* Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/
Blockly.GogoCode.init = function (workspace) {
// Create a dictionary of definitions to be printed before the code.
Blockly.GogoCode.definitions_ = Object.create(null)
// Create a dictionary mapping desired function names in definitions_
// to actual function names (to avoid collisions with user functions).
Blockly.GogoCode.functionNames_ = Object.create(null)
if (!Blockly.GogoCode.variableDB_) {
Blockly.GogoCode.variableDB_ =
new Blockly.Names(Blockly.GogoCode.RESERVED_WORDS_)
} else {
Blockly.GogoCode.variableDB_.reset()
}
Blockly.GogoCode.variableDB_.setVariableMap(workspace.getVariableMap())
var defvars = []
// Add developer variables (not created or named by the user).
var devVarList = Blockly.Variables.allDeveloperVariables(workspace)
for (var i = 0; i < devVarList.length; i++) {
// defvars.push(Blockly.GogoCode.variableDB_.getName(devVarList[i],
// Blockly.Names.DEVELOPER_VARIABLE_TYPE))
var defining = `set ${Blockly.GogoCode.variableDB_.getName(devVarList[i], Blockly.Names.DEVELOPER_VARIABLE_TYPE)} 0`
defvars.push(defining)
}
// Add user variables, but only ones that are being used.
var variables = Blockly.Variables.allUsedVarModels(workspace)
for (var j = 0; j < variables.length; j++) {
var defining2 = `set ${Blockly.GogoCode.variableDB_.getName(variables[j].getId(), Blockly.Variables.NAME_TYPE)} 0`
defvars.push(defining2)
}
// var variables = Blockly.Variables.allUsedVarModels(workspace);
// for (var j = 0; i < variables.length; i++) {
// defvars.push(Blockly.GogoCode.variableDB_.getName(variables[i].getId(),
// Blockly.Variables.NAME_TYPE));
// }
// Declare all of the variables.
if (defvars.length) {
Blockly.GogoCode.definitions_['variables'] = `[VAR]${defvars.join('\n')}[/VAR]`
}
}
// /**
// * Initialise the database of variable names.
// */
// Blockly.GogoCode.init = function (workspace) {
// // Create a dictionary of definitions to be printed before the code.
// Blockly.GogoCode.definitions_ = Object.create(null)
// // Create a dictionary mapping desired function names in definitions_
// // to actual function names (to avoid collisions with user functions).
// Blockly.GogoCode.functionNames_ = Object.create(null)
// if (Blockly.Variables) {
// if (!Blockly.GogoCode.variableDB_) {
// Blockly.GogoCode.variableDB_ =
// new Blockly.Names(Blockly.GogoCode.RESERVED_WORDS_)
// } else {
// Blockly.GogoCode.variableDB_.reset()
// }
// var defvars = []
// var variables = Blockly.Variables.allVariables()
// for (var x = 0; x < variables.length; x++) {
// defvars[x] = 'set ' +
// Blockly.GogoCode.variableDB_.getName(variables[x],
// Blockly.Variables.NAME_TYPE) + ' 0'
// }
// Blockly.GogoCode.definitions_['variables'] = defvars.join('\n')
// }
// }
/**
* Prepend the generated code with the variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.GogoCode.finish = function (code) {
// Convert the definitions dictionary into a list.
var definitions = []
for (var name in Blockly.GogoCode.definitions_) {
definitions.push(Blockly.GogoCode.definitions_[name])
}
// Clean up temporary data.
delete Blockly.GogoCode.definitions_
delete Blockly.GogoCode.functionNames_
Blockly.GogoCode.variableDB_.reset()
return definitions.join('\n\n') + '\n\n\n' + code
}
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything. A trailing semicolon is needed to make this legal.
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.GogoCode.scrubNakedValue = function (line) {
return line + ';\n'
}
/**
* Encode a string as a properly escaped GogoCode string, complete with
* quotes.
* @param {string} string Text to encode.
* @return {string} GogoCode string.
* @private
*/
Blockly.GogoCode.quote_ = function (string) {
// TODO: This is a quick hack. Replace with goog.string.quote
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/'/g, '\\\'')
return '\'' + string + '\''
}
/**
* Common tasks for generating GogoCode from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Blockly.Block} block The current block.
* @param {string} code The GogoCode code created for this block.
* @return {string} GogoCode code with comments and subsequent blocks added.
* @private
*/
Blockly.GogoCode.scrub_ = function (block, code) {
if (code === null) {
// Block has handled code generation itself.
return ''
}
var commentCode = ''
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block.
var comment = block.getCommentText()
if (comment) {
commentCode += this.prefixLines(comment, '// ') + '\n'
}
// Collect comments for all value arguments.
// Don't collect comments for nested statements.
for (var x = 0; x < block.inputList.length; x++) {
if (block.inputList[x].type === Blockly.INPUT_VALUE) {
var childBlock = block.inputList[x].connection.targetBlock()
if (childBlock) {
var commenti = this.allNestedComments(childBlock)
if (commenti) {
commentCode += this.prefixLines(commenti, '// ')
}
}
}
}
}
var nextBlock = block.nextConnection && block.nextConnection.targetBlock()
var nextCode = this.blockToCode(nextBlock)
return commentCode + code + nextCode
}
require('./blocks/basic/variable')(Blockly)
require('./blocks/basic/function')(Blockly)
require('./blocks/basic/logic')(Blockly)
require('./blocks/basic/loop')(Blockly)
require('./blocks/basic/math')(Blockly)
require('./blocks/basic/motor')(Blockly)
require('./blocks/basic/servo')(Blockly)
require('./blocks/basic/sensor')(Blockly)
require('./blocks/basic/sound')(Blockly)
require('./blocks/basic/time')(Blockly)
require('./blocks/basic/irRemote')(Blockly)
require('./blocks/basic/otherAction')(Blockly)
require('./blocks/basic/definition')(Blockly)
require('./blocks/modules/clockModule')(Blockly)
require('./blocks/modules/displayModule')(Blockly)
require('./blocks/modules/displayModule')(Blockly)
require('./blocks/modules/voiceModule')(Blockly)
require('./blocks/modules/i2c')(Blockly)
require('./blocks/pi/piCamera')(Blockly)
require('./blocks/pi/piCloudService')(Blockly)
require('./blocks/pi/piDataLogging')(Blockly)
require('./blocks/pi/piEmail')(Blockly)
require('./blocks/pi/piFingerScan')(Blockly)
require('./blocks/pi/piGogoCom')(Blockly)
require('./blocks/pi/piImage')(Blockly)
require('./blocks/pi/piRfid')(Blockly)
require('./blocks/pi/piSound')(Blockly)
require('./blocks/pi/piSms')(Blockly)
return Blockly.GogoCode
}
| 64.436533 | 1,688 | 0.764762 |
8b4567142753b3fb60ba83c5fa7d27efbd73f5b3 | 35,477 | js | JavaScript | public/home/themes/68ecshopcom_360buy/js/common.min.js | anning556/fenglei179 | 243724976074f19902aea4924f8b99cebdc2e7c4 | [
"MIT"
] | null | null | null | public/home/themes/68ecshopcom_360buy/js/common.min.js | anning556/fenglei179 | 243724976074f19902aea4924f8b99cebdc2e7c4 | [
"MIT"
] | null | null | null | public/home/themes/68ecshopcom_360buy/js/common.min.js | anning556/fenglei179 | 243724976074f19902aea4924f8b99cebdc2e7c4 | [
"MIT"
] | null | null | null | var _LOAD_SCRIPT_=function(a,c){if(!a){return;}if(!c){_LOAD_SCRIPT_DELAY_(a);return;}var b=document.createElement("script");b.type="text/javascript";b.async=true;b.src=a;setTimeout(function(){document.getElementsByTagName("head")[0].appendChild(b);},0);};var _G_SCRIPT_lIST_=[];var _LOAD_SCRIPT_DELAY_=function(a){_G_SCRIPT_lIST_[_G_SCRIPT_lIST_.length]=a;};var _RUNNING_LOAD_SCRIPT_=function(){if(_G_SCRIPT_lIST_&&_G_SCRIPT_lIST_.length>0){for(var a=0;a<_G_SCRIPT_lIST_.length;a++){_LOAD_SCRIPT_(_G_SCRIPT_lIST_[a],true);}}};function _LOAD_VIRTUAL_FUNCTION_(b,a){if(!a){window[b]=function(){};}else{window[b]=function(){return a;};}}function reSortDom(e,c){if(!e||!e.length){return[];}var f=[];for(var a=0,d=e.length;a<d;a++){if(e[a].nodeName=="#text"||e[a].nodeName=="#comment"){continue;}f.push([e[a],e[a].innerHTML]);}if(f.length>(c?0:1)){var b=f[0][0].parentNode;if(b.tagName.toLowerCase()=="tr"||b.tagName.toLowerCase()=="table"){return;}f=f.sort(function(){return Math.random()-0.5;});b.innerHTML="";for(var a=0,d=f.length;a<d;a++){if(typeof c=="string"){if(a===0){M.addClass(f[a][0],c);}}else{if(typeof firstClassFit=="function"){M.addClass(f[a][0],c(a));}}if(f[a][0].innerHTML===""){f[a][0].innerHTML=f[a][1];}b.appendChild(f[a][0]);}}return f;}function _SET_CHAT_DATA_READY_(a){window._MCHAT_DATA_READY_=a;}var M={lightBox:function(m,o,g,p,c,q,a){o=o||{};p=p||300;var j=document.createElement("div");var n=new Date();var b=n.getTime().toString(36);n="JS_lightBox_"+b;j.className="lightBox "+(a?a:"");j.id=n;if(c){j.style.cssText=c;}j.style.zIndex=p;var l='<div class="htmls">'+(m+"").replace(/\{=id\}/g,b)+"</div>";var f="";var e=1;for(var i in o){f+='<a id="'+n+"_"+i+'" class="lightbox_btns_'+i+" lightbox_btnsi_"+e+'">'+i+"</a>";e++;}if(f){f='<div class="btns">'+f+"</div>";}l=g?l+f:'<div class="in">'+l+f+"</div>";j.innerHTML=l;j._showMask=q;if(q){M.showMask(p-1);}document.body.appendChild(j);for(var i in o){if(o[i]=="close"){document.getElementById(n+"_"+i).onclick=function(){M.closeLightBox(n);};}else{if(typeof o[i]==="function"){document.getElementById(n+"_"+i).onclick=o[i];}}}M.lightBoxId=n;M.lightBoxTempId=b;return j;},closeLightBox:function(c,b){if(!c){c=M.lightBoxId;}c="JS_lightBox_"+((c+"").replace("JS_lightBox_",""));var a=M.$("#"+c);if(a){if(a._showMask){M.hideMask();}a.parentNode.removeChild(a);}if(typeof b=="function"){b(c);}},alert:function(a,b){b=M.extend({title:"提示",onOk:null,mask:true,type:"warn"},(b||{}));h='<div class="clearfix title"><div class="Left"><i style="display:inline-block;"></i><span>'+b.title+'</span></div><a href="javascript:;" class="Right" onclick="M.closeLightBox( \'{=id}\' , M.alert.setting.onOk );">×</a></div><div class="content"><table style="width:100%"><tr><td class="icons_td"><span class="icons icons_'+b.type+'"></span></td><td class="content_td">'+a+"</td></tr></table></div>";M.lightBox(h,{"确定":function(){M.closeLightBox(false,b.onOk);}},null,null,null,b.mask,"MALERT");M.alert.setting=b;},confirm:function(a,b){b=M.extend({title:"提示",onOk:null,onCancel:null,mask:true,type:"confirm"},(b||{}));h='<div class="clearfix title"><div class="Left"><i style="display:inline-block;"></i><span>'+b.title+'</span></div><a href="javascript:;" class="Right" onclick="M.closeLightBox( \'{=id}\' , M.confirm.setting.onCancel );">×</a></div><div class="content"><table style="width:100%"><tr><td class="icons_td"><span class="icons icons_'+b.type+'"></span></td><td class="content_td">'+a+"</td></tr></table></div>";M.lightBox(h,{"确定":function(){M.closeLightBox(false,b.onOk);},"取消":function(){M.closeLightBox(false,b.onCancel);}},null,null,null,b.mask,"MALERT MCONFIRM");M.confirm.setting=b;},showMask:function(c){if(M.maskDom){M.hideMask();}c=c||290;var a=document.createElement("div"),b=(document.body.scrollHeight>=window.screen.availHeight)?document.body.scrollHeight:window.screen.availHeight;a.id="JS_mask";a.className="c-mask";a.style.cssText="height:"+b+"px;width:100%;position:absolute;background:#000;z-index:900;top:0;left:0;opacity:0.5;filter:alpha(opacity=50);z-index:"+c;document.body.appendChild(a);M.maskDom=a;},hideMask:function(){if(M.maskDom){M.maskDom.parentNode.removeChild(M.maskDom);M.maskDom=null;}},sendFrom:function(a,c,b){},goExpr:function(e,a,d,c){if(!e){return;}if(e=="index.html"){M.setCookie("curr_page_sn","index",5,"meilele.com");M.setCookie("region_id",0,5,"meilele.com");M.setCookie("region_pinyin","",-1,"meilele.com");M.setCookie("region_name","全国",5,"meilele.com");if(d==2){location.href="/expr.html";}else{location.href="/";}}else{M.setCookie("curr_page_sn",0,5,"meilele.com");M.setCookie("region_id",a,5,"meilele.com");M.setCookie("region_pinyin",e,5,"meilele.com");if(c){M.setCookie("region_name",c,5,"meilele.com");}else{M.setCookie("region_name","",-1,"meilele.com");}if(d==2){location.href="/"+e+"/expr.html";}else{var b=location.href.split("/");if(b[b.length-1]=="expr.html"){location.href="/"+e+"/expr.html";}else{location.href="/"+e+"/";}}}},setCookie:function(a,d,c,b,f){c=c||360;f=f||"/";b=b?";domain="+b:";domain=meilele.com";var e=new Date();e.setTime(e.getTime()+parseInt(c,10)*24*60*60*1000);document.cookie=a+"="+encodeURIComponent(d)+(c=="session"?"":";expires="+e.toGMTString())+b+";path="+f;},getCookie:function(a){var e;if(document.cookie&&document.cookie!==""){var d=document.cookie.split(";");var f=d.length;for(var c=0;c<f;c++){var b=d[c].replace(/(^\s*)|(\s*$)/g,"");if(b.substring(0,a.length+1)==(a+"=")){e=decodeURIComponent(b.substring(a.length+1));break;}}}return e;},showLoginBox:function(b,a){if(M.getCookie("meilele_login")=="1"&&M.getCookie("ECS[username]")){if(typeof b=="function"){b();}return;}M.showLoginBox.dom=document.getElementById("MLL_login_box");if(!M.showLoginBox.dom){M.showLoginBox.dom=document.createElement("div");document.body.appendChild(M.showLoginBox.dom);M.showLoginBox.dom.className="MLL_LOGIN_BOX";M.showLoginBox.dom.innerHTML='<div style="text-align:center; padding-top:30px;"><span style="padding:20px;display:inline-block; background:#fff;border:1px solid #ccc;border-radius:5px;">载入中,请稍候...</span></div>';M.showLoginBox.dom.setAttribute("id","MLL_login_box");M.showLoginBox.dom.style.width="400px";}else{M.showLoginBox.dom.style.display="block";}M.showLoginBox.callback=b;M.showLoginBox.refresh=a;if(M.showLoginBox.loginScript&&window.loginBox){loginBox.show();}else{M.showLoginBox.loginScript=document.createElement("script");M.showLoginBox.loginScript.type="text/javascript";M.showLoginBox.loginScript.src=M.__IMG+"/themes/paipai/js/loginbox.min.js?0614";setTimeout(function(){document.getElementsByTagName("head")[0].appendChild(M.showLoginBox.loginScript);},0);}},searchSuggest:{init:function(c,b){var a=this;a.data=a.data||{};a.data.obj=c;b=b||window.event;a.data.event=b;a.data.v=c.value;a.data.l=document.getElementById("JS_search_suggest");if(a.data.show&&(b.keyCode==38||b.keyCode==40)){a.data.focusOn=a.data.focusOn||0;a.data.arrow=b.keyCode-39;a.changeFocus();return false;}else{if(a.data.v===""){a.data.show=false;a.data.l.style.display="none";}else{a.get();}}},changeFocus:function(){var c=this;var b=c.data.focusOn+c.data.arrow;if(b>=0&&b<=c.data.jsonLength+3){var d=c.data.l.childNodes[b-1];for(var a=0;a<c.data.l.childNodes.length;a++){c.data.l.childNodes[a].className="";}if(!c.data.focusOn){c.data.oldValue=c.data.obj.value;}if(b>0){if(d.getAttribute("id")&&d.getAttribute("id").indexOf("none")===0){c.data.obj.value=c.data.oldValue;}else{c.data.obj.value=d.innerHTML;}d.className="current";}if(b===0){c.data.obj.value=c.data.oldValue;}c.data.focusOn=b;}},get:function(){var a=this;a.data.cache=a.data.cache||{};if(a.data.timer){clearTimeout(a.data.timer);}a.data.timer=setTimeout(function(){a.data.v=a.data.obj.value;if(a.data.v===""){return false;}if(a.data.cache[a.data.v]){a.response(a.data.cache[a.data.v]);}else{if(M.searchSuggest.ajaxHolder&&M.searchSuggest.ajaxHolder.request){M.searchSuggest.ajaxHolder.request.abort();}M.searchSuggest.ajaxHolder=M.ajax({url:"/search_suggest.html?act=search_suggest&k="+encodeURIComponent(a.data.v),dataType:"json",cache:true,success:function(b){a.data.cache[a.data.v]=b;a.response(b);M.searchSuggest.ajaxHolder=null;}});}},500);},response:function(b){var e=this;if(b&&b.length){e.data.focusOn=0;e.data.jsonLength=b.length;var d="";for(var a=0;a<b.length;a++){d+='<a href="/keywords/'+b[a].pinyin+'/" target="'+(window._SearchDoNotNewWindow?"_self":"_blank")+'" onmouseout="this.className=\'\'">'+b[a].keyword+"</a>";if(a===0){d+='<a id="none1" href="javascript:;" onclick="M.searchSuggest.getFormAction(0);">在<strong class="red">家具</strong>分类中搜索</a><a id="none2" href="javascript:;" onclick="M.searchSuggest.getFormAction(1);">在<strong class="red">建材</strong>分类中搜索</a><a id="none3" href="javascript:;" onclick="M.searchSuggest.getFormAction(2);">在<strong class="red">家居饰品</strong>分类中搜索</a>';}}e.data.show=true;e.data.l.innerHTML=d;e.data.l.style.display="block";if(!e.data.blinkEvent){var c=document.body;if(c.addEventListener){c.addEventListener("click",function(){e.hide();},false);}else{if(c.attachEvent){c.attachEvent("onclick",function(){e.hide();});}}e.data.blinkEvent=true;}}else{e.hide();}},getFormAction:function(a){var b=M.$("#JS_search_form");b.action="/category-9999/mcat0-scat0-b0-max0-min0-st"+a+"-attr-page-1-sort-sort_order-order-asc.html";b.setAttribute("target",window._SearchDoNotNewWindow?"_self":"_blank");b.submit();},hide:function(){var a=this;a.data.l.style.display="none";a.data.show=false;}},ajax:function(a){var b=this;return new b.ajax.prototype.init(a);},sendSms:function(b,a){return new this.sendSms.prototype.init(b,a);},orderQuery:function(c,a,b){M.orderQuery.orderSn=c;M.orderQuery.phone=a;if(b){M.orderQuery.callback=b;}if(M.orderQuery.loginScript&&window.Query){window.Query.show();}else{M.orderQuery.loginScript=document.createElement("script");M.orderQuery.loginScript.type="text/javascript";M.orderQuery.loginScript.src=M.__IMG+"/js/mll/order_query.min.js?0220";setTimeout(function(){document.getElementsByTagName("head")[0].appendChild(M.orderQuery.loginScript);},0);window._queryTmp=setInterval(function(){if(window.Query){window.Query.show();clearTimeout(window._queryTmp);}},500);}},costDownTip:function(a){if(M.costDown){M.costDown.init(a);}else{M.costDownTip.loginScript=document.createElement("script");M.costDownTip.loginScript.type="text/javascript";M.costDownTip.loginScript.src=M.__IMG+"/js/mll/costdowntip.min.js?0816";setTimeout(function(){document.getElementsByTagName("head")[0].appendChild(M.costDownTip.loginScript);},0);M.costDownTip.timer=setInterval(function(){if(M.costDown){M.costDown.init(a);clearTimeout(M.costDownTip.timer);}},100);}},offsetTop:function(c){var a=c;if(!c){return 0;}var b=0;while(a!=null&&a!=document.body){b+=a.offsetTop;a=a.offsetParent;}return b;},addToCart:function(e,c,d,b,a){M.showMask();if(M.toCart){M.toCart.init(e,c,d,b,a);}else{M.addToCart.loginScript=document.createElement("script");M.addToCart.loginScript.type="text/javascript";M.addToCart.loginScript.src=M.__IMG+"/js/mll/addtocart.min.js?0613";setTimeout(function(){document.getElementsByTagName("head")[0].appendChild(M.addToCart.loginScript);},0);M.addToCart.timer=setInterval(function(){if(M.toCart){M.toCart.init(e,c,d,b||"",a);clearTimeout(M.addToCart.timer);}},100);}},comment:function(a,c,b){if(M.comment.commentScript&&window.mllComment){window.mllComment.show(a,c);}else{M.comment.commentScript=document.createElement("script");M.comment.commentScript.type="text/javascript";M.comment.commentScript.src="http://image.meilele.com/js/mll/mll_comment.min.js";setTimeout(function(){document.getElementsByTagName("head")[0].appendChild(M.comment.commentScript);},0);window._commentTmp=setInterval(function(){if(window.mllComment){window.mllComment.show(a,c);clearTimeout(window._commentTmp);}},100);}if(typeof b=="function"){b();}},hash:function(c){if(M._hash&&!c){return M._hash;}M._hash={};var e=(location.hash+"").replace("#","");e=e.split("&");for(var a=0,d=e.length;a<d;a++){var b=e[a].split("=");M._hash[b[0]]=b[1];}return M._hash;}};M.ajax.prototype={init:function(c){var f=this;var g;f.type=c.type?c.type.toUpperCase():"GET";f.dataType=c.dataType||"html";f.success=c.success||false;f.error=c.error||false;f.url=c.url||"";f.data=c.data||"";f.cache=c.cache===false?false:true;f.request=f.getRequest();g=(f.url.indexOf("?")>-1)?"&":"?";if(M.typeOf(f.data)=="object"){var d="";for(var a in f.data){d+="&"+a+"="+f.data[a];}if(d){f.data=d.replace("&","");}d=null;}if(f.type=="GET"){f.url+=f.data?(g+f.data):"";}if(!f.cache){var b=new Date();b=b.getTime();f.url+=g+"_="+b;}if(f.request){var e=f.request;e.onreadystatechange=f.bindFunction(f.stateChange,f);e.open(f.type,f.url,true);if(f.type=="POST"){e.setRequestHeader("Content-type","application/x-www-form-urlencoded");e.send(f.data);}else{e.send(null);}}},getRequest:function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP");}else{if(window.XMLHttpRequest){return new XMLHttpRequest();}}return false;},bindFunction:function(b,a){return function(){return b.apply(a,[a]);};},stateChange:function(object){that=this;if(that.request.readyState==4){if(that.request.status==200){if(that.dataType=="json"){var json;try{if(typeof JSON==="object"){json=JSON.parse(that.request.responseText);}else{json=eval("("+that.request.responseText+")");}}catch(e){if(that.error){that.error();return false;}}if(typeof json==="object"){if(that.success){that.success(json,that.request.status,that.request);return true;}}else{if(that.error){that.error();return false;}}}else{if(that.success){that.success(that.request.responseText,that.request.status,that.request);return true;}}}else{if(that.error){that.error(that.request);return false;}}}}};M.ajax.prototype.init.prototype=M.ajax.prototype;M.sendSms.prototype={constructor:M.sendSms,bg:"http://image.meilele.com/images/zhuanti/upload/a_1374111909.gif",styleInserted:false,init:function(b,a){if(!b){return;}if(M._currentSendSmsBox){M._currentSendSmsBox.remove();}this.setting=M.extend({type:"exprAddress",phoneNumber:false,autoSend:false,autoClose:true},a);this.exprId=b;this.setStyleRule();this.dom=this.show();M._currentSendSmsBox=this;this.msgBox=M.$("#_JS_sndSms_msg_box_");this.inpt=M.$("#_JS_sndSms_input_");this.btn=M.$("#_JS_sndSms_btn_");this.captcha=M.$("#_JS_sndSms_captcha_");this.captchaImg=M.$("#_JS_sndSms_captchaImg_");if(this.setting.phoneNumber&&this.setting.autoSend){this.send();}this.getCaptcha(this.setting.captchaSrc);},setStyleRule:function(){if(!this.styleInserted){var a=[];var b;a.push(".sms_box {width:338px;padding-bottom:20px;border:5px solid #aaa;border-color:rgba(170,170,170,.8);background:#fff;margin:0px auto;overflow:hidden;}");a.push(".sms_content {padding-left:26px;padding-top:19px;}");a.push(".sms_input {width:205px;height:28px;border:1px solid #c1c1c1;padding:0;margin:0;color:#555;padding-left:5px;line-height:28px;}");a.push(".sms_captcha {width:34px;height:28px;border:1px solid #c7c7c7;padding:0;margin:0;vertical-align:top;color:#555;padding-left:5px;line-height:28px;}");a.push(".sms_content label {height:28px; line-height: 28px;}");a.push(".sms_submit {height:31px;background:#d00 url("+this.bg+") 0px 0px;width:81px;color:#fff;text-align:center;border:none;margin:0;padding:0;font-weight:bold;}");a.push(".sms_submit:hover {background-position: 0 -31px;}");try{b=document.createStyleSheet();b.cssText=a.join("");}catch(c){b=document.createElement("style");b.type="text/css";b.textContent=a.join("");document.getElementsByTagName("HEAD").item(0).appendChild(b);}this.styleInserted=true;}},show:function(){var a="请输入您的手机号";var b="";b+='<div class="sms_box" style="">';b+='<div class="clearfix" style="height:40px;line-height:40px;border-bottom:1px solid #dedede;padding-left:32px;color:#333;background:#f1f1f1 url('+this.bg+') -56px -62px no-repeat;"><div class="Left" style="font-size:16px;font-family:微软雅黑;">免费发送体验馆地址到手机</div><div class="Right" style="padding-right:10px;"><a style="font-size:18px;color:#909090;font-weight:bold;" href="javascript:;" onclick="M.closeLightBox(\'{=id}\');">×</a></div></div>';b+='<div class="sms_content" style="">';b+='<div><label for="_JS_sndSms_input_">手机号:</label><input class="sms_input" value="'+(this.setting.phoneNumber||a)+'" onfocus="if(this.value==\''+a+'\')this.value=\'\'" onkeypress="M._currentSendSmsBox.keyPress(event);" id="_JS_sndSms_input_" name="_JS_sndSms_input_" /></div>';b+='<div style="margin-top:10px;"><label for="_JS_sndSms_captcha_">验证码:</label><input class="sms_captcha" value="'+(this.setting.captcha||"")+'" onfocus="if(this.value==\'验证码\')this.value=\'\'" id="_JS_sndSms_captcha_" name="_JS_sndSms_captcha_" onkeypress="M._currentSendSmsBox.keyPress(event);" ><img src="http://image.meilele.com/themes/paipai/images/blank.gif" style="width:75px;margin-right:5px;height:30px;vertical-align:top;margin-left:8px;cursor:pointer" title="换一张" onclick="M._currentSendSmsBox.getCaptcha();return false;" id="_JS_sndSms_captchaImg_" /><input id="_JS_sndSms_btn_" type="button" style="" class="pointer sms_submit" onclick="M._currentSendSmsBox.send();" value=" " /></div>';b+='<div style="margin-top:20px;"><a href="/topic/meilelegw.html" target="_blank">关注美乐乐微信公众号,关注有好礼,100%中奖!</a></div>';b+='<div style="color:#454545;padding-top:10px;" id="_JS_sndSms_msg_box_"></div>';b+="</div>";b+="</div>";b+="";return M.lightBox(b,{},true);},getCaptcha:function(a){if(a){M._currentSendSmsBox.captchaImg.setAttribute("src",a);}else{M.ajax({url:"/user/?act=get_captcha",cache:false,success:function(b){M._currentSendSmsBox.captchaImg.setAttribute("src",b);}});}},remove:function(){if(M._currentSendSmsBox&&M._currentSendSmsBox.dom&&M._currentSendSmsBox.dom.parentNode){M._currentSendSmsBox.dom.parentNode.removeChild(M._currentSendSmsBox.dom);delete (M._currentSendSmsBox);}},send:function(){var c=parseInt(M._currentSendSmsBox.inpt.value.replace(/\D/g,""),10);var b=M._currentSendSmsBox.captcha.value;M._currentSendSmsBox.inpt.value=c||"";if(!c){M._currentSendSmsBox.msg("请输入正确手机号码。");return;}if(!b||b=="验证码"){M._currentSendSmsBox.msg("请输入正确验证码。");return;}M._currentSendSmsBox.msg("发送中...");M._currentSendSmsBox.btn.disabled=true;var d={};for(var a in M._currentSendSmsBox.setting){if(a!="captcha"&&a!=="captchaSrc"&&typeof M._currentSendSmsBox.setting[a]!="object"&&typeof M._currentSendSmsBox.setting[a]!="function"){d[a]=M._currentSendSmsBox.setting[a];}}M.ajax({url:"/ajax_ajax.html?act=send_expr_message&expr_id="+M._currentSendSmsBox.exprId+"&mobile="+c+"&captcha="+b+"&url="+encodeURIComponent(location.href),data:d,type:"get",dataType:"json",success:function(e){M._currentSendSmsBox.getCaptcha();if(e.error=="0"){var f=M.getCookie("MLLFROM");window._gaq=window._gaq||[];_gaq.push(["_trackEvent","sms",M._currentSendSmsBox.setting.type,((M.getCookie("MLLFROM")||M.getCookie("MLLSEO"))+"_undefined").split("_")[0]+(M._currentSendSmsBox.setting.click?("_"+M._currentSendSmsBox.setting.click):"")]);if(M._currentSendSmsBox.setting.autoClose){e.msg+="<br />本窗口将在2秒后自动关闭。";setTimeout(M._currentSendSmsBox.remove,4000);}M._currentSendSmsBox.msg(e.msg,true);if(M._currentSendSmsBox.setting.success){M._currentSendSmsBox.setting.success(e);}}else{M._currentSendSmsBox.msg(e.msg);M._currentSendSmsBox.btn.disabled=false;}},error:function(){M._currentSendSmsBox.getCaptcha();M._currentSendSmsBox.msg("发送失败");M._currentSendSmsBox.btn.disabled=false;}});},msg:function(b,c){var a=c?"-42":"-27";b='<span style="display:inline-block;vertical-align:middle;width:14px;height:14px;background:url('+this.bg+") "+a+'px -65px;margin-right:6px;"></span><span style="vertical-align:middle;color:#f24443;">'+b+"</span>";M._currentSendSmsBox.msgBox.innerHTML=b;},keyPress:function(a){a=a||window.event;if(a.keyCode==13){M._currentSendSmsBox.send();}}};M.sendSms.prototype.init.prototype=M.sendSms.prototype;function MLLBanner(lists,setting){if(!(lists&&lists.length)){return false;}var banner=[],doc=document,tmpId=(new Date()).getTime().toString(36),length=lists.length,now,next,over,outStep,inStep,countList=[],focus=true,must=false;var defaultSetting={width:1190,height:60,domId:"JS_banner",delay:6000,inTimer:600,outTimer:300,stepTimer:40};var timeDefaultSetting={content:"$D天 $H:$I:$S",style_position:"absolute","style_margin-left":"600px","style_margin-top":"15px","style_font-size:":"16px"};setting=mergeSetting(defaultSetting,setting);var bannerDom=doc.getElementById(setting.domId);if(!bannerDom){return false;}bannerDom.style.display="block";outStep=100/(setting.outTimer/setting.stepTimer);inStep=100/(setting.inTimer/setting.stepTimer);var Banner=function(info,key){this.info=info||[];this.key=key;this.opacity=0;this.createHTML();};Banner.prototype={createHTML:function(){this.html='<div id="JS_banner_box_'+this.key+"_"+tmpId+'" style="display:none;background:url(http://image.meilele.com/themes/paipai/images/loading.gif) center center no-repeat;filter:alpha(opacity=100);'+(window.LOAD?"":"margin-left:-105px;")+'">';if(this.info[3]){try{eval("this.info[3]="+this.info[3]);}catch(e){}if(this.info[3]&&typeof this.info[3]=="object"&&this.info[3].endTime){this.timeSetting=mergeSetting(timeDefaultSetting,this.info[3]);this.timeSetting.timeLeft=toSecond(this.timeSetting.endTime)-(new Date()).getTime();countList.push([this.key,this.timeSetting]);this.html+='<div style="'+styleToString(this.timeSetting)+'" id="JS_banner_time_'+this.key+"_"+tmpId+'"></div>';}}this.html+='<a id="JS_banner_link_'+this.key+"_"+tmpId+'" href="'+(this.info[1]||"/")+'" title="'+(this.info[2]||"")+'" target="_blank"><img id="JS_banner_img_'+this.key+"_"+tmpId+'" src="'+this.info[0]+'" width="'+setting.width+'" height="'+setting.height+'"></a>';this.html+="</div>";},changeOpacity:function(to){M.changeOpacity(this.box,to,true);this.opacity=to;}};function mergeSetting(defaultSetting,setting){setting=setting||{};for(var k in defaultSetting){if(setting[k]===undefined){setting[k]=defaultSetting[k];}}return setting;}function switchBanner(){if(over&&!must){return;}if(!focus&&!must){return;}next=(now+1)%length;if(banner[now].opacity>0){banner[now].changeOpacity(banner[now].opacity-outStep);must=true;setTimeout(switchBanner,setting.stepTimer);}else{if(banner[next].opacity<100){banner[next].changeOpacity(banner[next].opacity+outStep);must=true;setTimeout(switchBanner,setting.stepTimer);}else{must=false;now=next;}}}function styleToString(style){var r=[];for(var key in style){if(key.indexOf("style_")===0){r.push(key.replace("style_","")+":"+style[key]);}}return r.join(";");}function toSecond(string){var t=string.split("-");var d=new Date(t[0],parseInt(t[1],10)-1,t[2]);return d.getTime();}function count(){for(var k=0,kk=countList.length;k<kk;k++){var c=countList[k];if(c&&banner[c[0]]&&banner[c[0]].time){var dom=banner[c[0]].time;c[1].timeLeft-=1000;if(c[1].timeLeft<=0){c[1].timeLeft=0;}dom.innerHTML=fixTime(c[1]);}}}function fixTime(time){var sec=parseInt(time.timeLeft/1000,10);if(sec<0){sec=0;}var s=sec%60;if(s<10){s="0"+s;}var m=parseInt(sec%3600/60,10);if(m<10){m="0"+m;}var h=parseInt(sec%(3600*24)/3600,10);if(h<10){h="0"+h;}var d=parseInt(sec/(3600*24),10);if(time.content.indexOf("$D")<0){h=(d*24)-0+(h-0);}return time.content.replace("$D",d).replace("$H",h).replace("$I",m).replace("$S",s);}var h="";for(var k=0,kk=length;k<kk;k++){banner[k]=new Banner(lists[k],k);h+=banner[k].html;}bannerDom.innerHTML=h;bannerDom.onmouseover=function(){over=true;};bannerDom.onmouseout=function(){over=false;};for(var k=0,kk=length;k<kk;k++){banner[k].box=doc.getElementById("JS_banner_box_"+k+"_"+tmpId);banner[k].link=doc.getElementById("JS_banner_link_"+k+"_"+tmpId);banner[k].img=doc.getElementById("JS_banner_img_"+k+"_"+tmpId);banner[k].time=doc.getElementById("JS_banner_time_"+k+"_"+tmpId);if(!k){banner[k].opacity=100;banner[k].box.style.display="block";now=k;}}if(countList.length){setInterval(count,1000);}if(length>1){setInterval(switchBanner,setting.delay);}}(function(d,c,e){e=e||{};var a=document.body,b=c.getElementsByTagName("head")[0];e.typeOf=function(f){return typeof f;};e.extend=function(i,g){i=i||{};g=g||{};for(var f in g){i[f]=g[f];}return i;};e.addHandler=function(k,j,i,g){function f(m){var l=m?m:window.event;l.target=m.target||m.srcElement;return i.apply(g||this,arguments);}k.eventHash=k.eventHash||{};(k.eventHash[j]=k.eventHash[j]||[]).push({name:j,handler:i,fn:f,scope:g});if(k.addEventListener){k.addEventListener(j,f,false);}else{if(k.attachEvent){k.attachEvent("on"+j,f);}else{k["on"+j]=f;}}};e.removeHandler=function(m,l,k,j){m.eventHash=m.eventHash||{};var i=m.eventHash[l]||[],g=i.length;if(g>0){for(;g--;){var f=i[g];if(f.name==l&&f.handler===k&&f.scope===j){if(m.removeEventListener){m.removeEventListener(l,f.fn,false);}else{if(m.detachEvent){m.detachEvent("on"+l,f.fn);}else{m["on"+l]=null;}}i.splice(g,1);break;}}}};e.inArray=function(j,l){var g=-1;if(j&&l&&l.length){for(var f=0,i=l.length;f<i;f++){if(j==l[f]){return f;}}}return g;};e.$=function(f,j){var l;if(!f){return false;}if(j===undefined){j=document;}if(e.typeOf(j)==="string"){j=e.$(j);}if(!j){return false;}if(f.indexOf("#")===0){l=j.getElementById(f.substr(1));}else{if(f.indexOf(".")===0){if(j.getElementsByClassName&&0){l=j.getElementsByClassName(f.replace(".",""));}else{l=[];all=j.getElementsByTagName("*");for(var g=0;g<all.length;g++){var k=all[g];var m=k.className;if(m){m=m.split(/\s/g);if(e.inArray(f.replace(".",""),m)>=0){l.push(k);}}}}}else{l=j.getElementsByTagName(f);}}return l;};e.addClass=function(g,i){if(g){if(g&&g.classList&&g.classList.add){i=i.split(/\s/g);for(var f=0;f<i.length;f++){g.classList.add(i[f]);}}else{var j=(g.className+"").split(/\s/g)||[];if(e.inArray(i,j)==-1){j.push(i);g.className=j.join(" ");}}}return g;};e.removeClass=function(l,m){if(l&&l.classList&&l.classList.remove){m=m.split(/\s/g);for(var f=0;f<m.length;f++){l.classList.remove(m[f]);}}else{if(m&&typeof m=="string"&&l&&typeof l.className=="string"){var g=l.className.split(/\s/g);var i=[];if(g&&g.length){for(var f=0,j=g.length;f<j;f++){if(g[f]!=m){i.push(g[f]);}}}l.className=i.join(" ");}}return l;};e.bindFunction=function(i,f){var g=Array.prototype.slice.call(arguments).slice(2);return function(){return f.apply(i,g.concat(Array.prototype.slice.call(arguments)));};};})(window,document,window.M);window.requestAnimFrame=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(b,a){window.setTimeout(b,1000/60);};})();M.Animate=function(c,a,b,e,d){return new M.Animate.prototype.init(c,a,b,e,d);};M.Animate.prototype={init:function(e,c,d,g,f){var b=/opacity\s*=\s*([^)]*)/;this.dom=e;this.time=d||300;this.preTime=10;this.list=c;this.callback=f;this.tweenType=g||"easeInOut";this._d=Math.ceil(this.time/this.preTime);this._t=0;this._c={};this._b={};for(var a in this.list){this._b[a]=parseFloat(("opacity|".indexOf(a+"|")>-1&&e.currentStyle)?(b.test(e.currentStyle.filter)?(0.01*parseFloat(RegExp.$1)):1):(this.currentStyle()[a]||0));this._c[a]=parseFloat(this.list[a])-this._b[a];}if(this.dom._animate){this.dom._animate.stop();}this.run();this.dom._animate=this;},currentStyle:function(){var a=this.dom;return a.currentStyle||document.defaultView.getComputedStyle(a,null);},run:function(){if(this._t>this._d){if(M.typeOf(this.callback)=="function"){this.callback();}return;}else{if(this._stop){return;}else{for(var a in this.list){var b=this.tween[this.tweenType](this._t,this._b[a],this._c[a],this._d)+(("opacity|".indexOf(a+"|")>-1)?"":"px");this.dom.style[a]=b;if("opacity|".indexOf(a+"|")>-1){this.dom.style.filter="alpha(opacity="+b*100+")";}}this._t++;requestAnimFrame(M.bindFunction(this,this.run),this.preTime);}}},stop:function(){this._stop=true;},tween:{easeIn:function(e,a,g,f){return g*(e/=f)*e*e*e+a;},easeOut:function(e,a,g,f){return -g*((e=e/f-1)*e*e*e-1)+a;},easeInOut:function(e,a,g,f){if((e/=f/2)<1){return g/2*e*e*e*e+a;}return -g/2*((e-=2)*e*e*e-2)+a;},linear:function(e,a,g,f){return g*e/f+a;}}};M.Animate.prototype.init.prototype=M.Animate.prototype;var taobao=1;function static_dynamic(page_sn){var dom=document.getElementById("static_dynamic");if(!dom){return;}page_sn=dom.getAttribute("page_sn");if(typeof page_sn=="undefined"||!page_sn||page_sn.length===0){var href=location.href;if(href.substr(-4)==".com"||href.substr(-4)=="com/"){page_sn="index";}else{if(href.indexOf("category-")!=-1){if(href.indexOf("goods-")>href.indexOf("category-")){page_sn="goods";}else{page_sn="category";}}else{if(href.indexOf("article_cat")!=-1){if(href.indexOf("article-")>href.indexOf("article_cat")){page_sn="article";}else{page_sn="article_cat";}}}}}var url="/ajax_static_dynamic/?nojs&page_sn="+page_sn;goods_id=dom.getAttribute("goods_id");rgn_id=dom.getAttribute("rgn_id");debug=dom.getAttribute("debug");if(typeof goods_id!="undefined"&&goods_id&&goods_id>0){url=url+"&goods_id="+goods_id;}if(typeof rgn_id!="undefined"&&rgn_id&&rgn_id>0){url=url+"&rgn_id="+rgn_id;}if(typeof debug!="undefined"&&debug&&debug>0){url=url+"&debug=1";}M.ajax({url:url,dataType:"json",data:window._STATIC_DATA_||null,cache:false,success:function(json){var tmp={};for(var k in json){var callback=null;var key=json[k].node_name;if(key){tmp[key]=json[k];}if(json[k].node_name&&json[k].html_content.toString().length&&document.getElementById(json[k].node_name)){document.getElementById(json[k].node_name).innerHTML=json[k].html_content;}if(json[k].js_call_func_name){try{callback=eval(json[k].js_call_func_name);}catch(e){}if(callback&&typeof callback=="function"){callback(json[k]);}}}if(window._STATIC_DYNAMIC_CALLBACK&&typeof window._STATIC_DYNAMIC_CALLBACK=="function"){window._STATIC_DYNAMIC_CALLBACK(tmp);}}});return true;}M.lazyImg={domList:{},waitList:[],downList:[],status:0,loader:false,start:function(b,a){if(this.status>1){return;}this.status=1;this.type=b;this.setting=M.extend({scrollTimer:300,defaultLimit:30,attributeTag:"data-src",loaderNumber:4,offset:50,callback:null},a);this.init();},init:function(){this.initDomList();if(!this.type||parseInt(this.type,10)>0){this.setRealType();}if(this.type=="scroll"||this.type=="both"){this.initDomOffsetTop();this.initEvent();this.scrollResponse();}else{this.prepend(this.domList);}},setRealType:function(){if(!this.type){this.type=this.setting.defaultLimit;}if(parseInt(this.type,10)>0){this.type=(this.domListLength>=this.type)?"both":"lazy";}},initDomList:function(){this.domListLength=0;var f=document.images;var e;for(var a=0,d=f.length;a<d;a++){if(Object.prototype.toString.apply(this.setting.attributeTag)==="[object Array]"){loopin:for(var b=0,c=this.setting.attributeTag.length;b<c;b++){e=f[a].getAttribute(this.setting.attributeTag[b]);if(e){break loopin;}}}else{e=f[a].getAttribute(this.setting.attributeTag);}if(f[a]&&e){this.domList["init_"+a]={target:f[a],src:e};this.domListLength++;}}},initDomOffsetTop:function(){for(var a in this.domList){if(this.domList[a]&&this.domList[a].target){this.domList[a]._offsetTop=M.offsetTop(this.domList[a].target);}}},initEvent:function(){M.addHandler(window,"scroll",M.lazyImg.scrollResponse);M.addHandler(window,"resize",M.lazyImg.scrollResponse);},scrollResponse:function(){var a=M.lazyImg;if(window.scrollTimer){clearTimeout(window.scrollTimer);}window.scrollTimer=window.setTimeout(function(){var d=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0;var c=[];for(var b in a.domList){if(d+document.documentElement.clientHeight+a.setting.offset>a.domList[b]._offsetTop&&d-a.setting.offset<a.domList[b]._offsetTop+(a.domList[b].target.height||a.domList[b].target.cilentHeight)){c.push(a.domList[b]);delete a.domList[b];}}a.prepend(c);c=null;},a.setting.scrollTimer);},prepend:function(a){if(this.status==="0"){this.start();}a=this.formatImglist(a);this.concatList(a,this.waitList);},append:function(a){if(this.status==="0"){this.start();}a=this.formatImglist(a);this.concatList(this.waitList,a);},formatImglist:function(c){c=c||[];var b=[];for(var a in c){if(typeof c[a]=="string"){c[a]={src:c[a]};}b.push(c[a]);}return b;},concatList:function(){this.waitList=Array.prototype.concat.apply([],arguments);if(this.waitList.length>0){this.startLoad();}},initLoader:function(){this.loader=[];for(var a=0;a<this.setting.loaderNumber;a++){this.loader.push(new this.Loader(a));}},checkAllLoaderIsReset:function(){var b=true;for(var a=0;a<this.loader.length;a++){if(this.loader[a].status=="1"){return false;}}return b;},startLoad:function(){if(!this.loader){this.initLoader();arguments.callee.apply(this);return;}for(var a=0,b=this.loader.length;a<b;a++){this.loader[a].run();}},Loader:function(a){this.key=a;this.run();},loadPrototype:{run:function(){if(this.status==1||!M.lazyImg.waitList[0]){return;}this.job=M.lazyImg.waitList.shift();if(this.job&&this.job.src){this.status=1;this.img=new Image;this.img.loaderKey=this.key;this.img.onload=this.img.onerror=function(){var a=this.loaderKey;setTimeout(function(){M.lazyImg.onloadResponse(a);},0);this.onload=this.onerror=null;};this.img.src=this.job.src;}else{this.run();}}},onloadResponse:function(e){var a=M.lazyImg.loader[e];if(a.job.target&&a.job.src){a.job.target.setAttribute("src",a.job.src);}a.status=2;var b=true;if(M.lazyImg.type=="scroll"||M.lazyImg.type=="both"){var d=[];loop:for(var c in M.lazyImg.domList){if(M.lazyImg.type=="both"&&M.lazyImg.waitList.length===0){d.push(M.lazyImg.domList[c]);delete M.lazyImg.domList[c];}b=false;break loop;}Array.prototype.unshift.apply(M.lazyImg.waitList,d);d=null;if(b){M.removeHandler(window,"scroll",M.lazyImg.scrollResponse);M.removeHandler(window,"resize",M.lazyImg.scrollResponse);}}if(b&&typeof M.lazyImg.setting.callback=="function"&&!M.lazyImg.waitList[0]&&!M.lazyImg.called&&M.lazyImg.checkAllLoaderIsReset()){M.lazyImg.setting.callback();M.lazyImg.called=true;}a.run();}};M.lazyImg.Loader.prototype=M.lazyImg.loadPrototype;M.changeOpacity=function(b,c,a){if(b.filters){b.filters.alpha.opacity=c;}else{b.style.opacity=c/100;}if(a){if(c<=0){b.style.display="none";}else{b.style.display="block";}}};function _INIT_HEAD_PHONE_SCROLL_(){var a=document.getElementById("JS_header_phone");if(!a){return;}a.innerHTML+="<br>"+a.innerHTML;_HEAD_PHONE_SCROLL_();}function _HEAD_PHONE_SCROLL_(){var c=document.getElementById("JS_header_phone");if(!c){return;}var b=20;var d=c.innerHTML.toLowerCase().split(/<br\s?\/?>/g).length;var a=(parseInt(c.style.marginTop,10)||0)-1;if(a<0-b*d/2){a=-1;}c.style.marginTop=a+"px";if(a%b){setTimeout(_HEAD_PHONE_SCROLL_,20);}else{setTimeout(_HEAD_PHONE_SCROLL_,5000);}}M.ad=M.ad2=function(tags,setting){var defaultTemplate='<a href="<%=ad[0].url%>" title="<%=ad[0].desc%>" target="<%=ad[0].target%>"><img src="<%=ad[0].src%>" width="<%=width%>" height="<%=height%>" alt="<%=ad[0].desc%>" /></a>';var fill=function(d){M.ad._data=d;d.template=d.template||defaultTemplate;d.template=d.template.replace(/<\%=(.*?)%\>/g,function($0,$1){return eval("M.ad._data."+$1);});d.dom.innerHTML=d.template;};setting=setting||{};var ck=M.getCookie("MLL_AD");var tag=setting.tag||ck||setting.defaultTag;var tagId=[];try{tag=encodeURIComponent(tag).replace(/%/g,"");}catch(e){}if(!tag||tag=="undefined"||tag=="null"){tag="DEFAULT";}for(var k in tags){if(tags[k]&&tags[k].dom){tagId.push(k);}}M.ajax({url:"/ad_img/"+tag+"/"+tagId.join("_")+"/",dataType:"json",success:function(json){for(var k in json){if(json[k]&&json[k].length&&tags[k]){var d=tags[k];var v=json[k];d.ad=v;if(!d.notFill){fill(d);}if(d.callback){d.callback(v);}}}}});};M.addHandler(window,"load",_RUNNING_LOAD_SCRIPT_);
/*LDZ:2013-07-18 17:43:32*/ | 17,738.5 | 35,449 | 0.724216 |
8b46484c14fbaf2f313c5a27a2404b09c7988c79 | 1,470 | js | JavaScript | script.js | malikbenkirane/42.d9dit | 734c425ed3f09a90561b46a0e8fed7e6eebfe9d5 | [
"MIT"
] | null | null | null | script.js | malikbenkirane/42.d9dit | 734c425ed3f09a90561b46a0e8fed7e6eebfe9d5 | [
"MIT"
] | null | null | null | script.js | malikbenkirane/42.d9dit | 734c425ed3f09a90561b46a0e8fed7e6eebfe9d5 | [
"MIT"
] | null | null | null | var webPage = require('webpage');
var pages = [];
/*
var id = '02';
target = {
'url': 'https://projects.intra.42.fr/piscine-c-day-09-' + id + '/mine',
'id': id
};
*/
var timeout = 20000;
var main_page = require('webpage').create();
console.log('User agent : ' + main_page.settings.userAgent);
main_page.open('https://intra.42.fr', function(status) {
if (status !== 'success') {
console.log('Unable to access');
} else {
console.log('Login Prompted ..')
main_page.evaluate(function() {
ilogin = document.getElementById('user_login');
ipassw = document.getElementById('user_password');
ilogin.value = 'USER_LOGIN';
ipassw.value = 'HIDDENPASSWORD';
signin_button = document.querySelector('input.btn.btn-login');
signin_button.click();
});
setTimeout(function() {
main_page.evaluate(function() {
document.location.href = TARGET_URL;
});
setTimeout(function() {
main_page.render('screen'+TARGET_ID+'.png');
href = main_page.evaluate(function() {
return document.querySelector('a[href$=".pdf"]').href;
});
console.log(href);
phantom.exit();
}, timeout);
}, 6000);
}
});
/*
setTimeout(function() {
page.evaluate(function() {
document.location.href = 'https://projects.intra.42.fr/piscine-c-day-09-04/mine';
});
page.open();
});
*/
| 27.222222 | 84 | 0.57483 |
8b46601f156aa46870633a6150b995090153d529 | 5,735 | js | JavaScript | test/needle-api/needle-client-react-mobx.spec.js | yeoman-projects/generator-jhipster-react-mobx | b10a1b8cfe173590406a9781459cc5ad8e26f177 | [
"Apache-2.0"
] | null | null | null | test/needle-api/needle-client-react-mobx.spec.js | yeoman-projects/generator-jhipster-react-mobx | b10a1b8cfe173590406a9781459cc5ad8e26f177 | [
"Apache-2.0"
] | null | null | null | test/needle-api/needle-client-react-mobx.spec.js | yeoman-projects/generator-jhipster-react-mobx | b10a1b8cfe173590406a9781459cc5ad8e26f177 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Erki Ehtla.
*
* 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.
*/
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const constants = require('generator-jhipster/generators/generator-constants');
const ClientGenerator = require('../../generators/client');
const REACT = constants.SUPPORTED_CLIENT_FRAMEWORKS.REACT;
const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const mockBlueprintSubGen = class extends ClientGenerator {
constructor(args, opts) {
super(args, { fromBlueprint: true, ...opts }); // fromBlueprint variable is important
const jhContext = (this.jhipsterContext = this.options.jhipsterContext);
if (!jhContext) {
this.error('This is a JHipster blueprint and should be used only like jhipster --blueprints myblueprint');
}
this.configOptions = jhContext.configOptions || {};
// This sets up options for this sub generator and is being reused from JHipster
jhContext.setupEntityOptions(this, jhContext, this);
}
get initializing() {
return super._initializing();
}
get prompting() {
return super._prompting();
}
get configuring() {
return super._configuring();
}
get default() {
return super._default();
}
get writing() {
const phaseFromJHipster = super.writing;
const customPhaseSteps = {
addAppCssStep() {
// please change this to public API when it will be available see https://github.com/jhipster/generator-jhipster/issues/9234
this.addAppSCSSStyle('@import without-comment');
this.addAppSCSSStyle('@import with-comment', 'my comment');
},
addEntityToMenuStep() {
this.addEntityToMenu('routerName', false, REACT, false);
},
addEntityToModuleStep() {
this.addEntityToModule(
'entityInstance',
'entityClass',
'entityName',
'entityFolderName',
'entityFileName',
'entityUrl',
REACT,
'microServiceNam'
);
}
};
return { ...phaseFromJHipster, ...customPhaseSteps };
}
};
describe('needle API React: JHipster client generator with blueprint', () => {
before(done => {
helpers
.run('generator-jhipster/generators/client')
.withOptions({
'from-cli': true,
build: 'maven',
auth: 'jwt',
db: 'mysql',
skipInstall: true,
blueprint: 'myblueprint',
skipChecks: true,
skipServer: true
})
.withGenerators([
[mockBlueprintSubGen, 'jhipster-myblueprint:client', path.join(__dirname, '../../generators/client/index.js')]
])
.withPrompts({
baseName: 'jhipster',
clientFramework: REACT,
enableTranslation: true,
nativeLanguage: 'en',
languages: ['en', 'fr']
})
.on('end', done);
});
it('Assert entity is added to menu', () => {
assert.fileContent(
`${CLIENT_MAIN_SRC_DIR}app/shared/layout/menus/entities.tsx`,
'<MenuItem icon="asterisk" to="/routerName">\n Router Name\n </MenuItem>'
);
});
it('Assert entity is added to module', () => {
const indexModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/index.tsx`;
const indexReducerPath = `${CLIENT_MAIN_SRC_DIR}app/shared/reducers/index.ts`;
const indexStorePath = `${CLIENT_MAIN_SRC_DIR}app/shared/stores/createStore.ts`;
assert.noFile(indexReducerPath);
assert.fileContent(indexModulePath, "import entityName from './entityFolderName';");
assert.fileContent(indexModulePath, '<ErrorBoundaryRoute path={`${match.url}entityFileName`} component={entityName} />'); // eslint-disable-line
assert.fileContent(
indexStorePath,
'// prettier-ignore\n' +
'import entityInstance, {\n' +
' entityNameStore\n' +
"} from 'app/entities/entityFolderName/entityFileName.store';"
);
assert.fileContent(indexStorePath, 'readonly entityInstanceStore: entityNameStore;');
assert.fileContent(indexStorePath, 'rootStore.entityInstanceStore = new entityNameStore(rootStore);');
});
it('Assert app.scss is updated', () => {
assert.fileContent(`${CLIENT_MAIN_SRC_DIR}app/app.scss`, '@import without-comment');
assert.fileContent(`${CLIENT_MAIN_SRC_DIR}app/app.scss`, '@import with-comment');
assert.fileContent(
`${CLIENT_MAIN_SRC_DIR}app/app.scss`,
'* ==========================================================================\n' +
'my comment\n' +
'========================================================================== */\n'
);
});
});
| 38.233333 | 152 | 0.57524 |
8b4881df5beb046fad662e533012f5deb3d91b12 | 108 | js | JavaScript | src/components/Reusable/SpanP.js | TypeTech/typetech.org | 8847be2d5926cc8fa96761b7cd3e43d5c0e613d3 | [
"MIT"
] | null | null | null | src/components/Reusable/SpanP.js | TypeTech/typetech.org | 8847be2d5926cc8fa96761b7cd3e43d5c0e613d3 | [
"MIT"
] | 1 | 2020-09-23T00:19:28.000Z | 2020-09-23T00:19:28.000Z | src/components/Reusable/SpanP.js | TypeTech/website | 8847be2d5926cc8fa96761b7cd3e43d5c0e613d3 | [
"MIT"
] | null | null | null | import styled from '@emotion/styled'
const SpanP=styled.span`
color: #007bb7;
`;
export default SpanP; | 15.428571 | 36 | 0.722222 |
8b48f29f6bf6e19194a19cb5a0aceaa2d4585bb4 | 927 | js | JavaScript | 0003_longestSubstringWithoutRepeatingCharacters.js | charlesbuczel/leetcode.js | 0f5917ea146e94c1981a1aa977734d3424347354 | [
"MIT"
] | 3 | 2017-04-25T00:08:44.000Z | 2022-01-09T00:03:23.000Z | 0003_longestSubstringWithoutRepeatingCharacters.js | charlesbuczel/leetcode.js | 0f5917ea146e94c1981a1aa977734d3424347354 | [
"MIT"
] | null | null | null | 0003_longestSubstringWithoutRepeatingCharacters.js | charlesbuczel/leetcode.js | 0f5917ea146e94c1981a1aa977734d3424347354 | [
"MIT"
] | 1 | 2022-02-15T10:50:11.000Z | 2022-02-15T10:50:11.000Z | /**
* @param {string} s Input string.
* @return {number} Length of longest substring without repeating characters.
* @summary Longest Substring Without Repeating Characters {@link https://leetcode.com/problems/longest-substring-without-repeating-characters/}
* @description Given a string, find length of its longest substring without repeating characters.
* Space O(n) - hash object storing data will have no more than n elements.
* Time O(n) - one iteration of n elements.
*/
const lengthOfLongestSubstring = s => {
const charMap = {};
let maxLength = 0;
let currentStart = 0;
for (let index = 0; index < s.length; index++) {
const c = s[index];
if (charMap[c] !== undefined && charMap[c] >= currentStart) {
maxLength = Math.max(maxLength, index - currentStart);
currentStart = charMap[c] + 1;
}
charMap[c] = index;
}
return Math.max(maxLength, s.length - currentStart);
};
| 34.333333 | 144 | 0.686084 |
8b495525ab3dedae535e03f1ebe49b7db5cf82e2 | 148 | js | JavaScript | covid-frontend/src/components/common/index.js | mfleming99/COVID-QA | 53808624a3c9736e4096c7a4a6e48ba03889bc61 | [
"Apache-2.0"
] | 336 | 2020-03-17T12:46:42.000Z | 2022-03-24T14:54:19.000Z | covid-frontend/src/components/common/index.js | mfleming99/COVID-QA | 53808624a3c9736e4096c7a4a6e48ba03889bc61 | [
"Apache-2.0"
] | 81 | 2020-03-20T17:13:25.000Z | 2022-03-02T14:53:38.000Z | covid-frontend/src/components/common/index.js | mfleming99/COVID-QA | 53808624a3c9736e4096c7a4a6e48ba03889bc61 | [
"Apache-2.0"
] | 142 | 2020-03-20T17:24:26.000Z | 2022-02-22T07:25:32.000Z | export { default as InputContainer } from './InputContainer';
export { default as Tag } from './Tag';
export { default as Loader } from './Loader';
| 37 | 61 | 0.695946 |
8b49b4cab09eeef1203b8f5ab7485630fbed844f | 612 | js | JavaScript | src/components/CardList.js | DarkRoastOtter/Robofriends | 77fcc95559f41f9d9ff24cdc6db959b34f3e16d8 | [
"MIT"
] | null | null | null | src/components/CardList.js | DarkRoastOtter/Robofriends | 77fcc95559f41f9d9ff24cdc6db959b34f3e16d8 | [
"MIT"
] | null | null | null | src/components/CardList.js | DarkRoastOtter/Robofriends | 77fcc95559f41f9d9ff24cdc6db959b34f3e16d8 | [
"MIT"
] | null | null | null | import React from 'react';
import Card from './Card';
const CardList = ({ Robots }) => {
return (
<div>
{
Robots.map((user, id) => {
return (
<Card
key={id}
id={Robots[id].id}
name={Robots[id].name}
email={Robots[id].email}
username={Robots[id].username}
/>
);
})
}
</div>
)
}
export default CardList; | 25.5 | 58 | 0.310458 |
8b49daad49fb0313dca876319ddd0ff10c8b625f | 1,109 | js | JavaScript | src/org/credentialengine/ProficiencyScale.js | cassproject/cass-npm | bd399d69d464d5fc42039fe9deb736013fff87cd | [
"Apache-2.0"
] | null | null | null | src/org/credentialengine/ProficiencyScale.js | cassproject/cass-npm | bd399d69d464d5fc42039fe9deb736013fff87cd | [
"Apache-2.0"
] | 95 | 2018-04-20T15:57:41.000Z | 2022-03-30T02:04:13.000Z | src/org/credentialengine/ProficiencyScale.js | gloverkari/cass-npm | 96e14eeca654679b3cf941608cc3d7f13d46e8c9 | [
"Apache-2.0"
] | 2 | 2017-10-02T20:29:06.000Z | 2021-04-30T15:09:54.000Z | /**
* credentialengine.org/ProficiencyScale
* The class of structured profiles describing discrete levels of expertise and performance mastery.
* Proficiency scales define levels of performance (what a person does) as distinct from knowledge of specific information (what a person knows) and outline tasks a person can manage and the skills necessary to progressively accomplish explicit competencies at increasing levels of complexity. Proficiency scales: (1) assist in making judgments about the kinds of tasks related to a competency that a person is able to perform; and (2) to compare the abilities of different persons with regard to achievement of those competencies at different levels.
* @author credentialengine.org
* @class ProficiencyScale
* @module org.credentialengine
* @extends EducationalFramework
*/
module.exports = class ProficiencyScale extends EcRemoteLinkedData {
/**
* Constructor, automatically sets @context and @type.
* @constructor
*/
constructor() {
super();
this.setContextAndType(
"http://schema.eduworks.com/simpleCtdl",
"ProficiencyScale"
);
}
};
| 48.217391 | 551 | 0.780884 |
8b4a2597f51aba8af35ce8696049ed1306680f92 | 936 | js | JavaScript | src/store/index.js | antoineFrau/video-game-website | de829631574746f32ce506cadbe8eccfeda3fa12 | [
"MIT"
] | 1 | 2019-03-02T15:36:57.000Z | 2019-03-02T15:36:57.000Z | src/store/index.js | antoineFrau/video-game-website | de829631574746f32ce506cadbe8eccfeda3fa12 | [
"MIT"
] | null | null | null | src/store/index.js | antoineFrau/video-game-website | de829631574746f32ce506cadbe8eccfeda3fa12 | [
"MIT"
] | null | null | null | import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
connected: false,
userid: '',
username: ''
},
plugins: [
createPersistedState({
paths: ['connected', 'userid', 'username'],
getState: (key) => Cookies.getJSON(key),
setState: (key, state) => Cookies.set(key, state, {expires: 365})
})
],
mutations: {
logout (state) {
state.connected = false
state.userid = ''
state.username = ''
},
login (state, user) {
state.connected = true
state.userid = user.id
state.username = user.name
}
},
getters: {
doesConnected (state) {
return state.connected
},
getUserId (state) {
return state.userid
},
getUserName (state) {
return state.username
}
}
})
| 20.8 | 71 | 0.588675 |
8b4b0ba609c288ea15079728d737667f5bbaf22c | 1,188 | js | JavaScript | demo/gui/transform3d/myapp.js | compking2012/YYGUI | 182b81dcef834240b302d36aaac34992c58e336f | [
"MIT"
] | 3 | 2015-07-23T04:51:19.000Z | 2015-07-23T06:54:46.000Z | demo/gui/transform3d/myapp.js | compking2012/YYGUI | 182b81dcef834240b302d36aaac34992c58e336f | [
"MIT"
] | 8 | 2015-12-28T04:58:23.000Z | 2015-12-30T06:16:43.000Z | demo/gui/transform3d/myapp.js | compking2012/YYGUI | 182b81dcef834240b302d36aaac34992c58e336f | [
"MIT"
] | 1 | 2015-07-23T04:55:06.000Z | 2015-07-23T04:55:06.000Z | "use strict";
var fx = require("framework");
var Class = fx.import("framework.Class");
var App = fx.import("framework.app.App");
var View = fx.import("framework.ui.view.View");
var PropertyAnimation = fx.import("framework.ui.animation.PropertyAnimation");
Class.define("MyApp", App, {
onStart: function() {
this.window.background = "#00FF00";
var view = new View();
view.background = "#FF0000";
view.left = 110;
view.top = 110;
view.width = 100;
view.height = 100;
// view.originX = 50;
// view.originY = 50;
// view.rotationX = Math.PI / 180 * 1;
// view.rotationY = Math.PI / 180 * 0.1;
this.window.rotationX = Math.PI / 180 * 45;
this.window.addChild(view);
// var animation1 = new PropertyAnimation(view);
// // DO NOT WORK: translationZ, rotationX, rotationY
// animation1.from = {rotationX: 0};
// animation1.to = {rotationX: 2 * Math.PI};
// animation1.duration = 5000;
// animation1.repeat = "infinite";
// animation1.easing = "cubic-bezier(0.42, 0, 0.58, 1.0)";
// animation1.start();
}
}, module);
| 33 | 78 | 0.575758 |
8b4b508f195a055ab5b75d724859dc80e8e6f691 | 4,687 | js | JavaScript | server/controllers/user.js | jjtfsalgado/todo-mern-app | 3f920c2fc15a95daf8f1b83050d420bade8aabc7 | [
"MIT"
] | 7 | 2018-07-23T17:39:13.000Z | 2020-11-16T21:38:38.000Z | server/controllers/user.js | jjtfsalgado/todo-mern-app | 3f920c2fc15a95daf8f1b83050d420bade8aabc7 | [
"MIT"
] | null | null | null | server/controllers/user.js | jjtfsalgado/todo-mern-app | 3f920c2fc15a95daf8f1b83050d420bade8aabc7 | [
"MIT"
] | 3 | 2018-05-17T09:30:46.000Z | 2019-04-10T12:38:23.000Z | const _ = require('lodash');
const {ObjectID} = require('mongodb');
const nodemailer = require('nodemailer');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const {config} = require('./../config/passwords');
var {mongoose} = require('./../db/mongoose');
var {User} = require('./../models/user');
var {Todo} = require('./../models/todo');
var userController = {};
userController.addUser = [
function(req,res,next) {
var body = _.pick(req.body, ['email', 'password']);
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: config.EMAIL,
pass: config.PASSWORD
}
});
var token = jwt.sign({body}, config.HASH);
var link="http://"+req.get('host')+"/users?verify="+token;
let mailOptions = {
from: '"ToDo Mern" <todomern.info@gmail.com>', // sender address
to: `${body.email}`, // list of receivers
subject: 'Hello stranger!', // Subject line
html: `<p>Please click on the link to confirm your email <br/><a href=${link}>Click Here!</a></p>`, // plain text body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.status(400).send(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
res.status(200).send(body);
});
}
];
userController.getUser = [
function(req,res,next) {
var token = req.query.verify;
var decoded = jwt.verify(token, config.HASH);
var user = new User(decoded.body);
user.save().then(() => {
res.redirect('/');
}).catch((e) => {
res.status(400).send(e);
})
}
];
userController.deleteUser = [
function(req,res,next) {
var id = req.user.id;
User.findByIdAndRemove(id).then((user) => {
var response = {
message: "user successfully deleted",
user: user
}
res.status(200).send(response);
}).then(() => {
Todo.remove({_creator: id}).then(() => {
}).catch((e) => {
res.status(400).send(e);
})
}).catch((e) => {
res.status(400).send(e);
})
}
];
userController.resetPassword = [
function(req,res,next) {
var body = _.pick(req.body, ['email', 'password']);
console.log(body);
if (!body.password) {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: config.EMAIL,
pass: config.PASSWORD
}
});
var token = jwt.sign({email : body.email}, config.HASH);
var link="http://"+req.get('host')+"/#/password?verify="+token;
let mailOptions = {
from: '"ToDo Mern" <todomern.info@gmail.com>', // sender address
to: `${body.email}`, // list of receivers
subject: 'Request to reset password', // Subject line
html: `<p>We received a request to reset your password. Please click on the link to confirm <br/><a href=${link}>Click Here!</a></p>`, // plain text body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.status(400).send(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
res.status(200).send(body);
});
} else if (body.email && body.password) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(body.password, salt, (err, hash) => {
body.password = hash;
User.update({email:body.email}, {$set: {password: body.password}}).then((user) => {
res.status(200).send(user);
}).catch((e) => {
res.status(400).send(e);
});
});
});
}
}
];
userController.loginUser = [
function(req,res,next) {
var body = _.pick(req.body, ['email','password']);
User.findByCredentials(body.email, body.password).then((user) => {
return user.generateAuthToken().then((token) => {
res.header('x-auth', token).send(user);
});
}).catch((e) => {
res.status(400).send(e);
});
}
];
userController.logoutUser = [
function(req,res,next) {
req.user.removeToken(req.token).then(() => {
res.status(200).send();
}, () => {
res.status(400).send();
})
}
];
userController.checkEmail = [
function(req,res,next) {
var body = _.pick(req.body, ['email']);
User.find({email:body.email}).then((user) => {
res.status(200).send(user);
}).catch((e) => {
res.status(400).send();
});
}
];
userController.getEmail = [
function(req,res,next) {
var email = req.user.email;
if (!email) {
res.status(400).send(e);
}
res.status(200).send(email);
}
];
module.exports = userController;
| 26.782857 | 161 | 0.5607 |
8b4c5724f4f724168280cbd70e4cadd305a1c7ae | 3,080 | js | JavaScript | resources/js/store/modules/builders.js | Shyamjitiwari/new | bb9130dad15b8c66f0675dcab27a87e3c967a845 | [
"MIT"
] | null | null | null | resources/js/store/modules/builders.js | Shyamjitiwari/new | bb9130dad15b8c66f0675dcab27a87e3c967a845 | [
"MIT"
] | null | null | null | resources/js/store/modules/builders.js | Shyamjitiwari/new | bb9130dad15b8c66f0675dcab27a87e3c967a845 | [
"MIT"
] | null | null | null | import router from "../../router/router";
const state = {
builders: {},
builder: {},
builders_active: {},
};
const getters = {
getBuilders(state) {
return state.builders;
},
getBuilder(state) {
return state.builder;
},
getBuildersActive(state){
return state.builders_active;
}
};
const mutations = {
setBuilders(state, payload) {
state.builders = payload;
},
setBuilder(state, payload) {
state.builder = payload;
},
setBuildersActive(state, payload) {
state.builders_active = payload;
}
};
const actions = {
fetchBuilders(context, payload) {
this.dispatch("dispatch_request", {
method: "GET",
url: "builders?page=" +
payload.next_page +
"&name=" +
payload.search.name +
"&status=" +
payload.search.status,
success_callback: function success_callback(response) {
context.commit("setBuilders", response.data.data);
}
})
},
fetchShowBuilder(context, payload) {
this.dispatch("dispatch_request", {
method: "GET",
url: "builders/" + payload,
success_callback: function success_callback(response) {
context.commit("setBuilder", response.data.data);
}
})
},
fetchEditBuilder(context, payload) {
this.dispatch("dispatch_request", {
method: "GET",
url: "builders/" + payload + '/edit',
success_callback: function success_callback(response) {
context.commit("setBuilder", response.data.data);
}
})
},
dispatchCreateBuilder(context, payload) {
this.dispatch("dispatch_request", {
method: "POST",
url: "builders",
data: payload,
success_callback: function success_callback() {
router.go(-1);
}
})
},
dispatchEditBuilder(context, payload) {
this.dispatch("dispatch_request", {
method: "PUT",
url: "builders/" + payload.id,
data: payload,
success_callback: function success_callback() {
router.go(-1);
}
})
},
deleteBuilder(context, payload) {
this.dispatch("dispatch_request", {
method: "DELETE",
url: "builders/" + payload.id,
success_callback: function success_callback() {
router.go(-1);
}
})
},
fetchAllActiveBuilders(context, payload) {
this.dispatch("dispatch_request", {
method: "POST",
url: "get-all-active",
data: { 'table': 'builders' },
success_callback: function success_callback(response) {
context.commit("setBuildersActive", response.data.data);
}
})
},
};
export default {
state,
getters,
mutations,
actions
}; | 27.017544 | 72 | 0.522727 |
8b4c95c963994f8dbf81f84b594ebe5992fdf4e9 | 1,464 | js | JavaScript | test/test.js | chloeleichen/birthday | cd04be4ad74cd45de32e979b9ee67c0352a563ac | [
"Apache-2.0"
] | null | null | null | test/test.js | chloeleichen/birthday | cd04be4ad74cd45de32e979b9ee67c0352a563ac | [
"Apache-2.0"
] | null | null | null | test/test.js | chloeleichen/birthday | cd04be4ad74cd45de32e979b9ee67c0352a563ac | [
"Apache-2.0"
] | null | null | null | //Unit testing
describe('birthday', function() {
var mainCtrl, scope;
var urlPath = "http://localhost:8080/#/ddd";
beforeEach(module('birthday'))
beforeEach(inject(function($controller, $rootScope){
//crucial:
scope= $rootScope.$new();
mainCtrl = $controller('MainController', {$scope: scope});
}));
describe('MainController', function(){
it("invitation", function(){
expect(scope.setMessage("Jess", 0)).toEqual("Hi Jess, You are invited to Jeremy's 40th Party!");
expect(scope.setMessage("Sue", 1)).toEqual("Hi Sue, You have RSVPed to Jeremy's 40th Party!");
expect(scope.setMessage("Matt", 2)).toEqual("Hi Matt, You won't be coming to Jeremy's 40th Party!");
expect(scope.setMessage("John", 3)).toEqual("Hi John, You have a pending invitation to Jeremy's 40th Party!");
expect(scope.setMessage("", 4)).toEqual("Hi stranger, looks like you are not on the guest list");
});
it("Check guest list", function(){
var arr = [{
"name": "John",
"rsvp": "0",
"number": "1"
},
{
"name": "Linden and Daisy",
"rsvp": "2",
"number": "2"
}];
scope.guest = arr[1];
expect(scope.getGuest("john", arr).name).toBe("John");
expect(scope.getGuest("linden and daisy", arr).name).toBe("Linden and Daisy");
expect(scope.getGuest("", arr).name).toBe(null);
expect(scope.setClass()).toBe("rsvp2");
});
});
});
| 38.526316 | 116 | 0.60041 |
8b4cba25871fbf7ea50f21dc94eb701b82e6e64e | 844 | js | JavaScript | frontend/fill-indicator.js | Artur-/dynamic-svg | 6faf5b4f943f0d9aee024fe77c15cd0988016034 | [
"Unlicense"
] | null | null | null | frontend/fill-indicator.js | Artur-/dynamic-svg | 6faf5b4f943f0d9aee024fe77c15cd0988016034 | [
"Unlicense"
] | 5 | 2021-05-06T15:30:57.000Z | 2022-02-27T05:56:44.000Z | frontend/fill-indicator.js | Artur-/dynamic-svg | 6faf5b4f943f0d9aee024fe77c15cd0988016034 | [
"Unlicense"
] | null | null | null | import { css, svg, LitElement } from "lit-element";
export class FillIndicator extends LitElement {
static get properties() {
return { value: {}, fill: { value: "#0f0" } };
}
render() {
return svg`
<svg style="height: 100px" viewbox="0 0 50 110">
<rect class="progress"
transform="rotate(180 10 5) translate(-30 -100)"
x="10"
y="5"
height="${this.value}"
width="30"
stroke-width="5"
stroke="none"
fill=${this.fill}
/>
<rect
class="border"
x="10"
y="3"
rx="2"
height="100"
width="30"
stroke-width="5"
stroke="black"
fill="transparent"
/>
</svg>
`;
}
}
customElements.define("fill-indicator", FillIndicator);
| 22.210526 | 58 | 0.481043 |
8b4ebba632c125997e66273907830ea070da1278 | 790 | js | JavaScript | packages/orm/src/query/update.js | afialapis/calustra | ff481e838a231b2832afda8a02312c018ce5a998 | [
"MIT"
] | null | null | null | packages/orm/src/query/update.js | afialapis/calustra | ff481e838a231b2832afda8a02312c018ce5a998 | [
"MIT"
] | null | null | null | packages/orm/src/query/update.js | afialapis/calustra | ff481e838a231b2832afda8a02312c018ce5a998 | [
"MIT"
] | null | null | null | import {objToTuple} from '../util'
function prepare_query_update(tablename, tablefields, values, filter) {
const utuple = objToTuple(values, tablefields)
const ufields = utuple[0]
const uvalues = utuple[1]
if (ufields.length == 0) {
return [undefined, undefined]
}
const sfields = 'SET ' + ufields.map((f, i) => f + ' = $' + (i + 1)).join(',')
const wtuple = objToTuple(filter, tablefields)
const wfields = wtuple[0]
const wvalues = wtuple[1]
let swhere = ''
if (wfields.length > 0)
swhere = ' WHERE ' + wfields.map((f, i) => f + ' = $' + (i + 1 + ufields.length)).join(' AND ')
const allvalues= uvalues.concat(wvalues)
const query = `UPDATE ${tablename} ${sfields} ${swhere}`
return [query, allvalues]
}
export default prepare_query_update | 26.333333 | 103 | 0.640506 |
8b4f234fed86b2a52a697f2eb4495f18bc933ec4 | 225 | js | JavaScript | src/containers/faq/index.js | geniuspom/YNU-Survey | 1210e60ec643f4cf7715a946fea9e74e1b6209e2 | [
"MIT"
] | null | null | null | src/containers/faq/index.js | geniuspom/YNU-Survey | 1210e60ec643f4cf7715a946fea9e74e1b6209e2 | [
"MIT"
] | 10 | 2020-09-07T16:47:01.000Z | 2022-03-03T22:57:42.000Z | src/containers/faq/index.js | geniuspom/YNU-Faq-Modern | 03154ef59a0be32f64a110306494351a3c021bd5 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
class FaqHome extends Component {
render() {
return (
<Redirect to='/my_account:th' />
)
}
}
export default FaqHome
| 15 | 44 | 0.635556 |
8b4f28716166276588fd01af061898f81f348fc4 | 1,556 | js | JavaScript | script.js | marss-hub/text-animation-on-JS-function | a884fe884e62e2e4ee3ae90d51017912a740d326 | [
"MIT"
] | null | null | null | script.js | marss-hub/text-animation-on-JS-function | a884fe884e62e2e4ee3ae90d51017912a740d326 | [
"MIT"
] | null | null | null | script.js | marss-hub/text-animation-on-JS-function | a884fe884e62e2e4ee3ae90d51017912a740d326 | [
"MIT"
] | null | null | null | const PREFIX_ID = "id_";
const DEFAULT_CONTEXT_ELEMENT = "div";
const DEFAULT_CONTEXT_CLASS = "context-element";
function createContext(id) {
const htmlNode = document.createElement(DEFAULT_CONTEXT_ELEMENT);
htmlNode.classList.add(DEFAULT_CONTEXT_CLASS);
htmlNode.id = PREFIX_ID + id;
document.body.append(htmlNode);
}
function setContextStyle(id, style) {
if (!hasContext(id)) throw new Error(`context (id = ${id}) is not found`);
const contextId = `#${PREFIX_ID}${id}`;
const htmlNode = document.querySelector(contextId);
htmlNode.setAttribute("style", style);
}
function getContextStyle(id) {
if (!hasContext(id)) throw new Error(`context (id = ${id}) is not found`);
const contextId = `#${PREFIX_ID}${id}`;
return document.querySelector(contextId).getAttribute("style");
}
function hasContext(id) {
return !!document.querySelector(`#${PREFIX_ID}${id}`);
}
function removeContext(id) {
if (!hasContext(id)) throw new Error(`context (id = ${id}) is not found`);
const contextId = `#${PREFIX_ID}${id}`;
document.body.remove(document.querySelector(contextId));
}
function writeContext(id, text) {
if (!hasContext(id)) throw new Error(`context (id = ${id}) is not found`);
const contextId = `#${PREFIX_ID}${id}`;
document.querySelector(contextId).innerHTML = text;
}
function readContext(id) {
if (!hasContext(id)) throw new Error(`context (id = ${id}) is not found`);
const contextId = `#${PREFIX_ID}${id}`;
return document.querySelector(contextId).innerHTML;
}
| 33.826087 | 77 | 0.68509 |
8b501c667c5cdd9d4e5edb97884ff54d22161b56 | 664 | js | JavaScript | client/web/notepad/src/index.js | SuperTanker/tanker-ui-demos | 668d2df79bfc508cdab7dfc91ea170cd284a382b | [
"Apache-2.0"
] | 12 | 2018-11-06T16:33:20.000Z | 2022-03-05T00:45:41.000Z | client/web/notepad/src/index.js | TankerHQ/quickstart-examples | 668d2df79bfc508cdab7dfc91ea170cd284a382b | [
"Apache-2.0"
] | 8 | 2020-03-17T17:50:50.000Z | 2021-12-24T11:13:04.000Z | client/web/notepad/src/index.js | SuperTanker/tanker-ui-demos | 668d2df79bfc508cdab7dfc91ea170cd284a382b | [
"Apache-2.0"
] | 1 | 2020-01-07T09:58:06.000Z | 2020-01-07T09:58:06.000Z | // Load polyfills for IE11 (added Array#find for react-bootstrap)
import 'react-app-polyfill/ie11';
import 'core-js/features/array/find'; // eslint-disable-line import/no-extraneous-dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Tanker } from '@tanker/client-browser';
import Session from './Session';
import App from './components/App';
const session = new Session();
/* eslint-disable-next-line */
console.log(`Tanker version: ${Tanker.version}`);
ReactDOM.render(
<BrowserRouter>
<App session={session} />
</BrowserRouter>,
document.getElementById('root'),
);
| 27.666667 | 94 | 0.72741 |
8b50244f058bc72770f35260ffe8d582bc2d8168 | 449 | js | JavaScript | src/components/BlogRoll.js | dberhane/pwa-demo | 5c35b2865797c7a22f57b6a5a7e1ef90ea1f10a3 | [
"MIT"
] | null | null | null | src/components/BlogRoll.js | dberhane/pwa-demo | 5c35b2865797c7a22f57b6a5a7e1ef90ea1f10a3 | [
"MIT"
] | 8 | 2020-02-24T11:46:25.000Z | 2022-02-10T16:32:36.000Z | src/components/BlogRoll.js | dberhane/pwa-demo | 5c35b2865797c7a22f57b6a5a7e1ef90ea1f10a3 | [
"MIT"
] | null | null | null | import React from 'react'
const BlogRoll = () => (
<div style={{ paddingBottom: '0.5em' }}>
<h2>Blogroll</h2>
<ul style={{ listStyleType: 'none', paddingBottom: 20 }}>
<li>ALPSP</li>
<li>CEBM</li>
<li>COPE</li>
<li>JISC Managing Research Data programme</li>
<li>OASPA blog</li>
<li>Research Information Network</li>
<li>UK PubMed Central Blog</li>
</ul>
</div>
)
export default BlogRoll
| 21.380952 | 61 | 0.585746 |
8b510ada77349b3bf04516d52854b976d0065844 | 66 | js | JavaScript | dist/math/vec2/Vec2Dot.js | Mattykins/phaser-1 | d8b6aada4d74d913496f7b8b3fef175d8b7de5d6 | [
"MIT"
] | 235 | 2020-04-14T14:51:51.000Z | 2022-03-31T09:17:36.000Z | dist/math/vec2/Vec2Dot.js | Mattykins/phaser-1 | d8b6aada4d74d913496f7b8b3fef175d8b7de5d6 | [
"MIT"
] | 19 | 2020-04-18T06:28:18.000Z | 2021-11-12T23:43:43.000Z | dist/math/vec2/Vec2Dot.js | Mattykins/phaser-1 | d8b6aada4d74d913496f7b8b3fef175d8b7de5d6 | [
"MIT"
] | 25 | 2020-04-18T08:44:16.000Z | 2022-02-24T00:49:48.000Z | export function Vec2Dot(a, b) {
return a.x * b.x + a.y * b.y;
}
| 16.5 | 31 | 0.560606 |
8b51e149abac111bfde7ba6283b3b0a0fddf3a83 | 807 | js | JavaScript | lib/tower/support/validation.js | vjsingh/tower | ffef44f9d92aaed2200358cf37b4029417fee2cb | [
"MIT"
] | 1 | 2019-01-15T20:49:54.000Z | 2019-01-15T20:49:54.000Z | lib/tower/support/validation.js | vjsingh/tower | ffef44f9d92aaed2200358cf37b4029417fee2cb | [
"MIT"
] | null | null | null | lib/tower/support/validation.js | vjsingh/tower | ffef44f9d92aaed2200358cf37b4029417fee2cb | [
"MIT"
] | null | null | null | var casting, check, sanitize, sanitizing, validator;
validator = require('validator');
check = validator.check;
sanitize = validator.sanitize;
casting = {
toInt: function(value) {
return sanitize(value).toInt();
},
toBoolean: function(value) {
return sanitize(value).toBoolean();
}
};
sanitizing = {
trim: function(value) {
return sanitize(value).trim();
},
ltrim: function(value, trim) {
return sanitize(value).ltrim(trim);
},
rtrim: function(value, trim) {
return sanitize(value, trim).rtrim(trim);
},
xss: function(value) {
return sanitize(value).xss();
},
entityDecode: function(value) {
return sanitize(value).entityDecode();
},
"with": function(value) {
return sanitize(value).chain();
}
};
_.mixin(casting);
_.mixin(sanitizing);
| 19.214286 | 52 | 0.654275 |
8b52857195ba223ec8a29c0a633c878eb930dd2b | 13,315 | js | JavaScript | views/javascripts/main.js | Hellslicer/Chaunli | b3a2bf81361a31114795e3f8f171d4ea1383e76a | [
"MIT"
] | 4 | 2015-01-08T08:46:24.000Z | 2018-01-24T08:27:59.000Z | views/javascripts/main.js | Hellslicer/Chaunli | b3a2bf81361a31114795e3f8f171d4ea1383e76a | [
"MIT"
] | null | null | null | views/javascripts/main.js | Hellslicer/Chaunli | b3a2bf81361a31114795e3f8f171d4ea1383e76a | [
"MIT"
] | null | null | null | (function($) {
$(document).ready(function() {
var userList = $("div ul.list-inline")
, tabs = $("#rooms")
, tabsContent = $("div.tab-content")
, loggedUsers = []
, notificationEnabled = false
, unreadMessages = 0
, offsetTime = 0
, i18n = new I18n({directory: "/locales", extension: ".json"});
$.idleTimer(300000);
moment.locale(window.navigator.userLanguage || window.navigator.language);
i18n.setLocale(window.navigator.userLanguage || window.navigator.language);
var socket = io.connect("//" + window.location.host);
socket.on("userList", function (users) {
loggedUsers = users;
refreshUserList();
}).on("syncTime", function (serverTime) {
offsetTime = moment(serverTime).diff(new Date().toISOString());
}).on("syncLocale", function(locale) {
moment.locale(locale);
i18n.setLocale(locale);
}).on("roomsList", function(rooms) {
var firstRoom = true;
if (tabs.html().length > 0) {
socket.disconnect();
setTimeout(function(){ window.location.reload(); }, 2000);
return;
}
for(var i = 0, length = rooms.length; i < length; i++) {
var roomName = i18n.__(rooms[i].name) || rooms[i].name;
tabs.append(tmpl("room_tab_template", { name: roomName, id: rooms[i].id, active: firstRoom }));
tabsContent.append(tmpl("room_template", { id: rooms[i].id, active: firstRoom, i18n: i18n }));
chat(rooms[i]);
if (firstRoom) {
firstRoom = false;
}
}
});
var chat = function(room) {
var messageBox = $("#" + room.id + " #messages")
, textarea = $("#" + room.id + " #message")
, writingList = $("#" + room.id + " #writing")
, usersWriting = [];
var socket = io.connect("//" + window.location.host + room.URI);
socket.on("message", function(message) {
if (message.i18n != null) {
message.author.name = i18n.__(message.author.name);
message.msg = i18n.__(message.msg, message.i18n);
}
appendLine(message.author.name, message.msg, message.date);
if (notificationEnabled && !(!!message.init)) {
unreadMessages++;
document.title = "(" + unreadMessages + ") Chaunli";
if (message.notif) {
show(message.author, message.msg);
}
}
}).on("writing", function(data) {
var found = false;
usersWriting = $.grep(usersWriting, function(user, i) {
if (user.name === data.user.name) {
found = true;
if (!(!!data.status)) {
return false;
}
}
return true;
});
if (!found && !!data.status) {
usersWriting.push(data.user);
}
refreshWritingUser();
}).on("reload", function(reload) {
if (!!reload.status) {
window.location.reload();
}
});
var refreshWritingUser = function () {
writingList.html("");
if (usersWriting.length === 1) {
for (var user in usersWriting) {
if (usersWriting.hasOwnProperty(user)) {
writingList.append(tmpl("writing_single_template", { name: usersWriting[user].name, i18n: i18n }));
}
}
} else if (usersWriting.length > 1) {
var users = usersWriting.map(function(user) {
return user.name;
}).join(", ");
writingList.append(tmpl("writing_multi_template", { names: users, i18n: i18n }));
}
};
var appendLine = function(name, message, date) {
messageBox.append(tmpl("message_template", { name: name, message: emojify.replace(message), date: date, formated_date: moment(date).add(offsetTime, "milliseconds").format("LLL") }));
messageBox.stop().animate({scrollTop: messageBox[0].scrollHeight}, "slow");
$('[data-toggle="tooltip"]').tooltip();
};
var send = function() {
if (textarea.val().length > 0) {
socket.emit("writing", {status: false});
socket.emit("message", {msg: textarea.val()}, function (message) {
$("#" + room.id + " #message").val("");
appendLine(message.author.name, message.msg, message.date);
});
}
};
$("#" + room.id + " #send").bind("click", send);
textarea.keydown(function (e) {
if ((e.keyCode === 10 || e.keyCode === 13)) {
if (e.ctrlKey || e.shiftKey) {
e.preventDefault();
textarea.insertAtCaret("\r\n");
} else {
e.preventDefault();
send();
return;
}
}
socket.emit("writing", { status: true });
callbackWithTimeOut(10000, function() {
socket.emit("writing", { status: false });
});
});
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType !== e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
notificationEnabled = true;
break;
case "focus":
document.title = "Chaunli";
unreadMessages = 0;
notificationEnabled = false;
break;
}
}
$(this).data("prevType", e.type);
});
};
socket.on("userChanged", function(action) {
var user = action.user;
if (action.type === "joined") {
loggedUsers.push(user);
refreshUserList();
} else if (action.type === "left") {
loggedUsers = removeFromObject(loggedUsers, "id", user);
refreshUserList();
} else if (action.type === "idle") {
refreshUser(user, action.changed);
}
});
$(document).on( "idle.idleTimer", function(event, elem, obj){
socket.emit("idle", { status: true }, function (user, changed) {
refreshUser(user, changed);
});
}).on( "active.idleTimer", function(event, elem, obj, triggerevent){
socket.emit("idle", { status: false }, function (user, changed) {
refreshUser(user, changed);
});
});
var refreshUser = function (user, changed) {
$.each(loggedUsers, function () {
if (this.id === user) {
var currentUser = this;
$.each(changed, function(key, value) {
currentUser[key] = value;
});
}
});
refreshUserList();
};
var refreshUserList = function () {
userList.html("");
var idleClass;
for (var user in loggedUsers) {
if (loggedUsers.hasOwnProperty(user)) {
idleClass = !!loggedUsers[user].idle ? "idle" : "";
userList.append(tmpl("user_template", { idleClass: idleClass, name: loggedUsers[user].name, md5: loggedUsers[user].md5 }));
}
}
$('[data-toggle="tooltip"]').tooltip();
};
var removeFromObject = function(object, property, value) {
var done = false;
return object.filter(function (item) {
var skip = false;
if (!done && item[property] === value) {
done = true;
skip = true;
}
return item[property] !== value || (done && !skip);
});
};
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
Notification.requestPermission(function (permission) {
// console.log(permission);
});
function show(exp, msg) {
var instance = new Notification(
exp.name, {
body: convertHtmlToText(msg),
icon: "http://www.gravatar.com/avatar/" + exp.md5 + "?s=128"
}
);
instance.onclick = function () {
// Something to do
};
instance.onerror = function () {
// Something to do
};
instance.onshow = function () {
setTimeout(function() {
instance.close();
}, 5000);
};
instance.onclose = function () {
// Something to do
};
return false;
}
var writeTimeout = null ;
function callbackWithTimeOut(time, callback) {
if (typeof callback !== "function") {
console.log("Callback must be a function") ;
return ;
}
if (null == time) {
time = 500 ;
}
if (null !== writeTimeout) {
clearTimeout(writeTimeout) ;
}
writeTimeout = setTimeout(callback, time) ;
}
function convertHtmlToText(html) {
var returnText = "" + html;
//-- remove BR tags and replace them with line break
returnText=returnText.replace(/<br>/gi, "\n");
returnText=returnText.replace(/<br\s\/>/gi, "\n");
returnText=returnText.replace(/<br\/>/gi, "\n");
//-- remove P and A tags but preserve what's inside of them
returnText=returnText.replace(/<p.*>/gi, "\n");
returnText=returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");
//-- remove all inside SCRIPT and STYLE tags
returnText=returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
returnText=returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
//-- remove all else
returnText=returnText.replace(/<(?:.|\s)*?>/g, "");
//-- get rid of more than 2 multiple line breaks:
returnText=returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\n\n");
//-- get rid of more than 2 spaces:
returnText = returnText.replace(/ +(?= )/g,'');
//-- get rid of html-encoded characters:
returnText=returnText.replace(/ /gi," ");
returnText=returnText.replace(/&/gi,"&");
returnText=returnText.replace(/"/gi,'"');
returnText=returnText.replace(/'/gi,'\'');
returnText=returnText.replace(/</gi,'<');
returnText=returnText.replace(/>/gi,'>');
return returnText;
}
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length - 1;
this.selectionEnd = startPos + myValue.length - 1;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
}
});
window.onbeforeunload = function(e) {
socket.disconnect();
};
});
})(jQuery);
| 40.348485 | 198 | 0.447165 |
8b5291a53888912805f287d2c7d9f9f57fe30ba5 | 411 | js | JavaScript | demo/build.js | weilao/include-tag | 6314dedcbf8f07ea9b34c830528da1f224b3f7c6 | [
"MIT"
] | 9 | 2016-01-02T11:14:28.000Z | 2021-08-19T13:11:43.000Z | demo/build.js | weilao/include-tag | 6314dedcbf8f07ea9b34c830528da1f224b3f7c6 | [
"MIT"
] | 1 | 2015-08-26T12:19:35.000Z | 2015-08-27T11:39:37.000Z | demo/build.js | weilao/include-tag | 6314dedcbf8f07ea9b34c830528da1f224b3f7c6 | [
"MIT"
] | 2 | 2016-03-02T03:31:31.000Z | 2018-04-11T15:39:20.000Z | // Use `node demo/build.js` command to run this.
var fs = require('fs');
var includeTag = require('../dist/includeTag');
var html = fs.readFileSync(__dirname + '/index.html').toString();
// Do it!
html = includeTag(__dirname, html);
// Remove includeTag.browser.js reference.
html = html.replace(/<script.*?includeTag.browser.js.*?<\/script>/gi, '');
fs.writeFileSync('demo/build.html', html, {flags: 'w+'}); | 34.25 | 74 | 0.681265 |
8b532ef238ef158cf80d3f28a33183a5ebe58736 | 1,968 | js | JavaScript | packages/lambda/test/api/getMaintenance/index.js | salekseev/LambStatus | 17158292b7fe7269ecba942aa6dce786344d7e77 | [
"Apache-2.0"
] | 1,415 | 2016-10-24T13:24:20.000Z | 2022-03-23T07:23:21.000Z | packages/lambda/test/api/getMaintenance/index.js | salekseev/LambStatus | 17158292b7fe7269ecba942aa6dce786344d7e77 | [
"Apache-2.0"
] | 136 | 2016-11-09T10:41:42.000Z | 2020-03-25T13:27:06.000Z | packages/lambda/test/api/getMaintenance/index.js | gibbsie/LambStatus | 5b04aa2020db960b673d8ff716297d9028209092 | [
"Apache-2.0"
] | 176 | 2016-11-14T11:05:41.000Z | 2022-03-22T11:39:20.000Z | // Code generated by generate-maintenance-handler. DO NOT EDIT.
/* eslint-disable */
import assert from 'assert'
import sinon from 'sinon'
import { handle } from 'api/getMaintenance'
import MaintenancesStore from 'db/maintenances'
import MaintenanceUpdatesStore from 'db/maintenanceUpdates'
import { Maintenance, MaintenanceUpdate } from 'model/maintenances'
import { NotFoundError } from 'utils/errors'
describe('getMaintenance', () => {
afterEach(() => {
MaintenancesStore.prototype.get.restore()
MaintenanceUpdatesStore.prototype.query.restore()
})
it('should return an maintenance', async () => {
const maintenance = new Maintenance({maintenanceID: '1'})
sinon.stub(MaintenancesStore.prototype, 'get').returns(maintenance)
const maintenanceUpdates = [new MaintenanceUpdate({maintenanceID: '1', maintenanceUpdateID: '1'})]
sinon.stub(MaintenanceUpdatesStore.prototype, 'query').returns(maintenanceUpdates)
return await handle({ params: { maintenanceid: '1' } }, null, (error, result) => {
assert(error === null)
assert(result.maintenanceID === '1')
assert(result.maintenanceUpdates.length === 1)
assert(result.maintenanceUpdates[0].maintenanceID === '1')
assert(result.maintenanceUpdates[0].maintenanceUpdateID === '1')
})
})
it('should handle not found error', async () => {
sinon.stub(MaintenancesStore.prototype, 'get').throws(new NotFoundError())
sinon.stub(MaintenanceUpdatesStore.prototype, 'query').throws()
return await handle({ params: { maintenanceid: '1' } }, null, (error, result) => {
assert(error.match(/not found/))
})
})
it('should return error on exception thrown', async () => {
sinon.stub(MaintenancesStore.prototype, 'get').throws()
sinon.stub(MaintenanceUpdatesStore.prototype, 'query').throws()
return await handle({ params: { maintenanceid: '1' } }, null, (error, result) => {
assert(error.match(/Error/))
})
})
})
| 41 | 102 | 0.695122 |
8b558b210a4d81d14e454ac4a67869af30250ace | 248 | js | JavaScript | src/templates/project/assets/Styled/index.js | jonl17/tvisting | a375f31c252656685c7717434073592b9b58a679 | [
"MIT"
] | null | null | null | src/templates/project/assets/Styled/index.js | jonl17/tvisting | a375f31c252656685c7717434073592b9b58a679 | [
"MIT"
] | null | null | null | src/templates/project/assets/Styled/index.js | jonl17/tvisting | a375f31c252656685c7717434073592b9b58a679 | [
"MIT"
] | null | null | null | import styled, { css } from "styled-components"
export const Grid = styled.div`
display: grid;
grid-gap: 20px;
grid-template-columns: 1fr 1fr;
${props =>
props.device === `mobile` &&
css`
grid-template-columns: 1fr;
`}
`
| 19.076923 | 47 | 0.616935 |
8b56f705684770e6704a9bad8e0e49287d37427d | 119 | js | JavaScript | node_modules/phaser3-rex-plugins/plugins/gameobjects/dynamictext/dynamictext/methods/SetWrapConfig.js | SamueleDelMoro/ACTAM.Project2122-TraningGame | 73a5070ea619abcb155a3e0a892f410866af49ed | [
"MIT"
] | 888 | 2018-03-29T05:11:21.000Z | 2022-03-31T14:02:58.000Z | node_modules/phaser3-rex-plugins/plugins/gameobjects/dynamictext/dynamictext/methods/SetWrapConfig.js | SamueleDelMoro/ACTAM.Project2122-TraningGame | 73a5070ea619abcb155a3e0a892f410866af49ed | [
"MIT"
] | 194 | 2018-07-20T07:39:24.000Z | 2022-03-31T23:08:01.000Z | node_modules/phaser3-rex-plugins/plugins/gameobjects/dynamictext/dynamictext/methods/SetWrapConfig.js | SamueleDelMoro/ACTAM.Project2122-TraningGame | 73a5070ea619abcb155a3e0a892f410866af49ed | [
"MIT"
] | 262 | 2018-05-17T06:45:48.000Z | 2022-03-24T11:48:52.000Z | var SetWrapConfig = function (config) {
this.wrapConfig = config;
return this;
}
export default SetWrapConfig; | 19.833333 | 39 | 0.722689 |
8b575c77f6ac378f91e7450de45f84d447ad7328 | 4,647 | js | JavaScript | assets/javascript/app.js | mgulham/Giphy-McBites | a8ad4af7c0624eb1664e595bd5e8910c3a529917 | [
"MIT"
] | null | null | null | assets/javascript/app.js | mgulham/Giphy-McBites | a8ad4af7c0624eb1664e595bd5e8910c3a529917 | [
"MIT"
] | null | null | null | assets/javascript/app.js | mgulham/Giphy-McBites | a8ad4af7c0624eb1664e595bd5e8910c3a529917 | [
"MIT"
] | null | null | null |
//Determing what my variables will be that are pushed into buttons
var villains = ["The Joker", "Bane", "Thanos", "Green Goblin", "Magneto", "Voldemort", "Darth Vader", "Palpatine", "Sauron", "Lex Luthor"]
// Function for displaying villain data
function renderButtons() {
// Deleting the villains prior to adding new villains
// (this is necessary otherwise you will have repeat buttons)
$("#buttons-view").empty();
// Looping through the array of villains
for (var i = 0; i < villains.length; i++) {
// Then dynamicaly generating buttons for each villain in the array
// This code $("<button>") is all jQuery needs to create the beginning and end tag. (<button></button>)
var newButton = $("<button>");
// Adding a class of villain-btn to our button
newButton.addClass("villain-btn");
newButton.addClass("btn-primary");
// Adding a data-attribute
newButton.attr("data-name", villains[i]);
// Providing the initial button text
newButton.text(villains[i]);
// Adding the button to the buttons-view div
$("#buttons-view").append(newButton);
}
}
// This function handles events where a villain button is clicked
$("#add-villain").on("click", function(event) {
event.preventDefault();
// This line grabs the input from the textbox
var villain = $("#villain-input").val().trim();
// Adding villain from the textbox to our array
villains.push(villain);
// Calling renderButtons which handles the processing of our villain array
renderButtons();
});
// Adding a click event listener to all elements with a class of "villain-btn"
$(document).on("click", ".villain-btn", displayvillainInfo);
// Calling the renderButtons function to display the intial buttons
renderButtons();
function displayvillainInfo() {
$("#villains-view").empty(); //empties gifs from div so new ones can be pushed from api request
var apiKey = "3N7NX6spXgkUbr96DuzjgxIHZBEnh2fY";
var villain = $(this).attr("data-name");
//API Key would not link to java on my deploy link for some reason
var queryURL = `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q="${villain}"&limit=10&offset=0&rating=PG-13&lang=en`
// Creating an AJAX call for the specific villain button being clicked
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
console.log(response);
// Storing the rating data
var gifs = response.data
for (var i = 0; i < gifs.length; i++){ //looping through response to manipulate data
var ratings = $(`<p>Rated: ${gifs[i].rating}<p>`); //Isolates rating for each gif and puts it into a <p> tag
var imagesURL = gifs[i].images.original.url; //isolates animated image url
var imageStillURL = gifs[i].images.original_still.url; //isolates still gif url
//creates image tag with sources that can be changed later. Each url is pulled from its respective data. Image starts still.
var imagesStill = $(`<img class='gif' src=${imageStillURL} data-still=${imageStillURL} data-animate=${imagesURL} data-state='still'>`);
console.log(imageStillURL)
console.log(imagesURL);
// imagesStill.attr("src", gifs[i].images.original_still.url) /// alternative to putting src in <img> tag
$("#villains-view").append(ratings) //ratings <p> tag pushed unto html
$("#villains-view").append(imagesStill); //still images pushed onto html
}
$(".gif").on("click", function(){
// The attr jQuery method allows us to change the value of any attribute on our HTML element
var state = $(this).attr("data-state");
// If the clicked image's state is still, src attribute is updated to link from what its data-animate value is.
// Then, set the image's data-state to animate
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
}
// If the clicked image's state is animate, src attribute is updated to link from what its data-still value is.
// Then, set the image's data-state to still
else if (state === "animate") {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
}
})
})}
//////////////////// FOR SOME REASON, ONLY EVERY OTHER GIFS DATA-STATE CAN BE CHANGED ///////////////////////////////////////
| 39.381356 | 144 | 0.622337 |
8b583c12280ddaf73586c093c52a6f7fdd447848 | 13,088 | js | JavaScript | game.js | max1220/balloons | d9e16a85be4af040b6b85cadb828c43c50538042 | [
"MIT"
] | null | null | null | game.js | max1220/balloons | d9e16a85be4af040b6b85cadb828c43c50538042 | [
"MIT"
] | null | null | null | game.js | max1220/balloons | d9e16a85be4af040b6b85cadb828c43c50538042 | [
"MIT"
] | null | null | null | var gameContainer = document.getElementById("game")
var modal_about = document.getElementById("modal_about")
var modal_gameover = document.getElementById("modal_gameover")
var modal_highscore = document.getElementById("modal_highscore")
var modals = { about: modal_about, gameover: modal_gameover, highscore: modal_highscore }
var span_score = document.getElementById("span_score")
var button_start = document.getElementById("button_start")
var button_submit = document.getElementById("button_submit")
var button_tryagain = document.getElementById("button_tryagain")
var button_higscore_restart = document.getElementById("button_higscore_restart")
var iframe_highscore = document.getElementById("iframe_highscore")
var game = new Phaser.Game(gameContainer.clientWidth, gameContainer.clientHeight, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
var state = {};
var cmode = "about";
var balloons = Array(0);
var text = "";
button_start.onclick = function() {
cmode = "start";
}
button_higscore_restart.onclick = function() {
cmode = "start";
}
button_submit.onclick = function() {
var username = window.prompt("Username?", config.last_username)
config.last_username = username
xhr = new XMLHttpRequest();
xhr.open("POST", config.highscore_url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(urlencode({
name: username,
config: JSON.stringify(config),
state: JSON.stringify(state)
}));
iframe_highscore.onload = function() {
iframe_highscore.style.height = iframe_highscore.contentWindow.document.body.scrollHeight + 'px';
}
iframe_highscore.innerHTML = '<h1>Please wait, loading highscore...</h1>';
setTimeout(function() {
iframe_highscore.src = config.highscore_url;
},1000);
showModal("highscore");
// cmode = "start";
}
button_tryagain.onclick = function() {
cmode = "start";
}
function urlencode(data) {
var ret = ""
Object.keys(data).forEach(function(index) {
ret += encodeURIComponent(index) + "=" + encodeURIComponent(data[index]) + "&";
})
return ret.slice(0, -1).replace(/%20/g, '+');
}
function showModal(modal) {
Object.keys(modals).forEach(function(index) {
if (index == modal) {
modals[index].classList.remove("hidden")
} else {
modals[index].classList.add("hidden")
}
})
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
function getRandomElement(arr, min, max) {
min = min || 0;
max = max || arr.length;
return arr[Math.floor(Math.random() * (max - min)) + min];
}
function Balloon(balloonconfig) {
var y = game.height - balloonconfig.ystart;
var x = getRandomInt(config.spacing_leftright, game.width - config.spacing_leftright);
var _this = this;
this.velocity = getRandom(balloonconfig.vmin, balloonconfig.vmax);
if (balloonconfig.sprite) {
this.img = game.add.sprite(x, y, balloonconfig.img);
if (balloonconfig.animation) {
var anim = this.img.animations.add(balloonconfig.animation);
// this.img.animations.add("explode");
if (typeof balloonconfig.onAnimationComplete == "object") {
balloonconfig.onAnimationComplete.forEach(function(handler) {
anim.onComplete.add(handler, _this);
})
}
}
} else {
this.img = game.add.image(x, y, balloonconfig.img);
}
this.img.smoothed = false;
this.img.inputEnabled = true;
this.img.input.pixelPerfectClick = true;
this.img.input.pixelPerfectAlpha = 1;
this.img.width = this.img.width * balloonconfig.scale;
this.img.height = this.img.height * balloonconfig.scale;
this.onClick = balloonconfig.onClick;
this.onOut = balloonconfig.onOut;
this.onUpdate = balloonconfig.onUpdate;
this.config = balloonconfig;
if (typeof this.onClick == "object") {
this.onClick.forEach(function(handler) {
_this.img.events.onInputDown.add(handler, _this);
})
}
}
function normalBalloon_onClick() {
if (!this.clicked) {
this.clicked = true;
//this.remove = true;
state.total_popped += 1;
state.normalBalloons_popped += 1;
this.img.animations.play(this.config.animation, 40, false);
snd_blop.play();
}
}
function normalBalloon_onOut(balloon) {
if (!balloon.clicked) {
snd_miss.play()
state.total_missed += 1;
state.normalBalloons_missed += 1;
state.lifes -= 1;
if (state.lifes < 0) {
cmode = "end";
}
}
}
function normalBalloon(name, img) {
var config = {
name: name + "Balloon",
sprite: true,
animation: "explode",
ystart: 10,
vmin: 0.1,
vmax: 0.3,
accel: 0,
img: img,
scale: 3,
onClick: [normalBalloon_onClick, function() {state[name + "Balloons_popped"] += 1}],
onOut: [normalBalloon_onOut, function() {state[name + "Balloons_missed"] += 1}],
onAnimationComplete: [function() { this.remove = true; }]
}
return new Balloon(config);
}
function bomb() {
var config = {
name: "bomb",
sprite: true,
ystart: 10,
vmin: 0.05,
vmax: 0.1,
accel: 0,
img: "bomb",
scale: 3,
onClick: [function() {
cmode = "end";
}],
onOut: [function() {
state.bombs_missed += 1
}],
onUpdate: [function(balloon, dt) {
// balloon.img.input.pointerOver() does not work when you don't move your mouse!
if (Phaser.Rectangle.containsPoint(balloon.img._bounds, game.input.activePointer)) {
balloon.img.animations.frame = 1;
}
else {
balloon.img.animations.frame = 0;
}
}]
}
return new Balloon(config);
}
function clearbomb() {
var config = {
name: "clearbomb",
sprite: true,
animation: "explode",
ystart: 10,
vmin: 0.3,
vmax: 0.4,
accel: 0,
img: "clearbomb",
scale: 3,
onClick: [function() {
//cmode = "end";
this.img.animations.play(this.config.animation, 60, false)
state.clearbombs_popped += 1
}],
onOut: [function() {
state.clearbombs_missed += 1
}],
onAnimationComplete: [function () {
balloons.forEach(function(balloon) {
balloon.remove = true;
})
}]
}
return new Balloon(config);
}
function changeBalloon() {
var b = new Balloon({
name: "changeBalloon",
width: 64,
height: 64,
ystart: 10,
vmin: 0.4,
vmax: 0.6,
accel: 0,
img: 'balloon',
scale: 3,
onClick: [normalBalloon_onClick, function() {
state.changeBalloonns_popped += 1;
state.lifes = Math.min(state.lifes + 1, 10);
this.remove = true;
}],
onOut: [normalBalloon_onOut, function() {
state.changeBalloons_missed += 1;
}],
onUpdate: [function(balloon, dt) {
balloon.hue += (balloon.hue_v * dt)
var c = colors[Math.floor(balloon.hue % 359)]
balloon.img.tint = (c.r << 16) + (c.g << 8) + c.b
}]
})
b.hue = getRandomInt(0, 359);
b.hue_v = getRandom(0.01, 1);
return b
}
function updateStats() {
// Add missing lifes
for (i=state.lifes_img.length; i<state.lifes; i++) {
var life = game.add.image(game.width - 16, 16, "heart");
life.width = life.width * config.heart_scale;
life.height = life.height * config.heart_scale;
life.x -= (i+1) * life.width;
life.smoothed = false;
state.lifes_img.push(life);
}
// Remove to many lifes
state.lifes_img = state.lifes_img.map(function(life, index, lifes) {
if (state.lifes <= index) {
if (life) {
life.destroy();
}
lifes.pop();
} else {
return life;
}
})
bmpText.text = state.total_popped;
span_score.innerHTML = state.total_popped;
}
function preload() {
// background Image
game.load.image('logo', 'assets/logo.png');
// heart symbole
game.load.image('heart', 'assets/heart.png');
// Sounds
game.load.audio('blop', 'assets/blop.mp3');
game.load.audio('end', 'assets/end.mp3');
game.load.audio('miss', 'assets/miss.mp3');
// Main font
game.load.bitmapFont('gem', 'assets/gem.png', 'assets/gem.xml');
// transparent balloon
game.load.image('balloon', 'assets/balloon.png');
// bomb
game.load.spritesheet('bomb', 'assets/bomb.png', 30, 30);
// clearbomb
game.load.spritesheet('clearbomb', 'assets/clearbomb.png', 30, 30);
// load all normal balloon images
config.balloon_colors.forEach(function(color) {
game.load.spritesheet('balloon_' + color, 'assets/balloon_' + color + '.png', config.balloon_sprite_width, config.balloon_sprite_height, config.balloon_sprite_count);
});
}
function create() {
colors = Phaser.Color.HSVColorWheel();
time = game.time.time;
state.startTime = time;
snd_blop = game.add.audio("blop");
snd_end = game.add.audio("end");
snd_miss = game.add.audio("miss");
logo = game.add.image(game.width / 2, game.height / 2, "logo");
logo.anchor.setTo(0.5, 0.5);
logo.smoothed = false;
var scale = ( game.width / 2 ) / logo.width;
logo.width = logo.width * scale;
logo.height = logo.height * scale;
bmpText = game.add.bitmapText(16, 16, 'gem', text, 32);
game.stage.backgroundColor = colors[200].rgba;
}
function update() {
var dt = (game.time.time - time);
time = game.time.time;
if (cmode == "start") {
state = {
total_popped: 0,
normalBalloons_popped: 0,
total_missed: 0,
normalBalloons_missed: 0,
startTime: time,
hue: 200,
lifes: config.max_lifes,
lifes_img: Array(0),
timepassed: 0,
speed: 0,
timers: [
{
left: getRandomInt(config.normal_spawn_min, config.normal_spawn_max),
action: function() {
var color = getRandomElement(config.balloon_colors);
balloons.push(normalBalloon(color, "balloon_" + color));
},
min: config.normal_spawn_min,
max: config.normal_spawn_max,
consume: false,
},
{
left: getRandomInt(120000, 180000),
action: function() {
balloons.push(changeBalloon())
},
min: 60000,
max: 120000,
consume: false,
},
{
left: getRandomInt(60000, 90000),
action: function() {
balloons.push(bomb());
},
min: 25000,
max: 45000,
consume: false,
},
{
left: getRandomInt(90000, 120000),
action: function() {
balloons.push(clearbomb());
},
min: 50000,
max: 90000,
consume: false,
},
]
}
// try_again.visible = false;
balloons = Array(0);
showModal();
cmode = "game";
}
else if (cmode == "game") {
state.hue = (state.hue + (dt / 100)) % 359;
game.stage.backgroundColor = colors[Math.floor(state.hue)].rgba;
state.timepassed += dt;
//logo.tint = logo.tint + (dt * 0x010101) % 0xFFFFFF;
state.timers.forEach(function(countdown) {
countdown.left -= dt;
if (countdown.left <= 0) {
countdown.left = getRandomInt(countdown.min, countdown.max);
if (typeof countdown.action == "object") {
countdown.action.forEach( function(action) {
action(countdown);
})
} else {
countdown.action(countdown);
}
}
});
balloons = balloons.filter( function(balloon) {
if (!balloon.img.inCamera) {
if (typeof balloon.onOut == "object") {
balloon.onOut.forEach( function(action) {
action(balloon);
})
}
return false;
}
if (balloon.remove) {
balloon.img.destroy();
return false;
}
if (typeof balloon.onUpdate == "object") {
balloon.onUpdate.forEach( function(action) {
action(balloon, dt);
})
}
state.speed = Math.min(state.speed + dt * config.speed_accel, config.speed_max)
balloon.img.y -= (dt * balloon.velocity) + (dt * state.speed);
return true;
});
updateStats();
} else if (cmode == "end") {
if (config.debug_mode) {
console.log("DEBUG MODE: You'd be dead right now!")
console.log("DEBUG MODE: Resetting lives, rejoining game...")
state.lifes = config.max_lifes;
cmode = "game"
return
}
balloons.filter(function(balloon) {
balloon.img.destroy();
return false;
})
//bmpText.text = "GAME OVER";
//try_again.visible = true;
showModal("gameover");
cmode = "ended"
} else if (cmode == "ended") {
} else if (cmode == "about") {
bmpText.text = "";
showModal("about")
}
}
| 25.024857 | 171 | 0.598258 |
8b58e4f53d4bf84551d0ed4d6da54d9ba6661716 | 2,041 | js | JavaScript | app/containers/AdminCandidatesListActions/saga.js | gustavmaskowitz/talentdb-gospel-demo | 7cfb1e3e4d10445d17d00a59764fd6b838a29026 | [
"MIT"
] | 2 | 2020-03-09T19:49:26.000Z | 2020-03-09T19:49:44.000Z | app/containers/AdminCandidatesListActions/saga.js | gustavmaskowitz/talentdb-gospel-demo | 7cfb1e3e4d10445d17d00a59764fd6b838a29026 | [
"MIT"
] | 1 | 2020-01-03T11:51:17.000Z | 2020-01-08T17:49:48.000Z | app/containers/AdminCandidatesListActions/saga.js | gustavmaskowitz/talentdb-gospel-demo | 7cfb1e3e4d10445d17d00a59764fd6b838a29026 | [
"MIT"
] | 1 | 2019-12-16T16:01:22.000Z | 2019-12-16T16:01:22.000Z | import { takeEvery, call, all, select, put } from 'redux-saga/effects';
import config from 'config';
import { dispatchSnackbar } from '../../common/snackbarSaga';
import { deleteRecords } from '../../common/gospelSaga';
import {
DATA_CLEAR_RECORDS,
DATA_REQUESTED,
DATA_DELETE_SUCCEDED,
} from '../Data/constants';
import {
ACCOUNTS_DELETE_REQUESTED,
ACCOUNTS_DELETE_SUCCEEDED,
ACCOUNTS_DELETE_FAILED,
ACCOUNTS_DELETE,
} from './constants';
function* deleteSuccess() {
yield call(dispatchSnackbar, 'Account(s) successfully deleted');
}
function* deleteFailure({ message }) {
yield call(
dispatchSnackbar,
`Account(s) could not be deleted: ${message}`,
'error',
);
}
function* deleteAccounts({ instanceID, selectedIds }) {
try {
const records = yield select(state => state.data[instanceID].records);
const toBeDeleted = records
.filter(record => selectedIds.includes(record.Id))
.reduce(
(acc, record) => [
...acc,
{
definition: config.recordDefinitions.talentsDataDefinition,
id: record.Id,
},
{
definition: config.recordDefinitions.piiDataDefinition,
id: record.Id,
},
{
definition: config.recordDefinitions.candidatesDefinition,
id: record['Email address'],
},
],
[],
);
yield call(deleteRecords, toBeDeleted, ACCOUNTS_DELETE);
yield put({ type: DATA_DELETE_SUCCEDED, instanceID });
yield put({ type: DATA_CLEAR_RECORDS, instanceID });
yield put({ type: DATA_REQUESTED, instanceID });
} catch (e) {
yield put({
type: ACCOUNTS_DELETE_FAILED,
instanceID,
message: e.message,
});
}
}
// Individual exports for testing
export default function* adminCandidatesListActions() {
yield all([
takeEvery(ACCOUNTS_DELETE_REQUESTED, deleteAccounts),
takeEvery(ACCOUNTS_DELETE_FAILED, deleteFailure),
takeEvery(ACCOUNTS_DELETE_SUCCEEDED, deleteSuccess),
]);
}
| 27.581081 | 74 | 0.651151 |
8b5a76d38d8772cfae99b798dbab3f8e7599dca5 | 4,892 | js | JavaScript | src/components/helper/customComponent/Menu.js | kashanmirza/react_redux_custom | c829f45fd1d65a01775ff0b3904e0d4533808116 | [
"MIT"
] | null | null | null | src/components/helper/customComponent/Menu.js | kashanmirza/react_redux_custom | c829f45fd1d65a01775ff0b3904e0d4533808116 | [
"MIT"
] | null | null | null | src/components/helper/customComponent/Menu.js | kashanmirza/react_redux_custom | c829f45fd1d65a01775ff0b3904e0d4533808116 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import logo from '../logo.svg';
import { Link } from 'react-router';
import $ from 'jquery';
// import menuIcon from '../img/icon1.png';
class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
sidebarCtrl: this.props.sidebarCtrl,
titleCtrl: this.props.titleCtrl,
selectedMenu: 'item1',
}
}
componentDidMount() {
}
componentWillReceiveProps(nextProps) {
this.setState({
sidebarCtrl: nextProps.sidebarCtrl,
titleCtrl: nextProps.titleCtrl
})
}
menuSelected(menuType) {
if (this.state.selectedMenu === menuType) {
this.setState({ selectedMenu: null })
}
else {
this.setState({ selectedMenu: menuType })
}
}
render() {
return (
<div className={this.state.sidebarCtrl}>
<ul className="sideMenu">
<li><Link className={this.state.selectedMenu === 'item1' ? 'active' : ''} onClick={() => this.menuSelected("item1")} to="/Overview"><i className="icon-eye"></i><title className={this.state.titleCtrl}>Overview</title></Link></li>
<li><Link className={this.state.selectedMenu === 'item3' ? 'active' : ''} onClick={() => this.menuSelected("item3")}><i className="icon-list"></i><title className={this.state.titleCtrl}>Datamanipulaton</title></Link>
{this.state.selectedMenu === 'item3' ?
<ul>
<li><Link to="/Dml"><title className={this.state.titleCtrl}>Table Handling</title></Link></li>
<li><Link to="/Formhandling"><title className={this.state.titleCtrl}>Form Handling</title></Link></li>
<li><Link to="/Stepsformhandling"><title className={this.state.titleCtrl}>Steps Form Handling</title></Link></li>
</ul>
: null}
</li>
<li><Link className={this.state.selectedMenu === 'item4' ? 'active' : ''} onClick={() => this.menuSelected("item4")}><i className="icon-support"></i><title className={this.state.titleCtrl}>Custom Components</title></Link>
{this.state.selectedMenu === 'item4' ?
<ul>
<li><Link to="/Icons"><title className={this.state.titleCtrl}>Icons</title></Link></li>
<li><Link to="/Portlate"><title className={this.state.titleCtrl}>Portlates</title></Link></li>
<li><Link to="/Messages"><title className={this.state.titleCtrl}>Messages</title></Link></li>
<li><Link to="/Buttons"><title className={this.state.titleCtrl}>Buttons</title></Link></li>
<li><Link to="/Tabs"><title className={this.state.titleCtrl}>Tabs</title></Link></li>
<li><Link to="/Modalexample"><title className={this.state.titleCtrl}>Modal</title></Link></li>
<li><Link to="/Tooltipexample"><title className={this.state.titleCtrl}>Tooltip</title></Link></li>
<li><Link to="/Progressbarcustom"><title className={this.state.titleCtrl}>Progressbar </title></Link></li>
<li><Link to="/Form"><title className={this.state.titleCtrl}>Forms</title></Link></li>
</ul>
: null}
</li>
<li><Link className={this.state.selectedMenu === 'item5' ? 'active' : ''} onClick={() => this.menuSelected("item5")}><i className="icon-layers"></i><title className={this.state.titleCtrl}>Third Party Components</title></Link>
{this.state.selectedMenu === 'item5' ?
<ul>
<li><Link to="/Charts"><title className={this.state.titleCtrl}>Charts</title></Link></li>
<li><Link to="/Datatable"><title className={this.state.titleCtrl}>Data Table</title></Link></li>
<li><Link to="/Switchbutton"><title className={this.state.titleCtrl}>Switch Button</title></Link></li>
<li><Link to="/Progressbar"><title className={this.state.titleCtrl}>Progress Bar</title></Link></li>
<li><Link to="/Ratingstar"><title className={this.state.titleCtrl}>Star Ratings</title></Link></li>
<li><Link to="/Scrollbar"><title className={this.state.titleCtrl}>Scrollbar</title></Link></li>
<li><Link to="/Datetimepicker"><title className={this.state.titleCtrl}>Datetime Picker</title></Link></li>
<li><Link to="/Reactseletc"><title className={this.state.titleCtrl}>React Seletc </title></Link></li>
<li><Link to="/Checkboxradiobutton"><title className={this.state.titleCtrl}>Checkbox Radio Button</title></Link></li>
<li><Link to="/Treemenu"><title className={this.state.titleCtrl}>Tree Menu</title></Link></li>
<li><Link to="/Qrcode"><title className={this.state.titleCtrl}>QR Code</title></Link></li>
</ul>
: null}
</li>
</ul>
</div>
);
}
}
export default Menu;
| 50.958333 | 238 | 0.597302 |
8b5ab7f3ab3fd16a0f819deb8834ab6ab8ca9644 | 92 | js | JavaScript | src/test1_files/jquery.color-2.1.2.min.js | The8thHorcrux/Decentralized-MilestoneBased-CrowdFunding | 312987e34f352564db6550803691a35105da05ac | [
"MIT"
] | null | null | null | src/test1_files/jquery.color-2.1.2.min.js | The8thHorcrux/Decentralized-MilestoneBased-CrowdFunding | 312987e34f352564db6550803691a35105da05ac | [
"MIT"
] | 3 | 2020-07-18T13:24:36.000Z | 2022-02-12T22:51:44.000Z | src/test1_files/jquery.color-2.1.2.min.js | The8thHorcrux/Decentralized-MilestoneBased-CrowdFunding | 312987e34f352564db6550803691a35105da05ac | [
"MIT"
] | null | null | null | typeof btjsonpcallback1571119154217 ==="function" && btjsonpcallback1571119154217 ("16%km"); | 92 | 92 | 0.804348 |
8b5b10150829d1f58fbaf397d61264b68046e6ab | 2,357 | js | JavaScript | extension/src/js/activate_laser.js | Bionic-Lazer/BionicLazer | 0dcbd3420967b407bec494cfebf0272057cbaf2b | [
"MIT"
] | null | null | null | extension/src/js/activate_laser.js | Bionic-Lazer/BionicLazer | 0dcbd3420967b407bec494cfebf0272057cbaf2b | [
"MIT"
] | null | null | null | extension/src/js/activate_laser.js | Bionic-Lazer/BionicLazer | 0dcbd3420967b407bec494cfebf0272057cbaf2b | [
"MIT"
] | null | null | null | var socket = io("http://localhost:3000");
var point = document.createElement('DIV');
var id;
var answers = [];
var width = window.innerWidth;
var height = window.innerHeight;
point.id = "LvUkES3XHDSCT";
point.setAttribute('style', 'width: 10px; height: 10px; background: red; border: 2px solid black; transform: rotate(45deg); background-size: cover; position: fixed; top: 50%; left: 50%; z-index: 5423543542; display: block');
function randomID() {
var dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var num1 = Math.floor(Math.random() * 62);
var num2 = Math.floor(Math.random() * 62);
var num3 = Math.floor(Math.random() * 62);
var num4 = Math.floor(Math.random() * 62);
return dict[num1] + dict[num2] + dict[num3] + dict[num4];
}
id = randomID();
function scale(x0, x1, y0, y1, x) {
return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//console.log(request);
if(request.laserActivate) {
sendResponse({id: id, runAgain: false});
}
if(request.hasOwnProperty("laserOn")) {
if(request.laserOn) {
document.body.appendChild(point);
} else {
document.body.removeChild(point);
}
}
if(request.question) {
console.log("Question received");
socket.emit('question', {id: id, question: request.question});
}
if(request.getAnswers) {
console.log(answers);
if(answers.length > 0) {
sendResponse(answers);
}
}
if(request.endSession) {
answers.splice(0, answers.length);
socket.emit('endQuestion', {id: id});
}
});
socket.on('type_request', function() {
socket.emit('type_response', {type: "receiver", key: id});
});
socket.on('motion', function(data) {
var x = data.x, y = data.y;
point.style.transform = "translate(" + scale(-90, 90, -width/2, width/2, x) + "px, " + scale(-60, 60, -height/2, height/2, y) + "px)";
});
socket.on('phoneClick', function(data) {
var x = scale(-90, 90, -width/2, width/2, data.x), y = scale(-60, 60, -height/2, height/2, data.y);
document.elementFromPoint(x + width/2, y + (width/2) - 52).click();
console.log("Click!");
});
socket.on('answer', function(answer) {
console.log("Answer this");
answers.push(answer);
});
| 31.851351 | 224 | 0.621977 |
8b5b32b488b6e2c3a18b53b3cd0984a4fb5b7ff8 | 6,635 | js | JavaScript | src/resourceful.resource.js | danmartens/ember-resourceful | 271b2c40026ba8257e614e85f78e1dc7c924e855 | [
"MIT"
] | 1 | 2018-08-25T14:37:01.000Z | 2018-08-25T14:37:01.000Z | src/resourceful.resource.js | danmartens/ember-resourceful | 271b2c40026ba8257e614e85f78e1dc7c924e855 | [
"MIT"
] | null | null | null | src/resourceful.resource.js | danmartens/ember-resourceful | 271b2c40026ba8257e614e85f78e1dc7c924e855 | [
"MIT"
] | null | null | null | /**
* @class Resourceful.Resource
* @constructor
*/
Resourceful.Resource = Ember.Object.extend({
resourceAdapter: null,
isPersisted: false,
isFetching: false,
isFetched: false,
isSaving: false,
isDeleting: false,
isDeleted: false,
isDirty: Ember.computed.bool('_dirtyAttributes.length'),
_lastRequest: null,
init: function() {
if (!this._data) this.setupData();
this._super();
},
/**
* @method setupData
*/
setupData: function() {
this.setProperties({
_data: {},
_persistedData: {},
_dirtyAttributes: []
});
},
/**
* Serializes the resource's data so it's ready to be sent to the server.
*
* @method serialize
* @return {Object} Serialized data object
*/
serialize: function() {
var serialized = {},
data = this.get('_data'),
_this = this;
Ember.keys(data).forEach(function(key) {
serialized[key] = _this._serializeAttr(key, data[key]);
});
if (this.resourceName) {
var s = {}; s[this.resourceName] = serialized;
return s;
} else {
return serialized;
}
},
/**
* Deserializes the passed data and adds it to the resource.
*
* @method deserialize
* @param {Object} data The data to be deserialized
* @return {Object} Serialized data object
*/
deserialize: function(data) {
var _this = this;
Ember.beginPropertyChanges(this);
Ember.keys(data).forEach(function(key) {
var collection, value = data[key];
if (_this.get(key + '.embedded')) {
collection = Resourceful.collectionFor(_this.get(key + '.foreignResourceClass'));
collection.loadAll(value);
} else {
_this.set(key, _this._deserializeAttr(key, data[key]));
}
});
this.set('isPersisted', true);
Ember.endPropertyChanges(this);
this._updatePersistedData();
return this;
},
/**
* Loads the resource from the server.
*
* @method findResource
* @param {Object} options Options to be passed to `ResourceAdapter#request()`
* @return {RSVP.Promise} The promise returned from the ResourceAdapter
*/
findResource: function(options) {
var resolved, rejected, _this = this;
this.set('isFetching', true);
if (!options) {
options = {};
}
if (!options.url) {
options.url = this._resourceUrl();
}
resolved = function(data) {
_this.deserialize(data);
_this.set('isFetching', false);
};
rejected = function() {
_this.set('isFetching', false);
}
return this._request('read', options).then(resolved, rejected);
},
/**
* Persists the resource to the server.
*
* @method saveResource
* @param {Object} options Options to be passed to `ResourceAdapter#request()`
* @return {RSVP.Promise} The promise returned from the ResourceAdapter
*/
saveResource: function(options) {
var method, resolved, promise, _this = this;
this.set('isSaving', true);
if (!options) {
options = {};
}
if (!options.url) {
options.url = this._resourceUrl();
}
if (!options.data) {
options.data = this.serialize();
}
method = this.get('isPersisted') ? 'create' : 'update';
resolved = function(data) {
_this.deserialize(data);
_this.set('isSaving', false);
};
rejected = function() {
_this.set('isSaving', false);
};
return this._request(method, options).then(resolved, rejected);
},
/**
* Deletes the resource from the server.
*
* @method deleteResource
* @param {Object} options Options to be passed to `ResourceAdapter#request()`
* @return {RSVP.Promise} The promise returned from the ResourceAdapter
*/
deleteResource: function(options) {
var resolved, rejected, _this = this;
this.set('isDeleting', true);
if (!options) {
options = {};
}
if (!options.url) {
options.url = this._resourceUrl();
}
resolved = function() {
_this.set('isDeleting', false);
_this.set('isDeleted', true);
};
rejected = function() {
_this.set('isDeleting', false);
};
return this._request('delete', options).then(resolved, rejected);
},
/**
* Reverts the passed attributes to their previous values (or all attributes if nothing is passed).
*
* @method revertAttributes
* @param {Array} keys Attributes to be reverted
*/
revertAttributes: function(keys) {
var keys, _this = this;
if (Ember.typeOf(keys) == 'string' && arguments.length > 0) {
keys = Array.prototype.slice.call(arguments, 0);
}
if (!keys) {
keys = Ember.keys(this._persistedData);
}
Ember.beginPropertyChanges(this);
keys.forEach(function(key) {
_this.set(key, _this._persistedData[key]);
_this._dirtyAttributes.removeObject(key);
});
Ember.endPropertyChanges(this);
},
_serializeAttr: function(key, value) {
var descs = Ember.meta(this.constructor.proto()).descs;
if (descs[key] && descs[key]._meta.type && descs[key]._meta.type.serialize) {
return descs[key]._meta.type.serialize(value);
} else {
return value;
}
},
_deserializeAttr: function(key, value) {
var descs = Ember.meta(this.constructor.proto()).descs;
if (descs[key] && descs[key]._meta.type && descs[key]._meta.type.deserialize) {
return descs[key]._meta.type.deserialize(value);
} else {
return value;
}
},
_updatePersistedData: function() {
var _this = this;
Ember.beginPropertyChanges(this);
this._dirtyAttributes.clear();
Ember.keys(this.get('_data')).forEach(function(key) {
_this.set('_persistedData.' + key, _this.get('_data.' + key));
});
Ember.endPropertyChanges(this);
},
_resourceUrl: function() {
var url, adapter = this.get('resourceAdapter');
url = adapter.buildURI(this.constructor.resourceUrl);
if (!this.get('isPersisted')) {
url += '/' + this.get('id');
}
return url;
},
_request: function() {
var args, adapter, request;
args = arguments;
adapter = this.resourceAdapter;
request = function() {
return adapter.request.apply(adapter, args);
};
this._lastRequest = (this._lastRequest) ? this._lastRequest.then(request, request) : request();
return this._lastRequest;
}
});
Resourceful.Resource.reopenClass({
find: function(id, options) {
var collection = Resourceful.collectionFor(this);
if (!id || Ember.typeOf(id) === 'object') {
return collection.findAllResources(id);
} else {
return collection.findResource(id, options);
}
}
});
| 22.645051 | 100 | 0.622758 |
8b5bb13114aaa8a7e4f2e78d6df409160bfe19a9 | 1,045 | js | JavaScript | src/Tests/Results.js | DasRed/loader.io | cb2f43d804083a7c4467d6685f67f22aefe4a139 | [
"MIT"
] | 1 | 2021-08-20T15:49:10.000Z | 2021-08-20T15:49:10.000Z | src/Tests/Results.js | DasRed/loader.io | cb2f43d804083a7c4467d6685f67f22aefe4a139 | [
"MIT"
] | 2 | 2020-11-24T20:27:23.000Z | 2020-11-30T08:41:50.000Z | src/Tests/Results.js | DasRed/loader.io | cb2f43d804083a7c4467d6685f67f22aefe4a139 | [
"MIT"
] | 1 | 2020-11-25T17:17:26.000Z | 2020-11-25T17:17:26.000Z | import Endpoint from '../Endpoint.js';
import Exception from '../Exception.js';
import Result from './Result.js';
import Client from '../Client.js';
export default class Results extends Endpoint {
/**
*
* @param {Client} client
* @param {string} testId
*/
constructor(client, testId) {
super(client);
this.testId = testId;
}
/**
*
* @param {string} id
* @return {Promise<Result>}
*/
async get(id) {
const data = await this.client.request(`tests/${this.testId}/results/${id}`, Client.METHOD.GET);
if (data === undefined) {
throw new Exception(`Loader.io result ${id} can not be found.`);
}
return new Result(data);
}
/**
* @return {Promise<Result[]>}
*/
async list() {
const data = await this.client.request(`tests/${this.testId}/results`, Client.METHOD.GET);
if (data === undefined) {
return [];
}
return data.map((entry) => new Result(entry));
}
}
| 23.75 | 104 | 0.546411 |
8b5c99997fc6d7f979f0fc724d02b576e002fb0a | 340 | js | JavaScript | src/components/Modal/ModalContent.js | wundery/wundery-ui-react | a0d4c6ac24948f6568a15f67639d1b99ae1db36b | [
"MIT"
] | 4 | 2017-01-19T11:21:11.000Z | 2020-07-23T13:33:55.000Z | src/components/Modal/ModalContent.js | wundery/wundery-ui-react | a0d4c6ac24948f6568a15f67639d1b99ae1db36b | [
"MIT"
] | 7 | 2016-11-08T15:47:04.000Z | 2021-05-09T06:13:57.000Z | src/components/Modal/ModalContent.js | wundery/wundery-ui-react | a0d4c6ac24948f6568a15f67639d1b99ae1db36b | [
"MIT"
] | null | null | null | import React from 'react';
// Utils
import classnames from 'classnames';
const ModalContent = (props) => {
const children = props.children;
return (
<div className={classnames('ui-modal-content')}>
{children}
</div>
);
};
ModalContent.propTypes = {
children: React.PropTypes.node,
};
export default ModalContent;
| 16.190476 | 52 | 0.670588 |
8b5d184190d6b2e5f000cd4c40dcf34b846465a0 | 246 | js | JavaScript | transforms/__testfixtures__/d3-shape.output.js | expobrain/d3-upgrade-codemods | a83fda3e1c333d9f7979c5a30e9387378c97327d | [
"MIT"
] | 3 | 2017-05-22T20:22:46.000Z | 2022-02-05T00:12:47.000Z | transforms/__testfixtures__/d3-shape.output.js | expobrain/d3-upgrade-codemods | a83fda3e1c333d9f7979c5a30e9387378c97327d | [
"MIT"
] | 3 | 2022-01-25T11:20:08.000Z | 2022-01-25T11:29:05.000Z | transforms/__testfixtures__/d3-shape.output.js | expobrain/d3-upgrade-codemods | a83fda3e1c333d9f7979c5a30e9387378c97327d | [
"MIT"
] | null | null | null | d3.line;
d3.radialLine;
d3.area;
d3.radialArea;
d3.arc;
d3.symbol;
d3.symbolTypes;
d3.pie;
d3.stack;
(function() {
throw Error("d3.svg.diagonal has been removed");
});
(function() {
throw Error("d3.svg.diagonal.radial has been removed");
});
| 15.375 | 57 | 0.691057 |
8b5db96c7e66e71d23112d987394e38771f34bcd | 833 | js | JavaScript | bolseiroDeValor/client/assets/js/app/views/NegotiationView.js | alexcamaroti/ecmascript | 87964b9421d2c281ecd01234585a5c8e82b6c09b | [
"MIT"
] | null | null | null | bolseiroDeValor/client/assets/js/app/views/NegotiationView.js | alexcamaroti/ecmascript | 87964b9421d2c281ecd01234585a5c8e82b6c09b | [
"MIT"
] | null | null | null | bolseiroDeValor/client/assets/js/app/views/NegotiationView.js | alexcamaroti/ecmascript | 87964b9421d2c281ecd01234585a5c8e82b6c09b | [
"MIT"
] | null | null | null | class NegotiationView extends View{
template(model){
return `
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>DATE</th>
<th>QUANTITY</th>
<th>COST</th>
<th>TOTAL</th>
</tr>
</thead>
<tbody>
${model.allNegotiations.map(item =>
`<tr>
<td>${DateHelper.dateToText(item.date)}</td>
<td>${item.quantity}</td>
<td>${item.cost}</td>
<td>${item.total}</td>
</tr>`
).join("")}
</tbody>
<tfoot>
<td colspan="3"></td>
<td>${model.allNegotiations.reduce((total, item) => total + item.total, 0.0)}</td>
</tfoot>
</table>`
}
} | 25.242424 | 90 | 0.406963 |
8b5e2bba93229e941c09d48639ecdc0454d93d23 | 405 | js | JavaScript | insurance/test/Insurance.js | Toiling-Lad/DApp_project | 34984b7acbf382aae646224962284344a2753a04 | [
"MIT"
] | null | null | null | insurance/test/Insurance.js | Toiling-Lad/DApp_project | 34984b7acbf382aae646224962284344a2753a04 | [
"MIT"
] | null | null | null | insurance/test/Insurance.js | Toiling-Lad/DApp_project | 34984b7acbf382aae646224962284344a2753a04 | [
"MIT"
] | null | null | null | // var Insurance = artifacts.require('./Insurance.sol')
// contract('Insurance', function(accounts) {
// it('initializes with two insurance Types', function() {
// return Insurance.deployed()
// .then(function(instance) {
// wait
// return instance.insuranceTypesCount()
// })
// .then(function(count) {
// assert.equal(count, 2)
// })
// })
// })
| 27 | 60 | 0.565432 |
8b5e549638528be1ee09eff533ca2d716c6999b3 | 6,725 | js | JavaScript | src/components/Register/index.js | ssolmonson/video-activity-hub | a93fdec9ff8d5986c93c2f9c97380a90264f01b1 | [
"Apache-2.0"
] | null | null | null | src/components/Register/index.js | ssolmonson/video-activity-hub | a93fdec9ff8d5986c93c2f9c97380a90264f01b1 | [
"Apache-2.0"
] | null | null | null | src/components/Register/index.js | ssolmonson/video-activity-hub | a93fdec9ff8d5986c93c2f9c97380a90264f01b1 | [
"Apache-2.0"
] | 1 | 2020-12-30T19:13:26.000Z | 2020-12-30T19:13:26.000Z | import React from 'react';
import Typography from '@material-ui/core/Typography';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import RegisterImage from './../../images/CatChau-18.png';
import FacebookIcon from '@material-ui/icons/Facebook';
import GitHubIcon from '@material-ui/icons/GitHub';
import TwitterIcon from '@material-ui/icons/Twitter';
import Button from '@material-ui/core/Button';
import { ReactComponent as GoogleLogo } from './google-logo.svg';
import Checkbox from '@material-ui/core/Checkbox';
import { fade, withStyles, makeStyles } from '@material-ui/core/styles';
import InputBase from '@material-ui/core/InputBase';
import { InputLabel } from '@material-ui/core';
import FormControl from '@material-ui/core/FormControl';
const RegisterPage = ({ classes }) => {
const BootstrapInput = withStyles(theme => ({
root: {
'label + &': {
marginTop: theme.spacing(3),
},
},
input: {
background: 'linear-gradient(45deg, #e6e6e6 30%, #f2f2f2 90%)',
borderRadius: 4,
position: 'relative',
backgroundColor: theme.palette.common.white,
fontSize: 16,
width: '100%',
padding: '10px 12px',
transition: theme.transitions.create(['border-color', 'box-shadow']),
// Use the system font instead of the default Roboto font.
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
'&:focus': {
boxShadow: `${fade(theme.palette.primary.main, 0.25)} 0 0 0 0.2rem`,
borderColor: theme.palette.primary.main,
},
},
}))(InputBase);
// const useStyles = makeStyles(theme => ({
// googleButton: {
// background: 'gray',
// color: 'rgb(0, 94, 166)',
// borderRadius: '4px',
// maxWidth: '65px',
// border: '2px solid rgb(2, 122, 197)',
// textTransform: 'none',
// boxShadow: 'none',
// padding: '0.3em 1em',
// [theme.breakpoints.down('sm')]: {
// width: '80%',
// },
// '&:hover': {
// background: 'white',
// boxShadow: 'none',
// },
// },
// }));
return (
<div className={classes.container}>
<div className={classes.leftContainer}>
<h1>The Hub</h1>
<img alt="Register" className={classes.image} src={RegisterImage} />
</div>
<form className={classes.form} noValidate autoComplete="off">
<Typography style={{ color: '#878787', marginBottom: '20px' }} align="right" variant="subtitle">
Already a member?{' '}
<span>
<a href="/login">Sign In</a>
</span>
</Typography>
<div className={classes.createAccount}>
<Typography align="left" variant="h5">
Create your account
</Typography>
<Typography align="left" variant="subtitle">
Start building experiences
</Typography>
</div>
<div className={classes.inputName}>
<FormControl className={classes.margin}>
<InputLabel className={classes.formInput} shrink htmlFor="bootstrap-input">
NAME
</InputLabel>
<BootstrapInput id="bootstrap-input" />
</FormControl>
<FormControl className={classes.margin}>
<InputLabel className={classes.formInput} shrink htmlFor="bootstrap-input">
SURNAME
</InputLabel>
<BootstrapInput id="bootstrap-input" />
</FormControl>
</div>
<FormControl className={classes.margin}>
<InputLabel className={classes.formInput} shrink htmlFor="bootstrap-input">
E-MAIL ADDRESS
</InputLabel>
<BootstrapInput id="bootstrap-input" />
</FormControl>
<FormControl className={classes.margin}>
<InputLabel className={classes.formInput} shrink htmlFor="bootstrap-input">
PASSWORD
</InputLabel>
<BootstrapInput defaultValue="" id="bootstrap-input" />
</FormControl>
<FormControlLabel control={<Checkbox />} label="I've read and accepted Terms of Service and Privacy Policy" />
<Button variant="contained" color="primary" type="submit">
Create an account
</Button>
<div style={{ margin: '20px 0' }}>
<h5 className={classes.horizontalText}>
<span style={{ background: '#fafafafa', padding: '0 20px ', color: '#c1c1c1' }}>OR</span>
</h5>
</div>
<div className={classes.btnWrap}>
<Button
style={{ marginBottom: '10px' }}
variant="contained"
className={classes.googleButton}
startIcon={<GoogleLogo />}
>
Sign in with Google
</Button>
<Button style={{ marginBottom: '10px' }} variant="contained" className={classes.googleButton}>
<FacebookIcon />
Sign in with Facebook
</Button>
<Button style={{ marginBottom: '10px' }} variant="contained" className={classes.googleButton}>
<TwitterIcon style={{ margin: '0 10px 5px 0' }} />
Sign in with Twitter
</Button>
<Button style={{ marginBottom: '10px' }} variant="contained" className={classes.googleButton}>
<GitHubIcon style={{ margin: '0 10px 5px 0' }} />
Sign in with GitHub
</Button>
</div>
</form>
</div>
);
};
const styles = ({ palette, breakpoints, spacing, typography }) => ({
container: {
display: 'flex',
justifyContent: 'center',
marginTop: '50px',
height: '100%',
},
form: {
display: 'flex',
flexDirection: 'column',
margin: '50px',
},
leftContainer: {
margin: '50px',
width: '40%',
borderRadius: '20px',
},
inputName: {
display: 'flex',
justifyContent: 'space-between',
marginBottom: '10px',
},
inputText: {
marginBottom: '10px',
},
image: {
width: '100%',
},
horizontalText: {
width: '100%',
textAlign: 'center',
borderBottom: '1px solid #c1c1c1',
lineHeight: '0.1em',
margin: '10px 0 20px',
},
formInput: {
color: '#878787',
},
formInputFiled: {
backgroundColor: '#c1c1c1',
},
createAccount: {
fontWeight: 900,
marginBottom: '10px',
},
btnWrap: {
display: 'flex',
flexWrap: 'wrap',
width: '450px',
height: 'auto',
justifyContent: 'space-between',
},
});
export default withStyles(styles)(RegisterPage);
| 32.177033 | 118 | 0.572491 |
8b5eeca2d1311ae33023dcdd072c1f846da04cfd | 179 | js | JavaScript | test/unit/helpers/fulfilled.js | Yuiham/loyal-promise | e828c1546867f0e46c10bb4dc2cc836d92ae52a8 | [
"MIT"
] | 2 | 2016-10-25T00:56:35.000Z | 2016-11-05T08:45:34.000Z | test/unit/helpers/fulfilled.js | Yuiham/loyal-promise | e828c1546867f0e46c10bb4dc2cc836d92ae52a8 | [
"MIT"
] | null | null | null | test/unit/helpers/fulfilled.js | Yuiham/loyal-promise | e828c1546867f0e46c10bb4dc2cc836d92ae52a8 | [
"MIT"
] | null | null | null | module.exports = function (promise) {
return {
then(fn) {
return promise.then(
val => fn.call(promise, val),
err => { throw err}
)
}
}
} | 17.9 | 38 | 0.486034 |
8b5f99999f5cc0e77fd38306fd878554666e70cb | 236 | js | JavaScript | dist/resources/prod/1524/63/chunk-KFS5E7J2.js | atompkins/fallenswordhelper | 5aa8006273029fbad59f2283e2913d959be671a6 | [
"MIT"
] | 5 | 2017-07-22T01:52:20.000Z | 2021-07-04T17:19:20.000Z | dist/resources/prod/1524/63/chunk-KFS5E7J2.js | atompkins/fallenswordhelper | 5aa8006273029fbad59f2283e2913d959be671a6 | [
"MIT"
] | 305 | 2015-05-18T20:40:40.000Z | 2022-03-31T23:20:41.000Z | dist/resources/prod/1524/63/chunk-KFS5E7J2.js | atompkins/fallenswordhelper | 5aa8006273029fbad59f2283e2913d959be671a6 | [
"MIT"
] | 13 | 2016-07-22T12:37:27.000Z | 2022-03-06T15:19:00.000Z | import{a as o}from"./chunk-7HLV5CMY.js";import{L as i,M as e}from"./chunk-TD2HJ4A4.js";import{a as r}from"./chunk-PMRPPTTZ.js";function n(){r.enableMaxGroupSizeToJoin?o(e):o(i)}export{n as a};
//# sourceMappingURL=chunk-KFS5E7J2.js.map
| 78.666667 | 192 | 0.733051 |
8b5fa1204adb8e46db7f7b4c6207f1b0e53475ee | 1,554 | js | JavaScript | src/core/categoryDbControl.js | aviskotian/Category_Product_REST-API | cf4470b7aeb56c40954b7c35ee26bfc96d76318c | [
"MIT"
] | null | null | null | src/core/categoryDbControl.js | aviskotian/Category_Product_REST-API | cf4470b7aeb56c40954b7c35ee26bfc96d76318c | [
"MIT"
] | null | null | null | src/core/categoryDbControl.js | aviskotian/Category_Product_REST-API | cf4470b7aeb56c40954b7c35ee26bfc96d76318c | [
"MIT"
] | null | null | null | const Category = require('../models/category')
const ErrorHandler = require('../errorHandler/error')
const createCategory = async (req) => {
try{
if(!req.body.name) {
throw new ErrorHandler(`Category name is required`)
}
if(req.body.parentCategoryID){
const category = await Category.findOne({_id : req.body.parentCategoryID})
if(!category){
throw new ErrorHandler(`Invalid parentCategoryID`)
}
}
const category = new Category({
...req.body,
parentCategoryID: req.body.parentCategoryID || 0
})
await category.save()
return Promise.resolve({
status: 'success',
category
})
}catch(e) {
return Promise.reject({
status: 'error',
message: e.message,
})
}
}
const getCategories = async () => {
try{
const categories = await Category.aggregate([
{ "$addFields": { "parentCategoryID": { "$toString": "$_id" }}},
{ "$lookup": {
"from": "categories",
"localField": "parentCategoryID",
"foreignField": "parentCategoryID",
"as": "child_categories"
}}
])
return Promise.resolve({
categories
})
}catch(e) {
return Promise.reject({
status: 'error',
message: e.message,
})
}
}
module.exports ={
createCategory,
getCategories
} | 25.9 | 86 | 0.507722 |
8b604277942c1d3614c4c171b36c753a4ea89f5c | 5,215 | js | JavaScript | src/index.js | MostlyJS/mostly-feathers-rest | 0b8c60e29fb31871418511e424208f53f5f38731 | [
"MIT"
] | 12 | 2017-05-03T01:05:33.000Z | 2019-10-17T01:54:21.000Z | src/index.js | MostlyJS/mostly-feathers-rest | 0b8c60e29fb31871418511e424208f53f5f38731 | [
"MIT"
] | 4 | 2020-01-15T02:18:01.000Z | 2021-05-07T13:04:24.000Z | src/index.js | MostlyJS/mostly-feathers-rest | 0b8c60e29fb31871418511e424208f53f5f38731 | [
"MIT"
] | 1 | 2019-05-22T12:37:55.000Z | 2019-05-22T12:37:55.000Z | const makeDebug = require('debug');
const wrappers = require('./wrappers');
const { ProxyService } = require('mostly-feathers');
const debug = makeDebug('mostly:feathers-rest');
function formatter (req, res, next) {
if (res.data === undefined) {
return next();
}
res.format({
'application/json': function () {
res.json(res.data);
}
});
}
module.exports = function rest (app, trans, path, customServices = [], domain = 'feathers', handler = formatter) {
// Register the REST provider
const uri = path || '';
debug(`REST handler for service route \`${uri}\``);
/** base route **/
const baseRoute = app.route(`${uri}/:service`)
// GET / -> find(params, cb)
.get(wrappers.find(trans, domain), handler)
// POST / -> create(data, params, cb)
.post(wrappers.create(trans, domain), handler)
// PUT / -> update(null, data, params)
.put(wrappers.update(trans, domain), handler)
// PATCH / -> patch(null, data, params)
.patch(wrappers.patch(trans, domain), handler)
// DELETE / -> remove(null, params)
.delete(wrappers.remove(trans, domain), handler);
/** route for custom services that handle the route themselves **/
for (const service of customServices) {
const customRoute = app.route(`${uri}/:service(${service})/:id(*)`)
// GET /:id -> get(id, params, cb)
.get(wrappers.get(trans, domain), handler)
// PUT /:id -> update(id, data, params, cb)
.put(wrappers.update(trans, domain), handler)
// PATCH /:id -> patch(id, data, params, callback)
.patch(wrappers.patch(trans, domain), handler)
// DELETE /:id -> remove(id, params, cb)
.delete(wrappers.remove(trans, domain), handler);
}
/** id route **/
const idRoute = app.route(`${uri}/:service/:id`)
// GET /:id -> get(id, params, cb)
.get(wrappers.get(trans, domain), handler)
// PUT /:id -> update(id, data, params, cb)
.put(wrappers.update(trans, domain), handler)
// PATCH /:id -> patch(id, data, params, callback)
.patch(wrappers.patch(trans, domain), handler)
// DELETE /:id -> remove(id, params, cb)
.delete(wrappers.remove(trans, domain), handler);
/** action route */
const actionRoute = app.route(`${uri}/:service/:id/:action`)
// PUT /:primary/:action -> action(id, data, params, cb)
.put(wrappers.update(trans, domain), handler)
// PATCH /:primary/:action -> action(id, data, params, callback)
.patch(wrappers.patch(trans, domain), handler)
// DELETE /:primary/:action -> action(id, params, callback)
.delete(wrappers.remove(trans, domain), handler);
/** subresources base route */
const subBaseRoute = app.route(`${uri}/:service/:primary/:subresources`)
// GET /:primary/:subresources -> find(params, cb)
.get(wrappers.subresources.find(trans, domain), handler)
// POST /:primary/:subresources -> create(data, params, cb)
.post(wrappers.subresources.create(trans, domain), handler);
/** subresources id route */
const subIdRoute = app.route(`${uri}/:service/:primary/:subresources/:id`)
// GET /:primary/:subresources/:id -> get(id, params, cb)
.get(wrappers.subresources.get(trans, domain), handler)
// PUT /:primary/:subresources/:id -> update(id, data, params, cb)
.put(wrappers.subresources.update(trans, domain), handler)
// PATCH /:primary/:subresources/:id -> patch(id, data, params, callback)
.patch(wrappers.subresources.patch(trans, domain), handler)
// DELETE /:primary/:subresources/:id -> remove(id, params, callback)
.delete(wrappers.subresources.remove(trans, domain), handler);
/** subresources action route */
const subActionRoute = app.route(`${uri}/:service/:primary/:subresources/:id/:action(*)`)
// PUT /:primary/:subresources/:id/:action -> action(id, data, params, cb)
.put(wrappers.subresources.update(trans, domain), handler)
// PATCH /:primary/:subresources/:id/:action -> action(id, data, params, callback)
.patch(wrappers.subresources.patch(trans, domain), handler)
// DELETE /:primary/:subresources/:id/:action -> action(id, params, callback)
.delete(wrappers.subresources.remove(trans, domain), handler);
// patch configure
app.configure = function (fn) {
fn && fn.call(app, app);
return app;
};
app.service = function (name) {
return new ProxyService({ name, domain, trans });
};
app.setup = function () {
return app;
};
const _superUse = app.use;
app.use = function (fn) {
let offset = 0;
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
}
}
var service = arguments[offset];
if (typeof service !== 'function') {
return app;
} else {
return _superUse.apply(app, arguments);
}
};
const _superListen = app.listen;
app.listen = function () {
const server = _superListen.apply(this, arguments);
app.setup(server);
return server;
};
app.feathers = {};
return function (req, res, next) {
req.feathers = { provider: 'rest' };
next();
};
}; | 34.536424 | 114 | 0.627229 |
8b60529483d1def91e69953c4bb5c89120e662de | 212 | js | JavaScript | webpack.dev.config.js | tangshuang/jqvm | a9c14059e0e29d88f5982596047f0093a0078886 | [
"MIT"
] | 48 | 2020-07-30T01:56:03.000Z | 2022-03-22T08:07:02.000Z | webpack.dev.config.js | tangshuang/jqvm | a9c14059e0e29d88f5982596047f0093a0078886 | [
"MIT"
] | 10 | 2021-03-10T08:04:17.000Z | 2022-02-27T09:06:34.000Z | webpack.dev.config.js | tangshuang/jqvm | a9c14059e0e29d88f5982596047f0093a0078886 | [
"MIT"
] | 5 | 2021-05-17T05:29:29.000Z | 2022-01-31T04:36:24.000Z | const [bundle, min] = require('./webpack.config.js')
module.exports = {
...bundle,
mode: 'none',
devServer: {
contentBase: __dirname,
port: 8099,
liveReload: true,
writeToDisk: true,
},
}
| 17.666667 | 52 | 0.608491 |
8b6103425342e35b977f6115fa6b9165478e9123 | 2,598 | js | JavaScript | src/locale/sl.js | jetiradoro/simple-react-validator | a0e42e47bed25c8cdf2ce4af0c3c9cbe0ac706c9 | [
"MIT"
] | 230 | 2017-05-09T20:12:17.000Z | 2022-03-29T13:15:48.000Z | src/locale/sl.js | jetiradoro/simple-react-validator | a0e42e47bed25c8cdf2ce4af0c3c9cbe0ac706c9 | [
"MIT"
] | 228 | 2017-07-20T15:35:20.000Z | 2022-03-30T19:21:25.000Z | src/locale/sl.js | jetiradoro/simple-react-validator | a0e42e47bed25c8cdf2ce4af0c3c9cbe0ac706c9 | [
"MIT"
] | 90 | 2017-07-20T09:59:11.000Z | 2022-03-25T06:43:02.000Z | // Slovenian
SimpleReactValidator.addLocale('sl', {
accepted : 'Polje :attribute mora biti izbrano.',
after : 'Polje :attribute mora biti večje od :date.',
after_or_equal : 'Polje :attribute mora biti večje ali enako :date.',
alpha : 'Polje :attribute lahko vsebuje samo črke.',
alpha_space : 'Polje :attribute lahko vsebuje samo črke in presledke.',
alpha_num : 'Polje :attribute lahko vsebuje samo črke in številke.',
alpha_num_space : 'Polje :attribute lahko vsebuje samo, številke in presledke.',
alpha_num_dash : 'Polje :attribute lahko vsebuje samo črke, številke in vezaje.',
alpha_num_dash_space : 'Polje :attribute lahko vsebuje samo črke, številke, vezaje in presledke.',
array : 'Polje :attribute mora biti niz.',
before : 'Polje :attribute mora biti manjše od :date.',
before_or_equal : 'Polje :attribute mora biti manjše ali enako :date.',
between : 'Polje :attribute mora biti med :min in :max:type.',
boolean : 'Polje :attribute mora biti logična spremenljivka.',
card_exp : 'Polje :attribute mora biti veljaven datum poteka kreditne kartice.',
card_num : 'Polje :attribute mora biti veljavna številka kreditne kartice.',
currency : 'Polje :attribute mora biti veljavna valuta.',
date : 'Polje :attribute mora biti datum.',
date_equals : 'Polje :attribute mora biti enak :date.',
email : 'Polje :attribute mora biti veljaven e-poštni naslov.',
in : 'Izbrano polje :attribute mora biti :values.',
integer : 'Polje :attribute mora biti celo število.',
max : 'Polje :attribute ne sme biti večje od :max:type.',
min : 'Polje :attribute mora biti večje od :min:type.',
not_in : 'Izbrano polje :attribute ne sme biti :values.',
not_regex : 'Polje :attribute ne sme biti v tem formatu.',
numeric : 'Polje :attribute mora biti število.',
phone : 'Polje :attribute mora biti veljavna telefonska številka.',
regex : 'Polje :attribute mora biti v tem formatu.',
required : 'Polje :attribute je obvezno.',
size : 'Polje :attribute mora biti :size:type.',
string : 'Polje :attribute mora biti beseda.',
typeof : 'Polje :attribute mora biti tipa :type.',
url : 'Polje :attribute mora biti URL povezava.'
});
| 68.368421 | 100 | 0.603926 |
8b6103e1eb507ec1e6c81f26aae63ea1a7c44d83 | 11,136 | js | JavaScript | test/utility.js | smltq/jPublic | d84f3da24d969d22fcbb195136c0f406ba27271c | [
"MIT"
] | 49 | 2019-04-09T09:38:20.000Z | 2022-01-02T12:01:08.000Z | test/utility.js | smltq/jPublic | d84f3da24d969d22fcbb195136c0f406ba27271c | [
"MIT"
] | 10 | 2019-05-31T03:50:39.000Z | 2022-02-11T03:49:15.000Z | test/utility.js | smltq/jPublic | d84f3da24d969d22fcbb195136c0f406ba27271c | [
"MIT"
] | 11 | 2019-04-09T09:52:53.000Z | 2020-11-16T10:17:24.000Z | (function () {
var _ = typeof require == 'function' ? require('..') : window._;
var templateSettings;
QUnit.module('utility', {
beforeEach: function () {
templateSettings = _.clone(_.templateSettings);
},
afterEach: function () {
_.templateSettings = templateSettings;
}
});
QUnit.test('获取随机数:getRandom', function (assert) {
var array = _.range(1000);
var min = Math.pow(2, 31);
var max = Math.pow(2, 62);
assert.ok(_.every(array, function () {
return _.getRandom(min, max) >= min;
}), '是否应该产生一个大于或等于最小值的随机数');
assert.ok(_.some(array, function () {
return _.getRandom(Number.MAX_VALUE) > 0;
}), '当传递“Number.MAX_VALUE”时,应该生成一个随机数');
});
QUnit.test('字节格式化:formatBytes', function (assert) {
assert.ok(_.formatBytes(1024) == '1 KB', '1KB转换正确');
assert.ok(_.formatBytes('1024') == '1 KB', '1KB转换正确');
assert.ok(_.formatBytes(1234) == '1.21 KB', '1.21KB转换正确');
assert.ok(_.formatBytes(1234, 3) == '1.205 KB', '1.205KB转换正确');
});
QUnit.test('比较两个数值的大小:numCompare', function (assert) {
assert.ok(_.numCompare(3, 5) == -1, '3<5,判断正确');
assert.throws(function () {
_.numCompare('ab', 3)
}, 'ab与3是不同类型无法判断');
assert.ok(_.numCompare(3, 3) == 0, '3>3,两个数值相等,判断错误');
assert.ok(_.numCompare(0.1, 0.11) == -1, '0.1<0.11,判断正确');
assert.ok(_.numCompare(-1, -2) == 1, '-1>-2,判断正确');
assert.ok(_.numCompare(0, -1) == 1, '0>-1,判断正确');
});
QUnit.test('去左空格:ltrim', function (assert) {
assert.ok(_.ltrim(' abcdegfg', ' ') == 'abcdegfg', ' abcdegfg去除左空格成功');
assert.ok(_.ltrim(' dff fad', ' ') == 'dff fad', ' dff fad去除左空格成功');
assert.ok(_.ltrim('dff fad', ' ') == 'dff fad', 'dff fad去除左空格成功');
assert.ok(_.ltrim('_ad', ' ') == '_ad', '_ad不含左空格');
});
QUnit.test('去右空格:rtrim', function (assert) {
assert.ok(_.rtrim('abcdegfg ', ' ') == 'abcdegfg', 'abcdegfg 去除右空格成功');
assert.ok(_.rtrim('abcd egfg ', ' ') == 'abcd egfg', 'abcd egfg 去除右空格成功');
assert.ok(_.rtrim('abcd egfg', ' ') == 'abcd egfg', 'abcd egfg去除右空格成功');
assert.ok(_.rtrim('ab——', ' ') == 'ab——', 'ab——不含右空格');
});
QUnit.test('判断是否为数组:_.isArray', function (assert) {
//assert.ok(_.isArray([{1:2},{1:3}]) == true,'[{1:2},{1:3}]是数组');
assert.ok(_.isArray([1, 2, 3]) == true, '[1,2,3]是数组');
assert.ok(_.isArray([[1], [3]]) == true, '[[1],[3]]是数组');
assert.ok(_.isArray([1]) == true, '[1]是数组');
assert.ok(_.isArray([1], [2]) == true, '[1],[2]是数组');
assert.ok(_.isArray({1: 2}) == false, '{1:2}不是数组');
//assert.ok(_.isArray(a) == false,'a不是数组');
assert.ok(_.isArray('a') == false, '字母a不是数组');
assert.ok(_.isArray("a") == false, '"a"不是数组');
assert.ok(_.isArray(123) == false, '123不是数组');
assert.ok(_.isArray(null) == false, 'null不是数组');
assert.ok(_.isArray(true) == false, 'true不是数组');
assert.ok(_.isArray(undefined) == false, 'undefinded不是数组');
//assert.ok(_.isArray(['a','b','c']) == true,'['a','b','c']是数组.');
});
QUnit.test('判断是否为数值: _.isNumeric', function (assert) {
var obj = [123, 0123, "123", 0, 123.12, +123, -123, "-12", [1], [1, 2], 0xFF, "0xFF", 8e5, "8e5", "a", ["a"], {11: 2}, null, true];
for (var i = 0; i < obj.length; i++) {
var result = _.isNumeric(obj[i]);
if (result)
assert.ok(result, obj[i] + '是数值');
else {
assert.notOk(result, obj[i] + '不是数值');
}
}
});
QUnit.test('阿拉伯数字转中文数字: _.cl', function (assert) {
//十口语化
assert.ok(_.cl("100111", {tenMin: true}) == "十万零一百一十一");
//非口语化
assert.ok(_.cl("100111") == "一十万零一百一十一");
//带小数点
assert.ok(_.cl("13.5", {tenMin: true}) == "十三点五");
//超大数
assert.ok(_.cl(1e16) == "一亿亿");
});
QUnit.test('固定获取月份第一天:_.firstDay', function (assert) {
assert.ok(_.dateFormat(_.firstDay(new Date('2019-05-09 06:20:30'))) == '2019-05-01 00:00:00', '2019年5月的第一天是2019-05-01');
});
QUnit.test('固定获取月份最后一天:_.firstDay', function (assert) {
assert.ok(_.dateFormat(_.lastDay(new Date('2019-11-1 06:20:30'))) == '2019-11-30 00:00:00', '2019年11月的最后一天是2019-11-30');
assert.ok(_.dateFormat(_.lastDay(new Date('2019-12-1 06:20:30'))) == '2019-12-31 00:00:00', '2019年12月的最后一天是2019-12-31');
assert.ok(_.dateFormat(_.lastDay(new Date('2019-2-3 06:20:30'))) == '2019-02-28 00:00:00', '2019年2月的最后一天是2019-02-28');
});
QUnit.test('获取随机日期:_.getRandomDate', function (assert) {
assert.ok(_.dateFormat(_.getRandomDate()), '随机日期' + _.dateFormat(_.getRandomDate()));
});
QUnit.test('随机获取月份第一天:_.firstDay', function (assert) {
var a = new Date()
for(var i = 0 ; i < 5; i++)
{
a = _.getRandomDate();
assert.ok(_.dateFormat(_.firstDay(a)), _.dateFormat(a) + '的第一天是' + _.dateFormat(_.firstDay(a)));
}
});
QUnit.test('随机获取月份最后一天:_.lastDay', function (assert) {
var a = new Date();
for(var i = 0; i < 5; i++)
{
a = _.getRandomDate();
assert.ok(_.dateFormat(_.lastDay(a)), _.dateFormat(a) + '的最后一天是' + _.dateFormat(_.lastDay(a)));
}
});
QUnit.test('数组差集:_.difference', function (assert) {
assert.ok(_.equals(_.difference([1, 2], [1, 2]), []), '[1, 2], [1, 2]的差集是[]');
assert.ok(_.equals(_.difference([1, 2, 3], [1, 2]), [3]), '[1, 2, 3], [1, 2]的差集是[3]');
assert.ok(_.equals(_.difference([1, 2, 3], [4, 5, 6]), [1, 2, 3]), '[1, 2, 3], [4, 5, 6]的差集是[1, 2, 3]');
//assert.ok(_.equals(_.difference([[1], [2]], [[1]]), [[2]]), 'pass');
assert.ok(_.equals(_.difference(['a', 'b'], ['a']), ['b']), 'pass');
assert.ok(_.equals(_.difference(["a", 'b'], ['b']), ['a']), 'pass');
//assert.ok(_.equals(_.difference([{11: 2}], [{4: 5}]), [{11: 2}]), 'pass');
});
QUnit.test('数组元素是否重复:_.isRepeat',function(assert){
assert.ok(_.isRepeat([1,2,3]) == false,'数组[1,2,3]没有重复元素');
assert.ok(_.isRepeat([1,2,3,3]),'数组[1,2,3,3]有重复元素');
assert.ok(_.isRepeat([1,2,3.2,3]) == false,'数组[1,2,3.2,3]没有重复元素');
assert.ok(_.isRepeat([-1,1]) == false,'数组[-1,1]没有重复元素');
assert.ok(_.isRepeat(['a','A']) == false,'数组[\'a\',\'A\']没有重复元素');
assert.ok(_.isRepeat([0,0,0,1]),'数组[0,0,0,1]有重复元素');
});
QUnit.test('获得本周的开始日期和结束日期:_.getWeekStartDate/_.getWeekEndDate',function(assert){
assert.ok(_.dateFormat(_.getWeekStartDate()),'本周的开始日期是'+_.dateFormat(_.getWeekStartDate()));
assert.ok(_.dateFormat(_.getWeekEndDate()),'本周的开始日期是'+_.dateFormat(_.getWeekEndDate()));
});
QUnit.test('返回日期的yyyy-MM-dd格式:_.shortDateFormat',function(assert){
assert.ok(_.now(),_.now());
assert.throws(function(){
_.shortDateFormat(new Date('adcvb'))
},'abcvb的日期格式不正确');
assert.throws(function(){
_.shortDateFormat(new Date(-100000000000))
},'-100000000000的日期格式不正确');
assert.ok(_.shortDateFormat(new Date(2016,4,5,17,55,55)),'2016,4,5,17,55,55的简洁日期为'+_.shortDateFormat(new Date(2016,4,5,17,55,55)));
assert.ok(_.shortDateFormat(new Date(2016,1,33,17,55,55)),'2016,1,33,17,55,55的简洁日期为'+_.shortDateFormat(new Date(2016,1,33,17,55,55)));
assert.ok(_.shortDateFormat(new Date(2016,4,5,17,55)),'2016,4,5,17,55的简洁日期为'+_.shortDateFormat(new Date(2016,4,5,17,55)));
assert.ok(_.shortDateFormat(new Date(2016,4,5,17)),'2016,4,5,17的简洁日期为'+_.shortDateFormat(new Date(2016,4,5,17)));
assert.ok(_.shortDateFormat(new Date(2016,4,5)),'2016,4,5的简洁日期为'+_.shortDateFormat(new Date(2016,4,5)));
assert.ok(_.shortDateFormat(new Date(2016,4)),'2016,4的简洁日期为'+_.shortDateFormat(new Date(2016,4)));
assert.ok(_.shortDateFormat(new Date(2016)),'2016的简洁日期为'+_.shortDateFormat(new Date(2016)));
assert.ok(_.shortDateFormat(new Date(99,4,5)),'99,4,5的简洁日期为'+_.shortDateFormat(new Date(99,4,5)));
assert.ok(_.shortDateFormat(new Date("October 13, 2014 11:13:00")),'"October 13, 2014 11:13:00"的简洁日期为'+_.shortDateFormat(new Date("October 13, 2014 11:13:00")));
assert.ok(_.shortDateFormat(new Date(100000000000)),'100000000000的简洁日期为'+_.shortDateFormat(new Date(100000000000)));
});
QUnit.test('将时间格式化为指定格式的String的相互转换:_.formatTime,_.unformatTime',function(assert){
//try{
assert.ok(_.formatTime(96420),'96420秒的指定string格式为'+_.formatTime(96420));
assert.ok(_.formatTime(0),'0秒的指定string格式为'+_.formatTime(0));
//assert.ok(_.formatTime(-20),'0秒的指定string格式为'+_.formatTime(-20));
assert.throws(function(){
_.formatTime(-20)
},'-20时间错误');
for(var i = 0 ; i<5 ; i++)
{
var a = _.getRandom(0,86400);
assert.ok(_.formatTime(a),a+'秒的指定string格式为'+_.formatTime(a));
assert.ok(_.unformatTime(_.formatTime(a)),_.formatTime(a)+'的秒格式为'+_.unformatTime(_.formatTime(a)));
}
//}catch(error){
//alert('时间错误');
//};
});
QUnit.test('洗牌数组: _.shuffle',function(assert){
assert.ok(_.shuffle([1,2,3,4,5]),'[1,2,3,4,5]洗牌后的数组'+_.shuffle([1,2,3,4,5]));
assert.ok(_.shuffle([1]),'[1]洗牌后的数组'+_.shuffle([1]));
assert.ok(_.shuffle(['a','b','c','d']),'[\'a\',\'b\',\'c\',\'d\']洗牌后的数组'+_.shuffle(['a','b','c','d']));
assert.ok(_.shuffle([2,'a','b','c','d',1,3]),'[2,\'a\',\'b\',\'c\',\'d\'1,3]洗牌后的数组'+_.shuffle([2,'a','b','c','d',1,3]));
});
QUnit.test('数组去重:_.unique ',function(assert){
assert.ok(_.unique([1, 2, 3, 5, 5]),'[1, 2, 3, 5, 5]数组去重后['+_.unique([1, 2, 3, 5, 5])+']');
assert.ok(_.unique([1, 1,1,1,1]),'[1, 1,1,1,1]数组去重后'+_.unique([1, 1,1,1,1]));
assert.ok(_.unique([1, -1,0,-0]),'[1,-1,0,-0]数组去重后'+_.unique([1,-1,0,-0]));
assert.ok(_.unique([1, 1, 'a', 'A']),'[1, 1, \'a\', \'A\']数组去重后'+_.unique([1, 1, 'a', 'A']));
assert.ok(_.unique(['abcd', 'ab']),'[\'abcd\', \'ab\']数组去重后'+_.unique(['abcd', 'ab']));
});
QUnit.test('数组严格比较:_.equals',function(assert){
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 4, 3];
var arr3 = [2, 2, 3, 4];
var arr4 = [1, 2, 3, 4];
var arr5 = [1,2];
assert.ok(_.equals(arr1,arr2) == false,'数组[1, 2, 3, 4]和数组 [2, 1, 4, 3]不是严格相等');
assert.ok(_.equals(arr1,arr2,false),'不严格比较数组[1, 2, 3, 4]和数组 [2, 1, 4, 3]是相等的');
assert.ok(_.equals(arr1,arr5) == false,'数组[1, 2, 3, 4]和数组 [1,2]不是严格相等');
assert.ok(_.equals(arr1,arr3) == false,'数组[1, 2, 3, 4]和数组 [2, 2, 3, 4]不是严格相等');
assert.ok(_.equals(arr1,arr4),'数组[1, 2, 3, 4]和数组 [[1, 2, 3, 4]是严格相等');
});
/**
* QUnit.test('获取当前服务器时间:_.serverTime',function(assert){
assert.ok(_.dateFormat(_.serverTime()),'服务器当前时间为'+_.dateFormat(_.serverTime()));
});
*/
}());
| 48.207792 | 169 | 0.54005 |
8b647df9c75820a5118d85d9708b632debcd0a82 | 579 | js | JavaScript | packages/ramda-extension/src/toSnakeCase.js | dphaener/ramda-extension | ce53719e30a197787f548cee8110fa1547730d45 | [
"Apache-2.0"
] | 162 | 2016-12-07T13:06:50.000Z | 2022-02-21T17:11:50.000Z | packages/ramda-extension/src/toSnakeCase.js | dphaener/ramda-extension | ce53719e30a197787f548cee8110fa1547730d45 | [
"Apache-2.0"
] | 139 | 2017-11-04T19:20:59.000Z | 2021-09-22T13:52:15.000Z | packages/ramda-extension/src/toSnakeCase.js | dphaener/ramda-extension | ce53719e30a197787f548cee8110fa1547730d45 | [
"Apache-2.0"
] | 31 | 2017-11-04T13:49:19.000Z | 2020-12-17T16:33:20.000Z | import { o, map, toLower } from 'ramda';
import splitByNonAlphaNumeric from './splitByNonAlphaNumeric';
import joinWithUnderscore from './joinWithUnderscore';
/**
* Converts string into snake_case.
*
* @func
* @category String
*
* @example
*
* R_.toSnakeCase('hello-world') // 'hello_world'
* R_.toSnakeCase('hello- world') // 'hello_world'
* R_.toSnakeCase(' hello-/ world/ ') // 'hello_world'
*
* @sig String -> String
*/
const toSnakeCase = o(
joinWithUnderscore,
o(map(toLower), splitByNonAlphaNumeric)
);
export default toSnakeCase;
| 23.16 | 62 | 0.670121 |
8b674e19248875e470901b2fc1c3864efc30ea2a | 100 | js | JavaScript | docs/search--/s_5299.js | Zalexanninev15/VitNX | 43f2dd04b8ba97c4a78ae51a99e7980a6b9b85a9 | [
"MIT"
] | 2 | 2022-01-25T12:09:46.000Z | 2022-01-27T11:26:48.000Z | docs/search--/s_5299.js | Zalexanninev15/VitNX | 43f2dd04b8ba97c4a78ae51a99e7980a6b9b85a9 | [
"MIT"
] | null | null | null | docs/search--/s_5299.js | Zalexanninev15/VitNX | 43f2dd04b8ba97c4a78ae51a99e7980a6b9b85a9 | [
"MIT"
] | null | null | null | search_result['5299']=["topic_00000000000016AC_props--.html","FontAwesomeExtensions Properties",""]; | 100 | 100 | 0.8 |
8b67b0230929ed8ca267866b7046f70ac9bec545 | 3,477 | js | JavaScript | src/js/main.js | cld-agency/craft-boilerplate | 6d3654b81258173343301e292e37bc5d0dd6fd23 | [
"MIT"
] | 7 | 2017-04-07T03:18:49.000Z | 2018-10-11T10:46:15.000Z | src/js/main.js | cld-agency/craft-boilerplate | 6d3654b81258173343301e292e37bc5d0dd6fd23 | [
"MIT"
] | null | null | null | src/js/main.js | cld-agency/craft-boilerplate | 6d3654b81258173343301e292e37bc5d0dd6fd23 | [
"MIT"
] | null | null | null | var CLIENTNAME = {
// --------------------------------------------
// CACHE SOME COMMON PROPERTIES
// --------------------------------------------
getSettings: function(){
this.$html = $('html');
},
// --------------------------------------------
// GET THIS PARTY STARTED...
// --------------------------------------------
init: function(){
CLIENTNAME.getSettings();
CLIENTNAME.bindUI();
},
// --------------------------------------------
// UI EVENT BINDINGS
// --------------------------------------------
bindUI: function(){
// --------------------------------------------
// ON-OFF TOGGLERS
// --------------------------------------------
$('.js-onOff').click(function(){
CLIENTNAME.onOff($(this));
return false;
});
$('.js-mobileTrigger').click(function(){
CLIENTNAME.toggleMobileNav($(this));
});
// --------------------------------------------
// PREVENT BACKGROUND SCROLLING esp on iOS while
// various overlays are on.
// Uses this lib: https://github.com/willmcpo/body-scroll-lock
// --------------------------------------------
// toggle method allows a single element to do both on and off functions...
$('.js-toggleScrollLock').click(function(){
if ($(this).data('scrollLockState') == 'off') {
var target = $($(this).data('scrollLockEl'))[0];
bodyScrollLock.disableBodyScroll(target);
$(this).data('scrollLockState','on');
} else {
bodyScrollLock.clearAllBodyScrollLocks();
$(this).data('scrollLockState','off');
}
});
},
// --------------------------------------------
// ON-OFF TOGGLERS This is a generic reusable
// function that switches one thing on (data-on=".selectors"),
// (or href attribute if it exists), and another thing off (data-off=".selectors").
// Use data-mode="instant" to avoid the need for creating .active class styles
//
// Pass data-suffix="-something" to break the link
// between ids and location.hash, thereby preventing
// browser auto-scroll to the hash location (E.g. tab UIs,
// where we want them to be URL-addressable but don't want
// the scroll position to change on window.load)
// --------------------------------------------
onOff: function(el){
var toggleTarget = (el.attr('href') && el.attr('href') != '#') ? $(el.attr('href')) : $(el.data('on'));
// reset toggleTarget if there's a suffix.
if (el.data('suffix')) { toggleTarget = $(el.data('on') + el.data('suffix')); }
var toggleOrigin = $(el.data('off'));
if (el.data('mode') == 'instant'){
toggleTarget.add(toggleOrigin).toggle();
} else {
toggleOrigin.removeClass('active');
toggleTarget.add(el).addClass('active');
}
},
toggleMobileNav: function(triggerEl){
// toggle .withNavOn on <html> el...
CLIENTNAME.$html.toggleClass('withNavOn');
// toggle aria expanded on the trigger button...
var expanded = triggerEl[0].getAttribute('aria-expanded') === 'true' || false;
triggerEl.attr('aria-expanded', !expanded);
// toggle tabindices on the nav items to prevent keyboard focusing them while hidden.
// (Typically, you'd instead give the parent a [hidden] attribute which would
// remove the need for this (hidden children are not focussable))... BUT, doing
// that makes it tricky to use transitions, so instead we can turn the tabIndex
// from -1 to 0 (0 is basically 'auto').
$('.mobileNav a').attr('tabIndex', function(i,attr){ return this.tabIndex == '-1' ? '0' : '-1'; });
}
};
CLIENTNAME.init(); | 34.088235 | 105 | 0.548749 |
8b67ffcdd9b568bec88ac423908f32a5b28dbab5 | 2,442 | js | JavaScript | test/tracker.spec.js | newrelic/video-core-js | c437dac0172e6e709b445f4d15a0dc060c433592 | [
"Apache-2.0"
] | 1 | 2020-11-05T01:56:11.000Z | 2020-11-05T01:56:11.000Z | test/tracker.spec.js | newrelic/video-core-js | c437dac0172e6e709b445f4d15a0dc060c433592 | [
"Apache-2.0"
] | 1 | 2020-04-22T15:45:35.000Z | 2020-04-22T15:45:35.000Z | test/tracker.spec.js | newrelic/video-core-js | c437dac0172e6e709b445f4d15a0dc060c433592 | [
"Apache-2.0"
] | null | null | null | import Tracker from '../src/tracker'
import Log from '../src/log'
import chai from 'chai'
import sinon from 'sinon'
const expect = chai.expect
const assert = chai.assert
describe('Tracker', () => {
let tracker
// Mute console
before(() => {
Log.level = Log.Levels.SILENT
})
after(() => {
Log.level = Log.Levels.ERROR
})
describe('setting', () => {
it('should unregister listeners when disposing', () => {
tracker = new Tracker()
let spy = sinon.spy(tracker, 'unregisterListeners')
tracker.dispose()
assert(spy.called, 'unregisterListeners not called')
spy.restore()
})
it('should set options', () => {
// construct
tracker = new Tracker({ customData: { key: 'value' } })
expect(tracker.customData.key).to.equal('value')
// no change
tracker.setOptions()
expect(tracker.customData.key).to.equal('value')
// change
tracker.setOptions({ customData: { key: 'value2' } })
expect(tracker.customData.key).to.equal('value2')
})
it('should send custom data', (done) => {
tracker = new Tracker({ customData: { a: 1 } })
tracker.on('EVENT', (e) => {
expect(e.data.a).to.equal(1)
done()
})
tracker.send('EVENT')
})
it('should return attributes', () => {
tracker = new Tracker()
let att = tracker.getAttributes()
expect(att.trackerName).to.not.be.undefined
expect(att.trackerVersion).to.not.be.undefined
expect(att.coreVersion).to.not.be.undefined
expect(att.timeSinceTrackerReady).to.not.be.undefined
})
})
describe('heartbeating', () => {
it('should return heartbeat', () => {
tracker = new Tracker()
expect(tracker.getHeartbeat()).to.equal(30000)
tracker.setOptions({ parentTracker: new Tracker({ heartbeat: 20000 }) })
expect(tracker.getHeartbeat()).to.equal(20000)
tracker.setOptions({ heartbeat: 10000 })
expect(tracker.getHeartbeat()).to.equal(10000)
})
it('should send heartbeat', (done) => {
tracker.on(Tracker.Events.HEARTBEAT, () => done())
tracker.sendHeartbeat()
})
it('should start and stop heartbeats', (done) => {
tracker = new Tracker({ heartbeat: 500 })
tracker.on(Tracker.Events.HEARTBEAT, () => done.fail())
setInterval(() => done(), 750)
tracker.startHeartbeat()
tracker.stopHeartbeat()
})
})
})
| 27.133333 | 78 | 0.602785 |
8b6a1460a37b31b48d5244131c2315e5b7c1fc5c | 519 | js | JavaScript | covervid.min.js | cybernetics/covervid | 654f1c6e0ef7571016d135181c67950b9643f8e3 | [
"MIT"
] | 1 | 2019-04-22T08:48:54.000Z | 2019-04-22T08:48:54.000Z | covervid.min.js | cybernetics/covervid | 654f1c6e0ef7571016d135181c67950b9643f8e3 | [
"MIT"
] | null | null | null | covervid.min.js | cybernetics/covervid | 654f1c6e0ef7571016d135181c67950b9643f8e3 | [
"MIT"
] | null | null | null | jQuery.fn.extend({coverVid:function(a,b){function c(){var c=d.parent().height(),e=d.parent().width(),f=a,g=b,h=c/g,i=e/f;d.css({position:"absolute",top:"50%",left:"50%","-webkit-transform":"translate(-50%, -50%)","-moz-transform":"translate(-50%, -50%)","-ms-transform":"translate(-50%, -50%)","-o-transform":"translate(-50%, -50%)",transform:"translate(-50%, -50%)"}),d.parent().css("overflow","hidden"),d.css(i>h?{height:"auto",width:e}:{height:c,width:"auto"})}$(document).ready(c),$(window).resize(c);var d=this}}); | 519 | 519 | 0.637765 |
8b6a1ba3d4e58256c51f85a0c52052f6e439dae7 | 5,173 | js | JavaScript | client/components/SingleProduct.js | 2103-team-css/grace-shopper | c960e419a9e1e98275fbd652c61936afcaba376b | [
"MIT"
] | 1 | 2021-04-19T18:37:23.000Z | 2021-04-19T18:37:23.000Z | client/components/SingleProduct.js | 2103-team-css/grace-shopper | c960e419a9e1e98275fbd652c61936afcaba376b | [
"MIT"
] | 27 | 2021-04-19T18:47:30.000Z | 2021-04-27T02:14:44.000Z | client/components/SingleProduct.js | 2103-team-css/grace-shopper | c960e419a9e1e98275fbd652c61936afcaba376b | [
"MIT"
] | 2 | 2021-04-19T15:40:06.000Z | 2021-04-20T19:08:20.000Z | import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchOneProduct } from '../store/singleProduct';
import { deleteProduct } from '../store/products';
import { createCartItem } from '../store/cart';
import { Link as RouterLink } from 'react-router-dom';
import {
Grid,
Card,
CardMedia,
CardContent,
Typography,
Button,
makeStyles,
Container,
Box,
} from '@material-ui/core';
const useStyles = makeStyles(() => ({
image: {
height: 300,
width: 300,
margin: '0 auto',
},
cardContainer: {
marginTop: '1rem',
padding: 10,
},
// editButton: {
// backgroundColor: '#52b788',
// },
maxHeight: {
height: '100%',
},
itemSpacing: {
marginBottom: 10,
},
}));
const SingleProduct = (props) => {
const classes = useStyles();
useEffect(() => {
props.getOneProduct(props.match.params.id);
}, []);
const { oneProduct, userId, isAdmin, deleteProduct } = props;
return (
<Container>
<Grid container justify="center">
<Grid item xs={12} md={8}>
<Card className={classes.cardContainer}>
<Grid container>
<Grid item xs={12} sm={6} container direction="column">
<Typography component="h3" variant="h3" align="center">
{oneProduct.name}
</Typography>
<Box mt={2}>
<CardMedia className={classes.image} image={oneProduct.imageUrl} />
</Box>
</Grid>
<Grid item xs={12} sm={6}>
<CardContent className={classes.maxHeight}>
<Grid
container
direction="column"
justify="space-around"
className={classes.maxHeight}
spacing={2}
wrap="nowrap"
>
<Grid item>
<Typography component="h6" variant="h6">
<strong>Price:</strong> ${oneProduct.price / 100}
</Typography>
</Grid>
<Grid item>
<Typography component="h6" variant="h6">
<strong>Availability:</strong> {oneProduct.quantity} Left in Stock
</Typography>
</Grid>
<Grid item>
<Typography component="h6" variant="h6">
<strong>Category:</strong> {oneProduct.category}
</Typography>
</Grid>
<Grid item>
<Typography component="h6" variant="h6">
<strong>Description:</strong> {oneProduct.description}
</Typography>
</Grid>
<Grid item>
<Button
variant="contained"
color="primary"
size="small"
disableElevation
onClick={() => {
props.addToCart(
userId,
oneProduct.name,
oneProduct.price,
1,
oneProduct.id
);
}}
>
Add to Cart
</Button>
</Grid>
{isAdmin && (
<Grid item container spacing={2}>
<Grid item>
<Button
to={`/admin/products/${oneProduct.id}`}
component={RouterLink}
color="primary"
variant="contained"
>
Edit Product
</Button>
</Grid>
<Grid item>
<Button
onClick={() => deleteProduct(oneProduct.id)}
color="secondary"
variant="contained"
>
Delete Product
</Button>
</Grid>
</Grid>
)}
</Grid>
</CardContent>
</Grid>
</Grid>
</Card>
</Grid>
</Grid>
</Container>
);
};
const mapState = (state) => {
return {
oneProduct: state.oneProduct,
userId: state.auth.id,
isAdmin: state.auth.isAdmin,
};
};
const mapDispatch = (dispatch, { history }) => {
return {
getOneProduct: (id) => dispatch(fetchOneProduct(id)),
addToCart: (userId, name, price, quantity, productId) =>
dispatch(createCartItem(userId, name, price, quantity, productId)),
deleteProduct: (id) => dispatch(deleteProduct(id, history)),
};
};
export default connect(mapState, mapDispatch)(SingleProduct);
| 31.351515 | 90 | 0.423352 |
8b6a22a1e062bc81ad9e8af34590857577307733 | 459 | js | JavaScript | public/import/custom/plugins/SwagPaymentPayPalUnified/Resources/views/backend/paypal_unified_settings/store/log_level.js | masystech/pompidu | 9929f5cf0d1afd96c9020b95ce1d60aa3f6b1677 | [
"MIT"
] | 20 | 2018-02-02T11:16:22.000Z | 2021-08-13T18:35:31.000Z | public/import/custom/plugins/SwagPaymentPayPalUnified/Resources/views/backend/paypal_unified_settings/store/log_level.js | masystech/pompidu | 9929f5cf0d1afd96c9020b95ce1d60aa3f6b1677 | [
"MIT"
] | 18 | 2018-06-08T06:42:22.000Z | 2022-03-30T11:33:37.000Z | public/import/custom/plugins/SwagPaymentPayPalUnified/Resources/views/backend/paypal_unified_settings/store/log_level.js | masystech/pompidu | 9929f5cf0d1afd96c9020b95ce1d60aa3f6b1677 | [
"MIT"
] | 24 | 2018-05-19T18:53:51.000Z | 2021-04-14T14:26:55.000Z | // {namespace name="backend/paypal_unified_settings/store/log_level"}
Ext.define('Shopware.apps.PaypalUnifiedSettings.store.LogLevel', {
extend: 'Ext.data.Store',
storeId: 'SwagPaymentPayPalUnifiedLogLevel',
fields: [
{ name: 'id', type: 'int' },
{ name: 'text', type: 'string' }
],
data: [
{ id: '0', text: '{s name="normal"}Normal{/s}' },
{ id: '1', text: '{s name="extended"}Extended{/s}' }
]
});
| 27 | 69 | 0.575163 |
8b6ad3a0d025c261e54818f7349b0aa3bc763989 | 1,469 | js | JavaScript | src/components/Board/Observable/index.js | mlajtos/L1 | b5b848d81a789c373a15634f09ba2ad0eaaa9f65 | [
"MIT"
] | 174 | 2018-07-29T20:18:17.000Z | 2022-02-13T06:00:27.000Z | src/components/Board/Observable/index.js | Pandinosaurus/L1 | b5b848d81a789c373a15634f09ba2ad0eaaa9f65 | [
"MIT"
] | 14 | 2018-08-03T19:45:48.000Z | 2019-03-10T21:23:29.000Z | src/components/Board/Observable/index.js | Pandinosaurus/L1 | b5b848d81a789c373a15634f09ba2ad0eaaa9f65 | [
"MIT"
] | 22 | 2018-07-29T21:50:17.000Z | 2022-02-02T08:12:28.000Z | import React, { PureComponent } from "react"
import ObjectProperty from "../ObjectProperty"
import "./style.sass"
export default class Observable extends PureComponent {
state = {
data: null,
value: undefined,
error: undefined,
completed: false
}
_mounted = false
onNext = (value) => this.setState({ value, error: undefined })
onError = (error) => this.setState({ value: undefined, error })
onCompleted = () => this.setState({ completed: true })
componentDidMount() {
this._mounted = true
this.subscription = this.props.data.subscribe(this.onNext, this.onError, this.onCompleted)
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.data !== prevState.data) {
return {
data: nextProps.data
}
}
return null
}
componentDidUpdate = (prevProps, prevState) => {
if (prevState.data !== this.state.data) {
this.subscription.unsubscribe()
this.subscription = this.state.data.subscribe(this.onNext, this.onError, this.onCompleted)
}
}
componentWillUnmount() {
this._mounted = false
this.subscription.unsubscribe()
}
render = () => (
<div className={"observable " + (this.state.error ? "error" : "")}>
<ObjectProperty {...this.props} data={this.state.error || this.state.value} />
</div>
)
} | 28.803922 | 102 | 0.594282 |
8b6b1aaf0a17a848b114ab7ce787043d21a3934a | 2,194 | js | JavaScript | AjaxControlToolkit/Scripts/HtmlEditor.ModePanel.min.js | skyhoshi/AjaxControlToolkit | d3ad8d0822c4584b8ebf54d041bb514b0007d1c2 | [
"BSD-3-Clause"
] | 319 | 2016-03-10T22:14:41.000Z | 2022-02-18T18:09:35.000Z | AjaxControlToolkit/Scripts/HtmlEditor.ModePanel.min.js | skyhoshi/AjaxControlToolkit | d3ad8d0822c4584b8ebf54d041bb514b0007d1c2 | [
"BSD-3-Clause"
] | 470 | 2016-03-10T17:14:21.000Z | 2022-02-25T09:55:52.000Z | AjaxControlToolkit/Scripts/HtmlEditor.ModePanel.min.js | skyhoshi/AjaxControlToolkit | d3ad8d0822c4584b8ebf54d041bb514b0007d1c2 | [
"BSD-3-Clause"
] | 159 | 2016-03-11T11:29:01.000Z | 2022-03-18T05:15:28.000Z | Type.registerNamespace("Sys.Extended.UI.HtmlEditor"),Sys.Extended.UI.HtmlEditor.ModePanel=function(t){Sys.Extended.UI.HtmlEditor.ModePanel.initializeBase(this,[t]),this._activated=!1,this._isActivating=!1,this._editPanel=null,this._cachedContent=null,this._onbeforeunload$delegate=Function.createDelegate(this,this._onbeforeunload)},Sys.Extended.UI.HtmlEditor.ModePanel.prototype={set_editPanel:function(t){this._editPanel=t},get_content:function(){return this._activated?this._getContent():null!=this._cachedContent?this._cachedContent:""},set_content:function(t){if(this._cachedContent=t,this._activated||this._isActivating){if(this._isActivating){var e=this;return setTimeout(function(){e.set_content(t)},10),!1}this._setContent(t)}else this._activate(t);return!0},_activate:function(){this.get_element().style.display="",this._isActivating=!0},_activateFinished:function(){this._activated=!0,this._isActivating=!1,this._editPanel._setActive(),this._editPanel.get_autofocus()&&this._focus()},_deactivate:function(){this.get_element().style.display="none",this._activated=!1,this._isActivating=!1},initialize:function(){Sys.Extended.UI.HtmlEditor.ModePanel.callBaseMethod(this,"initialize"),Sys.Extended.UI.HtmlEditor.isIE&&$addHandlers(window,{beforeunload:this._onbeforeunload$delegate})},dispose:function(){Sys.Extended.UI.HtmlEditor.isIE&&$common.removeHandlers(window,{beforeunload:this._onbeforeunload$delegate}),this._activated&&(Sys.Extended.UI.HtmlEditor.isIE&&this._onbeforeunload(),this._deactivate()),Sys.Extended.UI.HtmlEditor.ModePanel.callBaseMethod(this,"dispose")},_onbeforeunload:function(){this._activated&&(this._editPanel._contentPrepared||(this._editPanel._prepareContentForPostback(this.get_content()),this._editPanel._contentPrepared=!0))},_getContent:function(){return null!=this._cachedContent?this._cachedContent:""},_setContent:function(t){},_focus:function(){this._focused()},_focused:function(t){this._editPanel._focused(t),this._editPanel.set_autofocus(!0)},_really_focused:function(){this._editPanel._really_focused(),this._editPanel.set_autofocus(!0)}},Sys.Extended.UI.HtmlEditor.ModePanel.registerClass("Sys.Extended.UI.HtmlEditor.ModePanel",Sys.UI.Control); | 2,194 | 2,194 | 0.819508 |
8b6c5333a340ca1cb9cd49df327ad3a780dd87f2 | 2,654 | js | JavaScript | js/source.js | victoriadotdev/pomo-clock | 3de5fad30d8305074917c996a9b129eff974971c | [
"Apache-2.0"
] | null | null | null | js/source.js | victoriadotdev/pomo-clock | 3de5fad30d8305074917c996a9b129eff974971c | [
"Apache-2.0"
] | null | null | null | js/source.js | victoriadotdev/pomo-clock | 3de5fad30d8305074917c996a9b129eff974971c | [
"Apache-2.0"
] | 1 | 2018-01-03T02:38:16.000Z | 2018-01-03T02:38:16.000Z | var startCount;
var runCount;
function countdown(length, running) {
var start = Date.now(),
remains,
min,
sec;
console.log(running, start, remains, min, sec);
function timer() {
if (running) {
remains = length - (((Date.now() - start) / 1000) | 0);
min = parseInt(remains / 60);
if (min < 10) {
min = "0" + min
}
sec = parseInt(remains % 60)
if (sec < 10) {
sec = "0" + sec
}
$('#mins').html(min);
$('#secs').html(sec);
console.log(start, remains, min, sec);
if (remains === 0) {
running = false;
console.log('running: ',running);
if (runCount === 1) {
$('#pomo').addClass('hide');
$('#break').removeClass('hide');
} else
if (runCount === 0) {
$('#pomo').removeClass('hide');
$('#break').addClass('hide');
}
}
}
};
timer();
startCount = setInterval(timer, 1000);
}
$(document).ready(function () {
var pomoSet = 25;
var breakSet = 5;
var running;
runCount = 0;
$('#mins').html('25');
$('#secs').html('00');
$('#breakTime').html(breakSet);
$('#pomoTime').html(pomoSet);
$('.btn').click(function () {
clicked = $(this).attr('value');
if (clicked === 'breakLess') {
console.log(clicked);
if (breakSet === 1) {
breakSet = 1;
} else
breakSet -= 1;
}
if (clicked === 'breakMore') {
console.log(clicked);
if (breakSet === 60) {
breakSet = 60;
} else
breakSet += 1;
}
if (clicked === 'pomoLess') {
console.log(clicked);
if (pomoSet === 1) {
pomoSet = 1;
} else
pomoSet -= 1;
}
if (clicked === 'pomoMore') {
console.log(clicked, pomoSet);
if (pomoSet === 60) {
pomoSet = 60;
} else
pomoSet += 1;
}
if (clicked === 'stop') {
clearInterval(startCount);
$('#stop').toggle();
$('#reset').toggle();
if (runCount === 1) { runCount = 0; } else
if (runCount === 0) { runCount = 1; }
console.log(clicked, runCount);
}
if (clicked === 'reset') {
$('#mins').html('00');
$('#secs').html('00');
$('#stop').toggle();
$('#reset').toggle();
running = false;
console.log(clicked, runCount);
}
if (clicked === 'start') {
if (running === true) {
console.log('Already running!');
} else {
if (runCount === 0) {
console.log(clicked, runCount, 'for pomo');
running = true;
countdown(pomoSet * 60, running);
runCount = 1;
} else
if (runCount === 1) {
console.log(clicked, runCount, 'for break');
running = true;
countdown(breakSet * 60, running);
runCount = 0;
}
}
}
$('#breakTime').html(breakSet);
$('#pomoTime').html(pomoSet);
})
});
| 19.514706 | 58 | 0.525998 |
8b6d40af820130c3349fe4afd2cb257510d4eaa9 | 483 | js | JavaScript | src/Components/Card/Section/index.js | kennethsn/react-stories-api | 5a9101ab2ad7c7c3bf685706e91df890d28f0f15 | [
"MIT"
] | null | null | null | src/Components/Card/Section/index.js | kennethsn/react-stories-api | 5a9101ab2ad7c7c3bf685706e91df890d28f0f15 | [
"MIT"
] | 131 | 2019-11-19T17:49:35.000Z | 2021-12-30T18:21:13.000Z | src/Components/Card/Section/index.js | kennethsn/react-stories-api | 5a9101ab2ad7c7c3bf685706e91df890d28f0f15 | [
"MIT"
] | 1 | 2020-05-15T11:59:03.000Z | 2020-05-15T11:59:03.000Z | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import './style.scss';
/**
* Section for a Card Component.
*/
export default class CardSection extends Component {
static propTypes = {
/** Styling object of the `Card` */
style: PropTypes.object
};
static defaultProps = {
};
render() {
const { children, style } = this.props;
return (
<div className="story-card__section" style={style}>{children}</div>
)
}
}
| 19.32 | 73 | 0.63354 |
8b6e324b5f247755a59aaac52044e0b141e9a16a | 1,403 | js | JavaScript | src/start.js | MitMaro/auth0-ip-block-status | 110c806421c7ef5d247243b57decf7fbaa339b92 | [
"0BSD"
] | 2 | 2019-05-17T14:41:05.000Z | 2020-05-20T08:25:32.000Z | src/start.js | MitMaro/auth0-ip-block-status | 110c806421c7ef5d247243b57decf7fbaa339b92 | [
"0BSD"
] | null | null | null | src/start.js | MitMaro/auth0-ip-block-status | 110c806421c7ef5d247243b57decf7fbaa339b92 | [
"0BSD"
] | null | null | null | /* eslint-disable no-console */
'use strict';
const bootstrap = require('./bootstrap');
const SIGINT_ERROR = 120;
let sigint = false;
const system = bootstrap();
const {
downloader,
gRPCServer,
httpServer,
} = system;
async function shutdown() {
// catch second ctrl+c and force exit
if (sigint) {
process.exit(SIGINT_ERROR); // eslint-disable-line no-process-exit
}
sigint = true;
console.log();
console.log(`Gracefully shutting down process with PID ${process.pid}, this may take a few seconds`);
console.log('Use ctrl-c again to force');
console.log();
try {
await downloader.end();
await httpServer.end();
await gRPCServer.end();
}
catch (error) {
console.error(error);
}
}
async function start() {
try {
try {
await downloader.setup();
await downloader.start();
await httpServer.setup();
await httpServer.start();
await gRPCServer.setup();
await gRPCServer.start();
}
catch (startError) {
console.error(startError);
await downloader.end();
await httpServer.end();
await gRPCServer.end();
return;
}
}
catch (shutdownError) {
console.error(shutdownError);
return;
}
process.on('SIGINT', () => {
console.log();
console.log('SIGINT received, starting shutdown');
shutdown();
});
process.on('SIGTERM', () => {
console.log();
console.log('SIGTERM received, starting shutdown');
shutdown();
});
}
start();
| 18.959459 | 102 | 0.663578 |
8b6eaf08df7423c7c82ca2ba3d4211aee45bbbaa | 31 | js | JavaScript | src/card/index.js | ShaneKing/sk-react-antd | f9d08aa9b248bf5e9f9184dd17fbf5e663b637f1 | [
"Apache-2.0"
] | 3 | 2017-06-05T12:04:46.000Z | 2019-03-10T05:24:00.000Z | src/card/index.js | ShaneKing/sk-react-antd | f9d08aa9b248bf5e9f9184dd17fbf5e663b637f1 | [
"Apache-2.0"
] | 3 | 2018-03-31T06:08:21.000Z | 2019-02-23T17:58:20.000Z | src/card/index.js | ShaneKing/sk-antd | f9d08aa9b248bf5e9f9184dd17fbf5e663b637f1 | [
"Apache-2.0"
] | null | null | null | export SKCard from './SKCard';
| 15.5 | 30 | 0.709677 |
8b6fa604e024f145605d943464f95a2522d99bca | 1,160 | js | JavaScript | data-structures/queueClass.js | m1ckc3b/coding-interview-prep | 76cf2b4f5c3cdd96d1bb61432ef3c4064f375f38 | [
"MIT"
] | null | null | null | data-structures/queueClass.js | m1ckc3b/coding-interview-prep | 76cf2b4f5c3cdd96d1bb61432ef3c4064f375f38 | [
"MIT"
] | null | null | null | data-structures/queueClass.js | m1ckc3b/coding-interview-prep | 76cf2b4f5c3cdd96d1bb61432ef3c4064f375f38 | [
"MIT"
] | null | null | null | /**
* Coding Interview Prep #15
* Category: Data Structures
* Title: Create a Queue Class
* Instructions: Write an enqueue method that pushes an element to the tail of the queue, a dequeue method that removes
* and returns the front element, a front method that lets us see the front element,
* a size method that shows the length, and an isEmpty method to check if the queue is empty.
*/
/**
* Create a Queue Data Structure.
*
* @class Queue
*/
class Queue {
collection = []
print() {
console.log(this.collection);
}
enqueue(value) {
this.collection.push(value)
}
dequeue() {
return this.collection.shift()
}
front() {
return this.collection[0]
}
size() {
return this.collection.length
}
isEmpty() {
return this.collection.length === 0
}
}
const queue = new Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.print()
console.log("fornt:",queue.front());
console.log("size:",queue.size());
console.log("empty?",queue.isEmpty());
queue.dequeue()
queue.print()
console.log("front:",queue.front());
console.log("size:",queue.size());
console.log("empty?",queue.isEmpty()); | 19.333333 | 119 | 0.671552 |
8b70ba185cbe927d3f3d51d704a63a23891657d3 | 3,772 | js | JavaScript | src/components/devprojects.js | YonasBerhe/personal-website | 423257d1680449ef65526198d4e5eb68782cad34 | [
"MIT"
] | null | null | null | src/components/devprojects.js | YonasBerhe/personal-website | 423257d1680449ef65526198d4e5eb68782cad34 | [
"MIT"
] | null | null | null | src/components/devprojects.js | YonasBerhe/personal-website | 423257d1680449ef65526198d4e5eb68782cad34 | [
"MIT"
] | null | null | null | require('normalize.css');
require('styles/App.css');
import React from 'react';
import Navigation from './global/nav';
import {Grid, Row, Col, Button} from 'react-bootstrap';
import {Hero, Footer, Sectionm, Team, TeamMember, Section} from 'neal-react';
import {Link} from 'react-router';
import json from './projects.json';
console.log(json.results[0].reiproject.image);
const brandName = "";
const Rei = React.createClass({
getInitialState() {
return {
title: '',
previewtext: '',
image: '',
previewtext: '',
link: ''
};
},
componentDidMount() {
const myProjects = json.results[0];
this.setState({
title: myProjects.reiproject.title,
previewtext: myProjects.reiproject.previewtext,
image: myProjects.reiproject.image,
link: myProjects.reiproject.link
});
},
render() {
return(
<div>
<Grid>
<Row className="show-grid case-list">
<Col xs={12} md={4}>
<a href="#/rei/" className="preview-before">
<img src={this.state.image} alt="collabrative camping" className="img-responsive" />
</a>
<a className="rei-title-cases">{this.state.title}</a>
<h2> {this.state.previewtext}</h2>
<Button bsStyle="info" href="http://yonasberhe.github.io/p2UXDIPrototype/#/screens/133617882" >Prototype</Button>
</Col>
</Row>
</Grid>
</div>
)
}
})
const Wells = React.createClass({
getInitialState() {
return {
title: '',
previewtext: '',
image: '',
previewtext: '',
link: ''
};
},
componentDidMount() {
const myProjects = json.results[0];
this.setState({
title: myProjects.wellsproject.title,
previewtext: myProjects.wellsproject.previewtext,
image: myProjects.wellsproject.image,
link: myProjects.wellsproject.link
});
},
render() {
return(
<div>
<Grid>
<Row className="show-grid case-list">
<Col xs={12} md={4}>
<a href="#/rei/" className="preview-before">
<img src={this.state.image} alt="collabrative camping" className="img-responsive" />
</a>
<a className="rei-title-cases">{this.state.title}</a>
<h2> {this.state.previewtext}</h2>
<Button bsStyle="info" href="http://yonasberhe.github.io/p2UXDIPrototype/#/screens/133617882" >Prototype</Button>
</Col>
</Row>
</Grid>
</div>
)
}
})
class Case extends React.Component {
render() {
return (
<div>
<Navigation />
<Section className="subhero">
<Section>
<Team>
<TeamMember name="Member 1" title="Co-founder" imageUrl="img/people/grumpycat.jpg">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</TeamMember>
<TeamMember name="Member 2" title="Co-founder" imageUrl="img/people/boo.jpg">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</TeamMember>
<TeamMember name="Member 3" title="Co-founder" imageUrl="img/people/panda.jpg">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</TeamMember>
</Team>
</Section>
</Section>
<Footer brandName={brandName}
facebookUrl=""
twitterUrl=""
githubUrl="">
</Footer>
</div>
);
}
}
//
// AppComponent.defaultProps = {
// };
export default Case;
| 20.389189 | 241 | 0.651909 |
8b714deb5db706392b2bbb472e0efdb2dd9817da | 1,608 | js | JavaScript | src/api/discount.js | fuyuanxiu/xk-vue | b1b0170feea550764b73c892bc3c4205d60daa33 | [
"MIT"
] | null | null | null | src/api/discount.js | fuyuanxiu/xk-vue | b1b0170feea550764b73c892bc3c4205d60daa33 | [
"MIT"
] | null | null | null | src/api/discount.js | fuyuanxiu/xk-vue | b1b0170feea550764b73c892bc3c4205d60daa33 | [
"MIT"
] | null | null | null | import request from '@/utils/request'
//获取折扣方案类别
export function getCategory(data) {
return request({
url: '/discountCategory/getlist',
method: 'get',
params:data
})
}
//新增类别
export function addCategory(data) {
return request({
url: '/discountCategory/add',
method: 'post',
params:data
})
}
//编辑类别
export function editCategory(data) {
return request({
url: '/discountCategory/edit',
method: 'post',
params:data
})
}
//删除类别
export function delCategory(id) {
return request({
url: '/discountCategory/delete',
method: 'post',
params: { 'id':id }
})
}
//获取折扣方案
export function getDiscount(data) {
return request({
url: '/discount/getlist',
method: 'get',
params:data
})
}
//新增折扣方案
export function addDiscount(data) {
return request({
url: '/discount/add',
method: 'post',
params:data
})
}
//编辑折扣方案
export function editDiscount(data) {
return request({
url: '/discount/edit',
method: 'post',
params:data
})
}
//删除折扣方案
export function delDiscount(id) {
return request({
url: '/discount/delete',
method: 'post',
params: { 'id':id }
})
}
//禁用或解禁折扣方案
export function banDiscount(id, bsIsBan) {
return request({
url: '/discount/doBan',
method: 'post',
params: { 'id':id, 'bsIsBan':bsIsBan }
})
}
export function checkInfo(id) {
return request({
url: '/discount/check',
method: 'post',
params: { 'id':id}
})
}
export function reverseInfo(id) {
return request({
url: '/discount/reverse',
method: 'post',
params: { 'id':id}
})
}
| 15.461538 | 42 | 0.611318 |