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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36e0aaf75569dfb9292b6a886cd5b8e9fd0ddd05 | 3,308 | js | JavaScript | src/index.js | jsdaniell/mask-fields | 6d12e721bd8e50eb7b35d25514461b8a859f13c3 | [
"MIT"
] | 1 | 2020-01-03T10:24:48.000Z | 2020-01-03T10:24:48.000Z | src/index.js | jsdaniell/mask-fields | 6d12e721bd8e50eb7b35d25514461b8a859f13c3 | [
"MIT"
] | null | null | null | src/index.js | jsdaniell/mask-fields | 6d12e721bd8e50eb7b35d25514461b8a859f13c3 | [
"MIT"
] | null | null | null | /* All masks are created with regular expressions */
// Brazilian CPF Document Format [123.456.789-00]
var cpf = cpf => {
cpf = cpf.toString();
cpf = cpf.replace(/\D/g, "");
cpf = cpf.replace(/(\d{3})(\d)/, "$1.$2");
cpf = cpf.replace(/(\d{3})(\d)/, "$1.$2");
cpf = cpf.replace(/(\d{3})(\d{1,2})$/, "$1-$2");
return cpf;
};
// Telephone Number Format [(85) 12345 -7890]
var tel = tel => {
tel = tel.toString();
tel = tel.replace(/\D/g, "");
tel = tel.replace(/^(\d)/, "($1");
tel = tel.replace(/(.{3})(\d)/, "$1)$2");
if (tel.length == 9) {
tel = tel.replace(/(.{1})$/, "-$1");
} else if (tel.length == 10) {
tel = tel.replace(/(.{2})$/, "-$1");
} else if (tel.length == 11) {
tel = tel.replace(/(.{3})$/, "-$1");
} else if (tel.length == 12) {
tel = tel.replace(/(.{4})$/, "-$1");
} else if (tel.length > 12) {
tel = tel.replace(/(.{4})$/, "-$1");
}
return tel;
};
// CEP Brazilian Postal Number Format [12.355-201]
var cep = cep => {
cep = cep.toString();
cep = cep.replace(/\D/g, "");
cep = cep.replace(/^(\d{2})(\d)/, "$1.$2");
cep = cep.replace(/\.(\d{3})(\d)/, ".$1-$2");
return cep;
};
// CNPJ Format [12.345.678/1234-00]
var cnpj = cnpj => {
cnpj = cnpj.toString();
cnpj = cnpj.replace(/\D/g, "");
cnpj = cnpj.replace(/^(\d{2})(\d)/, "$1.$2");
cnpj = cnpj.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3");
cnpj = cnpj.replace(/\.(\d{3})(\d)/, ".$1/$2");
cnpj = cnpj.replace(/(\d{4})(\d)/, "$1-$2");
return cnpj;
};
// Only numbers filter mask, don't allow non-numeric characters.
var num = num => {
num = num.toString();
num = num.replace(/\D/g, "");
return num;
};
// RG General Brazillian Document Format [1234567890-1]
var rg = rg => {
rg = rg.toString();
rg = rg.replace(/(\d{2})(\d)/, "$1.$2");
rg = rg.replace(/(\d{5})(\d)/, "$1.$2");
rg = rg.replace(/(\d{3})(\d)/, "$1.$2");
rg = rg.replace(/(\d{9})(\d)/, "$1-$2");
return rg;
};
// Credit Card Numbers Format [1234.5678.3216.6547]
var card = card => {
card = card.toString();
card = card.replace(/\D/g, "");
card = card.replace(/(\d{4})(\d)/, "$1.$2");
card = card.replace(/(\d{4})(\d)/, "$1.$2");
card = card.replace(/(\d{4})(\d)/, "$1.$2");
card = card.replace(/(\d{4})(\d)/, "$1.$2");
return card;
};
// DateTime numbers format with "/" [02/08/2019]
var date = data => {
data = data.toString();
data = data.replace(/\D/g, "");
data = data.replace(/(\d{2})(\d)/, "$1/$2");
data = data.replace(/(\d{2})(\d)/, "$1/$2");
return data;
};
// Money format [100.00] - [1000.00]...
var money = moeda => {
moeda = moeda.toString();
moeda = moeda.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
return moeda;
};
// No latin letters → Permissives [123,.-=+...] ← No letters
var noLetters = string => {
string = string.toString();
string = string.replace(/[a-z]/gi, "");
return string;
};
// Allow only letters [abcDEF...]
var onlyLetters = string => {
string = string.toString();
string = string.replace(/[^a-zA-Z]+/g, "");
return string;
};
// Exports
exports.cpf = cpf;
exports.tel = tel;
exports.cep = cep;
exports.cnpj = cnpj;
exports.rg = rg;
exports.card = card;
exports.num = num;
exports.date = date;
exports.money = money;
exports.noLetters = noLetters;
exports.onlyLetters = onlyLetters;
| 24.503704 | 64 | 0.5263 |
36e0b486444ae07bc07c47259459b3a9d3c0f084 | 5,794 | js | JavaScript | components/editor-link.js | drupol/01-unraveling-the-jpeg | b655460c84cb1fd3fe781740f13fe961425c6fbc | [
"MIT"
] | 213 | 2019-05-01T20:04:21.000Z | 2022-03-15T02:26:24.000Z | components/editor-link.js | drupol/01-unraveling-the-jpeg | b655460c84cb1fd3fe781740f13fe961425c6fbc | [
"MIT"
] | 6 | 2019-06-08T10:43:45.000Z | 2021-06-06T22:36:32.000Z | components/editor-link.js | drupol/01-unraveling-the-jpeg | b655460c84cb1fd3fe781740f13fe961425c6fbc | [
"MIT"
] | 22 | 2019-05-02T08:25:24.000Z | 2022-03-15T02:26:28.000Z | const React = require('react');
class TextArea extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e) {
const { search, replace, line, editor, pattern, scale, DCT } = this.props;
const imageEditor = editor.component.imageEditor;
let text = imageEditor.resetText;
//let text = imageEditor.editor.getSession().getValue();
let lines = text.split('\n');
let sentValuesToEditor = false;
if (pattern == undefined) {
for (let i = 0; i < lines.length; i++) {
if (i == line - 1) {
lines[i] = lines[i].replace(search, replace);
break;
}
}
} else if (pattern == "zero-all") {
for (let i = 0; i < lines.length; i++) {
let numbers = lines[i].trim().split(" ");
for (let j = 0; j < numbers.length; j++) {
numbers[j] = "0";
}
lines[i] = numbers.join(" ");
}
} else if (pattern == "remove-zeros") {
// For each line, find the last non-zero value, then remove all remaining zeros
for (let i = 0; i < lines.length; i++) {
let reg = /(-?[1-9]0*)+/g;
let match;
let lastIndex = 0;
let lastLength = 1;
while ((match = reg.exec(lines[i])) != null) {
lastIndex = match.index;
lastLength = match[0].length;
}
lines[i] = lines[i].slice(0, lastIndex + lastLength);
}
} else if (pattern.indexOf("remove-{") != -1) {
// Remove the last n lines
let n = pattern.match(/{(\d+)}/)[1];
lines = lines.slice(0, lines.length-n);
} else if (pattern.indexOf("zero-{") != -1) {
// Zero out the first n numbers
let n = Number(pattern.match(/{(\d+)}/)[1]);
let first = true;
for (let i = 0; i < lines.length; i++) {
let numbers = lines[i].trim().split(" ");
for (let j = 0; j < numbers.length; j++) {
if (!first) {
numbers[j] = "0";
}
first = false;
n --;
if (n <= 0) break;
}
lines[i] = numbers.join(" ");
}
} else if (pattern == 'animate-DCT') {
let that = this;
if (window.currentInterval != undefined && this.interval == window.currentInterval) {
// Just pause
clearInterval(window.currentInterval);
window.currentInterval = undefined;
} else {
let values = [];
let lines = DCT.content.split("\n");
for (let line of lines) {
values = values.concat(line.trim().split(" "));
}
if (JSON.stringify(values) != JSON.stringify(imageEditor.finalValues)) {
// This is a new image!
imageEditor.currentValues = undefined;
}
imageEditor.finalValues = values;
// If it's already been going, and not done yet
if (imageEditor.currentValues != undefined && imageEditor.currentValues.length < imageEditor.finalValues.length) {
// No need to reset
} else {
// Otherwise, start from beginning
imageEditor.setResetText(DCT.content);
imageEditor.currentValues = [];
}
imageEditor.putValuesInEditor(imageEditor.currentValues, 64, false);
if (window.currentInterval) {
clearInterval(window.currentInterval);
}
window.currentInterval = setInterval(function(){
if (imageEditor.currentValues.length < imageEditor.finalValues.length) {
// Add as many non trivial numbers. Non trivial is defined as less than 10.
for (let i = imageEditor.currentValues.length; i < imageEditor.finalValues.length; i++) {
imageEditor.currentValues.push(imageEditor.finalValues[i]);
if (Math.abs(imageEditor.finalValues[i]) > 10) {
break;
}
}
imageEditor.putValuesInEditor(imageEditor.currentValues, 64, false);
} else {
clearInterval(window.currentInterval);
window.currentInterval = undefined;
}
}, 20);
this.interval = window.currentInterval;
}
sentValuesToEditor = true;
} else {
let count = 0;
let values = imageEditor.getValuesFromEditor(imageEditor.resetText);
let newValues = [];
for (let i = 0; i < values.length; i+= scale + 2) {
for (let j = 0; j < scale; j++) {
let lookAheadCb = values[i + scale];
let lookAheadCr = values[i + scale + 1];
let Y = (pattern == 'isolate-Y') ? values[i + j] : 128;
newValues.push(Y)
}
let Cb = (pattern == 'isolate-Cb') ? (values[i + scale]) : 128;
let Cr = (pattern == 'isolate-Cr') ? (values[i + scale + 1]) : 128;
newValues.push(Cb)
newValues.push(Cr);
}
let samplesPerLine = imageEditor.samplesPerLine;
imageEditor.putValuesInEditor(newValues, samplesPerLine);
sentValuesToEditor = true;
}
if (!sentValuesToEditor) {
text = lines.join('\n');
imageEditor.editor.setValue(text, -1);
imageEditor.editor.scrollToLine(line - 1);
}
// this.props.updateProps({ value: e.target.value });
}
render() {
const { hasError, idyll, updateProps, ...props } = this.props;
return (
<span className="replace-link" onClick={this.onClick}>{props.children}</span>
);
}
}
module.exports = TextArea;
| 35.765432 | 124 | 0.521747 |
36e19bc8112fbd5cb7eb9fd487bba993dfd3612a | 124 | js | JavaScript | test/lib/SomeOtherAnimal.js | objectlabs/maker | 6cb2775ab6d029aae35a65c6f72411e6d5f7b05a | [
"MIT"
] | 2 | 2015-03-16T08:02:54.000Z | 2015-08-12T15:11:59.000Z | test/lib/SomeOtherAnimal.js | objectlabs/maker | 6cb2775ab6d029aae35a65c6f72411e6d5f7b05a | [
"MIT"
] | null | null | null | test/lib/SomeOtherAnimal.js | objectlabs/maker | 6cb2775ab6d029aae35a65c6f72411e6d5f7b05a | [
"MIT"
] | null | null | null | var o = require('../../lib/maker').o(module, true)
module.exports = o({
_type: './Animal',
name: 'SomeOtherAnimal'
})
| 15.5 | 50 | 0.596774 |
36e30adfd077084416c8d83f817d3e76383f52b2 | 3,395 | js | JavaScript | template/server/utils/log_util.js | pengdou/vuekoa2 | 930b64d7a3bd92c45a99af23baafda78617fc8a1 | [
"MIT"
] | null | null | null | template/server/utils/log_util.js | pengdou/vuekoa2 | 930b64d7a3bd92c45a99af23baafda78617fc8a1 | [
"MIT"
] | null | null | null | template/server/utils/log_util.js | pengdou/vuekoa2 | 930b64d7a3bd92c45a99af23baafda78617fc8a1 | [
"MIT"
] | null | null | null | var log4js = require('log4js')
var logConfig = require('../config/log_config')
// 加载配置文件
log4js.configure(logConfig)
var logUtil = {}
// 调用预先定义的日志名称
var resLogger = log4js.getLogger('resLogger')
var errorLogger = log4js.getLogger('errorLogger')
var debugLogger = log4js.getLogger('debugLogger')
var consoleLogger = log4js.getLogger()
// 封装错误日志
logUtil.error = function (ctx, error, resTime) {
if (ctx && error) {
errorLogger.error(formatError(ctx, error, resTime))
}
}
// 封装debug日志
logUtil.debug = function (info) {
if (info) {
debugLogger.debug(formatDebug(info))
}
}
// 封装响应日志
logUtil.resp = function (ctx, resTime) {
if (ctx) {
resLogger.info(formatRes(ctx, resTime))
}
}
logUtil.info = function (info) {
if (info) {
consoleLogger.info(formatInfo(info))
}
}
var formatInfo = function (info) {
var logText = String()
// 响应日志开始
// logText += "\n" + "**************info log start ***************" + "\n"
// 响应内容
// logText += "info detail: " + "\n" + JSON.stringify(info) + "\n"
if (typeof (info) === 'string') {
logText += info
} else {
logText += JSON.stringify(info)
}
// 响应日志结束
// logText += "*************** info log end ***************" + "\n"
return logText
}
var formatDebug = function (info) {
var logText = String()
// 响应日志开始
// logText += "\n" + "**************info log start ***************" + "\n"
// 响应内容
// logText += "info detail: " + "\n" + JSON.stringify(info) + "\n"
if (typeof (info) === 'string') {
logText += info
} else {
logText += JSON.stringify(info)
}
// 响应日志结束
// logText += "*************** info log end ***************" + "\n"
return logText
}
// 格式化响应日志
var formatRes = function (ctx, resTime) {
var logText = String()
// 响应日志开始
logText += '\n' + '*************** response log start ***************' + '\n'
// 添加请求日志
logText += formatReqLog(ctx.request, resTime)
// 响应状态码
logText += 'response status: ' + ctx.status + '\n'
// 响应内容
logText += 'response body: ' + '\n' + JSON.stringify(ctx.body) + '\n'
// 响应日志结束
logText += '*************** response log end ***************' + '\n'
return logText
}
// 格式化错误日志
var formatError = function (ctx, err, resTime) {
var logText = String()
// 错误信息开始
logText += '\n' + '*************** error log start ***************' + '\n'
// 添加请求日志
logText += formatReqLog(ctx.request, resTime)
// 错误名称
logText += 'err name: ' + err.name + '\n'
// 错误信息
logText += 'err message: ' + err.message + '\n'
// 错误详情
logText += 'err stack: ' + err.stack + '\n'
// 错误信息结束
logText += '*************** error log end ***************' + '\n'
return logText
}
// 格式化请求日志
var formatReqLog = function (req, resTime) {
var logText = String()
var method = req.method
// 访问方法
logText += 'request method: ' + method + '\n'
// 请求原始地址
logText += 'request originalUrl: ' + req.originalUrl + '\n'
// 客户端ip
logText += 'request client ip: ' + req.ip + '\n'
// 开始时间
// var startTime
// 请求参数
if (method === 'GET') {
logText += 'request query: ' + JSON.stringify(req.query) + '\n'
// startTime = req.query.requestStartTime
} else {
logText += 'request body: ' + '\n' + JSON.stringify(req.body) + '\n'
// startTime = req.body.requestStartTime
}
// 服务器响应时间
logText += 'response time: ' + resTime + '\n'
return logText
}
module.exports = logUtil
| 22.939189 | 79 | 0.555817 |
36e4bea887db0a49c5ea8c286a60eb332a1d1a1f | 122 | js | JavaScript | src/api/base.js | taikongfeizhu/webpack-develop-startkit | a752a9c4259d2a673e8e4d1f5f202ec3dfd82af3 | [
"MIT"
] | 51 | 2017-05-04T14:33:15.000Z | 2020-11-03T03:22:13.000Z | src/api/base.js | taikongfeizhu/webpack-develop-startkit | a752a9c4259d2a673e8e4d1f5f202ec3dfd82af3 | [
"MIT"
] | null | null | null | src/api/base.js | taikongfeizhu/webpack-develop-startkit | a752a9c4259d2a673e8e4d1f5f202ec3dfd82af3 | [
"MIT"
] | 24 | 2017-06-07T04:04:51.000Z | 2020-05-23T13:06:15.000Z | const prefix = '/api/'
export default {
getOpporList: {
url: `${prefix}opportunity_list/`,
method: 'GET'
}
}
| 13.555556 | 38 | 0.598361 |
36e6f09cac3d43fb3158442f5c3246b5e1296243 | 3,309 | js | JavaScript | Binary_Tree/binary_tree_main.js | deveshdasandroid/test | a5a0525f181403a8924bfd7400f0644d47d753a5 | [
"MIT"
] | 1 | 2021-03-14T08:46:51.000Z | 2021-03-14T08:46:51.000Z | Binary_Tree/binary_tree_main.js | deveshdasandroid/test | a5a0525f181403a8924bfd7400f0644d47d753a5 | [
"MIT"
] | null | null | null | Binary_Tree/binary_tree_main.js | deveshdasandroid/test | a5a0525f181403a8924bfd7400f0644d47d753a5 | [
"MIT"
] | null | null | null | var insertButton = document.getElementById('insert')
var deleteButton = document.getElementById('delete')
var inputtext = document.getElementById('inputnum')
var container = document.getElementById('treeContainer')
var svg = "http://www.w3.org/2000/svg";
function openTab(evt, name) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(name).style.display = "block";
evt.currentTarget.className += " active";
}
function drawNode(node, node2) {
var container2 = document.createElementNS(svg, 'g')
var circle = document.createElementNS(svg, 'circle')
circle.setAttributeNS(null, 'cx', node.currX)
circle.setAttributeNS(null, 'cy', node.currY)
circle.setAttributeNS(null, 'r', node.radius)
circle.setAttributeNS(null, 'stroke', 'red')
circle.setAttributeNS(null, 'fill', 'white')
var textSvg = document.createElementNS(svg, 'text')
textSvg.setAttributeNS(null, 'x', node.currX - 8)
textSvg.setAttributeNS(null, 'y', node.currY + 3)
textSvg.setAttributeNS(null, 'stroke', 'black')
textSvg.setAttributeNS(null, 'font-size', '15')
textSvg.innerHTML = node.data
textSvg.style = 'z-index: 1;'
var line = document.createElementNS(svg, 'line')
line.setAttributeNS(null, 'x1', node.currX)
line.setAttributeNS(null, 'y1', node.currY)
line.setAttributeNS(null, 'x2', node2.currX)
line.setAttributeNS(null, 'y2', node2.currY)
line.setAttributeNS(null, 'stroke', 'red')
line.setAttributeNS(null, 'stroke-width', 3)
line.style = 'z-index: 1;'
container2.appendChild(line)
container2.appendChild(circle)
container2.appendChild(textSvg)
circle.classList.add('node')
textSvg.classList.add('node')
line.classList.add('node')
container.appendChild(container2)
//nodes.push(container2)
}
var tree = new BST();
insertButton.onclick = () => {
i = parseInt(inputtext.value);
document.getElementById('insertbt').click()
if (inputtext.value) {
tree.add(i);
tree.update()
document.getElementById('inputnum').value = ''
} else {
Alert.render('Please enter some value')
}
}
deleteButton.onclick = () => {
i = parseInt(inputtext.value);
document.getElementById('deletebt').click()
if (inputtext.value) {
tree.delete(i);
tree.update()
document.getElementById('inputnum').value = ''
} else {
Alert.render('Please enter some value')
}
}
document.getElementById('traverse').onclick = () => {
document.getElementById('traversebt').click()
tree.traverse()
}
document.getElementById('search').onclick = () => {
document.getElementById('searchbt').click()
tree.search(document.getElementById('inputnum').value);
document.getElementById('inputnum').value = ''
}
for (var i = 0; i < 4; i++) {
tree.add(Math.floor(Math.random() * (99 - 5 + 1)) + 5)
tree.update()
}
setInterval(async () => {
tree.draw()
}, 1000 / 60) | 31.817308 | 77 | 0.658507 |
36ea28b93092d4cffe9d51ff37372f5da770036f | 4,376 | js | JavaScript | src/routes/config/supplierCar/CarContainer.js | Xzg-github/tmsAPP | 423c577826f6d838bbdc784d9d7156e1d2618f16 | [
"MIT"
] | null | null | null | src/routes/config/supplierCar/CarContainer.js | Xzg-github/tmsAPP | 423c577826f6d838bbdc784d9d7156e1d2618f16 | [
"MIT"
] | 1 | 2022-01-22T09:13:46.000Z | 2022-01-22T09:13:46.000Z | src/routes/config/supplierCar/CarContainer.js | Xzg-github/tmsAPP | 423c577826f6d838bbdc784d9d7156e1d2618f16 | [
"MIT"
] | null | null | null | import {connect} from 'react-redux';
import CarDialog from './CarDialog';
import {Action} from '../../../action-reducer/action';
import showPopup from '../../../standard-business/showPopup';
import helper, {showError} from '../../../common/common';
import {getPathValue} from '../../../action-reducer/helper';
import showAddDialog from '../supplierDriver/addDialog/AddDialogContainer';
import {fetchDictionary, setDictionary2} from '../../../common/dictionary';
const action = new Action(['temp3']);
const URL_UPDATE = '/api/config/supplier_car/updateList';
const URL_CONFIG = '/api/config/supplierDriver/config';
const DRIVER = '/api/config/supplier_car/search/driver'; //司机下拉
const buildState = (config, title,value={},isSupplier) => {
value.isOwner = isSupplier ? 0 : 1;//如果为供应商车辆时,固定值为0,综合为1
return {
...config,
title: title,
visible: true,
value
};
};
const getSelfState = (state) => {
return getPathValue(state, ['temp3']);
};
const closeActionCreator = () => (dispatch) => {
dispatch(action.assign({visible: false, ok: false}));
};
const okActionCreator = () => async(dispatch,getState) => {
const state = getSelfState(getState());
if (helper.validValue(state.controls, state.value)) {
let body,sendMethod;
body = helper.convert(state.value);
const json = await helper.fetchJson(URL_UPDATE, helper.postOption(body,'post'));
if (json.returnCode) {
helper.showError(json.returnMsg);
} else {
dispatch(action.assign({visible: false, ok: json.result}));
}
} else {
dispatch(action.assign({valid: true}));
}
};
const clickActionCreators = {
close: closeActionCreator,
ok:okActionCreator
};
const clickActionCreator = (key) => {
if (clickActionCreators.hasOwnProperty(key)) {
return clickActionCreators[key]();
} else {
return {type: 'unknown'};
}
};
const searchActionCreator = (key,keyValue,keyControls) => async(dispatch,getState) => {
const {controls,value} = getSelfState(getState());
let json,id;
if(key === 'driverId' ){//司机标识跟所属供应商联动
if(!value.supplierId)
return showError('请先选择供应商');
id = value.supplierId.value;
const body = {
supplierId:id,
name:keyValue
};
json = await helper.fetchJson(keyControls.searchUrl,helper.postOption(body))
}else {
json = await helper.fuzzySearchEx(keyValue,keyControls);
}
if (!json.returnCode) {
const index = controls.findIndex(item => item.key == key);
dispatch(action.update({options:json.result}, 'controls', index));
}else {
helper.showError(json.returnMsg)
}
};
const changeActionCreator = (key, keyValue) => (dispatch,getState) => {
const {value} = getSelfState(getState());
if(key === 'supplierId'){
dispatch(action.assign({['driverId']: ''}, 'value'));
dispatch(action.update({options:[]}, 'controls', 4));
}
dispatch(action.assign({[key]: keyValue}, 'value'));
};
const exitValidActionCreator = () => {
return action.assign({valid: false});
};
const onAddActionCreator = (key) => async(dispatch,getState) => {
const {edit} = await helper.fetchJson(URL_CONFIG);
const {value} = getSelfState(getState());
if(key === 'driverId'){
let obj = {};
if(value.supplierId){
obj.supplierId = value.supplierId
}
const info = await showAddDialog(obj, edit);
if (info) {
dispatch(action.assign({driverId: {value: info.id, title: info.driverName}}, 'value'));
}
}
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onClick: clickActionCreator,
onSearch:searchActionCreator,
onChange:changeActionCreator,
onExitValid:exitValidActionCreator,
onAdd:onAddActionCreator
};
const URL_CONFIG_CAR = '/api/config/supplier_car/config';
export default async(value = {},title='新增',isSupplier = true) => {
const {edit,dictionary} = helper.getJsonResult(await helper.fetchJson(URL_CONFIG_CAR));
const dictionaryOptions = helper.getJsonResult(await fetchDictionary(dictionary));
setDictionary2(dictionaryOptions,edit.controls );
const Container = connect(mapStateToProps, actionCreators)(CarDialog);
global.store.dispatch(action.create(buildState(edit, title,value,isSupplier)));
await showPopup(Container,{}, true);
const state = getSelfState(global.store.getState());
global.store.dispatch(action.create({}));
return state.ok;
}
| 29.972603 | 93 | 0.684644 |
36eabed4c53c615ee1ca6fbf8b31c1995ee55d2e | 444 | js | JavaScript | env.js | GuOshiro/uplant-api | 18169a5465a03e51246590862568dfd2f3f3475b | [
"MIT"
] | null | null | null | env.js | GuOshiro/uplant-api | 18169a5465a03e51246590862568dfd2f3f3475b | [
"MIT"
] | null | null | null | env.js | GuOshiro/uplant-api | 18169a5465a03e51246590862568dfd2f3f3475b | [
"MIT"
] | null | null | null | const fs = require('fs');
if (fs.existsSync('./public')) {
process.env.NODE_ENV = 'production';
process.env.databaseUri = 'mongodb://patel:patel@ds153752.mlab.com:53752/db_uplantPublic';
process.env.databaseName = 'production database: db_uplantPublic';
} else {
process.env.NODE_ENV = 'development';
process.env.databaseUri = 'mongodb://localhost:27017/db_uplant';
process.env.databaseName = 'development database: db_uplant';
}
| 37 | 92 | 0.734234 |
36eaf4bb15a025c43923b5b3edabb8a9c9c73a7e | 215 | js | JavaScript | modules/radomMult.js | Harris-Shelby/cable_action | af862130e92e02de6d156fc7e43c7345f9b2da32 | [
"Apache-2.0"
] | 1 | 2021-01-07T15:25:22.000Z | 2021-01-07T15:25:22.000Z | modules/radomMult.js | Harris-Shelby/cable_action | af862130e92e02de6d156fc7e43c7345f9b2da32 | [
"Apache-2.0"
] | null | null | null | modules/radomMult.js | Harris-Shelby/cable_action | af862130e92e02de6d156fc7e43c7345f9b2da32 | [
"Apache-2.0"
] | null | null | null | module.exports = class MULT {
constructor () {
this.init()
}
init() {
this.mult = Math.random() * 4 + 6
this.ran = parseFloat((Math.random() * 3 + 0.5).toFixed(1))
}
} | 23.888889 | 68 | 0.47907 |
36ebd91c7f882dda2981924c0fd6bc0940a81abf | 8,363 | js | JavaScript | z-canvas.js | igroglaz/mangclient-js | a4c1e0d8f9a099f30de69d151c9334d51fe1a7ad | [
"CC0-1.0"
] | 1 | 2020-02-05T21:47:11.000Z | 2020-02-05T21:47:11.000Z | z-canvas.js | igroglaz/mangclient-js | a4c1e0d8f9a099f30de69d151c9334d51fe1a7ad | [
"CC0-1.0"
] | null | null | null | z-canvas.js | igroglaz/mangclient-js | a4c1e0d8f9a099f30de69d151c9334d51fe1a7ad | [
"CC0-1.0"
] | null | null | null | class ZTerm {
constructor(root_node, config) {
config = config || {}
let cnv = document.createElement('canvas');
this.rows = 0;
this.cols = 0;
this.cell_w = 0;
this.cell_h = 0;
this.dungeon_offset_col = config['dungeon_offset_col'] || 0;
this.dungeon_offset_row = config['dungeon_offset_row'] || 0;
this.colors = {
0: '#000000', /* TERM_DARK */
1: '#FFFFFF', /* TERM_WHITE */
2: '#808080', /* TERM_SLATE */
3: '#FF8000', /* TERM_ORANGE */
4: '#C00000', /* TERM_RED */
5: '#008040', /* TERM_GREEN */
6: '#0040FF', /* TERM_BLUE */
7: '#804000', /* TERM_UMBER */
8: '#606060', /* TERM_L_DARK */
9: '#C0C0C0', /* TERM_L_WHITE */
10:'#FF00FF', /* TERM_VIOLET */
11:'#FFFF00', /* TERM_YELLOW */
12:'#FF4040', /* TERM_L_RED */
13:'#00FF00', /* TERM_L_GREEN */
14:'#00FFFF', /* TERM_L_BLUE */
15:'#C08040',/* TERM_L_UMBER */
16:'purple',//#define COLOUR_PURPLE 16 /* p */
17:'#FF00FF',//#define COLOUR_VIOLET 17 /* v */ /* 4 0 4 */
18:'teal',//#define COLOUR_TEAL 18 /* t */
19:'brown',//#define COLOUR_MUD 19 /* m */
20:'yellow',//#define COLOUR_L_YELLOW 20 /* Y */
21: 'magenta',//#define COLOUR_MAGENTA 21 /* i */
22: 'blue',//#define COLOUR_L_TEAL 22 /* T */
23: 'violet',//#define COLOUR_L_VIOLET 23 /* V */
24: 'pink',//#define COLOUR_L_PINK 24 /* I */
25: 'yellow',//#define COLOUR_MUSTARD 25 /* M */
26: 'blue',//#define COLOUR_BLUE_SLATE 26 /* z */
27: 'blue',//#define COLOUR_DEEP_L_BLUE 27 /* Z */
28: 'transparent'//*
//#define COLOUR_SHADE 28 /* for shaded backgrounds */
//#define COLOUR_MULTI 29 /* for object shimmering code */
//#define COLOUR_SPECIAL 30 /* special coloring */
//#define COLOUR_SYMBOL 31 /* special coloring */
};
cnv.tabindex = 1;
root_node.appendChild(cnv);
this.canvas = cnv;
bnd(this, 'key_press');
bnd(this, 'mouse_click');
bnd(this, 'parse_stream');
root_node.addEventListener('keydown', this.key_press)
cnv.addEventListener('click', this.mouse_click)
this.setFont('Monospace', '14px');
this.setSize(24, 80);
this.eventHandlers = {}
}
mouse_click(e) {
let cp = getCursorPosition(this.canvas, e);
this.trigger('click', {
'code': 1,
'name': 'lmb',
'key': 'lmb',
'x': cp[0],
'y': cp[1],
'col': parseInt(cp[0] / this.cell_w),
'row': parseInt(cp[1] / this.cell_h),
});
}
key_press(e) {
if (e.target.nodeName == 'INPUT') return;
let code = e.keyCode;
console.log(e);
const key_names = {
13: 'return',
16: 'shift',
17: 'ctrl',
18: 'alt',
27: 'escape',
32: 'space',
33: 'page_up',
34: 'page_down',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
91: 'meta',
97: 'kp_end',
98: 'kp_down',
99: 'kp_page_down',
100: 'kp_left',
101: 'kp_stay',
102: 'kp_right',
103: 'kp_home',
104: 'kp_up',
105: 'kp_page_up',
112: 'f1', 113: 'f2', 114: 'f3', 115: 'f4', 116: 'f5', 117: 'f6',
118: 'f7', 119: 'f8', 120: 'f9', 121: 'f10', 122: 'f11', 123: 'f12',
}
let name = key_names[code];
if (!name) name = 'undefined'+code;
if (name == 'shift' || name == 'ctrl'
|| name == 'alt' || name == 'meta')
return false;
if (e.ctrlKey) name = 'control-'+name;
if (e.altKey) name = 'alt-' + name;
if (e.shiftKey) name = 'shift-' + name;
if (e.metaKey) name = 'meta-'+name;
this.trigger('keypress', {
'code': code,
'name': name,
'key': e.key,
});
e.preventDefault();
return false;
}
on(evt, func) {
this.eventHandlers[evt] = func;
}
off(evt) {
this.eventHandlers[evt] = undefined;
}
trigger(evt, e) {
if (!this.eventHandlers[evt]) return;
this.eventHandlers[evt](e);
}
wipe_tile(x, y) {
const ctx = this.canvas.getContext("2d");
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.rect(x * this.cell_w, y * this.cell_h, this.cell_w, this.cell_h);
ctx.fill();
}
wipe_text(x, y, s) {
const ctx = this.canvas.getContext("2d");
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.rect(x * this.cell_w, y * this.cell_h, this.cell_w * (""+s).length, this.cell_h);
ctx.fill();
}
draw_text(x, y, a, s) {
this.wipe_text(x, y, s);
const ctx = this.canvas.getContext("2d");
ctx.fillStyle = this.colors[a];
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText(s, x * this.cell_w, y * this.cell_h);
}
draw_char(x, y, a, c) {
this.wipe_tile(x, y);
const ctx = this.canvas.getContext("2d");
ctx.fillStyle = this.colors[a];
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText(chr(c), x * this.cell_w, y * this.cell_h, this.cell_w, this.cell_h);
}
draw_pict(x, y, a, c) {
this.wipe_tile(x, y);
//...
}
setFont(fontName, fontSize) {
let fs = getFontSize(fontName, fontSize);
this.fontStyle = fontSize + " " + fontName;
this.cell_w = fs[0];
this.cell_h = fs[1];
let ctx = this.canvas.getContext("2d");
ctx.font = this.fontStyle;
this.canvas.width = this.cols * this.cell_w;
this.canvas.height = this.rows * this.cell_h;
}
setSize(rows, cols) {
this.rows = rows;
this.cols = cols;
this.canvas.width = this.cols * this.cell_w;
this.canvas.height = this.rows * this.cell_h;
}
/* Hack ... */
parse_stream(e) {
let y = 0;
let x = 0;
for (let i = 0; i < e.info.main.length; i++) {
let y = e.info.y;
let x = e.info.x + i;
let a = e.info.main[i].a;
let c = e.info.main[i].c;
this.draw_char(
x + this.dungeon_offset_col,
y + this.dungeon_offset_row,
a, c);
}
}
}
function getFontSize(fontName, fontSize, parent){
parent = parent || document.body;
let who = document.createElement('div');
let css = 'display:inline-block; padding:0; line-height:1; position:absolute; visibility:hidden;';
css += 'font-family: ' + fontName + '; font-size: ' + fontSize + ';';
who.style.cssText = css
who.appendChild(document.createTextNode('M'));
parent.appendChild(who);
let fs = [who.offsetWidth, who.offsetHeight];
parent.removeChild(who);
return fs;
}
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
return [x, y];
}
class ZLogger {
constructor(root_node) {
let main_node = document.createElement('div');
main_node.style.cssText = 'width: 70%; height: 200px; overflow: scroll; background: #000;'
let input_node = document.createElement('input');
input_node.style.cssText = 'width: 60%;';
input_node.placeholder = "Enter chat message...";
let input_button = document.createElement('button');
input_button.textContent = 'SEND';
this.root_node = root_node;
this.main_node = main_node;
this.input_node = input_node;
this.input_button = input_button;
root_node.appendChild(main_node);
root_node.appendChild(input_node);
root_node.appendChild(input_button);
/* TODO: move this somewhere else :( */
this.colors = {
0: '#000000', /* TERM_DARK */
1: '#FFFFFF', /* TERM_WHITE */
2: '#808080', /* TERM_SLATE */
3: '#FF8000', /* TERM_ORANGE */
4: '#C00000', /* TERM_RED */
5: '#008040', /* TERM_GREEN */
6: '#0040FF', /* TERM_BLUE */
7: '#804000', /* TERM_UMBER */
8: '#606060', /* TERM_L_DARK */
9: '#C0C0C0', /* TERM_L_WHITE */
10:'#FF00FF', /* TERM_VIOLET */
11:'#FFFF00', /* TERM_YELLOW */
12:'#FF4040', /* TERM_L_RED */
13:'#00FF00', /* TERM_L_GREEN */
14:'#00FFFF', /* TERM_L_BLUE */
15:'#C08040',/* TERM_L_UMBER */
};
}
addMessage(chan, msg) {
let p = document.createElement('p');
p.textContent = msg;
p.style.cssText = "font-size: smaller; margin: 0; color: #eee;"
this.main_node.appendChild(p);
this.main_node.scrollTop = this.main_node.scrollHeight;
}
addMulticolorMessage(chan, multicolor_message) {
console.log("MC:", multicolor_message);
let p = document.createElement('p');
p.style.cssText = "font-size: smaller; margin: 0;"
for (let k in multicolor_message) {
let part = multicolor_message[k];
let span = document.createElement('span');
span.style.cssText = "color: " + this.colors[part.a];
span.textContent = part.str;
p.appendChild(span);
}
this.main_node.appendChild(p);
this.main_node.scrollTop = this.main_node.scrollHeight;
}
}
| 29.447183 | 99 | 0.604568 |
36ec3d002e4a0c73776fb03c39e30a9d4ce9cfb2 | 254 | js | JavaScript | src/decimalLength.js | wenyejie/utils | ba10a8d6a561812e5365dc3a36995af00d393ac9 | [
"MIT"
] | null | null | null | src/decimalLength.js | wenyejie/utils | ba10a8d6a561812e5365dc3a36995af00d393ac9 | [
"MIT"
] | 6 | 2020-09-19T19:11:19.000Z | 2022-02-27T01:42:58.000Z | src/decimalLength.js | wenyejie/utils | ba10a8d6a561812e5365dc3a36995af00d393ac9 | [
"MIT"
] | null | null | null | import isNumber from './isNumber.js'
const INTEGER_BIT = /^\d+\.?/
// 获取小数点长度
export const decimalLength = (number) => {
if (!isNumber(number)) {
return 0
}
return (`${number}`.replace(INTEGER_BIT, '')).length
}
export default decimalLength
| 18.142857 | 54 | 0.65748 |
36edf9b3961f74ac4ffa6db47bbeacff18c1c723 | 3,246 | js | JavaScript | cms/api/src/main/resources/org/hippoecm/frontend/js/message-bus.js | athenagroup/brxm | 58d3c299f2b925a857e55d689e0cb4ee0258d82c | [
"Apache-2.0"
] | null | null | null | cms/api/src/main/resources/org/hippoecm/frontend/js/message-bus.js | athenagroup/brxm | 58d3c299f2b925a857e55d689e0cb4ee0258d82c | [
"Apache-2.0"
] | 28 | 2020-10-29T15:59:43.000Z | 2022-03-02T12:50:38.000Z | cms/api/src/main/resources/org/hippoecm/frontend/js/message-bus.js | athenagroup/brxm | 58d3c299f2b925a857e55d689e0cb4ee0258d82c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Hippo B.V. (http://www.onehippo.com)
*
* 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.
*/
(function () {
"use strict";
window.Hippo = window.Hippo || {};
Hippo.createMessageBus = function () {
var subscriptions = {},
monitors = [];
function addCallback (list, callback, scope) {
list.push({
callback: callback,
scope: scope || window
});
}
function removeCallback (list, callback, scope) {
var scopeParameter, i, len, entry;
if (list === undefined) {
return false;
}
scopeParameter = scope || window;
for (i = 0, len = list.length; i < len; i++) {
entry = list[i];
if (entry.callback === callback && entry.scope === scopeParameter) {
list.splice(i, 1);
return true;
}
}
return false;
}
function call (entries, args) {
var i, len, entry;
if (entries === undefined) {
return true;
}
len = entries.length;
for (i = 0; i < len; i++) {
entry = entries[i];
if (entry.callback.apply(entry.scope, args) === false) {
return false;
}
}
return true;
}
return {
exception: function (msg, e) {
this.publish('exception', msg, e);
},
publish: function (topic) {
var argumentsWithoutTopic = Array.prototype.slice.call(arguments, 1);
return call(subscriptions[topic], argumentsWithoutTopic) && call(monitors, arguments);
},
subscribe: function (topic, callback, scope) {
if (subscriptions[topic] === undefined) {
subscriptions[topic] = [];
}
addCallback(subscriptions[topic], callback, scope);
},
subscribeOnce: function (topic, callback, scope) {
var self, interceptedCallback;
self = this;
interceptedCallback = function () {
var result = callback.apply(scope, arguments);
self.unsubscribe.call(self, topic, interceptedCallback, scope);
return result;
};
this.subscribe(topic, interceptedCallback, scope);
},
unsubscribe: function (topic, callback, scope) {
return removeCallback(subscriptions[topic], callback, scope);
},
unsubscribeAll: function () {
subscriptions = {};
},
monitor: function (callback, scope) {
return addCallback(monitors, callback, scope);
},
unmonitor: function (callback, scope) {
return removeCallback(monitors, callback, scope);
},
clear: function () {
this.unsubscribeAll();
monitors = [];
}
};
};
Hippo.Events = Hippo.createMessageBus();
}());
| 26.606557 | 94 | 0.5878 |
36ee7db6c2554c82f7ca8763bbe1a4eff18ad375 | 1,401 | js | JavaScript | WebContent/uploadFile.js | T0UGH/NEUSoup | 5ff10bb79fac559dea5cd025074904b48698a18c | [
"MIT"
] | 1 | 2020-12-06T05:29:23.000Z | 2020-12-06T05:29:23.000Z | WebContent/uploadFile.js | T0UGH/NEUSoup | 5ff10bb79fac559dea5cd025074904b48698a18c | [
"MIT"
] | null | null | null | WebContent/uploadFile.js | T0UGH/NEUSoup | 5ff10bb79fac559dea5cd025074904b48698a18c | [
"MIT"
] | null | null | null | var nextImg=0
function setImg(obj){//用于进行图片上传,返回地址
// alert(nextImg)
var f=$(obj).val();
if(nextImg==4){
return false;
}
if(f == null || f ==undefined || f == ''){
return false;
}
if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
{
$(obj).val('');
return false;
}
var data = new FormData();
$.each($(obj)[0].files,function(i,file){
data.append('file', file);
});
$.ajax({
type: "POST",
url: "/Soup/UploadServlet",//提交的地址
data: data,
cache: false,//禁用缓存
contentType: false, //不可缺//不懂
processData: false, //不可缺//禁止自动转换
dataType:"json",
success: function(suc) {
if(suc.code==0){
$("#img_url").attr("value",$("#img_url").attr("value")+suc.message+",")
$("#thumburlShow"+nextImg).attr("src",suc.message);//显示图片
nextImg+=1
}else{
alert("上传失败");
$("#url").val("");
$(obj).val('');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("上传失败,请检查网络后重试");
$("#url").val("");
$(obj).val('');
}
});
}
function checkSubmit(){
document.getElementById("time").setAttribute("value",""+new Date().getTime())
return true
} | 28.591837 | 93 | 0.460385 |
36eefee67f6032d82991505f8786ec6c87483879 | 39 | js | JavaScript | packages/2008/03/28/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 7 | 2017-07-03T19:53:01.000Z | 2021-04-05T18:15:55.000Z | packages/2008/03/28/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 1 | 2018-09-05T11:53:41.000Z | 2018-12-16T12:36:21.000Z | packages/2008/03/28/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 2 | 2019-01-27T16:57:34.000Z | 2020-10-11T09:30:25.000Z | module.exports = new Date(2008, 2, 28)
| 19.5 | 38 | 0.692308 |
36ef21c58d98b8352261eddc6ff0dfea9f3d6b0a | 1,847 | js | JavaScript | src/components/common/PayoutInfo/PayoutInfo.connect.js | GolosChain/golos.io | d7e1f766f6a25ba9808dd9039ae742ebcc677f06 | [
"MIT"
] | 5 | 2016-09-12T22:48:49.000Z | 2019-06-01T14:29:51.000Z | src/components/common/PayoutInfo/PayoutInfo.connect.js | GolosChain/golos.io | d7e1f766f6a25ba9808dd9039ae742ebcc677f06 | [
"MIT"
] | 363 | 2016-09-15T14:23:06.000Z | 2021-12-09T01:09:15.000Z | src/components/common/PayoutInfo/PayoutInfo.connect.js | GolosChain/golos.io | d7e1f766f6a25ba9808dd9039ae742ebcc677f06 | [
"MIT"
] | 7 | 2016-09-26T18:27:43.000Z | 2020-10-29T19:14:01.000Z | import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import BigNum from 'bignumber.js';
import { payoutSum } from 'utils/payout';
import { dataSelector, entitySelector } from 'store/selectors/common';
import PayoutInfo from './PayoutInfo';
export default connect(
createSelector(
[
(state, props) => {
const { type, id } = props.entity;
if (type === 'comment') {
let comment = entitySelector('replies', id)(state);
if (!comment) {
comment = entitySelector('postComments', id)(state);
}
if (!comment) {
comment = entitySelector('profileComments', id)(state);
}
return comment;
}
return entitySelector('posts', id)(state);
},
dataSelector(['settings', 'basic', 'rounding']),
],
({ payout }, payoutRounding) => {
const { done } = payout;
const author = {
value: new BigNum(payout.author.token.value)
.plus(payout.author.vesting.value)
.toFixed(payoutRounding),
sym: payout.author.token.name,
};
const curator = {
value: parseFloat(payout.curator.token.value).toFixed(payoutRounding),
sym: payout.curator.token.name,
};
const benefactor = {
value: parseFloat(payout.benefactor.token.value).toFixed(payoutRounding),
sym: payout.benefactor.token.name,
};
const unclaimed = {
value: parseFloat(payout.unclaimed.token.value).toFixed(payoutRounding),
sym: payout.unclaimed.token.name,
};
return {
author,
curator,
benefactor,
unclaimed,
done,
totalPayout: parseFloat(payoutSum(payout)).toFixed(payoutRounding),
payoutRounding,
};
}
),
null
)(PayoutInfo);
| 26.768116 | 81 | 0.586356 |
36ef338f4ebbb1249109799b882b49e3751700d9 | 57 | js | JavaScript | Blockchain/Web3-Solidity-Project/node_modules/browserify/test/json/invalid.js | Serafin-dev/what-I-ve-done | ffb35a24d4fd198beef1c6ee3a13d43c56654afa | [
"Apache-2.0"
] | 3,625 | 2017-08-29T18:30:59.000Z | 2022-03-31T14:19:12.000Z | Blockchain/Web3-Solidity-Project/node_modules/browserify/test/json/invalid.js | Serafin-dev/what-I-ve-done | ffb35a24d4fd198beef1c6ee3a13d43c56654afa | [
"Apache-2.0"
] | 447 | 2017-08-29T23:39:51.000Z | 2022-03-27T14:02:12.000Z | Blockchain/Web3-Solidity-Project/node_modules/browserify/test/json/invalid.js | Serafin-dev/what-I-ve-done | ffb35a24d4fd198beef1c6ee3a13d43c56654afa | [
"Apache-2.0"
] | 406 | 2017-08-29T23:59:26.000Z | 2022-03-27T15:57:55.000Z | ex(require('./invalid.json'));
ex(require('./invalid'));
| 19 | 30 | 0.631579 |
36f31217a32b15f68bb6f42d7d641b5de4c5199f | 132 | js | JavaScript | src/logger/schemas/index.js | lilithkarapetyan/npm-dependency-graph | 4f0bb038ac8de5882a0013c58c3a701946cd7269 | [
"MIT"
] | null | null | null | src/logger/schemas/index.js | lilithkarapetyan/npm-dependency-graph | 4f0bb038ac8de5882a0013c58c3a701946cd7269 | [
"MIT"
] | null | null | null | src/logger/schemas/index.js | lilithkarapetyan/npm-dependency-graph | 4f0bb038ac8de5882a0013c58c3a701946cd7269 | [
"MIT"
] | null | null | null | const LogSchema = require('./log');
const ErrorSchema = require('./error');
module.exports = {
LogSchema,
ErrorSchema,
};
| 14.666667 | 39 | 0.643939 |
36f4f62abde199ca78f1b2cf18cbd2fce52611c2 | 2,973 | js | JavaScript | src/components/pages/Home.js | open-tender/open-tender-pos | fb97aba940e7f4386f0c75385136d2464b03fd10 | [
"MIT"
] | 1 | 2022-03-26T19:22:39.000Z | 2022-03-26T19:22:39.000Z | src/components/pages/Home.js | open-tender/open-tender-pos | fb97aba940e7f4386f0c75385136d2464b03fd10 | [
"MIT"
] | null | null | null | src/components/pages/Home.js | open-tender/open-tender-pos | fb97aba940e7f4386f0c75385136d2464b03fd10 | [
"MIT"
] | null | null | null | import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import {
fetchRevenueCenter,
selectRevenueCenter,
selectOrder,
setOrderServiceType,
} from '@open-tender/redux'
import {
FlexCentered,
Greeting,
ButtonGroup,
Button,
} from '@open-tender/components-pos'
import { openModal, selectRevenueCenterId, selectStore } from '../../slices'
import { NotificationTest, AlertTest, WorkingTest, VersionTest } from '../tests'
import { useCashier } from '../../hooks'
import { maybeRefreshVersion } from '@open-tender/js'
const Home = () => {
const dispatch = useDispatch()
const history = useHistory()
const revenueCenterId = useSelector(selectRevenueCenterId)
const { orderType, serviceType } = useSelector(selectOrder)
const revenueCenter = useSelector(selectRevenueCenter)
const { name, greeting } = revenueCenter || {}
const msg = greeting || (name ? `Hi, ${name}!` : 'Hi there')
const { cashier } = useCashier()
const { order_page_swipe } = useSelector(selectStore)
const showTests = false
useEffect(() => {
const open = (args) => dispatch(openModal(args))
maybeRefreshVersion(open)
}, [dispatch])
useEffect(() => {
dispatch(fetchRevenueCenter(revenueCenterId))
if (!orderType || !serviceType) {
dispatch(setOrderServiceType('OLO', 'WALKIN'))
}
}, [dispatch, orderType, serviceType, revenueCenterId])
const startOrder = () => {
if (order_page_swipe) {
const args = {
roles: ['Manager', 'Cashier'],
action: () => history.push('/order'),
}
dispatch(openModal({ type: 'authAction', args }))
} else {
history.push('/order')
}
}
return (
<FlexCentered>
{msg && (
<Greeting title={msg}>
{!cashier ? (
<>
<p>
Please visit the manager section to assign a cashier to this
terminal.
</p>
{/* <Button
text="Assign Cashier"
onClick={assignCashier}
size="large"
color="active"
/> */}
</>
) : (
<>
<p>
{cashier.first_name} {cashier.last_name} is currently assigned
to this terminal.
</p>
<Button
text="Start Order"
onClick={startOrder}
size="large"
color="active"
/>
</>
)}
{showTests && (
<div style={{ margin: '3rem 0 0' }}>
<ButtonGroup>
<VersionTest />
<WorkingTest />
<AlertTest />
<NotificationTest />
</ButtonGroup>
</div>
)}
</Greeting>
)}
</FlexCentered>
)
}
Home.displayName = 'Home'
export default Home
| 27.785047 | 80 | 0.54255 |
36f791386af80e700657e2e7eb19a86e9de03f19 | 505 | js | JavaScript | dist/uncompressed/skylark-grapejs/dom_components/model/ComponentLabel.js | skylark-integration/skylark-grapejs | 5013189f3028a06ac9d7f90993f3ea9ae1c1eba0 | [
"BSD-3-Clause"
] | null | null | null | dist/uncompressed/skylark-grapejs/dom_components/model/ComponentLabel.js | skylark-integration/skylark-grapejs | 5013189f3028a06ac9d7f90993f3ea9ae1c1eba0 | [
"BSD-3-Clause"
] | 1 | 2021-10-17T03:42:16.000Z | 2021-10-17T03:42:16.000Z | src/dom_components/model/ComponentLabel.js | skylark-integration/skylark-grapejs | 5013189f3028a06ac9d7f90993f3ea9ae1c1eba0 | [
"BSD-3-Clause"
] | null | null | null | define([
"skylark-langx/langx",
'./ComponentText'
], function (langx,Component) {
'use strict';
return Component.extend({
defaults: {
...Component.prototype.defaults,
tagName: 'label',
traits: [
'id',
'title',
'for'
]
}
}, {
isComponent(el) {
if (el.tagName == 'LABEL') {
return { type: 'label' };
}
}
});
}); | 21.956522 | 44 | 0.384158 |
36f79b2e874008a3ba096ef0f89ca0f75e7b5795 | 178 | js | JavaScript | src/Pages/Page404/Components/FlappyBird/index.js | anameloni/catflix | d7e4b374c12b8efd436e901317ddf5a86933e519 | [
"MIT"
] | 1 | 2021-03-29T18:08:22.000Z | 2021-03-29T18:08:22.000Z | src/Pages/Page404/Components/FlappyBird/index.js | anameloni/catflix | d7e4b374c12b8efd436e901317ddf5a86933e519 | [
"MIT"
] | 4 | 2020-07-30T21:58:21.000Z | 2020-07-30T22:36:52.000Z | src/Pages/Page404/Components/FlappyBird/index.js | anameloni/catflix | d7e4b374c12b8efd436e901317ddf5a86933e519 | [
"MIT"
] | null | null | null | import React from 'react';
function FlappyBird() {
return(
<a href>
Copiar arquivos e HTML do FlappyBird
</a>
)
}
export default FlappyBird; | 16.181818 | 48 | 0.58427 |
36f79ef2446b04f0e74afe25cde6487a87475762 | 289 | js | JavaScript | src/Typography/Caption.js | Hummingbird-RegTech/react-mdc-web | dea96ebb7ffd1ea88e46518c914ccc3a1df00fa8 | [
"MIT"
] | 210 | 2017-01-12T16:55:24.000Z | 2019-06-10T18:29:25.000Z | src/Typography/Caption.js | Hummingbird-RegTech/react-mdc-web | dea96ebb7ffd1ea88e46518c914ccc3a1df00fa8 | [
"MIT"
] | 70 | 2017-01-26T09:24:45.000Z | 2022-02-10T02:06:28.000Z | src/Typography/Caption.js | Hummingbird-RegTech/react-mdc-web | dea96ebb7ffd1ea88e46518c914ccc3a1df00fa8 | [
"MIT"
] | 38 | 2017-02-09T09:05:31.000Z | 2019-09-06T01:07:26.000Z | import React from 'react';
import TypographyElement from './TypographyElement';
const defaultProps = {
component: 'span',
};
const Caption = props => (
<TypographyElement
modificator="caption"
{...props}
/>
);
Caption.defaultProps = defaultProps;
export default Caption;
| 16.055556 | 52 | 0.698962 |
36f7da78e7ef61b919bdd7e8f43118faa0a47d68 | 582 | js | JavaScript | src/global/CompareReducer.js | trithien98/aliomis-commerce | 87af5c7fffff404f21b4350fa0b0e6ec39c87a77 | [
"MIT"
] | null | null | null | src/global/CompareReducer.js | trithien98/aliomis-commerce | 87af5c7fffff404f21b4350fa0b0e6ec39c87a77 | [
"MIT"
] | null | null | null | src/global/CompareReducer.js | trithien98/aliomis-commerce | 87af5c7fffff404f21b4350fa0b0e6ec39c87a77 | [
"MIT"
] | 1 | 2021-04-15T10:32:45.000Z | 2021-04-15T10:32:45.000Z | export const CompareReducer = (state, action) => {
const compareList = state;
const product = action.payload;
switch (action.type) {
case "ADD_TO_COMPARE":
const productInCompareList = compareList.find(item => item.id === product.id);
if (productInCompareList) {
return state;
} else {
return [product, ...compareList];
}
case "REMOVE_FROM_COMPARE":
return compareList.filter(item => item.id !== product.id);
default:
return state;
}
} | 29.1 | 90 | 0.54811 |
36f7fcc1bf36d2bb5faaa7ae1088d91facbe9d04 | 8,123 | js | JavaScript | tenniscraft/pages/create/create.js | niyaou/ledong-tennis | 3710293ef972cec7979f6aa48f78fa0a0c623f4a | [
"Apache-2.0"
] | null | null | null | tenniscraft/pages/create/create.js | niyaou/ledong-tennis | 3710293ef972cec7979f6aa48f78fa0a0c623f4a | [
"Apache-2.0"
] | 1 | 2021-08-09T20:44:51.000Z | 2021-08-09T20:44:51.000Z | tenniscraft/pages/create/create.js | niyaou/ledong-tennis | 3710293ef972cec7979f6aa48f78fa0a0c623f4a | [
"Apache-2.0"
] | null | null | null | // pages/matches/matchlist.js
const app = getApp()
var http = require('../../utils/http.js')
var util = require('../../utils/util.js')
var pinyin = require('../../utils/pinyinUtil.js')
Page({
/**
* 页面的初始数据
*/
data: {
holderScore: 0,
challengerScore: 0,
isChoiceOpponent: false,
players: [],
holder: '',
time: util.formatTime(new Date()),
name: '',
id: '',
statusBarHeight: getApp().globalData.statusBarHeight,
totalBarHeight: getApp().globalData.totalBarHeight,
visible: false,
fruit: [{
id: 1,
name: '没参加比赛',
}, {
id: 2,
name: '比分记错了'
}],
current: '没参加比赛',
tags: [{
name: "磨神",
checked: false
}, {
name: "进攻凶猛",
checked: false
}, {
name: "发球大炮",
checked: false
}, {
name: "跑不死",
checked: false
}, {
name: "暴力正手",
checked: false
},
{
name: "魔鬼切削",
checked: false
}, {
name: "全场进攻",
checked: false
}, {
name: "变化多端",
checked: false
}, {
name: "发球上网",
checked: false
}, {
name: "底线AK47",
checked: false
},
],
currentTarget: [],
actions: [{
name: '申诉',
color: '#fff',
fontsize: '20',
width: 100,
icon: 'interactive',
background: '#ed3f14'
},
{
name: '返回',
width: 100,
color: '#80848f',
fontsize: '20',
icon: 'undo'
}
],
slideButtons: [{
text: '范大将军 ',
src: '范大将军', // icon的路径,
time: '黄金 段位',
result: '第1',
score: '-30',
toggle: false
}, {
text: 'jerry',
src: 'jerry', // icon的路径,
time: '黄金段位',
result: '第2',
score: '-30',
toggle: false
}, {
text: '小鱼儿 ',
src: '小鱼儿', // icon的路径,
time: '黄金 段位',
result: '第1',
score: '-30',
toggle: false
}, {
text: 'jerry',
src: 'jerry', // icon的路径,
time: '黄金段位',
result: '第2',
score: '-30',
toggle: false
}, {
text: '范大将军 ',
src: '范大将军', // icon的路径,
time: '黄金 段位',
result: '第1',
score: '-30',
toggle: false
}, {
text: 'jerry',
src: 'jerry', // icon的路径,
time: '黄金段位',
result: '第2',
score: '-30',
toggle: false
}],
},
hsChange(e) {
console.log(e)
this.setData({
holderScore: parseInt(e.detail.detail.value)
})
},
csChange(e) {
console.log(e)
this.setData({
challengerScore: parseInt(e.detail.detail.value)
})
},
onChange(e) {
console.log(e)
this.setData({
isChoiceOpponent: false,
name: e.currentTarget.dataset.id.name,
id: e.currentTarget.dataset.id.openId
})
},
handleClick(e) {
let url = 'match/postMatch'
http.postReq(`${url}`, app.globalData.jwt, { opponent: this.data.id }, (res) => {
if (res.code === 0) {
wx.showLoading({
mask: true,
title: '加载中',
})
setTimeout(() => {
this.finishMatch(res.data, 1)
}, 2500)
}
// console.log(res)
})
},
finishMatch(matchId, restTime) {
restTime = restTime - 1
if (restTime < 0) {
return
}
let url = 'match/matchResult/' + matchId
console.log('finishMatch', { holderScore: this.data.holderScore, challengerScore: this.data.challengerScore })
http.postReq(`${url}`, app.globalData.jwt, { holderScore: this.data.holderScore, challengerScore: this.data.challengerScore }, (res) => {
wx.hideLoading();
if (res.code === 0) {
wx.navigateBack({
delta: 0,
})
} else {
wx.showLoading({
mask: true,
title: '再次加载中',
})
setTimeout(() => {
this.finishMatch(res.data, restTime)
}, 800)
}
// console.log(res)
})
},
handleFruitChange({ detail = {} }) {
this.setData({
current: detail.value
});
},
choiceOpponent(e) {
this.setData({
isChoiceOpponent: true
})
},
handleTapped(e) {
// this.setData({visible:true})
console.log(e.detail)
wx.navigateTo({
url: './detail',
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
// this.pinyin();
},
pinyin: function() {
var char = "使";
// if (pinyinjs.hasOwnProperty(char)) {
// console.log(pinyinjs[char][0].substring(0,1))
// this.setData({
// pinyinval: pinyinjs[char].join(', ')
// });
// }
// else {
// this.setData({
// pinyinval: '找不到,^_^'
// });
// }
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
// console.log(pinyin.pinyinUtil)
// let nickName = pinyin.pinyinUtil.getFirstLetter("法国大使馆反对".substring(0,1))
// console.log(nickName)
this.setData({
holder: app.globalData.userInfo.nickName
})
let url = 'rank/rankList?count=500'
http.getReq(`${url}`, app.globalData.jwt, (res) => {
let storeCity = new Array(26);
const words = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"]
words.forEach((item, index) => {
storeCity[index] = {
key: item,
list: []
}
})
res.data.forEach((item) => {
let nickName = pinyin.pinyinUtil.getFirstLetter(item.nickName.substring(0, 1))
// console.log('item.nickName',item.nickName,'nickName',nickName)
let firstName = '#'
let index = words.length - 1
firstName = nickName[0].substring(0, 1);
index = words.indexOf(firstName.toUpperCase());
if (index === -1) {
index = words.length - 1
firstName = '#'
}
// console.log('firstName',firstName,'index',index)
storeCity[index].list.push({
name: item.nickName,
key: firstName,
openId: item.openId
});
})
this.data.players = storeCity;
this.setData({
players: this.data.players
})
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
}) | 25.624606 | 161 | 0.395297 |
36f82f9b3347a71d779f89f56ff36c210e97f547 | 418 | js | JavaScript | public/scripts/models/connections.js | FreeFlow/reddish | d909c742e529949d54558a585253edc44031b705 | [
"MIT"
] | 2 | 2015-05-22T08:19:31.000Z | 2015-08-26T12:15:52.000Z | public/scripts/models/connections.js | FreeFlow/reddish | d909c742e529949d54558a585253edc44031b705 | [
"MIT"
] | null | null | null | public/scripts/models/connections.js | FreeFlow/reddish | d909c742e529949d54558a585253edc44031b705 | [
"MIT"
] | null | null | null | (function() {
window.Reddish || (window.Reddish = {});
Reddish.ConnectionModel = Backbone.Model.extend({
defaults: {
key: null,
name: null,
password: null,
requires_pass: false,
type: 'name',
state: 'disconnected'
}
});
Reddish.ConnectionsCollection = Backbone.Collection.extend({
url: '/connections',
model: Reddish.ConnectionModel
});
}).call(this);
| 19 | 62 | 0.607656 |
36f8468722f8b51a500af35d1eaf13644a498a21 | 2,702 | js | JavaScript | client/src/components/Footer/index.js | Erebus009/Celestial | ecccda506ad229f3c876aa683a7917b030a983b4 | [
"MIT"
] | 3 | 2021-11-30T19:23:57.000Z | 2021-11-30T19:38:51.000Z | client/src/components/Footer/index.js | Erebus009/Celestial | ecccda506ad229f3c876aa683a7917b030a983b4 | [
"MIT"
] | 15 | 2021-12-01T02:20:41.000Z | 2021-12-16T23:28:24.000Z | client/src/components/Footer/index.js | Erebus009/Stellar_portrait | ecccda506ad229f3c876aa683a7917b030a983b4 | [
"MIT"
] | 1 | 2021-12-07T18:54:44.000Z | 2021-12-07T18:54:44.000Z | import React from 'react'
import Container from 'react-bootstrap/esm/Container'
import '../Footer/styles/footer.css';
const Footer = () =>{
return (
<Container class="footer">
<div class="container foot">
<div class="row">
<div class="col-md-7">
<h5 className="display-6"><i class="fa fa-copyright"></i> Celestial</h5>
<div className="row">
<div className="col-6">
<ul className="list-unstyled">
<li><a href="/">Mission</a></li>
<li><a href="/">Goal</a></li>
<li><a href="/">Partners</a></li>
<li><a href="/">Team</a></li>
</ul>
</div>
<div className="col-6">
<ul className="list-unstyled">
<li><a href="/">Documentation</a></li>
<li><a href="/">Support</a></li>
<li><a href="/">Legal Terms</a></li>
<li><a href="/">About</a></li>
</ul>
</div>
</div>
<ul className="nav">
<li class="nav-item"><a href="/" class="nav-link pl-0"><i class="fa fa-facebook fa-lg"></i></a></li>
<li class="nav-item"><a href="/" class="nav-link"><i class="fa fa-twitter fa-lg"></i></a></li>
<li class="nav-item"><a href="/" class="nav-link"><i class="fa fa-github fa-lg"></i></a></li>
<li class="nav-item"><a href="/" class="nav-link"><i class="fa fa-instagram fa-lg"></i></a></li>
</ul>
<br></br>
</div>
<div className="col-md-5">
<h5 className="text-md-right">Contact Us</h5>
<form>
<fieldset className="form-group">
<input type="email" className="form-control" id="exampleInputEmail1" placeholder="Enter email"/>
</fieldset>
<fieldset className="form-group">
<textarea className="form-control" id="exampleMessage" placeholder="Message"></textarea>
</fieldset>
<fieldset class="form-group text-xs-right contianer d-flex justify-content-end">
<button type="button" class="btn btn-dark btn-md text-white mt-2">Send</button>
</fieldset>
</form>
</div>
</div>
</div>
</Container>
)
}
export default Footer
| 40.328358 | 120 | 0.429312 |
36f866e2b566c8f4a7cba611794459f62e751a79 | 1,216 | js | JavaScript | src/components/CharacterList.js | debodirno/super-squad | 4da6d5486fc4b81f2a72c0bde4adfefa05c5670f | [
"MIT"
] | null | null | null | src/components/CharacterList.js | debodirno/super-squad | 4da6d5486fc4b81f2a72c0bde4adfefa05c5670f | [
"MIT"
] | 6 | 2021-03-09T07:51:54.000Z | 2022-02-18T02:03:26.000Z | src/components/CharacterList.js | debodirno/super-squad | 4da6d5486fc4b81f2a72c0bde4adfefa05c5670f | [
"MIT"
] | null | null | null | import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { addCharacterToSquadById } from "../actions/index";
class CharacterList extends Component {
render() {
return (
<div className="characters-container">
<div className="characters-header">
<div>
<h4>Characters</h4>
</div>
</div>
<div className="characters-list">
<ul className="list-group">
{this.props.characters.map(character => (
<li key={character.id} className="list-group-item">
<div className="list-item">{character.name}</div>
<div className="list-item right" onClick={() => this.props.addCharacterToSquadById(character.id)}>
+
</div>
</li>
))}
</ul>
</div>
</div>
);
}
}
const mapStateToProps = state => ({ characters: state.charactersToChooseFrom });
const mapDispatchToProps = dispatch => {
return bindActionCreators({ addCharacterToSquadById }, dispatch);
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(CharacterList);
| 28.952381 | 114 | 0.587993 |
36f916821925c756a7ae78882584617a103f2111 | 4,526 | js | JavaScript | packages/ui-utils/src/react/deprecated.js | tgroshon/instructure-ui | d4923536949ece68e72e6ccf880dfcf42d49635d | [
"MIT"
] | null | null | null | packages/ui-utils/src/react/deprecated.js | tgroshon/instructure-ui | d4923536949ece68e72e6ccf880dfcf42d49635d | [
"MIT"
] | null | null | null | packages/ui-utils/src/react/deprecated.js | tgroshon/instructure-ui | d4923536949ece68e72e6ccf880dfcf42d49635d | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 - present Instructure, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import getDisplayName from './getDisplayName'
import warning from '../warning'
/**
* ---
* category: utilities/react
* ---
* Deprecate React component props. Warnings will display in the console when deprecated
* props are used.
*
* ```js
* class Example extends Component {
* static propTypes = {
* currentProp: PropTypes.func
* }
* }
* export default deprecated('3.0.0', {
* deprecatedProp: 'currentProp',
* nowNonExistentProp: true
* })(Example)
* ```
*
* @module deprecated
* @param {string} version
* @param {object} oldProps (if this argument is null or undefined, the entire component is deprecated)
* @param {string} message
* @return {function} React component with deprecated props behavior
*/
export default function deprecated (version, oldProps, message) {
return function (ComposedComponent) {
const displayName = getDisplayName(ComposedComponent)
class DeprecatedComponent extends ComposedComponent {
static displayName = displayName
componentDidMount () {
if (oldProps) {
warnDeprecatedProps(displayName, version, this.props, oldProps, message)
} else {
warnDeprecatedComponent(version, displayName, message)
}
if (super.componentDidMount) {
super.componentDidMount()
}
}
componentWillReceiveProps (nextProps, nextContext) {
if (oldProps) {
warnDeprecatedProps(displayName, version, nextProps, oldProps, message)
} else {
warnDeprecatedComponent(version, displayName, message)
}
if (super.componentWillReceiveProps) {
super.componentWillReceiveProps(nextProps, nextContext)
}
}
}
return DeprecatedComponent
}
}
/**
*
* Trigger a console warning if the specified prop variant is deprecated
*
* @param {function} propType - validates the prop type. Returns null if valid, error otherwise
* @param {array} deprecated - an array of the deprecated variant names
* @param {string} message - additional information to display with the warning
*/
export const deprecatePropValues = (propType, deprecated = [], message) => {
return (props, propName, componentName, ...rest) => {
const isDeprecatedValue = deprecated.includes(props[propName])
warning(
(!isDeprecatedValue),
`[${componentName}] The '${props[propName]}' value for the \`${propName}\` prop is deprecated. ${message || ''}`
)
return isDeprecatedValue ? null : propType(props, propName, componentName, ...rest)
}
}
function warnDeprecatedProps (componentName, version, props, oldProps, message) {
Object.keys(oldProps).forEach((oldProp) => {
if (typeof props[oldProp] !== 'undefined') {
const newProp = typeof oldProps[oldProp] === 'string'
? oldProps[oldProp]
: null
warning(
false,
'[%s] `%s` was deprecated in %s%s. %s',
componentName, oldProp, version, (newProp ? `. Use \`${newProp}\` instead` : ''), message || ''
)
}
})
}
export function warnDeprecatedComponent (version, componentName, message) {
warning(false, '[%s] was deprecated in version %s. %s', componentName, version, message || '')
}
export function changedPackageWarning (prevPackage, newPackage) {
return `It has been moved from @instructure/${prevPackage} to @instructure/${newPackage}.`
}
| 34.549618 | 118 | 0.691781 |
36f9d600be62d766f333f54460c9a7a20274db3e | 10,308 | js | JavaScript | src/features/about/PrivacyPage.js | rohansinha16/SoulSaga | d03943aeb21ab9181fe6ad2dda52163bcefec91f | [
"Apache-2.0"
] | 2 | 2019-01-29T21:46:27.000Z | 2019-03-17T22:59:56.000Z | src/features/about/PrivacyPage.js | rohansinha16/SoulSaga | d03943aeb21ab9181fe6ad2dda52163bcefec91f | [
"Apache-2.0"
] | 14 | 2018-10-03T06:47:42.000Z | 2019-03-14T22:15:43.000Z | src/features/about/PrivacyPage.js | rohansinha16/SoulSaga | d03943aeb21ab9181fe6ad2dda52163bcefec91f | [
"Apache-2.0"
] | 2 | 2019-03-08T21:40:54.000Z | 2019-03-09T18:59:07.000Z | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Typography from '@material-ui/core/Typography';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actions from './redux/actions';
export class PrivacyPage extends Component {
static propTypes = {
about: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
};
render() {
return (
<div className="about-privacy-page">
<Typography variant="display1" className="about-about-page__d2">
Privacy Policy
</Typography>
<Typography variant="title" className="about-about-page__t">
Posted: September 15, 2018
</Typography>
<Typography className="about-about-page__p">
SoulSaga ("Service") is a web application built by Riya Sinha. This
site's services are provided at no cost and are intended
for use as-is. This document explains
what data my Service collects from you, and how we use it.
</Typography>
<Typography variant="title" className="about-about-page__t">
What data we collect and Why
</Typography>
<Typography className="about-privacy-page__privacy-para">
<i className="about-privacy-page__privacy-item">
Consent
</i><br/>
When you create an account with our Service, we will
always record your initial data storage preference, along with
any future changes you make to this option. We require this
information, because it helps us determine whether to store
any more of your data or not.
</Typography>
<Typography className="about-privacy-page__privacy-para">
<i className="about-privacy-page__privacy-item">
Social Media Information
</i><br/>
When you sign in via Google, we use your name, email and
profile photo for your SoulSaga profile, and for recording
data consent.
</Typography>
<Typography className="about-privacy-page__privacy-para">
<i className="about-privacy-page__privacy-item">
Timeline Events
</i><br/>
If applicable, we collect data added via the Timeline feature
for the purposes of storing your data for you in a secure
and easily accessible manner across your devices.
</Typography>
<Typography className="about-privacy-page__privacy-para">
<i className="about-privacy-page__privacy-item">
Cookies
</i><br/>
See the "Cookies" section below.
</Typography>
<Typography variant="title" className="about-about-page__t">
How we use your data
</Typography>
<Typography className="about-about-page__p">
Your stored data is used by SoulSaga only for purposes of
debugging the application for a better user experience, or
in order to help develop better services for you.
</Typography>
<Typography variant="title" className="about-about-page__t">
With whom we share your data
</Typography>
<Typography className="about-about-page__p">
SoulSaga does not share your data. However, we do
use third-parties for authentication and data storage.
Please consult the "Third-parties" section for more
information.
</Typography>
<Typography variant="title" className="about-about-page__t">
Data Retention
</Typography>
<Typography className="about-about-page__p">
We reserve the right to store any data you ask us to, for as long
as your account is active. You reserve the right to clear
your data or delete your account at any time. This can
be done so from your Profile page.
</Typography>
<Typography variant="title" className="about-about-page__t">
Cookies
</Typography>
<Typography className="about-about-page__p">
Cookies are small text files stored via your web browser. Cookies
are commonly used as anonymous unique identifiers.
</Typography>
<Typography className="about-about-page__p">
This Service does not use these “cookies” explicitly. However,
the app may use third party code and libraries that use “cookies”
to collect information and improve their services. You have the
option to either accept or refuse these cookies and know when a
cookie is being sent to your device. If you choose to refuse our
cookies, you may not be able to use some portions of this Service.
</Typography>
<Typography variant="title" className="about-about-page__t">
Third-parties
</Typography>
<Typography className="about-about-page__p">
We use Google Analytics to track site usage, in order to
understand our user base and improve our services. Google Analytics
does store cookies for visitors who are not signed in. If you have
concerns about this, cookies can be disabled or deleted by your browser.
</Typography>
<Typography className="about-about-page__p">
We use Firebase Database (by Google) in order to store your data.
This provides secure storage and encryption for your data on servers
and in transmission. You may opt out of this by choosing to
store and be responsible for your own data.
</Typography>
<Typography className="about-about-page__p">
We use Firebase Authentication (by Google) in order to provide a seamless
sign-in experience and to obtain personal information for:
</Typography>
<ul>
<li><Typography>Your SoulSaga profile</Typography></li>
<li><Typography>Recording data consent</Typography></li>
<li><Typography>
Ensuring users are of age of consent in their respective
countries
</Typography></li>
</ul>
<Typography className="about-about-page__p">
Firebase Authentication does store cookies on your browser as well,
in order to allow sign-in state to persist across refreshes for a
better user experience.
</Typography>
<Typography className="about-about-page__p">
<a href="https://www.google.com/policies/privacy/partners/">
How Google collects and processes your data
</a>
</Typography>
<Typography className="about-about-page__p">
<a href="https://policies.google.com/technologies/cookies">
About Google and Cookies
</a>
</Typography>
<Typography variant="title" className="about-about-page__t">
Links to Other Sites
</Typography>
<Typography className="about-about-page__p">
This Service may contain links to other sites. If you click
on a third-party link, you will be directed to that site.
Note that these external sites are not operated by me.
Therefore, I strongly advise you to review the Privacy Policy
of these websites. I have no control over and assume no
responsibility for the content, privacy policies, or practices
of any third-party sites or services.
</Typography>
<Typography variant="title" className="about-about-page__t">
Children’s Privacy
</Typography>
<Typography className="about-about-page__p">
These Services do not address anyone under the age of consent
in their respective country ("a child", "children"). I
do not knowingly collect personally identifiable information
from children without their parent's consent. In the case that
I discover that a child has provided me with personal information,
I immediately delete their account and any of their information
from our servers. If you are a parent or guardian and you are
aware that your child has provided us with personal information,
please contact me so that I may perform any necessary
actions.
</Typography>
<Typography variant="title" className="about-about-page__t">
Changes to this Privacy Policy
</Typography>
<Typography className="about-about-page__p">
We may update this policy to ensure continuous compliance
with legal requirements. As our services change,
this policy will be updated to reflect those changes as well.
</Typography>
<Typography className="about-about-page__p">
If changes to policies regarding data you have already
consented to occur, prior notice will be given to you in order
to manage your data before new policies take effect.
</Typography>
<Typography variant="title" className="about-about-page__t">
Contact Information
</Typography>
<Typography className="about-about-page__p">
If you have questions, concerns or suggestions regarding
our privacy policy, please do not hesitate to reach out.
</Typography>
<Typography className="about-about-page__p">
Riya Sinha<br/>riya.sinha@soulsaga.org
</Typography>
<Typography className="about-privacy-page__footer">
This privacy policy page was created at
<a href="https://privacypolicytemplate.net">
privacypolicytemplate.net
</a>
and modified/generated by
<a href="https://app-privacy-policy-generator.firebaseapp.com/">
App Privacy Policy Generator
</a>
</Typography>
</div>
);
}
}
/* istanbul ignore next */
function mapStateToProps(state) {
return {
about: state.about,
};
}
/* istanbul ignore next */
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ ...actions }, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(PrivacyPage);
| 42.771784 | 83 | 0.645809 |
36fc368f6df6803dea3e4c66dba2f1d9a9179f06 | 582 | js | JavaScript | src/api/user.js | yuanyuexiang/genesis-front | df748d9ce58b97a9b195732cce58fd1fdd077d1f | [
"MIT"
] | null | null | null | src/api/user.js | yuanyuexiang/genesis-front | df748d9ce58b97a9b195732cce58fd1fdd077d1f | [
"MIT"
] | null | null | null | src/api/user.js | yuanyuexiang/genesis-front | df748d9ce58b97a9b195732cce58fd1fdd077d1f | [
"MIT"
] | 1 | 2018-03-11T06:08:06.000Z | 2018-03-11T06:08:06.000Z | import fetch from 'utils/fetch';
export function getUserCount() {
return fetch({
url: '/genesis/v1/user/count',
method: 'get',
});
}
export function listUser(offset,limit,query) {
const sortby="id"
const order="desc"
const params = {
offset,
limit,
query,
sortby,
order
};
return fetch({
url: '/genesis/v1/user',
method: 'get',
params
});
}
export function deleteUser(id) {
return fetch({
url: '/genesis/v1/user/' + id,
method: 'delete',
});
} | 18.1875 | 46 | 0.522337 |
36fe242bc23bba93cbb89494c385c71bf56d5b3f | 19,561 | js | JavaScript | src/views/EditUserProfile.js | icokeamy2/ResearchProjectFrontend | af8addf62452a90c1c57340ee6556f7e0c815f07 | [
"MIT"
] | null | null | null | src/views/EditUserProfile.js | icokeamy2/ResearchProjectFrontend | af8addf62452a90c1c57340ee6556f7e0c815f07 | [
"MIT"
] | null | null | null | src/views/EditUserProfile.js | icokeamy2/ResearchProjectFrontend | af8addf62452a90c1c57340ee6556f7e0c815f07 | [
"MIT"
] | null | null | null | import React from "react";
import TagsInput from "react-tagsinput";
import {
Alert,
Container,
Row,
Col,
Button,
Card,
CardBody,
CardFooter,
Nav,
NavItem,
NavLink,
Form,
FormInput,
FormSelect,
FormCheckbox,
FormTextarea,
InputGroup,
InputGroupAddon,
InputGroupText
} from "shards-react";
import FormSectionTitle from "../components/edit-user-profile/FormSectionTitle";
import ProfileBackgroundPhoto from "../components/edit-user-profile/ProfileBackgroundPhoto";
class EditUserProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
messageData:[],
tags: [
"User Experience",
"UI Design",
"React JS",
"HTML & CSS",
"JavaScript",
"Bootstrap 4"
]
};
this.handleTagsChange = this.handleTagsChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
handleTagsChange(tags) {
this.setState({ tags });
}
handleFormSubmit(e) {
e.preventDefault();
}
componentDidMount() {
let ws = new WebSocket("ws://localhost:8080/websocket");
if (typeof (WebSocket) == "undefined") {
console.log("遗憾:您的浏览器不支持WebSocket");
} else {
console.log("恭喜:您的浏览器支持WebSocket");
ws.onopen = (evt) => {
console.log("Connection open ...");
ws.send("管理平台");
ws.send("新增人数");
};
ws.onmessage = (evt) => {
console.log("Received Message: " + evt.data);
// alert(evt.data)
//this.state.messageData 为接受数据的变量
let messageData = this.state.messageData;
this.setState({
messageData: evt.data
})
// ws.close();
};
ws.onclose = (evt) => {
// alert(evt.data)
console.log("Connection closed.");
// ws.close();
};
ws.onerror = (evt) => {
console.log("error")
};
window.onbeforeunload = (event) => {
console.log("关闭WebSocket连接!");
ws.send("关闭页面");
event.close();
}
}
}
render() {
return (
<div>
<Container fluid className="px-0">
<Alert theme="success" className="mb-0">
Ole! Your profile has been successfully updated!{this.state.messageData}
</Alert>
</Container>
<Container fluid className="main-content-container px-4">
<Row>
<Col lg="8" className="mx-auto mt-4">
<Card small className="edit-user-details mb-4">
<ProfileBackgroundPhoto />
<CardBody className="p-0">
<div className="border-bottom clearfix d-flex">
<Nav tabs className="border-0 mt-auto mx-4 pt-2">
<NavItem>
<NavLink active>General</NavLink>
</NavItem>
<NavItem>
<NavLink>Projects</NavLink>
</NavItem>
<NavItem>
<NavLink>Collaboration</NavLink>
</NavItem>
</Nav>
</div>
{/* Form Section Title :: General */}
<Form className="py-4" onSubmit={this.handleFormSubmit}>
<FormSectionTitle
title="General"
description="Setup your general profile details."
/>
<Row form className="mx-4">
<Col lg="8">
<Row form>
{/* First Name */}
<Col md="6" className="form-group">
<label htmlFor="firstName">First Name</label>
<FormInput
id="firstName"
value="Sierra"
onChange={() => {}}
/>
</Col>
{/* Last Name */}
<Col md="6" className="form-group">
<label htmlFor="lastName">Last Name</label>
<FormInput
type="text"
id="lastName"
value="Brooks"
onChange={() => {}}
/>
</Col>
{/* Location */}
<Col md="6" className="form-group">
<label htmlFor="userLocation">Location</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="material-icons"></i>
</InputGroupText>
</InputGroupAddon>
<FormInput
id="userLocation"
value="Remote"
onChange={() => {}}
/>
</InputGroup>
</Col>
{/* Phone Number */}
<Col md="6" className="form-group">
<label htmlFor="phoneNumber">Phone Number</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="material-icons"></i>
</InputGroupText>
</InputGroupAddon>
<FormInput
id="phoneNumber"
value="+40 1234 567 890"
onChange={() => {}}
/>
</InputGroup>
</Col>
{/* Email Address */}
<Col md="6" className="form-group">
<label htmlFor="emailAddress">Email</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="material-icons"></i>
</InputGroupText>
</InputGroupAddon>
<FormInput
id="emailAddress"
onChange={() => {}}
/>
</InputGroup>
</Col>
<Col md="6" className="form-group">
<label htmlFor="displayEmail">
Display Email Publicly
</label>
<FormSelect>
<option>Select an Option</option>
<option>Yes, display my email.</option>
<option>No, do not display my email.</option>
</FormSelect>
</Col>
</Row>
</Col>
{/* User Profile Picture */}
<Col lg="4">
<label
htmlFor="userProfilePicture"
className="text-center w-100 mb-4"
>
Profile Picture
</label>
<div className="edit-user-details__avatar m-auto">
<img
src={require("../images/avatars/0.jpg")}
alt="User Avatar"
/>
<label className="edit-user-details__avatar__change">
<i className="material-icons mr-1"></i>
<FormInput
id="userProfilePicture"
className="d-none"
/>
</label>
</div>
<Button
size="sm"
theme="white"
className="d-table mx-auto mt-4"
>
<i className="material-icons"></i> Upload
Image
</Button>
</Col>
</Row>
<Row form className="mx-4">
{/* User Bio */}
<Col md="6" className="form-group">
<label htmlFor="userBio">Bio</label>
<FormTextarea
style={{ minHeight: "87px" }}
id="userBio"
value="I'm a design focused engineer."
onChange={() => {}}
/>
</Col>
{/* User Tags */}
<Col md="6" className="form-group">
<label htmlFor="userTags">Tags</label>
<TagsInput
value={this.state.tags}
onChange={this.handleTagsChange}
/>
</Col>
</Row>
<hr />
{/* Form Section Title :: Social Profiles */}
<FormSectionTitle
title="Social"
description="Setup your social profiles info."
/>
<Row form className="mx-4">
{/* Facebook */}
<Col md="4" className="form-group">
<label htmlFor="socialFacebook">Facebook</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="fab fa-facebook-f" />
</InputGroupText>
</InputGroupAddon>
<FormInput id="socialFacebook" onChange={() => {}} />
</InputGroup>
</Col>
{/* Twitter */}
<Col md="4" className="form-group">
<label htmlFor="socialTwitter">Twitter</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="fab fa-twitter" />
</InputGroupText>
</InputGroupAddon>
<FormInput id="socialTwitter" onChange={() => {}} />
</InputGroup>
</Col>
{/* GitHub */}
<Col md="4" className="form-group">
<label htmlFor="socialGitHub">GitHub</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="fab fa-github" />
</InputGroupText>
</InputGroupAddon>
<FormInput id="socialGitHub" onChange={() => {}} />
</InputGroup>
</Col>
{/* Slack */}
<Col md="4" className="form-group">
<label htmlFor="socialSlack">Slack</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="fab fa-slack" />
</InputGroupText>
</InputGroupAddon>
<FormInput id="socialSlack" onChange={() => {}} />
</InputGroup>
</Col>
{/* Dribbble */}
<Col md="4" className="form-group">
<label htmlFor="socialDribbble">Dribbble</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="fab fa-dribbble" />
</InputGroupText>
</InputGroupAddon>
<FormInput id="socialDribbble" onChange={() => {}} />
</InputGroup>
</Col>
{/* Google Plus */}
<Col md="4" className="form-group">
<label htmlFor="socialGooglePlus">Google Plus</label>
<InputGroup seamless>
<InputGroupAddon type="prepend">
<InputGroupText>
<i className="fab fa-google-plus-g" />
</InputGroupText>
</InputGroupAddon>
<FormInput
id="socialGooglePlus"
onChange={() => {}}
/>
</InputGroup>
</Col>
</Row>
<hr />
{/* Form Section Title :: Notifications */}
<FormSectionTitle
title="Notifications"
description="Setup which notifications would you like to receive."
/>
{/* Notifications :: Conversations */}
<Row form className="mx-4">
<Col
tag="label"
htmlFor="conversationsEmailsToggle"
className="col-form-label"
>
Conversations
<small className="text-muted form-text">
Sends notification emails with updates for the
conversations you are participating in or if someone
mentions you.
</small>
</Col>
<Col className="d-flex">
<FormCheckbox
toggle
checked
className="ml-auto my-auto"
id="conversationsEmailsToggle"
onChange={() => {}}
/>
</Col>
</Row>
{/* Notifications :: New Projects */}
<Row form className="mx-4">
<Col
tag="label"
htmlFor="newProjectsEmailsToggle"
className="col-form-label"
>
New Projects
<small className="text-muted form-text">
Sends notification emails when you are invited to a
new project.
</small>
</Col>
<Col className="d-flex">
<FormCheckbox
toggle
className="ml-auto my-auto"
id="newProjectsEmailsToggle"
onChange={() => {}}
/>
</Col>
</Row>
{/* Notifications :: Vulnerabilities */}
<Row form className="mx-4">
<Col
tag="label"
htmlFor="conversationsEmailsToggle"
className="col-form-label"
>
Vulnerability Alerts
<small className="text-muted form-text">
Sends notification emails when everything goes down
and there's no hope left whatsoever.
</small>
</Col>
<Col className="d-flex">
<FormCheckbox
toggle
checked
className="ml-auto my-auto"
id="conversationsEmailsToggle"
onChange={() => {}}
/>
</Col>
</Row>
<hr />
{/* Change Password */}
<Row form className="mx-4">
<Col className="mb-3">
<h6 className="form-text m-0">Change Password</h6>
<p className="form-text text-muted m-0">
Change your current password.
</p>
</Col>
</Row>
<Row form className="mx-4">
{/* Change Password :: Old Password */}
<Col md="4" className="form-group">
<label htmlFor="oldPassword">Old Password</label>
<FormInput
id="oldPassword"
placeholder="Old Password"
onChange={() => {}}
/>
</Col>
{/* Change Password :: New Password */}
<Col md="4" className="form-group">
<label htmlFor="newPassword">New Password</label>
<FormInput
id="newPassword"
placeholder="New Password"
onChange={() => {}}
/>
</Col>
{/* Change Password :: Repeat New Password */}
<Col md="4" className="form-group">
<label htmlFor="repeatNewPassword">
Repeat New Password
</label>
<FormInput
id="repeatNewPassword"
placeholder="Old Password"
onChange={() => {}}
/>
</Col>
</Row>
</Form>
</CardBody>
<CardFooter className="border-top">
<Button
size="sm"
theme="accent"
className="ml-auto d-table mr-3"
>
Save Changes
</Button>
</CardFooter>
</Card>
</Col>
</Row>
</Container>
</div>
);
}
}
export default EditUserProfile;
| 38.430255 | 92 | 0.360411 |
3c01b05ecb259d5df1607aad23f032c3fd811c1f | 1,503 | js | JavaScript | resources/assets/js/main.js | slayerfat/gmd.com.ve | 93ef34026b884029746c00be68ed0d4aea5d6655 | [
"MIT"
] | null | null | null | resources/assets/js/main.js | slayerfat/gmd.com.ve | 93ef34026b884029746c00be68ed0d4aea5d6655 | [
"MIT"
] | null | null | null | resources/assets/js/main.js | slayerfat/gmd.com.ve | 93ef34026b884029746c00be68ed0d4aea5d6655 | [
"MIT"
] | null | null | null | 'use strict';
require('./bootstrap');
jQuery(function ($) {
//#main-slider
$('#main-slider').carousel({
interval: 8000
});
// accordion
$('.accordion-toggle').on('click', function () {
$(this).closest('.panel-group').children().each(function () {
$(this).find('>.panel-heading').removeClass('active');
});
$(this).closest('.panel-heading').toggleClass('active');
});
// Contact form
var form = $('#main-contact-form');
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
method: 'post',
data: form.serializeArray(),
beforeSend: function () {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function (data) {
form_status.html('<p class="text-success">' + data.message + '</p>')
.delay(3000)
.fadeOut();
}).error(function (data) {
form_status.html('<p class="text-danger">' + data.responseText + '</p>')
.delay(3000)
.fadeOut();
});
});
//goto top
$('.gototop').click(function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $("body").offset().top
}, 500);
});
}); | 30.06 | 124 | 0.491018 |
3c04c5c502ad17fa077441a80e56dc0f94956619 | 6,152 | js | JavaScript | src/components/Admin/UpdateProgram/UpdateProgram.js | zthaver/Enrollment-System | 4f76b88a188222127f68d45e8c7abd2a7de13838 | [
"MIT"
] | 1 | 2021-06-13T23:03:31.000Z | 2021-06-13T23:03:31.000Z | src/components/Admin/UpdateProgram/UpdateProgram.js | zthaver/Enrollment-System | 4f76b88a188222127f68d45e8c7abd2a7de13838 | [
"MIT"
] | 52 | 2021-05-23T22:54:05.000Z | 2021-08-15T22:29:47.000Z | src/components/Admin/UpdateProgram/UpdateProgram.js | zthaver/Enrollment-System | 4f76b88a188222127f68d45e8c7abd2a7de13838 | [
"MIT"
] | 3 | 2021-06-03T21:56:49.000Z | 2021-06-17T03:37:25.000Z | import { Formik } from "formik";
import { Paper, TextField } from '@material-ui/core';
import Grid from '@material-ui/core/Grid';
import { firestore } from "../../../firebase";
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import * as Yup from "yup";
import AdminNav from "../AdminNavbar/AdminNav";
function UpdateProgram() {
let { id } = useParams();
const paperStyle = { padding: 20, height: '70vh', width: 280, margin: "20px auto" }
let [error, setError] = useState("");
let [programName, setProgramName] = useState("");
let [programCode, setProgramCode] = useState("");
let [departmentDaata, setDepartmentData] = useState([]);
let [programDescription, setProgramDescription] = useState("");
let [departmentName, setDepartmentName] = useState("");
let empty = true;
console.log(id)
const ProgramSchema = Yup.object().shape({
programDescription: Yup.string()
.required('Required')
.min(20, 'Too Short!')
.max(50, 'Too Long!'),
programCode: Yup.string()
.required('Required')
.min(6, 'Too Short!')
//to check if the course code is unique
.test('checkProgramCodeUnique', 'This program is already registered', async value => {
let isProgramCodeUnique = false;
if (!value) {
value = " "
}
console.log(value)
await firestore.collection("programs").where("programCode", "==", value).get().then((val) => {
isProgramCodeUnique = val.empty;
})
return isProgramCodeUnique;
}),
});
useEffect(() => {
firestore.collection("department").get().then((departments) => {
setDepartmentData(departments.docs.map((department => department.data())));
})
firestore.collection("programs").doc(id).get().then((program) => {
var programData = program.data();
setProgramName(programData.programName)
setProgramCode(programData.programCode)
setProgramDescription(programData.programDescription)
setDepartmentName(programData.departmentName)
console.log("tamerere" + programCode);
})
}, [])
return (
<article>
<AdminNav />
<Grid>
<Paper elavation="20" style={paperStyle}>
<Grid >
<h2>Update Program</h2>
</Grid>
{programDescription!=""&&<Formik validationSchema={ProgramSchema} initialValues={{ programName: programName, programCode: programCode, programDescription: programDescription,departmentName:departmentName}} onSubmit={async (values, props) => {
console.log(values)
firestore.collection("programs").doc(id).update({
"programName": values.programName,
"programCode": values.programCode,
"programDescription":values.programDescription,
"departmentName":values.departmentName
}).then((val) => {
alert("success in updating program")
}).catch((err) => {
console.log("err is" + err);
})
}}
validateOnChange={false} validateOnBlur={false}>
{props => (
<form noValidate onSubmit={props.handleSubmit}>
<label htmlFor="programName">Program Name</label>
<input type="text"
name="programName"
onChange={props.handleChange}
defaultValue={programName}
requir>
</input>
<br></br>
<label htmlFor="programCode">Program Code</label>
<TextField type="text"
multiline={true}
name="programCode"
onChange={props.handleChange}
defaultValue={programCode}
helperText={props.errors.programCode}
error={!!props.errors.programCode} />
<label> Department Name</label>
<br></br>
<br></br>
<select onChange={(value) => { props.values.departmentName = value.target.value; }}>
{departmentDaata.map((department) =>
<option key={department.id}> {department.departmentName} </option>)};
</select>
<br></br><br></br>
<label> Program Description</label>
<TextField type="text"
multiline={true}
name="programDescription"
onChange={props.handleChange}
defaultValue={programDescription}
helperText={props.errors.programDescription}
error={!!props.errors.programDescription}
/>
<br></br><br></br>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
)}
</Formik>}
</Paper>
</Grid>
</article>
)
}
export default UpdateProgram; | 45.910448 | 262 | 0.457737 |
3c065f0ead6580731ccd296fe72e74a88af91e39 | 2,251 | js | JavaScript | src/runner.spec.js | davidspinat/tropic | 4aa0c74e3124d0e1615353dec65bb615cecceb39 | [
"Apache-2.0"
] | 27 | 2017-03-26T18:01:26.000Z | 2018-02-12T18:49:27.000Z | src/runner.spec.js | davidspinat/tropic | 4aa0c74e3124d0e1615353dec65bb615cecceb39 | [
"Apache-2.0"
] | 10 | 2018-12-18T09:43:55.000Z | 2021-05-11T05:43:50.000Z | src/runner.spec.js | ddneat/tropic | 4aa0c74e3124d0e1615353dec65bb615cecceb39 | [
"Apache-2.0"
] | 1 | 2020-02-28T22:33:05.000Z | 2020-02-28T22:33:05.000Z | const { miniTest, miniTestReport, createSpy } = require('../util/mini-test')()
const assert = require('assert')
const { createRunner } = require('./runner')
const options = { timeout: 200 }
miniTest('createRunner returns function executeTestsWithState', () => {
const noop = () => {}
const executeTestsWithState = createRunner(noop, noop, noop, options)
assert.strictEqual(Object.prototype.toString.call(executeTestsWithState), '[object Function]')
})
miniTest('executeTestsWithState calls the tests', () => {
const logPass = () => {}
const logFail = () => {}
const logReport = () => {}
const executeTestsWithState = createRunner(logPass, logFail, logReport, options)
const createTestSpy = () => {
return {
title: 'test spy',
callback: createSpy()
}
}
const state = {
test: [createTestSpy(), createTestSpy()],
only: [],
skip: []
}
executeTestsWithState(state)
assert.strictEqual(state.test[0].callback.args.length, 1)
assert.strictEqual(state.test[1].callback.args.length, 1)
})
miniTest('executeTestsWithState calls the only tests', () => {
const logPass = () => {}
const logFail = () => {}
const logReport = () => {}
const executeTestsWithState = createRunner(logPass, logFail, logReport, options)
const createTestSpy = () => {
return {
title: 'test spy',
callback: createSpy()
}
}
const state = {
test: [],
only: [createTestSpy(), createTestSpy()],
skip: []
}
executeTestsWithState(state)
assert.strictEqual(state.only[0].callback.args.length, 1)
assert.strictEqual(state.only[1].callback.args.length, 1)
})
miniTest('executeTestsWithState does not call the skip tests', () => {
const logPass = () => {}
const logFail = () => {}
const logReport = () => {}
const executeTestsWithState = createRunner(logPass, logFail, logReport, options)
const createTestSpy = () => {
return {
title: 'test spy',
callback: createSpy()
}
}
const state = {
test: [],
only: [],
skip: [createTestSpy(), createTestSpy()]
}
executeTestsWithState(state)
assert.strictEqual(state.skip[0].callback.args.length, 0)
assert.strictEqual(state.skip[1].callback.args.length, 0)
})
miniTestReport()
| 26.174419 | 96 | 0.649045 |
3c07de72beb612aead7ebdf3bf4fb2fd8266fc86 | 211 | js | JavaScript | packages/generator-single-spa/src/svelte/templates/src/main.js | neiloler/create-single-spa | c24c65463a689981f481a3049882ab1a15ed6ddf | [
"MIT"
] | 80 | 2020-03-04T07:11:52.000Z | 2022-03-29T17:01:32.000Z | packages/generator-single-spa/src/svelte/templates/src/main.js | neiloler/create-single-spa | c24c65463a689981f481a3049882ab1a15ed6ddf | [
"MIT"
] | 231 | 2020-02-13T23:30:24.000Z | 2022-03-14T11:08:08.000Z | packages/generator-single-spa/src/svelte/templates/src/main.js | neiloler/create-single-spa | c24c65463a689981f481a3049882ab1a15ed6ddf | [
"MIT"
] | 49 | 2020-02-10T23:33:42.000Z | 2022-03-14T12:25:21.000Z | import singleSpaSvelte from "single-spa-svelte";
import App from "./App.svelte";
const svelteLifecycles = singleSpaSvelte({
component: App,
});
export const { bootstrap, mount, unmount } = svelteLifecycles;
| 23.444444 | 62 | 0.748815 |
3c0894a875a637192f572f98febb5e642b9d1ee3 | 191 | js | JavaScript | docs/search/keywords/006100750074.js | AutoHotkey-V2/log4ahk | 69ef759b34307b86d29c897e32135ba9c81055f0 | [
"WTFPL"
] | 4 | 2018-11-30T04:33:33.000Z | 2021-02-23T14:08:25.000Z | docs/search/keywords/006100750074.js | AutoHotkey-V2/log4ahk | 69ef759b34307b86d29c897e32135ba9c81055f0 | [
"WTFPL"
] | 18 | 2018-11-05T12:51:20.000Z | 2020-12-03T08:00:22.000Z | docs/search/keywords/006100750074.js | AutoHotkey-V2/log4ahk | 69ef759b34307b86d29c897e32135ba9c81055f0 | [
"WTFPL"
] | 1 | 2018-11-02T13:44:41.000Z | 2018-11-02T13:44:41.000Z | NDSearch.OnPrefixDataLoaded("aut",["Section"],[["AutoHotkey",,[[,"log4ahk - Logging for AutoHotkey",,"log4ahk-logging for autohotkey",0,"File:log4ahk.ahk:log4ahk-Logging_for_AutoHotkey"]]]]); | 191 | 191 | 0.753927 |
3c098e6a32ba52694543d8d8a76761ff86bf44f5 | 760 | js | JavaScript | src/components/auto-dealer/auto-dealer-layout.js | gelcreative/choose-your-promo | be578245047c3f5606cad6cf4cf6d337e8c4e3f8 | [
"MIT"
] | null | null | null | src/components/auto-dealer/auto-dealer-layout.js | gelcreative/choose-your-promo | be578245047c3f5606cad6cf4cf6d337e8c4e3f8 | [
"MIT"
] | 7 | 2021-03-09T02:14:28.000Z | 2022-02-26T10:16:48.000Z | src/components/auto-dealer/auto-dealer-layout.js | gelcreative/choose-your-promo | be578245047c3f5606cad6cf4cf6d337e8c4e3f8 | [
"MIT"
] | null | null | null | /**
* Layout component that queries for data
* with Gatsby's StaticQuery component
*
* See: https://www.gatsbyjs.org/docs/static-query/
*/
import React from 'react'
import PropTypes from 'prop-types'
import { ThemeProvider } from 'styled-components'
import theme from '../theme'
import GlobalStyle from '../globalstyle'
import Header from './auto-dealer-header'
import Footer from './auto-dealer-footer'
const Layout = ({ children, data }) => {
return (
<ThemeProvider theme={theme}>
<>
<Header data={data} />
<GlobalStyle />
<main role="main">{children}</main>
<Footer data={data} />
</>
</ThemeProvider>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
| 21.714286 | 51 | 0.653947 |
3c099ae9512e919a45e988f4487090c14d42261c | 8,337 | js | JavaScript | src/imvujstest/assert.domtest.js | youngseppa23/imvujs | 344c399c9cc8a159f323591db7cfecdbab089fe2 | [
"MIT"
] | 8 | 2016-08-11T16:27:15.000Z | 2021-08-10T06:20:09.000Z | src/imvujstest/assert.domtest.js | youngseppa23/imvujs | 344c399c9cc8a159f323591db7cfecdbab089fe2 | [
"MIT"
] | 5 | 2016-09-14T22:48:31.000Z | 2017-03-16T18:42:17.000Z | src/imvujstest/assert.domtest.js | youngseppa23/imvujs | 344c399c9cc8a159f323591db7cfecdbab089fe2 | [
"MIT"
] | 6 | 2015-07-08T20:31:37.000Z | 2022-03-18T01:33:27.000Z | module({
}, function(imports) {
fixture('dom tests', function() {
this.tearDown(function() {
$('.test-sandbox').html('');
});
test('present', function() {
$('.test-sandbox').append('<div class="widget"></div>');
assert.dom.present('.test-sandbox .widget');
});
test('notPresent', function() {
assert.dom.notPresent('.test-sandbox .widget');
});
test('hasTag', function() {
$('.test-sandbox').append('<p class="para"></p>');
assert.dom.hasTag('p', '.test-sandbox .para');
});
test('hasClass', function() {
$('.test-sandbox').append('<div class="widget hidden"></div>');
assert.dom.hasClass('hidden', '.test-sandbox .widget');
});
test('notHasClass', function() {
$('.test-sandbox').append('<div class="widget"></div>');
assert.dom.notHasClass('hidden', '.test-sandbox .widget');
});
test('hasAttribute', function() {
$('.test-sandbox').append('<img data-src="test">');
assert.dom.hasAttribute('data-src', '.test-sandbox img');
});
test('notHasAttribute', function() {
$('.test-sandbox').append('<img data-src="test">');
assert.dom.notHasAttribute('src', '.test-sandbox img');
});
test('attr', function() {
$('.test-sandbox').append('<img data-src="test">');
assert.dom.attr('test', 'data-src', '.test-sandbox img');
});
test('prop', function() {
$('.test-sandbox').append('<input disabled>');
assert.dom.prop(true, 'disabled', '.test-sandbox input');
assert.dom.prop(undefined, 'idonotexist', '.test-sandbox input');
});
test('attributeValues', function() {
$('.test-sandbox').append('<input placeholder="test" value="foo" disabled>');
assert.dom.attributeValues({
placeholder: 'test',
disabled: 'disabled',
}, '.test-sandbox input');
});
test('text', function() {
assert.dom.text('', '.test-sandbox');
$('.test-sandbox').text('hello');
assert.dom.text('hello', '.test-sandbox');
});
test('value', function() {
$('.test-sandbox').append('<input value="foo">');
assert.dom.value('foo', '.test-sandbox input');
$('.test-sandbox input').val('bar');
assert.dom.value('bar', '.test-sandbox input');
});
test('count', function() {
$('.test-sandbox').append('<p></p><p></p><img>');
assert.dom.count(2, '.test-sandbox p');
assert.dom.count(1, '.test-sandbox img');
assert.dom.count(0, '.test-sandbox form');
});
test('visible', function() {
$('.test-sandbox').append('<div class="widget">x</div>');
assert.dom.visible('.test-sandbox .widget');
});
test('still considered visible if zero opacity', function() {
$('.test-sandbox').append('<div class="widget" style="opacity:0"></div>');
assert.dom.visible('.test-sandbox .widget');
});
test('still considered visible if no size', function() {
$('.test-sandbox').append('<div class="widget" style="width:0;height:0;"></div>');
assert.dom.visible('.test-sandbox .widget');
});
test('still considered visible if visibility hidden', function() {
$('.test-sandbox').append('<div class="widget" style="visibility:hidden"></div>');
assert.dom.visible('.test-sandbox .widget');
});
test('notVisible if display none', function() {
$('.test-sandbox').append('<div class="widget" style="display:none"></div>');
assert.dom.notVisible('.test-sandbox .widget');
});
test('visible includes styling summary', function() {
$('.test-sandbox').append('<div class="widget" style="width:0; height:1px; opacity:1; display:none"/>');
var e = assert.throws(Error, function() {
assert.dom.visible('.test-sandbox .widget');
});
assert.equal(
"Selector '.test-sandbox .widget' expected to be visible. " +
"Note: width: 0px; height: 1px; display: none; opacity: 1;",
e.message
);
});
test('notVisible includes styling summary', function() {
$('.test-sandbox').append('<div class="widget" style="width:0; height:1px; opacity:0; display:inline"/>');
var e = assert.throws(Error, function() {
assert.dom.notVisible('.test-sandbox .widget');
});
// 0px height because inline elements cannot be sized.
assert.equal(
"Selector '.test-sandbox .widget' expected to be NOT visible. " +
"Note: width: 0px; height: 0px; display: inline; opacity: 0;",
e.message
);
});
test('disabled', function() {
$('.test-sandbox').append('<input class="a" disabled><input class="b">');
assert.dom.disabled('.test-sandbox .a');
$('.test-sandbox .b').prop('disabled', true);
assert.dom.disabled('.test-sandbox .b');
});
test('enabled', function() {
$('.test-sandbox').append('<input class="a"><input class="b" disabled>');
assert.dom.enabled('.test-sandbox .a');
$('.test-sandbox .b').prop('disabled', false);
assert.dom.enabled('.test-sandbox .b');
});
test('focused', function() {
$('.test-sandbox').append('<input class="a"><input class="b">');
$('.test-sandbox .a').focus();
assert.dom.focused('.test-sandbox .a');
$('.test-sandbox .b').focus();
assert.dom.focused('.test-sandbox .b');
});
test('notFocused', function() {
$('.test-sandbox').append('<input class="a"><input class="b">');
$('.test-sandbox .a').focus();
assert.dom.notFocused('.test-sandbox .b');
$('.test-sandbox .b').focus();
assert.dom.notFocused('.test-sandbox .a');
});
test('html', function() {
var text = document.createTextNode('hi');
var div = document.createElement('div');
div.textContent = 'bye';
$('.test-sandbox').append(text);
$('.test-sandbox').append(div);
assert.dom.html('hi<div>bye</div>', '.test-sandbox');
});
test('css', function() {
$('.test-sandbox').append('<div style="width:1.5px;opacity:1.0;color:red;"></div>');
assert.dom.css('1.5px', 'width', '.test-sandbox div');
assert.dom.css('1', 'opacity', '.test-sandbox div');
assert.dom.css('rgb(255, 0, 0)', 'color', '.test-sandbox div');
});
test('cssPx', function() {
$('.test-sandbox').append('<div class="a" style="width:1px;"></div><div class="b" style="width:1.5px"></div>');
assert.dom.cssPx(1, 'width', '.test-sandbox .a');
assert.dom.cssPx(1.5, 'width', '.test-sandbox .b');
});
test('cssPxNear', function() {
$('.test-sandbox').append('<div class="a" style="width:1.7px;">');
$('.test-sandbox').append('</div><div class="b" style="width:314px"></div>');
assert.dom.cssPxNear(1.5, 'width', '.test-sandbox .a', 0.2);
assert.dom.cssPxNear(300, 'width', '.test-sandbox .b', 15);
});
test('empty', function() {
$('.test-sandbox').append('<p></p>');
assert.dom.empty('.test-sandbox p');
});
test('notEmpty', function() {
$('.test-sandbox').append('<p>x</p>');
assert.dom.notEmpty('.test-sandbox p');
});
test('pseudoElementCss', function() {
$('.test-sandbox').append('<div class="widget"></div><style>.test-sandbox .widget::after { content: \'hi\'; }</style>');
assert.dom.pseudoElementCss('hi', 'content', '.test-sandbox .widget', 'after');
});
});
});
| 40.470874 | 132 | 0.505218 |
3c0b4676b4761e32c9cce7971add93d4e9484847 | 3,677 | js | JavaScript | index.js | BrandedNomad/house-tour-VR | 5784d635b9911d2142ef0be97333c5fccf214efc | [
"Unlicense"
] | null | null | null | index.js | BrandedNomad/house-tour-VR | 5784d635b9911d2142ef0be97333c5fccf214efc | [
"Unlicense"
] | null | null | null | index.js | BrandedNomad/house-tour-VR | 5784d635b9911d2142ef0be97333c5fccf214efc | [
"Unlicense"
] | null | null | null | import React from 'react';
import {
asset,
AppRegistry,
StyleSheet,
Text,
View,
VrButton,
NativeModules,
Image,
} from 'react-360';
import {connect, changeRoom} from './store';
const {AudioModule} = NativeModules;
class AudioPanel extends React.Component {
playAmbientMusic(){
AudioModule.playEnvironmental({
source: asset('audio/ambient.wav'),
volume: 0.3,
});
}
stopAmbientMusic(){
AudioModule.stopEnvironmental();
}
render(){
return(
<View style={styles.audioPanel}>
<VrButton onClick={()=>{this.playAmbientMusic()}}>
<Image style={{height:50,width:50}} source={asset('audioOn.png')}/>
</VrButton>
<VrButton onClick={()=>{this.stopAmbientMusic()}}>
<Image style={{height:50,width:50}} source={asset('audioOff.png')}/>
</VrButton>
</View>
)
}
}
class HouseInfoPanel extends React.Component {
render() {
return (
<View>
<View style={styles.infoPanel}>
<Text style={styles.header}>Room Info</Text>
<Text style={{
fontSize: 20,
textAlign:'left',
fontWeight:'bold',
}}>{this.props.info}</Text>
</View>
</View>
);
}
};
class Button extends React.Component {
state={
hover: false
}
clickHandler(roomSelection){
changeRoom(roomSelection)
}
render(){
return(
<VrButton
style={this.state.hover ? styles.hover: styles.button}
onEnter={()=>this.setState({hover:true})}
onExit={()=>this.setState({hover:false})}
onClick={()=>{
this.clickHandler(this.props.room)
}}
>
<Text style={{textAlign:'center'}}>{this.props.room.split('_').join(' ')}</Text>
</VrButton>
)
}
}
class ButtonInfoPanel extends React.Component {
createRoomButtons(adjacentRooms){
let rooms = adjacentRooms;
let buttons = [];
rooms.map((room) =>{
buttons.push(
<Button key={`${room}-button`} room={room}/>
)
})
return buttons;
}
render() {
return (
<View>
<View style={styles.buttonPanel}>
<Text style={styles.header}>Room Selection</Text>
{this.createRoomButtons(this.props.adjacentRooms)}
<AudioPanel/>
</View>
</View>
);
}
};
const ConnectedButtonInfoPanel = connect(ButtonInfoPanel);
const ConnectedHouseInfoPanel = connect(HouseInfoPanel);
const styles = StyleSheet.create({
infoPanel: {
width: 400,
height: 400,
opacity: 0.8,
backgroundColor: 'rgb(255, 200, 50)',
borderColor:'rgb(255,255,255)',
borderWidth:5,
borderRadius:20,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
buttonPanel:{
width:400,
height:400,
opacity:0.8,
backgroundColor: 'rgb(255, 200, 50)',
borderColor:'rgb(255,255,255)',
borderWidth:5,
borderRadius:20,
flexDirection:'column',
justifyContent:'center',
alignItems:'center'
},
button:{
width: 200,
backgroundColor:'rgb(0,0,0)',
borderColor:'rgb(255,255,255)',
borderWidth:5,
},
hover:{
width:200,
backgroundColor:'rgb(0,45,72)',
borderColor:'rgb(255,255,255)',
borderWidth: 5,
},
header: {
fontSize: 40,
fontWeight: 'bold',
textAlign:'center'
},
audioPanel:{
flexDirection:'row'
}
});
AppRegistry.registerComponent('ConnectedButtonInfoPanel', () => ConnectedButtonInfoPanel);
AppRegistry.registerComponent('ConnectedHouseInfoPanel', () => ConnectedHouseInfoPanel);
| 20.892045 | 90 | 0.586348 |
3c0c29805f7ddd79ce1ea35a679556e878eb19e0 | 952 | js | JavaScript | gulpfile.js | charleslxh/Deployer | 27ca6f076bbeaf0f86087760f16dc7316de44f48 | [
"MIT"
] | 14 | 2017-12-03T15:25:14.000Z | 2021-03-24T17:24:05.000Z | gulpfile.js | charleslxh/Deployer | 27ca6f076bbeaf0f86087760f16dc7316de44f48 | [
"MIT"
] | null | null | null | gulpfile.js | charleslxh/Deployer | 27ca6f076bbeaf0f86087760f16dc7316de44f48 | [
"MIT"
] | 3 | 2020-09-11T02:28:50.000Z | 2021-04-22T11:47:55.000Z | var gulp = require('gulp');
const del = require('del');
const gutil = require('gulp-util');
const babel = require('gulp-babel');
const runSequence = require('run-sequence');
const errorHandler = require('gulp-error-handle');
runSequence.options.ignoreUndefinedTasks = true;
const paths = {
_clean: {
src: ['lib/**/*']
},
_babel: {
src: 'src/**/*.js',
dest: 'lib/'
}
}
gulp.task('clean', () => del(['dist/**/*', 'lib/**/*']));
gulp.task('babel', () => {
return gulp.src('src/**/*.js')
.pipe(errorHandler())
.pipe(babel({
presets: ['env'],
plugins: ['transform-runtime']
}))
.pipe(gulp.dest('./lib/'))
});
gulp.task('build', (callback) => runSequence('clean', 'babel', callback));
gulp.task('default', ['build'], () => {
gulp.watch('src/**/*.js', ['build']).on('change', (event) => {
gutil.log(gutil.colors.magenta('File ' + event.path + ' was ' + event.type + ', try rebuild'));
});
});
| 23.219512 | 99 | 0.561975 |
3c0c4ed013ecf1d6ad04634f55379ca4d61ea80a | 2,783 | js | JavaScript | test/worker.js | allevo/GearmanLib | e5e9d64302f85fb6c03644c957140ddf6a721192 | [
"MIT"
] | 2 | 2016-09-05T09:59:02.000Z | 2018-01-11T07:14:01.000Z | test/worker.js | allevo/GearmanLib | e5e9d64302f85fb6c03644c957140ddf6a721192 | [
"MIT"
] | null | null | null | test/worker.js | allevo/GearmanLib | e5e9d64302f85fb6c03644c957140ddf6a721192 | [
"MIT"
] | 1 | 2021-05-17T15:22:33.000Z | 2021-05-17T15:22:33.000Z | /* eslint-env mocha */
'use strict'
var assert = require('assert')
var EventEmitter = require('events').EventEmitter
var Worker = require('../Worker')
var Job = require('../Job')
describe('worker', function () {
it('canDo', function () {
var isCalledSync = false
var server = new EventEmitter()
server.canDo = function (fnName) {
assert.equal('pippo', fnName)
isCalledSync = true
}
var w = new Worker(server)
var cbk = function () { }
w.canDo('pippo', cbk)
assert.ok(isCalledSync)
assert.deepEqual(cbk, w.functions.pippo)
})
it('grab', function () {
var isCalledSync = false
var server = new EventEmitter()
server.grab = function () {
isCalledSync = true
}
var w = new Worker(server)
w.grab()
assert.ok(isCalledSync)
})
it('setClientId', function () {
var isCalledSync = false
var server = new EventEmitter()
server.setClientId = function () {
isCalledSync = true
}
var w = new Worker(server)
w.setClientId('pippo')
assert.ok(isCalledSync)
})
it('handleJobAssign', function () {
var isCalledSync = false
// no action on server. skip mocking
var w = new Worker(new EventEmitter())
w.functions.queueName = function queueCallback (job) {
assert.ok(job instanceof Job)
assert.equal('handle', job.jobHandle)
assert.equal('queueName', job.queue)
assert.deepEqual(new Buffer('the content!'), job.workload)
isCalledSync = true
}
w.handleJobAssign(Buffer.concat([
new Buffer('handle'),
new Buffer([0x00]),
new Buffer('queueName'),
new Buffer([0x00]),
new Buffer('the content!')
]))
assert.ok(isCalledSync)
})
it('handleNoJob', function () {
var isCalledSync = false
var server = new EventEmitter()
server.preSleep = function () {
isCalledSync = true
}
var w = new Worker(server)
w.handleNoJob()
assert.ok(isCalledSync)
})
it('handleNoOp', function () {
var isCalledSync = false
var server = new EventEmitter()
server.grab = function () {
isCalledSync = true
}
var w = new Worker(server)
w.handleNoOp()
assert.ok(isCalledSync)
})
it('preSleep', function () {
var isCalledSync = false
var server = new EventEmitter()
server.preSleep = function () {
isCalledSync = true
}
var w = new Worker(server)
w.preSleep()
assert.ok(isCalledSync)
})
it('emit error', function () {
var w = new Worker(new EventEmitter())
var errors = []
w.on('error', function (e) {
errors.push(e)
})
w.canDo('Pippo', function () { })
w.grab()
w.setClientId('clientId')
assert.equal(3, errors.length)
})
})
| 19.878571 | 64 | 0.602946 |
3c0c561691d521ca492aae207c016414888c64a5 | 797 | js | JavaScript | scripts/dice/start.js | yildiraykoyuncu/testing-module-project-simple-games | f17dc7097dc23201b9f3a2841811e5e9c14730dc | [
"MIT"
] | null | null | null | scripts/dice/start.js | yildiraykoyuncu/testing-module-project-simple-games | f17dc7097dc23201b9f3a2841811e5e9c14730dc | [
"MIT"
] | 15 | 2020-07-25T08:23:20.000Z | 2020-07-28T20:35:48.000Z | scripts/dice/start.js | yildiraykoyuncu/testing-module-project-simple-games | f17dc7097dc23201b9f3a2841811e5e9c14730dc | [
"MIT"
] | 1 | 2020-07-24T16:18:00.000Z | 2020-07-24T16:18:00.000Z |
function start() {
const player1 = document.getElementById('player1');
const player2 = document.getElementById('player2');
const article = document.getElementById('article');
const header = document.getElementById('header');
const reset = document.getElementById('reset');
const p = document.getElementById('p');
let number = Math.floor(Math.random()* 10) + 1;
if(number % 2 === 0){
p.innerHTML = `Start with player2`;
}else{
p.innerHTML = `Start with player1`
}
document.body.style.backgroundColor = "black";
player1.style.display = 'block';
player2.style.display = 'block';
article.style.display = 'block';
reset.style.display = "block";
p.style.display = 'block';
header.style.display = 'none';
}
| 30.653846 | 55 | 0.638645 |
3c0c744be37db7c200403e99d6e95c093e55cb04 | 2,605 | js | JavaScript | lib/ArrayMath.js | arupex/math-foreach | 2abae321da408ecefd5a9a41132189d9b496a786 | [
"Unlicense"
] | null | null | null | lib/ArrayMath.js | arupex/math-foreach | 2abae321da408ecefd5a9a41132189d9b496a786 | [
"Unlicense"
] | null | null | null | lib/ArrayMath.js | arupex/math-foreach | 2abae321da408ecefd5a9a41132189d9b496a786 | [
"Unlicense"
] | null | null | null | /**
* Created by daniel.irwin on 3/4/17.
*/
let Opperations = require('./Opperations');
class ArrayMath {
constructor(array, accessor){
this.array = array;
this.accessor = accessor;
}
toValue(){
return this.array;
}
valueOf(){
return this.array;
}
deviant(nth, accessor){
this.array = Opperations.deviant(this.array, nth, accessor || this.accessor);
return this;
}
derivative1d(nth, accessor){
this.array = Opperations.derivative1dNth(this.array, nth, accessor || this.accessor);
return this;
}
normalize(accessor, shiftMin){
this.array = Opperations.normalize(this.array, accessor || this.accessor, shiftMin);
return this;
}
positiveShift(accessor){
this.array = Opperations.positiveShift(this.array, accessor || this.accessor);
return this;
}
diff(array2, accessor){
this.array = Opperations.diff(this.array, array2, accessor || this.accessor);
return this;
}
onlyAbove(targetValue, accessor, dontInclude){
this.array = Opperations.onlyAbove(this.array, targetValue, accessor || this.accessor, dontInclude);
return this;
}
onlyBelow(targetValue, accessor, dontInclude){
this.array = Opperations.onlyBelow(this.array, targetValue, accessor || this.accessor, dontInclude);
return this;
}
onlyEqual(targetValue, accessor, dontInclude){
this.array = Opperations.onlyEqual(this.array, targetValue, accessor || this.accessor, dontInclude);
return this;
}
add(targetValue, accessor){
this.array = Opperations.add(this.array, targetValue, accessor || this.accessor);
return this;
}
multiply(targetValue, accessor){
this.array = Opperations.multiply(this.array, targetValue, accessor || this.accessor);
return this;
}
abs(accessor){
this.array = Opperations.abs(this.array, accessor || this.accessor);
return this;
}
/** Return Values **/
avg(accessor){
return Opperations.onlyAbove(this.array, accessor || this.accessor);
}
min(accessor){
return Opperations.min(this.array, accessor || this.accessor);
}
max(accessor){
return Opperations.max(this.array, accessor || this.accessor);
}
median(accessor){
return Opperations.median(this.array, accessor || this.accessor);
}
mode(accessor){
return Opperations.mode(this.array, accessor || this.accessor);
}
}
module.exports = ArrayMath; | 25.792079 | 108 | 0.633397 |
3c0f96f60ffe6fce6da60ed6c0b5b3707e3af486 | 911 | js | JavaScript | src/components/BackgroundSection.js | pasglop/ctopartnersgroup | 5c8dee50fe9053c5deffdc439344f4c800e70d59 | [
"MIT"
] | 1 | 2020-06-02T18:05:21.000Z | 2020-06-02T18:05:21.000Z | src/components/BackgroundSection.js | pasglop/ctopartnersgroup | 5c8dee50fe9053c5deffdc439344f4c800e70d59 | [
"MIT"
] | null | null | null | src/components/BackgroundSection.js | pasglop/ctopartnersgroup | 5c8dee50fe9053c5deffdc439344f4c800e70d59 | [
"MIT"
] | null | null | null | import React from "react";
import { graphql, StaticQuery } from 'gatsby'
import BackgroundImage from 'gatsby-background-image';
const BackgroundSection = ({ path, className, title }) => (
<StaticQuery
query={graphql`
query getImage($path: String) {
desktop: file(relativePath: { eq: $path }) {
childImageSharp {
fluid(quality: 90, maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`}
render={data => {
// Set ImageData.
const imageData = data.desktop.childImageSharp.fluid
return (
<BackgroundImage
Tag="section"
className={className}
fluid={imageData}
>
<h1>{title}</h1>
</BackgroundImage>
)
}}
/>
);
| 27.606061 | 64 | 0.482986 |
3c109c3bce8397aafbbf59283bab470ee6f6d379 | 477 | js | JavaScript | docs/html/search/all_3.js | NMMI/SoftHand2 | d05184fb8f9959b16e43a690a31e412ca1c2a765 | [
"BSD-3-Clause"
] | 1 | 2020-12-05T11:46:00.000Z | 2020-12-05T11:46:00.000Z | docs/html/search/all_3.js | NMMI/SoftHand2 | d05184fb8f9959b16e43a690a31e412ca1c2a765 | [
"BSD-3-Clause"
] | null | null | null | docs/html/search/all_3.js | NMMI/SoftHand2 | d05184fb8f9959b16e43a690a31e412ca1c2a765 | [
"BSD-3-Clause"
] | null | null | null | var searchData=
[
['default_5fcurrent_5flimit',['DEFAULT_CURRENT_LIMIT',['../globals_8h.html#ae0001cc59fb1ba0290c6ef8c2c5692d7',1,'globals.h']]],
['delta',['DELTA',['../utils_8h.html#a3fd2b1bcd7ddcf506237987ad780f495',1,'utils.h']]],
['direction',['direction',['../structst__calib.html#a99283a3fa628676ec7ca1edcba1fea6a',1,'st_calib']]],
['discard',['DISCARD',['../globals_8h.html#a723f289c2be966c5e6c8dfe3d0b46f1ea2c65e1f3e87da84f74b4fc2a908bf69d',1,'globals.h']]]
];
| 59.625 | 129 | 0.752621 |
3c1132cd9d873853676f7c0283e9425404d686f7 | 100 | js | JavaScript | tests/eventing/code/bktop.js | bochun/perfrunner | e215c73240381cf82fddc40856f560369c9b75a8 | [
"Apache-2.0"
] | 18 | 2015-10-28T23:12:07.000Z | 2022-01-04T14:23:37.000Z | tests/eventing/code/bktop.js | bochun/perfrunner | e215c73240381cf82fddc40856f560369c9b75a8 | [
"Apache-2.0"
] | 11 | 2019-03-19T12:02:31.000Z | 2022-02-11T03:39:44.000Z | tests/eventing/code/bktop.js | bochun/perfrunner | e215c73240381cf82fddc40856f560369c9b75a8 | [
"Apache-2.0"
] | 39 | 2015-06-07T09:17:16.000Z | 2022-03-06T20:32:01.000Z | function OnUpdate(doc, meta) {
bucket1[meta.id]=doc["alt_email"];
}
function OnDelete(doc) {
}
| 14.285714 | 38 | 0.67 |
3c11dcb393dc2f5622f0e3f8c60eef92c1a804cf | 423 | js | JavaScript | src/components/Header.js | oengusmacinog/mealplanner-app | 6b619bf7fa7fd35ecb362a8878273f9bcaaaf749 | [
"MIT"
] | null | null | null | src/components/Header.js | oengusmacinog/mealplanner-app | 6b619bf7fa7fd35ecb362a8878273f9bcaaaf749 | [
"MIT"
] | null | null | null | src/components/Header.js | oengusmacinog/mealplanner-app | 6b619bf7fa7fd35ecb362a8878273f9bcaaaf749 | [
"MIT"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
class Header extends React.Component {
render() {
return (
<header className="top">
<h1>My Meal Planner</h1>
<h3 className="tagline"><span>{this.props.tagline}</span></h3>
</header>
)
}
}
Header.propTypes = {
tagline: PropTypes.string.isRequired
};
export default Header;
| 20.142857 | 78 | 0.574468 |
3c122b39b4338040e6e21878ccbbcc1629db46b6 | 127 | js | JavaScript | Documents/html/search/functions_2.js | ddelgadoJS/Cell-Segmentation-System | 0ab829ea507caa90c188910b611bf3199f094d5d | [
"MIT"
] | null | null | null | Documents/html/search/functions_2.js | ddelgadoJS/Cell-Segmentation-System | 0ab829ea507caa90c188910b611bf3199f094d5d | [
"MIT"
] | null | null | null | Documents/html/search/functions_2.js | ddelgadoJS/Cell-Segmentation-System | 0ab829ea507caa90c188910b611bf3199f094d5d | [
"MIT"
] | null | null | null | var searchData=
[
['modeltojson',['ModelToJSON',['../namespace_model.html#a00000312b074c9b8f27c20faf6142dc6',1,'Model']]]
];
| 25.4 | 105 | 0.732283 |
3c135bb84f20631e42cb9fa1731c1139a52560de | 1,745 | js | JavaScript | test/browser-codepath-test.js | denilsonsa/zopfli.js | d4b909a24316a6bdc6b101fea4d510bd151c0210 | [
"Apache-1.1"
] | 26 | 2015-01-16T23:53:42.000Z | 2021-11-03T23:30:26.000Z | test/browser-codepath-test.js | mcanthony/zopfli.js | d4b909a24316a6bdc6b101fea4d510bd151c0210 | [
"Apache-1.1"
] | 2 | 2015-05-09T20:15:30.000Z | 2019-03-06T22:07:04.000Z | test/browser-codepath-test.js | mcanthony/zopfli.js | d4b909a24316a6bdc6b101fea4d510bd151c0210 | [
"Apache-1.1"
] | 6 | 2015-03-21T23:17:31.000Z | 2020-12-23T13:02:51.000Z | (function() {
var assert = buster.assert;
buster.testCase(
"code path",
{
setUp: function() {
var size = 3500;
var testData = new (USE_TYPEDARRAY ? Uint8Array : Array)(size);
console.log("use typedarray:", USE_TYPEDARRAY);
this.testData = testData;
this.raw = sinon.spy(window, "_compress_deflate");
this.zlib = sinon.spy(window, "_compress_zlib");
this.gzip = sinon.spy(window, "_compress_gzip");
},
tearDown: function() {
this.raw.restore();
this.zlib.restore();
this.gzip.restore();
},
"raw": function() {
makeRandomData(this.testData);
inflateTest(Zopfli.RawDeflate, Zlib.RawInflate, this.testData);
assert(this.raw.called);
refute(this.zlib.called);
refute(this.gzip.called);
},
"zlib": function() {
makeRandomData(this.testData);
inflateTest(Zopfli.Deflate, Zlib.Inflate, this.testData);
refute(this.raw.called);
assert(this.zlib.called);
refute(this.gzip.called);
},
"gzip": function() {
makeRandomData(this.testData);
inflateTest(Zopfli.Gzip, Zlib.Gunzip, this.testData);
refute(this.raw.called);
refute(this.zlib.called);
assert(this.gzip.called);
}
}
);
// inflate test
function inflateTest(compressor, decompressor, testData) {
var deflate;
var inflate;
// deflate
deflate = new compressor(testData).compress();
console.log("deflated data size:", deflate.length);
// inflate
inflate = (new decompressor(deflate, {
verify: true
})).decompress();
console.log("inflated data size:", inflate.length)
// assertion
assert(inflate.length, testData.length);
assert(arrayEquals(inflate, testData));
}
})();
| 24.236111 | 69 | 0.637822 |
3c14e9e5ded5fe6df3a4b2de1af4d3139d00f8f3 | 1,146 | js | JavaScript | models/Drink.js | Samwisebuze/BrewHaha | a15cccc80c0e449ab0c106ddc37d5f908e4e0f2c | [
"MIT"
] | 1 | 2019-03-30T17:43:17.000Z | 2019-03-30T17:43:17.000Z | models/Drink.js | Samwisebuze/BrewHaha | a15cccc80c0e449ab0c106ddc37d5f908e4e0f2c | [
"MIT"
] | null | null | null | models/Drink.js | Samwisebuze/BrewHaha | a15cccc80c0e449ab0c106ddc37d5f908e4e0f2c | [
"MIT"
] | null | null | null | const mongoose = require('mongoose');
const slug = require('slugs');
mongoose.Promise = global.Promise;
const drinkSchema = new mongoose.Schema({
name: {
type: String,
required: 'Please provide a name.',
},
slug: String,
type: {
type: String,
required: 'Please select a type.',
},
tags: [{
type: String,
}],
ingredients: [{
type: String,
}],
distributor: {
type: String,
required: 'Please list the distributor.',
},
});
/**
* preSave Hook
* - Modifys drink.slug IFF name a has been modified.
* - Don't Create new models if nothing has changed
*/
drinkSchema.pre('save', async function preSave(next) {
// If edit slug IFF name is added/changed
if (!this.isModified('slug')) {
this.slug = slug(this.name);
const slugRegExp = new RegExp(`^(${this.slug})((-[0-9]*$)?)`, 'i');
// Find other stores with the same slug
const stores = await this.constructor.find()
.where('slug').equals(slugRegExp);
if (stores.length) {
this.slug = `${this.slug}-${stores.length + 1}`;
}
}
return next();
});
module.exports = mongoose.model('Drink', drinkSchema);
| 23.387755 | 71 | 0.617801 |
3c155353390742608df180235c2a984e13a4cbc5 | 1,459 | js | JavaScript | src/GameObject.js | aejester/canvas-game-engine | 89080e87dcf71c549fb6f4544713ae36f3da9f24 | [
"MIT"
] | null | null | null | src/GameObject.js | aejester/canvas-game-engine | 89080e87dcf71c549fb6f4544713ae36f3da9f24 | [
"MIT"
] | null | null | null | src/GameObject.js | aejester/canvas-game-engine | 89080e87dcf71c549fb6f4544713ae36f3da9f24 | [
"MIT"
] | null | null | null | class GameObject {
constructor(x, y, width, height, name, material = new Material("#000000", "#000000")) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.name = name;
this.material = material;
}s
getPos() {
return {
x: this.x,
y: this.y
}
}
setPos(x, y) {
this.x = x;
this.y = y;
}
getX() {
return this.x;
}
setX(x) {
this.x = x;
}
getY() {
return this.y;
}
setY(y) {
this.y = y;
}
getDimensions() {
return {
width: this.width,
height: this.height
}
}
setDimensions(width, heigth) {
this.width = width;
this.height = heigth;
}
getWidth() {
return this.width;
}
setWidth(width) {
this.width = width;
}
getHeight() {
return this.height;
}
setHeight(height) {
this.height = height;
}
getMaterial() {
return this.material;
}
setMaterial(material) {
this.material = material;
}
getName() {
return this.name;
}
setName(name) {
this.name = name;
}
updateMaterial(ctx) {
ctx.fillStyle = this.material.getFill();
ctx.strokeStyle = this.material.getStroke();
}
draw(ctx) {
this.updateMaterial(ctx);
}
} | 17.369048 | 91 | 0.464016 |
3c1a22ddc62daaeda107d959070c3aa2fe0b1596 | 823 | js | JavaScript | middlewares/05-errors.js | AlNovik/node-course | 670872f812edca66831d6fd7791d66331f405597 | [
"MIT"
] | null | null | null | middlewares/05-errors.js | AlNovik/node-course | 670872f812edca66831d6fd7791d66331f405597 | [
"MIT"
] | null | null | null | middlewares/05-errors.js | AlNovik/node-course | 670872f812edca66831d6fd7791d66331f405597 | [
"MIT"
] | null | null | null | const handlers = {
'400': err => {
let result = {
errors: {}
};
const fields = Object.keys(err.errors);
for (let field of fields) {
result.errors[field] = err.errors[field].message;
}
return result;
}
};
module.exports = function*(next) {
try {
yield* next;
} catch (e) {
if (e.status) {
if (handlers[e.status]) {
this.body = handlers[e.status](e);
} else {
this.body = e.message;
}
this.status = e.status;
} else if (e.name === 'ValidationError') {
this.status = 400;
this.body = handlers['400'](e);
} else {
this.body = 'Error 500';
this.status = 500;
}
}
}; | 23.514286 | 61 | 0.431349 |
3c1ac5899cf0fecbad72d82733988f102923c98f | 370 | js | JavaScript | src/settings.js | dezhidki/soundboard | bbbd35b9d42010ca6d4aa35f88f3e78d7bbef989 | [
"MIT"
] | null | null | null | src/settings.js | dezhidki/soundboard | bbbd35b9d42010ca6d4aa35f88f3e78d7bbef989 | [
"MIT"
] | null | null | null | src/settings.js | dezhidki/soundboard | bbbd35b9d42010ca6d4aa35f88f3e78d7bbef989 | [
"MIT"
] | null | null | null | const DEFAULT_BUTTON_SETTINGS = {
loop: false,
stopAll: false,
buttonColor: "#757575",
playingColor: "#757575",
title: "",
type: "toggle",
key: "",
audioSrc: "",
col: 0,
row: 0
};
function createDefaultButtonSettings() {
return {...DEFAULT_BUTTON_SETTINGS};
}
export { createDefaultButtonSettings, DEFAULT_BUTTON_SETTINGS }; | 20.555556 | 64 | 0.643243 |
3c1cc3edcf8919fbc28c78d21c273431de35ef90 | 6,715 | js | JavaScript | src/hooks/use-data-fetch.js | PinkAirship/useDataFetch | bbb943d535058fbe75a56d381848bfd081b7978d | [
"MIT"
] | null | null | null | src/hooks/use-data-fetch.js | PinkAirship/useDataFetch | bbb943d535058fbe75a56d381848bfd081b7978d | [
"MIT"
] | 9 | 2021-02-08T23:57:44.000Z | 2021-03-31T19:02:32.000Z | src/hooks/use-data-fetch.js | PinkAirship/useDataFetch | bbb943d535058fbe75a56d381848bfd081b7978d | [
"MIT"
] | 2 | 2021-02-10T22:24:29.000Z | 2021-02-11T23:29:12.000Z | import { useContext, useMemo } from 'react'
import { DataFetchContext } from '../contexts/data-fetch-provider'
// stable function signature for equality checks
function noop() {}
export function useDataFetch(
path,
{
updateStateHook: hookUpdateStateHook,
alertScreenReaderWith: alertScreenReaderWith,
requestConfig: hookRequestConfig,
useCache: hookUseCache,
requestStateListener: hookRequestStateListener,
} = {
alertScreenReaderWith: undefined,
hookRequestConfig: {},
hookUseCache: undefined,
hookRequestStateListener: noop,
}
) {
const {
dataFetchInstance,
screenReaderAlert,
cache,
useCache: contextUseCache,
updateStateHook: providerUpdateStateHook,
} = useContext(DataFetchContext)
function makeRequest(
method,
data,
{
methodUseCache,
methodRequestConfig: methodRequestConfig,
methodUpdateStateHook: methodUpdateStateHook,
requestStateListener: methodRequestStateListener,
} = {
methodRequestConfig: {},
methodUpdateStateHook: undefined,
}
) {
const updateStateHook =
typeof hookUpdateStateHook != 'undefined'
? hookUpdateStateHook
: providerUpdateStateHook
const hookToUpdateState =
typeof methodUpdateStateHook != 'undefined'
? methodUpdateStateHook
: updateStateHook
// Order of precedence: method use - method defined - context defined
let computedUseCache =
(typeof hookUseCache != 'undefined'
? hookUseCache
: contextUseCache) && method.toLowerCase() == 'get'
computedUseCache =
typeof methodUseCache != 'undefined'
? methodUseCache
: computedUseCache
const requestStateListener =
typeof methodRequestStateListener != 'undefined'
? methodRequestStateListener
: hookRequestStateListener || noop
let promise
if (computedUseCache) {
const cachedValue = cache.get(path)
if (cachedValue) {
requestStateListener('success')
promise = Promise.resolve(cachedValue)
}
}
if (!promise) {
// don't overwrite data from requestConfig unless it is present.
const requestData = data ? { data } : {}
const finalRequestConfig = {
method,
url: path,
...hookRequestConfig,
...methodRequestConfig,
...requestData,
}
requestStateListener('running')
promise = dataFetchInstance(finalRequestConfig)
}
return promise
.then((responseData) => {
requestStateListener('success')
if (computedUseCache) cache.set(path, responseData)
return responseData
})
.then((responseData) => {
if (hookToUpdateState) hookToUpdateState(responseData)
return responseData
})
.then((responseData) => {
if (alertScreenReaderWith)
screenReaderAlert(alertScreenReaderWith)
return responseData
})
.catch((error) => {
requestStateListener('error')
return error
})
}
const get = useMemo(
() => (
data,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) =>
makeRequest('get', data, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: requestConfig,
requestStateListener,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
const query = useMemo(
() => (
params,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) =>
makeRequest('get', undefined, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: { ...requestConfig, params },
requestStateListener,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
const post = useMemo(
() => (
data,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) => {
return makeRequest('post', data, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: requestConfig,
requestStateListener,
})
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
const put = useMemo(
() => (
data,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) =>
makeRequest('put', data, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: requestConfig,
requestStateListener,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
const patch = useMemo(
() => (
data,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) =>
makeRequest('patch', data, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: requestConfig,
requestStateListener,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
const destroy = useMemo(
() => (
data,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) =>
makeRequest('delete', data, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: requestConfig,
requestStateListener,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
const request = useMemo(
() => (
data,
{
useCache,
requestConfig,
requestStateListener,
updateStateHook,
} = {}
) => {
const mergedConfig = { ...hookRequestConfig, ...requestConfig }
if (!hookRequestConfig.url) {
throw 'Request must have url set.'
}
if (!hookRequestConfig.method) {
throw 'Request must have a method set.'
}
return makeRequest('request', data, {
methodUseCache: useCache,
methodUpdateStateHook: updateStateHook,
methodRequestConfig: mergedConfig,
requestStateListener,
})
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[hookUpdateStateHook]
)
return {
get,
post,
put,
patch,
destroy,
request,
query,
}
}
| 25.629771 | 73 | 0.613552 |
3c1d67decf0675dc68f45a0e3463f3d768b34297 | 1,558 | js | JavaScript | app/controllers/home.js | squarescale/sqsc-demo-app | 772f3e3a374e7f657a2b16f1d58c22c76474046f | [
"MIT"
] | null | null | null | app/controllers/home.js | squarescale/sqsc-demo-app | 772f3e3a374e7f657a2b16f1d58c22c76474046f | [
"MIT"
] | 3 | 2017-08-22T08:46:02.000Z | 2018-02-09T16:25:58.000Z | app/controllers/home.js | squarescale/sqsc-demo-app | 772f3e3a374e7f657a2b16f1d58c22c76474046f | [
"MIT"
] | 13 | 2017-08-21T07:02:38.000Z | 2019-08-14T09:31:17.000Z | const express = require('express');
const router = express.Router();
const processingQueueName = process.env.PROCESSING_QUEUE_NAME || "processingQueue";
module.exports = function(app) {
app.use('/', router);
};
router.get('/', function(req, res, next) {
let app = req.app;
let infos = app.get('infos');
res.render('index', {
title: 'SquareScale demo',
infos: infos
});
});
router.post('/launch', function(req, res) {
let params = req.body;
let app = req.app;
let taskMessage;
for (let currentY = 0; currentY < parseInt(params.height); currentY += parseInt(params.stepY)) {
for (let currentX = 0; currentX < parseInt(params.width); currentX += parseInt(params.stepX)) {
taskMessage = getTaskMessage(params, currentX, currentY);
app.get('rabbitMQChannel').sendToQueue(processingQueueName, taskMessage);
console.log(`app - [x] Sent new task ${taskMessage}`);
app.get('socketIO').emit('compute_task_created', {clientToken: params.clientToken});
}
}
res.sendStatus(200);
});
function getTaskMessage(params, currentX, currentY) {
return Buffer.from(JSON.stringify({
x: parseFloat(params.x),
y: parseFloat(params.y),
scaleX: parseFloat(params.scaleX),
scaleY: parseFloat(params.scaleY),
width: parseInt(params.width),
height: parseInt(params.height),
startX: currentX,
startY: currentY,
stepX : parseInt(params.stepX) || 10,
stepY : parseInt(params.stepY) || 10,
iter: parseInt(params.maxIteration) || 10,
clientToken: params.clientToken
}));
}
| 30.54902 | 99 | 0.674583 |
3c1e31a27a2ea293f4471238fd6d1860d7e5bd2c | 1,645 | js | JavaScript | src/apps/rental_car/errors.js | mrkazawa/notary_node | 59c52ccfcce8c524a394f836085295e34d3df1b0 | [
"MIT"
] | 1 | 2021-11-10T01:20:59.000Z | 2021-11-10T01:20:59.000Z | src/apps/rental_car/errors.js | mrkazawa/notary_node | 59c52ccfcce8c524a394f836085295e34d3df1b0 | [
"MIT"
] | null | null | null | src/apps/rental_car/errors.js | mrkazawa/notary_node | 59c52ccfcce8c524a394f836085295e34d3df1b0 | [
"MIT"
] | null | null | null | class RentalCarError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
class CoreEngineSendError extends RentalCarError {
constructor(data) {
super(`Cannot send ${data} to the Core Engine.`);
}
}
class DatabaseWriteError extends RentalCarError {
constructor(data) {
super(`Cannot insert ${data} to the local database.`);
}
}
class CarOwnerMismatchedError extends RentalCarError {
constructor(expectedOwner, givenOwner) {
super(`Car owner does not match (expected: ${expectedOwner} but given: ${givenOwner}).`);
}
}
class InvalidIpfsHashError extends RentalCarError {
constructor(ipfsHash) {
super(`${ipfsHash} is not an IPFS hash.`);
}
}
class IpfsGetError extends RentalCarError {
constructor(ipfsHash) {
super(`Cannot get ${ipfsHash} content.`);
}
}
class IotaExecutionError extends RentalCarError {
constructor(error) {
super(`IOTA error: ${error}`);
}
}
class EthereumExecutionError extends RentalCarError {
constructor(error) {
super(`Ethereum error: ${error}`);
}
}
class InvalidDomain extends RentalCarError {
constructor(ip) {
super(`Your ip ${ip} is not eligible to access this request.`);
}
}
class InvalidPaymentHash extends RentalCarError {
constructor(tailTxHash) {
super(`The payment hash ${tailTxHash} is invalid.`);
}
}
module.exports = {
CoreEngineSendError,
DatabaseWriteError,
CarOwnerMismatchedError,
InvalidIpfsHashError,
IpfsGetError,
IotaExecutionError,
EthereumExecutionError,
InvalidDomain,
InvalidPaymentHash
} | 22.534247 | 93 | 0.722796 |
3c1e4bd757a6de965d150f49365bbe49dc57d867 | 1,368 | js | JavaScript | routes/users.js | vishnuroshan/admin-panel-task | 0b599d603472eda775d602bd1c3dd55157ff63cd | [
"MIT"
] | null | null | null | routes/users.js | vishnuroshan/admin-panel-task | 0b599d603472eda775d602bd1c3dd55157ff63cd | [
"MIT"
] | null | null | null | routes/users.js | vishnuroshan/admin-panel-task | 0b599d603472eda775d602bd1c3dd55157ff63cd | [
"MIT"
] | null | null | null | const router = require("express").Router();
const userController = require("../controllers/users");
const { celebrate, Joi, errors } = require("celebrate");
router.post(
"/list-employees",
celebrate({
body: Joi.object().keys({
range: Joi.object()
.keys({
from: Joi.string().required(),
to: Joi.string().required(),
})
.optional(),
search: Joi.string().optional(),
}),
}),
errors(),
(request, response) => {
userController.listEmployees(request.user, request.body).then(
(list) => {
response.status(200).json(list);
},
(err) => {
console.log(err);
response.status(err.status).json(err);
}
);
}
);
router.post(
"/add-employee",
celebrate({
body: Joi.object().keys({
firstname: Joi.string().required(),
lastname: Joi.string().optional(),
email: Joi.string().required(),
password: Joi.string().optional(),
}),
}),
errors(),
(request, response) => {
console.log(request.body, request.user);
userController.addEmployee(request.body, request.user).then(
(employee) => {
response.status(200).json({
status: 200,
...employee,
});
},
(err) => {
response.status(err.status).json(err);
}
);
}
);
module.exports = router;
| 22.8 | 66 | 0.545322 |
3c1e5699bcbfb7faf678c56e23f6c47bfa15302b | 2,065 | js | JavaScript | markdown-webserver-modules/basic_search/src/SearchEngine.js | dadikovi/markdown-webserver | f093d63157a63d37bff6073474bdb470a9e0b41e | [
"Apache-2.0"
] | null | null | null | markdown-webserver-modules/basic_search/src/SearchEngine.js | dadikovi/markdown-webserver | f093d63157a63d37bff6073474bdb470a9e0b41e | [
"Apache-2.0"
] | null | null | null | markdown-webserver-modules/basic_search/src/SearchEngine.js | dadikovi/markdown-webserver | f093d63157a63d37bff6073474bdb470a9e0b41e | [
"Apache-2.0"
] | null | null | null | var NO_RESULTS = -1;
/**
* Very simple search implementation:
* - Orders results by match count desc.
* - It can find only non-case-sensitive full matches
* - It can display only the first match in a given file.
*/
class SearchEngine {
doSearch(mdArray, query) {
var resultArray = [];
var regex = new RegExp(query, "ig")
for (var i = 0; i < mdArray.length; i++) {
var file = mdArray[i];
var at = file.content.search(regex);
if (at !== NO_RESULTS) {
var relevance = file.content.match(regex).length;
resultArray.push(this.createResultObject(file, query, at, relevance));
}
}
return resultArray.sort(this.compareResults);
}
createResultObject(file, query, at, relevance) {
return {
name: this.calculateName(file, query),
path: file.path,
relevance: relevance,
content: this.calculateContent(file, query, at)
};
}
calculateName(file, query) {
var dotPos = file.name.lastIndexOf(".");
var printableName = file.name.substring(0, dotPos);
return printableName.replace(query, "<span class=\"match\">" + query + "</span>");
}
calculateContent(file, query, at) {
var lineStart = this.getLineStart(file.content, at);
var lineEnd = this.getLineEnd(file.content, at);
var line = file.content.substring(lineStart, lineEnd);
return line.replace(query, "<span class=\"match\">" + query + "</span>");
}
getLineStart(text, pos) {
var textBefore = text.substring(0, pos);
return textBefore.lastIndexOf("\n");
}
getLineEnd(text, pos) {
var textAfter = text.substring(pos);
return textAfter.search("\n") + pos;
}
/**
* Orders results by relevance DESC
* @param {relevance, *} a
* @param {relevance, *} b
*/
compareResults(a, b) {
return b.relevance - a.relevance;
}
}
module.exports = new SearchEngine(); | 30.367647 | 90 | 0.579661 |
3c204874fef6f4a9961f19b45dc00ab1ba2750cc | 335 | js | JavaScript | es6/widgets/widgets.js | chustar/metro-start | a7e9599712b907d2cf07cc44024faf7b677df107 | [
"MIT"
] | 2 | 2020-10-09T07:11:12.000Z | 2021-09-04T16:32:55.000Z | es6/widgets/widgets.js | metro-start/metro-start | 67808a20a63570080ebde2cc0d24afd741a83945 | [
"MIT"
] | 37 | 2017-02-19T00:14:37.000Z | 2022-02-26T02:29:51.000Z | es6/widgets/widgets.js | chustar/metro-start | a7e9599712b907d2cf07cc44024faf7b677df107 | [
"MIT"
] | 1 | 2015-04-26T15:57:27.000Z | 2015-04-26T15:57:27.000Z | import weather from './weather';
import themes from './themes';
import about from './about';
export default {
weather: weather,
themes: themes,
about: about,
data: [weather, themes, about],
init: function(document) {
this.data.forEach((module) => {
module.init(document);
});
},
}; | 20.9375 | 39 | 0.585075 |
3c20a4c885a307142eb219d7323508b15a4cc9f1 | 371 | js | JavaScript | resources/js/functions/zoom.js | petersongomes/jetneo-theme-evaluation | 1395773402d18dbc74b8457e62b69f5ea1bae31b | [
"MIT"
] | null | null | null | resources/js/functions/zoom.js | petersongomes/jetneo-theme-evaluation | 1395773402d18dbc74b8457e62b69f5ea1bae31b | [
"MIT"
] | null | null | null | resources/js/functions/zoom.js | petersongomes/jetneo-theme-evaluation | 1395773402d18dbc74b8457e62b69f5ea1bae31b | [
"MIT"
] | null | null | null | /**
* PLUGIN ZOOM
*
**/
export function ZoomReset() {
let $easyzoom = $(".easyzoom").easyZoom();
let $thumb = $easyzoom.filter('.easyzoom--with-thumbnails').data('easyZoom');
$('.thumbnails').on('click', 'a', function (e) {
let $this = $(this);
e.preventDefault();
$thumb.swap($this.data('standard'), $this.attr('href'));
});
} | 28.538462 | 81 | 0.555256 |
3c20ff74d4f57c7b86b6611df8276179aa7d22af | 3,470 | js | JavaScript | server.js | hkidd/NoteTaker_HW11 | 6680d2a1cd323b00ce733d76418cc28a48342b50 | [
"MIT"
] | null | null | null | server.js | hkidd/NoteTaker_HW11 | 6680d2a1cd323b00ce733d76418cc28a48342b50 | [
"MIT"
] | null | null | null | server.js | hkidd/NoteTaker_HW11 | 6680d2a1cd323b00ce733d76418cc28a48342b50 | [
"MIT"
] | null | null | null | // Required dependencies
const express = require("express");
const db = require("./db/db.json");
const path = require("path");
const fs = require("fs");
const PORT = process.env.PORT || 3001;
const uuid = require("./helpers/uuid");
// Initialize express application
const app = express();
// Middleware for parsing application/json and url data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Client facing files are in a "public" folder, so the static method can be used
app.use(express.static("public"));
// We have GET, POST, and DELETE methods in the index.js for the '/api/notes' route
// GET route
app.get("/api/notes", (req, res) => {
console.info(`${req.method} request received for the api/notes route`);
// this route should read the db.json file and return all saved notes as json
res.json(db);
});
// POST route
app.post("/api/notes", (req, res) => {
console.info(`${req.method} request received for the api/notes route`);
// this route should recieve a new note to save on the request body, add it to the db.json file, and then return the new note to the client with a unique id (using uuid, like our previous example)
// grabbing the request body and saving that as a "newNote"
let newNote = req.body;
// need to ad a unique id to this note (using uuid)
newNote.id = uuid();
// after adding unique id, this note should be added to the db.json file
db.push(newNote);
// Tried append file, but that was making it unhappy. So overwriting the db file each time a new note is added
fs.writeFile(`./db/db.json`, JSON.stringify(db), (err) =>
err
? console.error(err)
: console.log(`New Note has been written to JSON db`)
);
// Pass along the new db as a response
res.send(db);
});
// DELETE route needs the specific note id to delete the correct one
app.delete("/api/notes/:id", (req, res) => {
console.info(`${req.method} request received for the api/notes route`);
// using the id parameter, create a noteId variable
let noteId = req.params.id;
console.log(noteId);
// loop through the entire note database, and find the one note with a matching id
for (let i = 0; i < db.length; i++) {
const currentNote = db[i];
if (currentNote.id === noteId) {
// splice out one element starting at that noteId (only that note)
db.splice(i, 1);
res.json(`Note has been deleted`);
console.log(db);
// after splicing out the note, write a new file with the updated db array
fs.writeFile("./db/db.json", JSON.stringify(db), (err) =>
err ? console.log(err) : console.log("Success!")
);
return;
}
}
// Pass along the new db as a response
res.send(db);
});
// Need the get /notes route to return the notes.html file
app.get("/notes", (req, res) => {
console.info(`${req.method} request received for the /notes route`);
// the response should be to send the notes.html to the client
res.sendFile(path.join(__dirname, "/public/notes.html"));
});
// Need the get * route to return the index.html file. THIS SHOULD BE LAST
app.get("*", (req, res) => {
console.info(`${req.method} request received for the /index route`);
// the response should be to send the index.html to the client
res.sendFile(path.join(__dirname, "/public/index.html"));
});
// Need to have the app lsitening at the specified port
app.listen(PORT, () =>
console.log(`App listening at http://localhost:${PORT} 😎`)
);
| 34.7 | 198 | 0.672046 |
3c214431a1dfc0267864d8c0c165b88840fff08c | 5,896 | js | JavaScript | controllers/book.js | shenkai1/createbooklist | d32d12e3c540f07535c384c94b15516384fa5274 | [
"MIT"
] | null | null | null | controllers/book.js | shenkai1/createbooklist | d32d12e3c540f07535c384c94b15516384fa5274 | [
"MIT"
] | null | null | null | controllers/book.js | shenkai1/createbooklist | d32d12e3c540f07535c384c94b15516384fa5274 | [
"MIT"
] | null | null | null | // create a reference to the model
let Book = require('../models/book');
// async function insertBookData(){
// try {
// await Book.insertMany([
// {
// "Title": "Eloquent JavaScript, Third Edition",
// "Description": "JavaScript lies at the heart of almost every modern web application, from social apps like Twitter to browser-based game frameworks like Phaser and Babylon. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications.",
// "Price": "12.50",
// "Author": "Marijn Haverbeke",
// "Genre":"JavaScript"
// },
// {
// "Title": "Practical Modern JavaScript",
// "Description": "To get the most out of modern JavaScript, you need learn the latest features of its parent specification, ECMAScript 6 (ES6). This book provides a highly practical look at ES6, without getting lost in the specification or its implementation details.",
// "Price": "15.20",
// "Author": "JNicolás Bevacqua",
// "Genre":"JavaScript"
// },
// {
// "Title": "Understanding ECMAScript 6",
// "Description": "ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types, syntax, and other exciting changes that ECMAScript 6 brings to JavaScript.",
// "Price": "10.00",
// "Author": "Nicholas C. Zakas",
// "Genre":"ECMAScript"
// },
// {
// "Title": "Speaking JavaScript",
// "Description": "Like it or not, JavaScript is everywhere these days -from browser to server to mobile- and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.",
// "Price": "9.80",
// "Author": "Axel Rauschmayer",
// "Genre":"JavaScript"
// }
// ]);
// } catch (error) {
// console.log('err:'+ error);
// }
// }
// insertBookData();
// Gets all books from the Database and renders the page to list all books.
module.exports.bookList = function(req, res, next) {
Book.find((err, bookList) => {
// console.log(bookList);
if(err)
{
return console.error(err);
}
else
{
res.render('book/list', {
title: 'Book List',
books: bookList
})
}
});
}
// Gets a book by id and renders the details page.
module.exports.details = (req, res, next) => {
let id = req.params.id;
Book.findById(id, (err, bookToShow) => {
if(err)
{
console.log(err);
res.end(err);
}
else
{
//show the edit view
res.render('book/details', {
title: 'Book Details',
book: bookToShow
})
}
});
}
// Renders the Add form using the add_edit.ejs template
module.exports.displayAddPage = (req, res, next) => {
let newBook = Book();
res.render('book/add_edit', {
title: 'Add a new Book',
book: newBook
})
}
// Processes the data submitted from the Add form to create a new book
module.exports.processAddPage = (req, res, next) => {
let newBook = Book({
Title: req.body.Title,
Description: req.body.Description,
Price: req.body.Price,
Author: req.body.Author,
Genre : req.body.Genre
});
Book.create(newBook, (err, book) =>{
if(err)
{
console.log(err);
res.end(err);
}
else
{
// refresh the book list
console.log(book);
res.redirect('/book/list');
}
});
}
// Gets a book by id and renders the Edit form using the add_edit.ejs template
module.exports.displayEditPage = (req, res, next) => {
let id = req.params.id;
Book.findById(id, (err, bookToEdit) => {
if(err)
{
console.log(err);
res.end(err);
}
else
{
//show the edit view
res.render('book/add_edit', {
title: 'Edit Book',
book: bookToEdit
})
}
});
}
// Processes the data submitted from the Edit form to update a book
module.exports.processEditPage = (req, res, next) => {
let id = req.params.id
let updatedItem = Book({
_id :id,
Title: req.body.Title,
Description: req.body.Description,
Price: req.body.Price,
Author: req.body.Author,
Genre : req.body.Genre
});
Book.updateOne({_id: id}, updatedItem, (err) => {
if(err)
{
console.log(err);
res.end(err);
}
else
{
// console.log(req.body);
// refresh the book list
res.redirect('/book/list');
}
});
}
// Deletes a book based on its id.
module.exports.performDelete = (req, res, next) => {
let id = req.params.id;
Book.remove({_id: id}, (err) => {
if(err)
{
console.log(err);
res.end(err);
}
else
{
// refresh the book list
res.redirect('/book/list');
}
});
} | 30.549223 | 341 | 0.512212 |
3c221fd1980cd36980b1fc579e0674cc97962c7f | 1,021 | js | JavaScript | packages/ms-auth/services/account.test.js | jxjwilliam/ws-fullstack | 3463adf1d8645d8249f7d78052ba51746a5f30e9 | [
"MIT"
] | null | null | null | packages/ms-auth/services/account.test.js | jxjwilliam/ws-fullstack | 3463adf1d8645d8249f7d78052ba51746a5f30e9 | [
"MIT"
] | null | null | null | packages/ms-auth/services/account.test.js | jxjwilliam/ws-fullstack | 3463adf1d8645d8249f7d78052ba51746a5f30e9 | [
"MIT"
] | null | null | null | const { expect } = require('chai')
const mongoose = require('mongoose')
const connectMongoDB = require('../connect')
const Account = require('../models/Account')
describe('Account', () => {
before('connect', done => {
new Promise(resolve => {
setTimeout(() => {
connectMongoDB()
resolve('connected')
}, 1000)
}).then(() => done())
})
after('connect', done => {
mongoose.connection.close()
done()
})
let callback
beforeEach(() => {
callback = function () {}
})
it('account', () => {
const account = Account.find({
username: 'admin',
'role.name': 'admin',
'category.name': 'local',
phone: { $in: ['1347', '8221246'] },
})
.limit(10)
.sort({ username: -1 })
.select({ username: 1, phone: 1 })
.exec(callback)
expect([1, 2]).to.be.an('array').that.does.not.include(3)
})
})
describe('Authentication', () => {
it('authentication', () => {
expect({ a: 1 }).to.not.have.property('b')
})
})
| 22.688889 | 61 | 0.532811 |
3c23418de5a0442f88ed529eab4f02516443871c | 284 | js | JavaScript | webpack.config.js | 59naga/pixel-webp | 5f3f583b6bef45373a82df3b3d678b83fcc36401 | [
"MIT"
] | 1 | 2021-07-15T13:28:28.000Z | 2021-07-15T13:28:28.000Z | webpack.config.js | 59naga/pixel-webp | 5f3f583b6bef45373a82df3b3d678b83fcc36401 | [
"MIT"
] | null | null | null | webpack.config.js | 59naga/pixel-webp | 5f3f583b6bef45373a82df3b3d678b83fcc36401 | [
"MIT"
] | 1 | 2021-07-15T13:28:29.000Z | 2021-07-15T13:28:29.000Z | module.exports = {
mode: 'production',
node: {
fs: 'empty'
},
output: {
library: 'pixelWebp',
libraryTarget: 'umd',
// https://github.com/webpack/webpack/issues/6784#issuecomment-375941431
globalObject: 'typeof self !== \'undefined\' ? self : this'
}
};
| 21.846154 | 76 | 0.612676 |
3c24093b74e22313334a83e016975330296d7f8a | 1,391 | js | JavaScript | src/assets/skillParser.js | Waltari10/warband-manager | 01e4d3002804029020b1f8cb267f03f1e3b98f92 | [
"MIT"
] | null | null | null | src/assets/skillParser.js | Waltari10/warband-manager | 01e4d3002804029020b1f8cb267f03f1e3b98f92 | [
"MIT"
] | 10 | 2021-02-22T18:50:03.000Z | 2022-03-28T23:19:34.000Z | src/assets/skillParser.js | Waltari10/warband-manager | 01e4d3002804029020b1f8cb267f03f1e3b98f92 | [
"MIT"
] | null | null | null |
import units, { heroIndexes, henchmenIndexes } from './unitTemplates';
const basicSkillCategories = {
'Academic': true,
'Special': true,
'Speed': true,
'Combat': true,
'Strength': true,
'Shooting': true,
'Lesser Magic': true,
};
// Objective: Figure out which skills(spells) are available for each warband
// Steps:
// Iterate through all units of each warband
// Mark up skills they have available
// Those are the skills that that warband can use
export const getWarbandSkills = (warbandId) => {
const heroesIndexArr = heroIndexes[warbandId];
const henchmenIndexArr = henchmenIndexes[warbandId];
if (!warbandId || !henchmenIndexArr) {
return Object.keys(basicSkillCategories);
}
const warbandSkills = { ...basicSkillCategories };
if (heroesIndexArr) {
heroesIndexArr.forEach((heroIndex) => {
const template = units[heroIndex] || { skill_lists: [] };
template.skill_lists.forEach((skill) => {
if (!warbandSkills[skill]) {
warbandSkills[skill] = true;
}
});
});
}
if (henchmenIndexArr) {
henchmenIndexArr.forEach((heroIndex) => {
const template = units[heroIndex] || { skill_lists: [] };
template.skill_lists.forEach((skill) => {
if (!warbandSkills[skill]) {
warbandSkills[skill] = true;
}
});
});
}
return Object.keys(warbandSkills);
}; | 24.839286 | 76 | 0.644141 |
3c24600d9c87afb5aa5684b531dfaacd9982d413 | 194 | js | JavaScript | src/common/utils/index.js | GhettoGeek/pwask | 94a0e71eca815998f1d5db7206fd859612a65c03 | [
"Apache-2.0"
] | null | null | null | src/common/utils/index.js | GhettoGeek/pwask | 94a0e71eca815998f1d5db7206fd859612a65c03 | [
"Apache-2.0"
] | 1 | 2021-09-02T19:31:23.000Z | 2021-09-02T19:31:23.000Z | src/common/utils/index.js | GhettoGeek/pwask | 94a0e71eca815998f1d5db7206fd859612a65c03 | [
"Apache-2.0"
] | null | null | null | import apiUtil from './api'
import scriptUtil from './script'
import storageUtil from './storage'
import * as urlUtil from './url'
export {
apiUtil,
scriptUtil,
storageUtil,
urlUtil,
}
| 16.166667 | 35 | 0.706186 |
3c25182256a1441a8409766050a1d620ae0b7e58 | 3,014 | js | JavaScript | src/reducers/playersReducer.js | manucasares/Estratega | df16890cd684e76f324c09360a9cd1105c3e82f9 | [
"MIT"
] | null | null | null | src/reducers/playersReducer.js | manucasares/Estratega | df16890cd684e76f324c09360a9cd1105c3e82f9 | [
"MIT"
] | null | null | null | src/reducers/playersReducer.js | manucasares/Estratega | df16890cd684e76f324c09360a9cd1105c3e82f9 | [
"MIT"
] | null | null | null | import { types } from "../types/types";
const initialState = {
playerSelector: 0
}
export const playersReducer = ( state = initialState, action ) => {
switch ( action.type ) {
case types.playersSetPlayers:
return {
...state,
players: action.payload
}
case types.playersSetChoice:
const { id, choice } = action.payload;
return {
...state,
players: state.players.map( player => {
if ( player.id === id ) {
player.choice = choice
}
return player;
})
};
case types.playersChangeSelector:
return {
...state,
playerSelector: action.payload
}
case types.playersSetRoundWin:
return {
...state,
players: state.players.map( player => {
if ( player.id === action.payload ) {
player.won = true;
}
return player;
})
}
case types.playersSetRoundLose:
return {
...state,
players: state.players.map( player => {
if ( player.id === action.payload ) {
player.won = false;
}
return player;
})
}
case types.playersSetScores:
return {
...state,
players: state.players.map( player => {
const { won, score, choice } = player;
if ( won ) {
const pointsWon = choice ? 5 + choice : 1;
score.push( score[ score.length - 1 ] + pointsWon );
} else {
// si pierde pusheamos el mismo score que tenía
score.push( score[ score.length - 1 ] );
}
return player;
})
}
case types.playersReset:
return {
...state,
playerSelector: 0,
players: state.players.map( player => {
player.choice = null
player.won = null
return player;
})
}
case types.playersChangePlayersOrder:
return {
...state,
players: state.players.map( ( player, index, arr ) => {
// si es el ultimo que se convierta en el primero
return ( index === ( arr.length - 1 ) )
? arr[ 0 ]
: arr[ index + 1 ]
})
}
default:
return state;
}
} | 25.542373 | 78 | 0.374917 |
3c2666a947b25da0961faa1daea333cfdae8980a | 2,538 | js | JavaScript | dist/multiform/internal/GridElem.js | phovea/phovea_core | 7c92bc9995d37555ed5ebba6eb4e9daf14763a57 | [
"BSD-3-Clause"
] | 4 | 2017-02-10T04:39:11.000Z | 2019-07-01T18:41:09.000Z | dist/multiform/internal/GridElem.js | phovea/phovea_core | 7c92bc9995d37555ed5ebba6eb4e9daf14763a57 | [
"BSD-3-Clause"
] | 123 | 2016-11-05T18:56:47.000Z | 2021-02-04T09:10:33.000Z | dist/multiform/internal/GridElem.js | phovea/phovea_core | 7c92bc9995d37555ed5ebba6eb4e9daf14763a57 | [
"BSD-3-Clause"
] | 14 | 2016-11-03T15:36:21.000Z | 2019-12-13T09:53:02.000Z | /**
* Created by sam on 26.12.2016.
*/
import { BaseUtils } from '../../base/BaseUtils';
import { DataUtils } from '../../data';
import { VisUtils } from '../../vis';
import { FormUtils } from './FormUtils';
/**
* @internal
*/
export class GridElem {
constructor(range, pos, data) {
this.range = range;
this.pos = pos;
this.data = data;
}
setContent(c) {
this.content = c;
DataUtils.assignData(this.content, this.data);
}
subrange(r) {
const ri = this.range.intersect(r);
return this.range.indexOf(ri);
}
get hasOne() {
return this.actVis != null;
}
destroy() {
if (this.actVis && typeof (this.actVis.destroy) === 'function') {
this.actVis.destroy();
}
}
get size() {
return this.actVis ? this.actVis.size : [100, 100];
}
get rawSize() {
return this.actVis ? this.actVis.rawSize : [100, 100];
}
persist() {
return {
range: this.range.toString(),
content: this.actVis && typeof (this.actVis.persist) === 'function' ? this.actVis.persist() : null
};
}
restore(persisted) {
//FIXME
/*if (persisted.id) {
var selected = search(this.visses, (e) => e.id === persisted.id);
if (selected) {
this.switchTo(selected).then((vis) => {
if (vis && persisted.content && isFunction(restore)) {
restore(persisted.content);
}
});
}
}*/
return null;
}
switchDestroy() {
//remove content dom side
FormUtils.clearNode(this.content);
if (this.actVis && typeof (this.actVis.destroy) === 'function') {
this.actVis.destroy();
}
this.actVis = null;
}
build(plugin, options) {
this.actVis = plugin.factory(this.data, this.content, options);
VisUtils.assignVis(this.content, this.actVis);
return this.actVis;
}
get location() {
const o = BaseUtils.offset(this.content);
return {
x: o.left,
y: o.top
};
}
transform(scale, rotate) {
if (this.actVis) {
if (arguments.length > 0) {
return this.actVis.transform(scale, rotate);
}
else {
return this.actVis.transform();
}
}
return {
scale: [1, 1],
rotate: 0
};
}
}
//# sourceMappingURL=GridElem.js.map | 27 | 110 | 0.50788 |
3c26d3e8154ce3cb9a8de5b4dfacd622987b7f87 | 117 | js | JavaScript | example/src/components/index.js | nbrookie/react-particles-webgl | 0d6bb36cab5ce4540822bc958f64c289c289c5b2 | [
"MIT"
] | 407 | 2019-03-24T08:59:15.000Z | 2022-03-31T17:25:22.000Z | example/src/components/index.js | ad044/react-particles-webgl | d757b73eaf08b42333f726e1f339b41b890bd005 | [
"MIT"
] | 14 | 2019-03-25T23:15:18.000Z | 2022-02-26T10:12:03.000Z | example/src/components/index.js | flyskywhy/react-native-particles-webgl | 8e53a0478af0c1fa0b28bd2ab7a42ec22317405a | [
"MIT"
] | 36 | 2019-03-24T17:05:31.000Z | 2022-03-07T08:43:28.000Z | import DatUI from './DatUI';
import PerformanceStats from './PerformanceStats';
export { DatUI, PerformanceStats };
| 23.4 | 50 | 0.760684 |
3c26dae5bfc5295b1907028240e596757bc280cc | 786 | js | JavaScript | src/reducers/baseReducer.js | mubashirhanif/smart-matching-client | 6303490fba49f2ce0ebbb3113abc6a0716fb067a | [
"MIT"
] | null | null | null | src/reducers/baseReducer.js | mubashirhanif/smart-matching-client | 6303490fba49f2ce0ebbb3113abc6a0716fb067a | [
"MIT"
] | null | null | null | src/reducers/baseReducer.js | mubashirhanif/smart-matching-client | 6303490fba49f2ce0ebbb3113abc6a0716fb067a | [
"MIT"
] | null | null | null | const initState = {
user: null,
theme: "light",
isLoggedIn: false,
notificationHandler: null,
};
const baseReducer = (state = initState, action) => {
switch (action.type) {
case "setApiUrl":
return {
...state,
url: action.url,
};
case "setTheme":
return {
...state,
theme: action.theme,
};
case "setUser":
return {
...state,
user: action.user,
};
case "setIsLoggedIn":
return {
...state,
isLoggedIn: action.isLoggedIn,
};
case "setNotificationHandler":
return {
...state,
notificationHandler: action.notificationHandler,
};
default:
return state;
}
};
export default baseReducer;
| 19.170732 | 58 | 0.521628 |
3c2744da0f6d481effc97e950c9750855c74ff67 | 4,110 | js | JavaScript | lib/client/Usage.js | demmojo/ethstats-cli | 6d45ce02e10ba5e77d6b360a3732a457d5d7ab27 | [
"MIT"
] | 39 | 2018-11-28T22:18:06.000Z | 2021-07-07T02:44:04.000Z | lib/client/Usage.js | demmojo/ethstats-cli | 6d45ce02e10ba5e77d6b360a3732a457d5d7ab27 | [
"MIT"
] | 16 | 2019-02-22T19:54:33.000Z | 2022-02-12T10:00:43.000Z | lib/client/Usage.js | d3vk0n/funcoin-cli | 1e95d43c364fc25c8df88f1d19252c88e7a374a8 | [
"MIT"
] | 18 | 2018-12-04T14:31:15.000Z | 2022-02-10T23:13:33.000Z | export default class Usage {
constructor(diContainer) {
this.log = diContainer.logger;
this.systemInfo = diContainer.systemInfo;
this.errorHandler = diContainer.clientErrorHandler;
this.server = diContainer.server;
this.nodeProcessName = null;
}
getCpuLoad() {
let result = 0;
return this.systemInfo.currentLoad().then(data => {
if (data) {
result = data.currentload;
}
return result;
}).catch(error => {
this.log.error(this.errorHandler.resolve(error));
return result;
});
}
getMemLoad() {
let result = {
memTotal: 0,
memUsed: 0
};
return this.systemInfo.mem().then(data => {
if (data) {
result.memTotal = data.total;
result.memUsed = data.used;
}
return result;
}).catch(error => {
this.log.error(this.errorHandler.resolve(error));
return result;
});
}
async getNetworkStats() {
let result = {
rxSec: 0,
txSec: 0
};
let iface = await this.systemInfo.networkInterfaceDefault();
return this.systemInfo.networkStats(iface).then(data => {
if (data) {
result.rxSec = data[0].rx_sec;
result.txSec = data[0].tx_sec;
}
return result;
}).catch(error => {
this.log.error(this.errorHandler.resolve(error));
return result;
});
}
getFileSystemStats() {
let result = {
rxSec: 0,
wxSec: 0
};
return this.systemInfo.fsStats().then(data => {
if (data) {
result.rxSec = data.rx_sec;
result.wxSec = data.wx_sec;
}
return result;
}).catch(error => {
this.log.error(this.errorHandler.resolve(error));
return result;
});
}
getDiskIO() {
let result = {
rIOSec: 0,
wIOSec: 0
};
return this.systemInfo.disksIO().then(data => {
if (data) {
result.rIOSec = data.rIO_sec;
result.wIOSec = data.wIO_sec;
}
return result;
}).catch(error => {
this.log.error(this.errorHandler.resolve(error));
return result;
});
}
getProcessLoad(processName) {
let result = {
cpu: 0,
mem: 0
};
return this.systemInfo.processLoad(processName).then(data => {
if (data) {
result.cpu = data.cpu;
result.mem = data.mem;
}
return result;
}).catch(error => {
this.log.error(this.errorHandler.resolve(error));
return result;
});
}
setNodeProcessName(node) {
if (node) {
this.nodeProcessName = node.split('/')[0].toLowerCase();
}
}
async getStats() {
this.log.debug('Get usage');
let result = {
hostCpuLoad: await this.getCpuLoad(),
hostMemTotal: 0,
hostMemUsed: 0,
hostNetRxSec: 0,
hostNetTxSec: 0,
hostFsRxSec: 0,
hostFsWxSec: 0,
hostDiskRIOSec: 0,
hostDiskWIOSec: 0,
nodeCpuLoad: 0,
nodeMemLoad: 0,
clientCpuLoad: 0,
clientMemLoad: 0
};
let memLoad = await this.getMemLoad();
result.hostMemTotal = memLoad.memTotal;
result.hostMemUsed = memLoad.memUsed;
let networkStats = await this.getNetworkStats();
result.hostNetRxSec = networkStats.rxSec < 0 ? 0 : networkStats.rxSec;
result.hostNetTxSec = networkStats.txSec < 0 ? 0 : networkStats.txSec;
let fsStats = await this.getFileSystemStats();
result.hostFsRxSec = fsStats.rxSec < 0 ? 0 : fsStats.rxSec;
result.hostFsWxSec = fsStats.wxSec < 0 ? 0 : fsStats.wxSec;
let diskIO = await this.getDiskIO();
result.hostDiskRIOSec = diskIO.rIOSec < 0 ? 0 : diskIO.rIOSec;
result.hostDiskWIOSec = diskIO.wIOSec < 0 ? 0 : diskIO.wIOSec;
if (this.nodeProcessName) {
let nodeLoad = await this.getProcessLoad(this.nodeProcessName);
result.nodeCpuLoad = nodeLoad.cpu;
result.nodeMemLoad = nodeLoad.mem;
}
let clientLoad = await this.getProcessLoad('ethstats-cli');
result.clientCpuLoad = clientLoad.cpu;
result.clientMemLoad = clientLoad.mem;
this.server.send('usage', result);
return result;
}
}
| 23.089888 | 74 | 0.59854 |
3c2770640f02ab7437a38c654cedccde3b8972ad | 1,341 | js | JavaScript | scripts/check_data.js | breeze-foundation/breeze | d4074fe2e38c074059a33bf6b73ac029de1a5881 | [
"MIT"
] | null | null | null | scripts/check_data.js | breeze-foundation/breeze | d4074fe2e38c074059a33bf6b73ac029de1a5881 | [
"MIT"
] | 1 | 2022-03-02T03:02:00.000Z | 2022-03-02T03:02:00.000Z | scripts/check_data.js | breeze-foundation/breeze | d4074fe2e38c074059a33bf6b73ac029de1a5881 | [
"MIT"
] | 1 | 2022-02-11T07:11:46.000Z | 2022-02-11T07:11:46.000Z | const https = require('https')
const http = require('http')
let apis = [
'http://localhost:3001',
'https://api.breezechain.org',
'https://api.breezescan.io',
]
let witnesses = [
'breeze', 'zurich'
]
let results = []
let finished = 0
for (let y = 0; y < witnesses.length; y++) {
results.push(Array(apis.length))
for (let i = 0; i < apis.length; i++) {
let protocol = http
if (apis[i].indexOf('https://') === 0)
protocol = https
protocol.get(apis[i]+'/account/'+witnesses[y], (resp) => {
let data = ''
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
finished++
results[y][i] = JSON.parse(data).balance%100
if (finished === apis.length * witnesses.length) {
for (let r = 0; r < results.length; r++) {
console.log('\n\n'+witnesses[r])
console.log(results[r])
}
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
}
| 27.367347 | 74 | 0.445936 |
3c27a837c5500b8deb47d3416e8eac4bce1f8632 | 1,670 | js | JavaScript | frameworks/non-keyed/simi/build.js | andyhasit/js-framework-benchmark | 0d8fe1859d57a0ea96766b40d1272b07eee2d329 | [
"Apache-2.0"
] | 4,579 | 2016-01-27T10:27:34.000Z | 2022-03-31T19:01:15.000Z | frameworks/non-keyed/simi/build.js | andyhasit/js-framework-benchmark | 0d8fe1859d57a0ea96766b40d1272b07eee2d329 | [
"Apache-2.0"
] | 936 | 2016-01-27T12:15:44.000Z | 2022-03-31T04:21:04.000Z | frameworks/non-keyed/simi/build.js | andyhasit/js-framework-benchmark | 0d8fe1859d57a0ea96766b40d1272b07eee2d329 | [
"Apache-2.0"
] | 799 | 2016-01-28T14:47:56.000Z | 2022-03-30T23:16:20.000Z | (async () => {
const spawnSync = require('child_process').spawnSync
function spawnSyncOrThrow() {
const result = spawnSync(...arguments)
if (result.error) {
throw result.error
} else if (result.status !== 0) {
const args = Array.from(arguments)
throw new Error(args[0] + ' ' + args[1].join(' ') + ': exit status=' + result.status)
}
return result
}
if (spawnSync('rustup', ['--version'], { stdio: 'inherit' }).status !== 0) {
throw new Error('The build process for this framework is intended for a Rust user (via rustup).' +
'If you want to install Rust, visit https://www.rust-lang.org/.' +
'Otherwise, you can run the benchmark with the provided `.js` and `.wasm` files.' +
'(Note that other dependencies (require by this framework) will be installed automatically by "npm run build-prod-force")')
}
spawnSyncOrThrow('rustup', ['toolchain', 'install', 'nightly'], { stdio: 'inherit' })
spawnSyncOrThrow('rustup', ['target', 'add', 'wasm32-unknown-unknown', '--toolchain', 'nightly'], { stdio: 'inherit' })
if (spawnSync('wasm-bindgen', ['--version'], { stdio: 'inherit' }).status !== 0) {
spawnSyncOrThrow('cargo', ['install', 'wasm-bindgen-cli', '--version', '0.2.29'], { stdio: 'inherit' })
}
if (spawnSync('simi', ['--version'], { stdio: 'inherit' }).status !== 0) {
spawnSyncOrThrow('cargo', ['install', 'simi-cli'], { stdio: 'inherit' })
}
const build_mode = process.argv[2]
spawnSyncOrThrow('simi', ['build', build_mode], { stdio: 'inherit' })
})().catch(console.dir)
| 46.388889 | 135 | 0.588623 |
3c29839a0167636daad740f3ba846d9c4167ce40 | 576 | js | JavaScript | src/utils/API.js | tjvig94/employeedirectory | affffc9596e46ad6f6c51b2ef09546b86fdf4190 | [
"Unlicense",
"MIT"
] | 1 | 2021-05-03T01:38:51.000Z | 2021-05-03T01:38:51.000Z | src/utils/API.js | tjvig94/employeedirectory | affffc9596e46ad6f6c51b2ef09546b86fdf4190 | [
"Unlicense",
"MIT"
] | null | null | null | src/utils/API.js | tjvig94/employeedirectory | affffc9596e46ad6f6c51b2ef09546b86fdf4190 | [
"Unlicense",
"MIT"
] | null | null | null | /* eslint-disable import/no-anonymous-default-export */
import axios from 'axios'
async function getUsers() {
return await axios.get('https://randomuser.me/api/?results=30&inc=name,email,phone,picture').then(res => {
const users = res.data.results;
return users.map(user => {
return {
first: user.name.first,
last: user.name.last,
email: user.email,
phone: user.phone,
image: user.picture.thumbnail
}
})
})
}
export default getUsers;
| 27.428571 | 110 | 0.553819 |
3c2b53717480ba7adda1d6613265a82c515bac38 | 327 | js | JavaScript | local_modules/page-config/browser.js | glintcms/glintcms-starter-cannesbanannes | 1c5db58d200a13da83c40b87fe12990312a16bbf | [
"MIT"
] | null | null | null | local_modules/page-config/browser.js | glintcms/glintcms-starter-cannesbanannes | 1c5db58d200a13da83c40b87fe12990312a16bbf | [
"MIT"
] | null | null | null | local_modules/page-config/browser.js | glintcms/glintcms-starter-cannesbanannes | 1c5db58d200a13da83c40b87fe12990312a16bbf | [
"MIT"
] | null | null | null | var debug = require('debug')('page-config');
var defaults = require('defaults');
var c = require('./config');
module.exports = function config(o) {
o = defaults(o, context.options || {});
o = defaults(o, c);
Object.defineProperty(window, 'options', {
get: function() {
return o;
}
});
return o;
};
| 17.210526 | 44 | 0.593272 |
3c2ce7d572f86e90a5bb1e2ce726bbf7d8e52a27 | 826 | js | JavaScript | backend/validation/events.js | matt2yu/home_court | 29876a2fbeadf2cf9eaf5e4566c1747c2e56c463 | [
"MIT"
] | 2 | 2021-06-13T22:54:01.000Z | 2021-06-21T16:21:06.000Z | backend/validation/events.js | matt2yu/home_court | 29876a2fbeadf2cf9eaf5e4566c1747c2e56c463 | [
"MIT"
] | null | null | null | backend/validation/events.js | matt2yu/home_court | 29876a2fbeadf2cf9eaf5e4566c1747c2e56c463 | [
"MIT"
] | 1 | 2021-07-07T04:44:18.000Z | 2021-07-07T04:44:18.000Z | const Validator = require('validator');
const validText = require('./valid-text');
module.exports = function validateEventInput(data) {
let errors = {};
data.title = validText(data.title) ? data.title : '';
data.description = validText(data.description) ? data.description : '';
if (!Validator.isLength(data.title, { min: 5, max: 50 })) {
errors.title = 'Title must be between 5 and 50 characters';
}
if (Validator.isEmpty(data.title)) {
errors.title = 'Text field is required';
}
if (!Validator.isLength(data.description, { min: 5, max: 140 })) {
errors.title = 'Description must be between 5 and 140 characters';
}
if (Validator.isEmpty(data.description)) {
errors.title = 'Text field is required';
}
return {
errors,
isValid: Object.keys(errors).length === 0
};
}; | 27.533333 | 73 | 0.656174 |
3c2e65f0e13648656cfb5ae0b9a32cf17c4fcc80 | 260 | js | JavaScript | node_modules/@patternfly/react-tokens/dist/esm/c_search_input__text_before_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | fa565d0dddd5310ed3eb7c31bff4abee870bf266 | [
"MIT"
] | null | null | null | node_modules/@patternfly/react-tokens/dist/esm/c_search_input__text_before_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | fa565d0dddd5310ed3eb7c31bff4abee870bf266 | [
"MIT"
] | 5 | 2021-08-31T22:44:01.000Z | 2022-02-27T12:47:44.000Z | node_modules/@patternfly/react-tokens/dist/esm/c_search_input__text_before_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | fa565d0dddd5310ed3eb7c31bff4abee870bf266 | [
"MIT"
] | 1 | 2021-08-22T16:13:36.000Z | 2021-08-22T16:13:36.000Z | export const c_search_input__text_before_BorderColor = {
"name": "--pf-c-search-input__text--before--BorderColor",
"value": "#f0f0f0",
"var": "var(--pf-c-search-input__text--before--BorderColor)"
};
export default c_search_input__text_before_BorderColor; | 43.333333 | 62 | 0.757692 |
3c30d95d8456029fff71a1c5ffad44bd962bcd18 | 1,331 | js | JavaScript | src/command/commands.js | chenchenalex/javascript-patterns | 83d7dc1c055b73bfb39ae2ecec7d7ab1f0848062 | [
"MIT"
] | null | null | null | src/command/commands.js | chenchenalex/javascript-patterns | 83d7dc1c055b73bfb39ae2ecec7d7ab1f0848062 | [
"MIT"
] | null | null | null | src/command/commands.js | chenchenalex/javascript-patterns | 83d7dc1c055b73bfb39ae2ecec7d7ab1f0848062 | [
"MIT"
] | null | null | null | // The base command class defines the common interface for all
import editor from "./editor";
import App from "./app";
// concrete commands.
class BaseCommand {
backup: "";
constructor(editor, app) {
this.editor = editor;
this.app = app;
}
undo() {
this.editor.state = history.pop();
}
saveBackup() {
this.backup = this.editor.state;
}
execute() {}
}
class copyCommand extends BaseCommand {
execute = () => {
App.clipboard = this.editor.getSelection();
this.editor.deleteSelection();
};
}
class pasteCommand extends BaseCommand {
execute = () => {
this.saveBackup();
const selection = editor.getSelection();
editor.replaceSelection(App.clipboard);
};
}
class undoCommand extends BaseCommand {
execute() {
this.app.undo();
}
}
class CutCommand extends Command {
// The cut command does change the editor's state, therefore
// it must be saved to the history. And it'll be saved as
// long as the method returns true.
execute() {
this.saveBackup();
this.app.clipboard = this.editor.getSelection();
this.editor.deleteSelection();
}
}
export const copy = new copyCommand(editor, App);
export const paste = new pasteCommand(editor, App);
export const undo = new undoCommand(editor, App);
export const undo = new undoCommand(editor, App);
| 22.559322 | 62 | 0.674681 |
3c30e89adee2b7c03530818aed40584cd8a4bf98 | 3,180 | js | JavaScript | modules/download_extra/download.render.js | yujun2013/electron-demo | ab20b5704848bdf1092bcb9a15588fd935da4327 | [
"MIT"
] | null | null | null | modules/download_extra/download.render.js | yujun2013/electron-demo | ab20b5704848bdf1092bcb9a15588fd935da4327 | [
"MIT"
] | 1 | 2019-12-10T04:01:07.000Z | 2019-12-10T04:01:07.000Z | modules/download_extra/download.render.js | yujun2013/electron-demo | ab20b5704848bdf1092bcb9a15588fd935da4327 | [
"MIT"
] | null | null | null | /*
https://electron.atom.io/docs/api/ipc-main/
*/
const {ipcRenderer, remote, dialog} = require('electron')
const request = require('request')
const fs = require('fs')
const path = require('path')
const url = require("url");
let downloadListener = {}
let app = remote.app
//暴露方法给页面dom注册调用
var showSaveDialog = (file_url , target_path, messageId, callback) => {
ipcRenderer.send('show-save-dialog', file_url , target_path, messageId)
window.RongDesktop.downloadCallback[messageId] = callback;
}
ipcRenderer.on('beginDownload', (event, file_url , target_path, messageId) => {
var callback = window.RongDesktop.downloadCallback[messageId];
downloadFile(file_url , target_path, messageId, callback)
delete window.RongDesktop.downloadCallback[messageId]
})
var downloadFile = (file_url , target_path, messageId, callback) => {
var received_bytes = 0;
var total_bytes = 0;
var req = request({
method: 'GET',
uri: file_url
});
downloadListener[messageId] = req || [];
var out = fs.createWriteStream(target_path);
req.pipe(out);
var params = {
state: '',
messageId: '',
receivedBytes: '',
totalBytes: '',
targetPath: ''
};
req.on('response', function ( data ) {
params = {
state: 'preDownload',
messageId: messageId,
receivedBytes: 0,
totalBytes: total_bytes,
targetPath: target_path
};
received_bytes = 0;
total_bytes = parseInt(data.headers['content-length' ]);
callback(params);
});
req.on('data', function(chunk) {
// console.log(chunk.length);
received_bytes += chunk.length;
params = {
state: 'downloading',
messageId: messageId,
receivedBytes: received_bytes,
totalBytes: total_bytes,
targetPath: target_path
};
// mainWindow.webContents.send('onDownload', params)
callback(params);
});
req.on('end', function() {
params = {
state: 'downloaded',
messageId: messageId,
receivedBytes: received_bytes,
totalBytes: total_bytes,
targetPath: target_path
};
callback(params);
});
req.on('error', function(error) {
console.log('error', error.status);
params = {
state: 'downloadError',
messageId: messageId,
receivedBytes: received_bytes,
totalBytes: total_bytes,
targetPath: target_path,
error: error
};
callback(params);
// logger.error(error);
});
};
function pause (id) {
var curRequest = downloadListener[id]
if(curRequest){
curRequest.pause()
}
}
function resume (id) {
var curRequest = downloadListener[id]
if(curRequest){
curRequest.resume()
}
}
function cancel (id) {
var curRequest = downloadListener[id]
if(curRequest){
curRequest.abort()
}
}
module.exports = {
download: showSaveDialog,
pause: pause,
resume: resume,
cancel: cancel
}
| 26.065574 | 79 | 0.588994 |
3c30ee1de8455adc858bd196cd74d19f3dc5c20c | 1,516 | js | JavaScript | app/components/TakePhoto.js | vishenkov/photo-tv | e215a9f7427486af5cf177f0673b36efa397eb9a | [
"MIT"
] | null | null | null | app/components/TakePhoto.js | vishenkov/photo-tv | e215a9f7427486af5cf177f0673b36efa397eb9a | [
"MIT"
] | null | null | null | app/components/TakePhoto.js | vishenkov/photo-tv | e215a9f7427486af5cf177f0673b36efa397eb9a | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import Button from 'material-ui/Button';
import CameraIcon from 'material-ui-icons/PhotoCamera';
import styles from './TakePhoto.css';
export default class TakePhoto extends Component {
componentDidMount() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
this.video.src = window.URL.createObjectURL(stream);
this.video.play();
return stream;
})
.catch((err) =>
console.error(err));
}
}
handlePhoto = event => {
const context = this.canvas.getContext('2d');
event.preventDefault();
this.canvas.width = 640;
this.canvas.height = 480;
context.drawImage(this.video, 0, 0, 640, 480);
const data = this.canvas.toDataURL();
// console.log(data);
this.props.handleTakePhoto(data);
}
render() {
return (
<div className={styles.container}>
<video
className={styles.video}
autoPlay
ref={video => { this.video = video; }}
>
<track kind="captions" label="Camera" />
</video>
<canvas
style={{ display: 'none' }}
ref={canvas => { this.canvas = canvas; }}
/>
<div className={styles.photoButton}>
<Button variant="fab" color="primary" onClick={this.handlePhoto}>
<CameraIcon />
</Button>
</div>
</div>);
}
}
| 28.074074 | 75 | 0.578496 |
3c32928190c9df6f5df0721699bb084609ecb9ea | 1,501 | js | JavaScript | src/components/search.js | RadGade/minutes | 18e83848361b2fd2c9c48c50a225b6972d4e84d3 | [
"MIT"
] | null | null | null | src/components/search.js | RadGade/minutes | 18e83848361b2fd2c9c48c50a225b6972d4e84d3 | [
"MIT"
] | 4 | 2020-07-18T21:51:39.000Z | 2021-05-10T20:05:58.000Z | src/components/search.js | RadGade/minutes | 18e83848361b2fd2c9c48c50a225b6972d4e84d3 | [
"MIT"
] | null | null | null | import React, { useState } from 'react'
import TextField from '@material-ui/core/TextField';
import { useStyles } from './css/login-css'
const Gun = require('gun');
const SEA = require('gun/sea');
var gun = Gun();
export const Search = () => {
const classes = useStyles();
const [uid, setUid] = useState([])
return (
<div>
<TextField
id="search"
label="Search field"
type="search"
onKeyPress = {(event) => {
if (event.key === 'Enter') {
var name = "~@" + document.getElementById('search').value
gun.get(name).once((data, key)=>{setUid()});
console.log(uid)
}
}}
classes={{
root: classes.search
}}
margin="normal"
/>
</div>
)
}
// const classes = useStyles();
// return (
// <div>
// <TextField
// id="search"
// label="Search field"
// type="search"
// classes={{
// root: classes.search
// }}
// margin="normal"
// />
// <Button onClick={find}> Find</Button>
// </div>
// )
// }
// function find () {
// var name = "~@" + document.getElementById('search').value
// gun.get(name).once((data, key)=>{console.log(data)});
// } | 22.073529 | 73 | 0.423051 |
3c32978c1578332cd782ed23513ecfe9071be4b5 | 59 | js | JavaScript | app/src/pages/common/settingsPage/patternAnalysisTab/modals/renamePatternModal/index.js | waynesun09/service-ui | 0030542c8d2b622e87cee851ecbb2964a8f2d563 | [
"Apache-2.0"
] | null | null | null | app/src/pages/common/settingsPage/patternAnalysisTab/modals/renamePatternModal/index.js | waynesun09/service-ui | 0030542c8d2b622e87cee851ecbb2964a8f2d563 | [
"Apache-2.0"
] | null | null | null | app/src/pages/common/settingsPage/patternAnalysisTab/modals/renamePatternModal/index.js | waynesun09/service-ui | 0030542c8d2b622e87cee851ecbb2964a8f2d563 | [
"Apache-2.0"
] | null | null | null | export { RenamePatternModal } from './renamePatternModal';
| 29.5 | 58 | 0.779661 |
3c334ac2dd76d4cce46b9cbc53f7f2746d4eb62a | 969 | js | JavaScript | frontend/components/Banner/FooterBanner/index.js | SydBal/redoot | c0d293555f4487dcfe99675892e8b9ec6d04f793 | [
"MIT"
] | 10 | 2017-12-04T19:27:08.000Z | 2019-12-13T18:11:41.000Z | frontend/components/Banner/FooterBanner/index.js | SydBal/redoot | c0d293555f4487dcfe99675892e8b9ec6d04f793 | [
"MIT"
] | null | null | null | frontend/components/Banner/FooterBanner/index.js | SydBal/redoot | c0d293555f4487dcfe99675892e8b9ec6d04f793 | [
"MIT"
] | null | null | null | import React from 'react';
import {connect} from 'react-redux';
class FooterBanner extends React.Component {
render() {
return (
<div className="banner container-fluid footer" id="stickyFooter">
<div className="container text-center text-white">
<img src="/img/redootLogoWhite.png" className="footLogo" alt="redoot"/>
<p>
Redoot is released under the MIT license.
</p>
<p>
Please feel free to use this as a tool to start your own React-Redux + Bootstrap website.
</p>
<p>
Good luck with your projects, and leave feedback on <a href="http://github.com/SydBal/redoot">GitHub!</a>
</p>
Sincerely - Dominic Balassone
</div>
</div>
);
}
}
export default connect()(FooterBanner) | 35.888889 | 129 | 0.509804 |
3c347a121597c76a41e6a11e76b4752e912d3fef | 9,837 | js | JavaScript | routes/documents.js | cristianradulescu/reimbursement-app | 922a8c89559f5b974aa9f724156b01257b19aa1e | [
"MIT"
] | null | null | null | routes/documents.js | cristianradulescu/reimbursement-app | 922a8c89559f5b974aa9f724156b01257b19aa1e | [
"MIT"
] | null | null | null | routes/documents.js | cristianradulescu/reimbursement-app | 922a8c89559f5b974aa9f724156b01257b19aa1e | [
"MIT"
] | null | null | null | const express = require('express');
const router = express.Router();
const moment = require('moment');
const models = require('../models');
const documentService = require('../services/documentService');
let getDocumentFormData = (document = undefined) => {
var formData = {};
return models.Employee
.findAll(
{
attributes: ['id', 'last_name', 'first_name'],
order: [['last_name', 'ASC'], ['first_name', 'ASC']]
}
)
.then(employees => {
formData.employees = employees;
})
.then(() => {
return models.DocumentType
.findAll()
.then(documentTypes => {
formData.documentTypes = documentTypes;
})
})
.then(() => {
return models.DocumentStatus
.findAll()
.then(documentStatuses => {
formData.documentStatuses = documentStatuses;
})
})
.then(() => {
return models.ReimbursementType
.findAll()
.then(reimbursementTypes => {
formData.reimbursementTypes = reimbursementTypes;
})
})
.then(() => {
return models.TravelPurpose
.findAll()
.then(travelPurposes => {
formData.travelPurposes = travelPurposes;
})
})
.then(() => {
return models.TravelDestination
.findAll()
.then(travelDestinations => {
formData.travelDestinations = travelDestinations;
})
})
.then(() => {
return formData;
})
};
let printTravelDocument = (res, document) => {
res.render(
'documents/print/travel',
{
layout: false,
PLACEHOLDER_COST_CENTER: document.employee.company.cost_center,
PLACEHOLDER_EMPLOYEE_NAME: document.employee.name,
PLACEHOLDER_EMPLOYEE_JOB_TITLE: document.employee.jobTitle.name,
PLACEHOLDER_TRAVEL_PURPOSE: document.travel.purpose.name,
PLACEHOLDER_TRAVEL_DESTINATION: document.travel.destination.name,
PLACEHOLDER_COMPANY_NAME: document.employee.company.name,
PLACEHOLDER_EMPLOYEE_ICN: document.employee.identity_card_number,
PLACEHOLDER_EMPLOYEE_PNC: document.employee.personal_numeric_code,
PLACEHOLDER_DATE_FROM: moment(document.travel.date_start).format('DD.MM.YYYY'),
PLACEHOLDER_DATE_TO: moment(document.travel.date_end).format('DD.MM.YYYY'),
PLACEHOLDER_DESTINATION_ARRIVAL_TIME: moment(document.travel.destination_arrival_time).format('DD.MM.YYYY HH:mm'),
PLACEHOLDER_DESTINATION_LEAVE_TIME: moment(document.travel.destination_leave_time).format('DD.MM.YYYY HH:mm'),
PLACEHOLDER_STARTPOINT_LEAVE_TIME: moment(document.travel.departure_leave_time).format('DD.MM.YYYY HH:mm'),
PLACEHOLDER_STARTPOINT_ARRIVAL_TIME: moment(document.travel.departure_arrival_time).format('DD.MM.YYYY HH:mm'),
PLACEHOLDER_MANAGER_LAST_NAME: document.employee.company.divisionManager.last_name,
PLACEHOLDER_MANAGER_FIRST_NAME: document.employee.company.divisionManager.first_name,
PLACEHOLDER_EMPLOYEE_LAST_NAME: document.employee.last_name,
PLACEHOLDER_EMPLOYEE_FIRST_NAME: document.employee.first_name,
PLACEHOLDER_TRAVEL_TOTAL_AMOUNT: document.travel.totalAmount,
PLACEHOLDER_DAYS_ON_TRAVEL: document.travel.period,
PLACEHOLDER_TRAVEL_ALLOWANCE: document.travel.travelAllowance
}
);
}
let printReimbursementDocument = (res, document) => {
res.render(
'documents/print/reimbursement',
{
layout: false,
PLACEHOLDER_COST_CENTER: document.employee.company.cost_center,
PLACEHOLDER_COMPANY_NAME: document.employee.company.name,
PLACEHOLDER_EMPLOYEE_NAME: document.employee.name,
PLACEHOLDER_EMPLOYEE_JOB_TITLE: document.employee.jobTitle.name,
PLACEHOLDER_MANAGER_LAST_NAME: document.employee.company.divisionManager.last_name,
PLACEHOLDER_MANAGER_FIRST_NAME: document.employee.company.divisionManager.first_name,
PLACEHOLDER_REIMBURSEMENT_TOTAL_AMOUNT: document.totalAmount,
reimbursements: document.reimbursements
}
);
}
/* GET documents listing. */
router.get('/', function(req, res, next) {
models.Document.findAll(
{
order: [['status_id', 'ASC'], ['updated_at', 'DESC']],
include: ['employee', 'status', 'type', 'reimbursements', 'travel']
}
)
.then(documents => {
res.render(
'documents/list',
{
title: 'Reimbursement | List documents',
documents: documents
}
);
})
});
router.get('/show/:documentId', function(req, res, next) {
documentService.getDocumentById(req.params.documentId)
.then(document => {
res.render(
'documents/show',
{
title: `Reimbursement | Show document #${document.id}`,
document: document
}
);
}).catch(err => {
res.render(
'error',
{
'message': 'Unable to display the requested document',
'error': err
}
);
})
});
router.get('/create', function(req, res, next) {
getDocumentFormData().then(formData => {
res.render(
'documents/create',
{
title: 'Reimbursement | Create new document',
formData
}
);
});
});
router.post('/create', function(req, res, next) {
var params = req.body;
models.sequelize.transaction(createDocumentTransaction => {
return documentService.createDocument(params['document'], createDocumentTransaction)
.then(document => {
switch (parseInt(params['document']['type_id'])) {
case models.DocumentType.build().travelTypeId:
console.log('Creating a new Travel document');
return documentService.createTravelDocument(document, params['travel'], createDocumentTransaction)
.then(travel => {
document.setTravel(travel);
return document;
});
case models.DocumentType.build().reimbursementTypeId:
console.log('Creating a new Reimbursement document');
return new Promise((resolve, reject) => {
params['reimbursement'].forEach(reimbursementParams => {
console.log(reimbursementParams);
documentService.createReimbursementDocument(document, reimbursementParams, createDocumentTransaction)
.then(reimbursement => {
document.addReimbursement(reimbursement);
});
});
resolve(document);
});
default:
throw 'Invalid document type';
}
});
})
.then(document => {
console.log('Transaction has been committed');
console.log('Added new document #'+document.id);
res.redirect('/documents/show/'+document.id);
})
.catch(err => {
console.log('Transaction has been rolled back');
res.render(
'error',
{
'message': 'Transaction has been rolled back',
'error': err
}
);
});
});
router.get('/edit/:documentId', function(req, res, next) {
documentService.getDocumentById(req.params.documentId)
.then(document => {
getDocumentFormData(document)
.then(formData => {
res.render(
'documents/edit',
{
title: `Reimbursement | Edit document #${document.id}`,
document,
formData
}
);
});
})
.catch(err => {
res.render(
'error',
{
'message': 'Unable to edit the requested document',
'error': err
}
);
});
});
router.post('/edit/:documentId', function(req, res, next) {
var params = req.body;
models.sequelize.transaction(editDocumentTransaction => {
return documentService.getDocumentById(req.params.documentId)
.then(document => {
return document.update(
{
employee_id: params['document']['employee_id'],
status_id: params['document']['status_id']
},
{
editDocumentTransaction
}
)
.then(document => {
if (document.isTravel) {
return documentService.updateTravelDocument(document.travel, params['travel'], editDocumentTransaction)
.then(travel => {
return document;
})
} else if (document.isReimbursement) {
return new Promise((resolve, reject) => {
document.reimbursements.forEach(reimbursement => {
var reimbursementParams = params.reimbursement[reimbursement.id];
documentService.updateReimbursementDocument(reimbursement, reimbursementParams, editDocumentTransaction)
});
resolve(document);
});
}
throw Error('Document type is invalid.');
});
});
})
.then(document => {
console.log('Transaction has been committed');
console.log('Updated document #'+document.id);
res.redirect('/documents/show/'+document.id);
}).catch(err => {
console.log('Transaction has been rolled back');
res.render(
'error',
{
'message': 'Transaction has been rolled back',
'error': err
}
);
});
});
router.get('/print/:documentId', function(req, res, next) {
documentService.getDocumentById(req.params.documentId)
.then(document => {
if (document.isTravel) {
printTravelDocument(res, document);
} else if (document.isReimbursement) {
printReimbursementDocument(res, document);
}
}).catch(err => {
res.render(
'error',
{
'message': 'Unable to display the requested document',
'error': err
}
);
})
});
module.exports = router;
| 31.834951 | 120 | 0.610959 |
3c356a668dac2e9c65f2e647e54cd6859b2681ee | 500 | js | JavaScript | WebExample/grails-app/assets/javascripts/controllers.js | amondel2/techtalk | 837d270549d0c0a5e32e26afdd7e328c1ddb82c6 | [
"MIT"
] | null | null | null | WebExample/grails-app/assets/javascripts/controllers.js | amondel2/techtalk | 837d270549d0c0a5e32e26afdd7e328c1ddb82c6 | [
"MIT"
] | null | null | null | WebExample/grails-app/assets/javascripts/controllers.js | amondel2/techtalk | 837d270549d0c0a5e32e26afdd7e328c1ddb82c6 | [
"MIT"
] | null | null | null | angular.module('myApp.controllers', []).controller('OrgController',['$scope', '$http', 'apiUrl', function($scope, $http, apiUrl) {
$scope.multipleOrgs = false;
$scope.changeOrgCount = function(newCount) {
$scope.orgCount = newCount;
$scope.multipleOrgs = newCount != 1;
};
$http.get(apiUrl + 'company').success(function(data, status, headers, config) {
$scope.companyName = data.name;
$scope.changeOrgCount(data.organizations.length);
});
}]); | 33.333333 | 131 | 0.636 |
3c367b9f7851e9f2fac30d36015e4b8815aee7ce | 4,647 | js | JavaScript | resources/js/components/_3_hiding-nav.js | mrsmith123/hproject2 | a4121f76a6f7feefa6a559269318a0bb227ead6b | [
"MIT"
] | 1 | 2020-05-07T15:52:37.000Z | 2020-05-07T15:52:37.000Z | resources/js/components/_3_hiding-nav.js | mrsmith123/hproject2 | a4121f76a6f7feefa6a559269318a0bb227ead6b | [
"MIT"
] | null | null | null | resources/js/components/_3_hiding-nav.js | mrsmith123/hproject2 | a4121f76a6f7feefa6a559269318a0bb227ead6b | [
"MIT"
] | null | null | null | // File#: _2_hiding-nav
// Usage: codyhouse.co/license
(function() {
var hidingNav = document.getElementsByClassName('js-hide-nav');
if(hidingNav.length > 0 && window.requestAnimationFrame) {
var mainNav = Array.prototype.filter.call(hidingNav, function(element) {
return Util.hasClass(element, 'js-hide-nav--main');
}),
subNav = Array.prototype.filter.call(hidingNav, function(element) {
return Util.hasClass(element, 'js-hide-nav--sub');
});
var scrolling = false,
previousTop = window.scrollY,
currentTop = window.scrollY,
scrollDelta = 10,
scrollOffset = 150, // scrollY needs to be bigger than scrollOffset to hide navigation
headerHeight = 0;
var navIsFixed = false; // check if main navigation is fixed
if(mainNav.length > 0 && Util.hasClass(mainNav[0], 'hide-nav--fixed')) navIsFixed = true;
// store button that triggers navigation on mobile
var triggerMobile = getTriggerMobileMenu();
// init navigation and listen to window scroll event
initSecondaryNav();
resetHideNav();
window.addEventListener('scroll', function(event){
if(scrolling) return;
scrolling = true;
window.requestAnimationFrame(resetHideNav);
});
window.addEventListener('resize', function(event){
if(scrolling) return;
scrolling = true;
window.requestAnimationFrame(function(){
if(headerHeight > 0 && subNav.length > 0) {
headerHeight = mainNav[0].offsetHeight;
subNav[0].style.top = headerHeight+'px';
}
// reset both navigation
hideNavScrollUp();
scrolling = false;
});
});
function initSecondaryNav() { // if there's a secondary nav, set its top equal to the header height
if(subNav.length < 1 || mainNav.length < 1) return;
headerHeight = mainNav[0].offsetHeight;
subNav[0].style.top = headerHeight+'px';
};
function resetHideNav() { // check if navs need to be hidden/revealed
currentTop = window.scrollY;
if(currentTop - previousTop > scrollDelta && currentTop > scrollOffset) {
hideNavScrollDown();
} else if( previousTop - currentTop > scrollDelta || (previousTop - currentTop > 0 && currentTop < scrollOffset) ) {
hideNavScrollUp();
} else if( previousTop - currentTop > 0 && subNav.length > 0 && subNav[0].getBoundingClientRect().top > 0) {
setTranslate(subNav[0], '0%');
}
// if primary nav is fixed -> toggle bg class
if(navIsFixed) {
var scrollTop = window.scrollY || window.pageYOffset;
Util.toggleClass(mainNav[0], 'hide-nav--has-bg', (scrollTop > headerHeight));
}
previousTop = currentTop;
scrolling = false;
};
function hideNavScrollDown() {
// if there's a secondary nav -> it has to reach the top before hiding nav
if( subNav.length > 0 && subNav[0].getBoundingClientRect().top > headerHeight) return;
// on mobile -> hide navigation only if dropdown is not open
if(triggerMobile && triggerMobile.getAttribute('aria-expanded') == "true") return;
if( mainNav.length > 0 ) {
setTranslate(mainNav[0], '-100%');
mainNav[0].addEventListener('transitionend', addOffCanvasClass);
}
if( subNav.length > 0 ) setTranslate(subNav[0], '-'+headerHeight+'px');
};
function hideNavScrollUp() {
if( mainNav.length > 0 ) {setTranslate(mainNav[0], '0%'); Util.removeClass(mainNav[0], 'hide-nav--off-canvas');mainNav[0].removeEventListener('transitionend', addOffCanvasClass);}
if( subNav.length > 0 ) setTranslate(subNav[0], '0%');
};
function addOffCanvasClass() {
mainNav[0].removeEventListener('transitionend', addOffCanvasClass);
Util.addClass(mainNav[0], 'hide-nav--off-canvas');
};
function setTranslate(element, val) {
element.style.transform = 'translateY('+val+')';
};
function getTriggerMobileMenu() {
// store trigger that toggle mobile navigation dropdown
var triggerMobileClass = hidingNav[0].getAttribute('data-mobile-trigger');
if(!triggerMobileClass) return false;
var trigger = hidingNav[0].getElementsByClassName(triggerMobileClass);
if(trigger.length > 0) return trigger[0];
return false;
};
} else {
// if window requestAnimationFrame is not supported -> add bg class to fixed header
var mainNav = document.getElementsByClassName('js-hide-nav--main');
if(mainNav.length < 1) return;
if(Util.hasClass(mainNav[0], 'hide-nav--fixed')) Util.addClass(mainNav[0], 'hide-nav--has-bg');
}
}()); | 40.060345 | 185 | 0.651173 |
3c369088ee58fb466ea644572dcf80eb5773e8aa | 720 | js | JavaScript | app/libs/Flurry Android SDK vAndroid SDK 5.5.0/Android 5.5.0/Flurry Android API Documentation/classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.js | jsho32/Conversion-Calculator_Android | 79b9f39399b2c77784d08ca9b688559b2f07571a | [
"Apache-2.0"
] | null | null | null | app/libs/Flurry Android SDK vAndroid SDK 5.5.0/Android 5.5.0/Flurry Android API Documentation/classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.js | jsho32/Conversion-Calculator_Android | 79b9f39399b2c77784d08ca9b688559b2f07571a | [
"Apache-2.0"
] | 35 | 2015-05-12T18:06:08.000Z | 2015-08-03T15:09:09.000Z | app/libs/Flurry Android SDK vAndroid SDK 5.5.0/Android 5.5.0/Flurry Android API Documentation/classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.js | jsho32/Conversion-Calculator_Android | 79b9f39399b2c77784d08ca9b688559b2f07571a | [
"Apache-2.0"
] | 1 | 2016-02-15T04:15:05.000Z | 2016-02-15T04:15:05.000Z | var classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset =
[
[ "getAssetView", "classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.html#ab6c0fa6d92176b83e3de90b3898410f1", null ],
[ "getName", "classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.html#a78ee178b6a73658d65ca60da4d1e6683", null ],
[ "getType", "classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.html#a7e660a2efdded00d76b07f0e20ba5c46", null ],
[ "getValue", "classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.html#a574b29843fb09dff2bf8edd82341f051", null ],
[ "loadAssetIntoView", "classcom_1_1flurry_1_1android_1_1ads_1_1FlurryAdNativeAsset.html#a616cfa7b719595ae74f66ead87f597b2", null ]
]; | 90 | 135 | 0.851389 |
3c3772643b875121b0b092fbce979a207cfb5e6f | 68 | js | JavaScript | env/reactdjangoreduxapp/frontend/src/index.js | leadsoftengineer/react-django-redux-app | 9ec5e643ed44719d3265f9f38b51733d1d0c05bf | [
"bzip2-1.0.6"
] | null | null | null | env/reactdjangoreduxapp/frontend/src/index.js | leadsoftengineer/react-django-redux-app | 9ec5e643ed44719d3265f9f38b51733d1d0c05bf | [
"bzip2-1.0.6"
] | null | null | null | env/reactdjangoreduxapp/frontend/src/index.js | leadsoftengineer/react-django-redux-app | 9ec5e643ed44719d3265f9f38b51733d1d0c05bf | [
"bzip2-1.0.6"
] | null | null | null | /**
* KYIV MEDIA 25.11.2019
*/
import App from './components/App';
| 13.6 | 35 | 0.632353 |
3c37f06af7461866f07aff5dc0b05ff84b046ebc | 3,663 | js | JavaScript | resources/js/components/house/reservations/ReservationDetails.js | kgoofori/project-stater | b6787966a2fd03cb4d8a8e8e7fe9b6f74cae889c | [
"MIT"
] | null | null | null | resources/js/components/house/reservations/ReservationDetails.js | kgoofori/project-stater | b6787966a2fd03cb4d8a8e8e7fe9b6f74cae889c | [
"MIT"
] | null | null | null | resources/js/components/house/reservations/ReservationDetails.js | kgoofori/project-stater | b6787966a2fd03cb4d8a8e8e7fe9b6f74cae889c | [
"MIT"
] | null | null | null | import FormErrors from "../../../libs/FormErrors";
export default {
props: {
reservationId: {
require: true,
type: String
},
rooms: {
type: Array
}
},
data() {
return {
newStatus: null,
processingForm: false,
payData: { amount: null, channel: null },
payErrors: new FormErrors
}
},
methods: {
confirmStatus(status){
this.newStatus = status;
this.$confirm(
`Are you sure you want to <strong>${this.statusString}</strong> this reservation?`,
"Warning",
{
dangerouslyUseHTMLString: true,
confirmButtonText: "Yes, I am sure",
cancelButtonText: "Cancel",
type: "warning",
}
).then(() => {
this.changeReservationStatus();
}).catch(()=> {});
},
changeReservationStatus() {
this.processingForm = true
axios
.patch(hotelUrl(`reservations/${this.reservationId}`), {
'status': this.newStatus,
})
.then(({ data }) => {
flash({ type: "success", message: data.message, onClose: () => {
window.location = hotelUrl(`reservations/${this.reservationId}`)
} });
})
.catch(({ response }) => {
flash(response.data);
this.processingForm = false;
$('.modal').modal('hide');
})
},
payReservation() {
this.processingForm = true
axios
.post(hotelUrl(`reservations/${this.reservationId}/pay`), this.payData)
.then(({ data }) => {
flash({ type: "success", message: data.message, onClose: () => {
window.location = hotelUrl(`reservations/${this.reservationId}`)
} });
})
.catch(({ response }) => {
flash(response.data);
this.processingForm = false;
})
},
printPaymentReceipt(id) {
let mywindow = window.open(hotelUrl(`payments/${id}/receipt`),
"PRINT",
"height=500,width=800"
);
mywindow.addEventListener("load", function () {
mywindow.print();
setTimeout(() => {
mywindow.close();
}, 500);
});
},
printDivInvoice() {
let head = document.getElementsByTagName('head')[0].innerHTML;;
let mywindow = window.open('', 'PRINT', 'height=500,width=800');
mywindow.document.write(head);
mywindow.document.write($('#ivoice-card').html());
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.addEventListener('load', function () {
mywindow.print();
setTimeout(() => {
mywindow.close();
}, 300);
});
}
},
computed: {
statusString() {
if (this.newStatus == null) return '';
if (this.newStatus == 'CLOSED') return 'close';
return this.newStatus.replace('ED', '').toLowerCase()
}
}
} | 30.02459 | 100 | 0.424788 |
3c382405beef14446f6e5e60bc602a3c4ca4a868 | 1,978 | js | JavaScript | lib/model/streams.js | Ireisme/nTweetStreamer | f376dfde03d28b05bd7e57e30d41d7e4d4b4e6e8 | [
"MIT"
] | 1 | 2015-01-05T23:11:08.000Z | 2015-01-05T23:11:08.000Z | lib/model/streams.js | Ireisme/nTweetStreamer | f376dfde03d28b05bd7e57e30d41d7e4d4b4e6e8 | [
"MIT"
] | null | null | null | lib/model/streams.js | Ireisme/nTweetStreamer | f376dfde03d28b05bd7e57e30d41d7e4d4b4e6e8 | [
"MIT"
] | null | null | null | var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var mongoUri;
fs.readFile('./config/config.json', function(err, data){
if(err)
{
console.log("Error Loading MongoConfig:" + err);
return;
}
mongoUri = JSON.parse(data).mongoUri;
});
var streamModel = {};
//Save streams
streamModel.saveStream = function(stream, callback){
MongoClient.connect(mongoUri, function(err, db)
{
if(err) { return console.log(err); }
var collection = db.collection('streams');
collection.save(stream, function(error, result){
db.close();
});
if(callback)
callback(stream);
});
};
//Get All Streams
streamModel.getAllStreams = function(callback){
MongoClient.connect(mongoUri, function(err, db)
{
if(err) { return console.log(err); }
var collection = db.collection('streams');
collection.find().toArray(function(err, results){
if(callback)
callback(results);
db.close();
});
});
};
//Tweets for a Stream
streamModel.getTweetCount = function(id, callback){
MongoClient.connect(mongoUri, function(err, db)
{
if(err) { return console.log(err); }
var collection = db.collection(id);
collection.count(function(err, count){
if(callback)
callback(count);
db.close();
});
});
};
//Find Streams
streamModel.findStream = function(id, callback){
MongoClient.connect(mongoUri, function(err, db) {
if(err) { return console.log(err); }
var collection = db.collection('streams');
collection.findOne({ _id: id }, function(err, item){
if(callback)
callback(item);
db.close();
});
});
};
//Delete Streams
streamModel.deleteStream = function(id, callback){
MongoClient.connect(mongoUri, function(err, db) {
if(err) { return console.log(err); }
var streams = db.collection('streams');
streams.remove( {_id: id}, function(err, result){});
var collection = db.collection(id);
collection.drop();
if(callback)
callback("Ok");
db.close();
});
};
module.exports = streamModel;
| 19.979798 | 56 | 0.670374 |
3c3b59163a4f54b9b6c96ba733b1c3957aa84937 | 766 | js | JavaScript | cli/env.js | jchip/xarc-run | 7017fe908d77b93b2326bb01d8f9fbf898460246 | [
"Apache-2.0"
] | 32 | 2017-06-07T19:53:53.000Z | 2019-07-29T08:34:56.000Z | cli/env.js | jchip/xarc-run | 7017fe908d77b93b2326bb01d8f9fbf898460246 | [
"Apache-2.0"
] | 12 | 2017-08-21T17:51:55.000Z | 2019-04-18T19:40:54.000Z | cli/env.js | jchip/xarc-run | 7017fe908d77b93b2326bb01d8f9fbf898460246 | [
"Apache-2.0"
] | 2 | 2018-02-07T22:22:46.000Z | 2018-04-04T22:44:02.000Z | "use strict";
const assert = require("assert");
const lib = {
container: process.env,
xrunTaskFile: "XRUN_TASKFILE",
xrunPackagePath: "XRUN_PACKAGE_PATH",
xrunId: "XRUN_ID",
forceColor: "FORCE_COLOR",
xrunCwd: "XRUN_CWD",
xrunVersion: "XRUN_VERSION",
xrunBinDir: "XRUN_BIN_DIR",
xrunNodeBin: "XRUN_NODE_BIN",
get(key) {
assert(key, `env.get invalid key: ${key}`);
return lib.container[key];
},
set(key, val) {
assert(key, `env.set invalid key: ${key}`);
lib.container[key] = `${val}`;
},
has(key) {
assert(key, `env.has invalid key: ${key}`);
return lib.container.hasOwnProperty(key);
},
del(key) {
assert(key, `env.del invalid key: ${key}`);
delete lib.container[key];
}
};
module.exports = lib;
| 22.529412 | 47 | 0.633159 |
3c3b691ebfbfa3fd475daa4e6655c85bd45e14f2 | 715 | js | JavaScript | src/pages/index.js | monkeez/coote.games | 9ef77bf163a26f84099430bb6c1ee0b7b6d5a774 | [
"RSA-MD"
] | null | null | null | src/pages/index.js | monkeez/coote.games | 9ef77bf163a26f84099430bb6c1ee0b7b6d5a774 | [
"RSA-MD"
] | null | null | null | src/pages/index.js | monkeez/coote.games | 9ef77bf163a26f84099430bb6c1ee0b7b6d5a774 | [
"RSA-MD"
] | null | null | null | import * as React from "react"
import { graphql, Link } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"
import Layout from "../components/layout"
import Seo from "../components/seo"
const IndexPage = ({ data }) => (
<Layout>
<Seo title="Home" />
{
data.allItchioGame.nodes.map((node) => (
<article key={node.title}>
<h2>{node.title}</h2>
<a href={node.url}><img src={node.cover_url} alt="Alt text"></img></a>
<hr></hr>
</article>
))
}
</Layout>
)
export const query = graphql`
query {
allItchioGame(limit: 10) {
nodes {
title
url
cover_url
}
}
}
`
export default IndexPage
| 19.861111 | 80 | 0.553846 |
3c3c6870779476f46550389565a64447ab29ec3e | 1,001 | js | JavaScript | src/graphql/types/scheduled-ride/resolver.js | MarkNjunge/Unipool-backend | bc0a4c5384a45c75c048fc8cf701a42318c06f46 | [
"MIT"
] | 3 | 2019-03-31T13:47:20.000Z | 2019-07-21T06:42:33.000Z | src/graphql/types/scheduled-ride/resolver.js | MarkNjunge/Unipool-backend | bc0a4c5384a45c75c048fc8cf701a42318c06f46 | [
"MIT"
] | null | null | null | src/graphql/types/scheduled-ride/resolver.js | MarkNjunge/Unipool-backend | bc0a4c5384a45c75c048fc8cf701a42318c06f46 | [
"MIT"
] | null | null | null | const { ScheduledRide, User } = require('../../../database/models')
const resolvers = {
Query: {
getAllScheduledRides(_, args) {
return ScheduledRide.getAll()
},
getScheduledRidesForUser(_, args) {
return ScheduledRide.getForUser(args.userId)
},
getScheduledRideById(_, args) {
return ScheduledRide.getById(args.rideId)
}
},
Mutation: {
addScheduledRide(_, args) {
return ScheduledRide.add(args)
},
deleteScheduledRide(_, args) {
return ScheduledRide.delete(args.rideId)
},
setScheduledRideDriver(_, args) {
return ScheduledRide.setDriver(args.rideId, args.driverId)
}
},
ScheduledRide: {
user(scheduledRide) {
return User.find(scheduledRide.userId)
},
driver(scheduledRide) {
return User.find(scheduledRide.driverId)
}
}
}
module.exports = resolvers
| 27.054054 | 70 | 0.57043 |
3c3cdf767fb13ad88f5f370419d003e58b7132ef | 2,174 | js | JavaScript | src/components/SongKeyDialog.js | justinlawrence/ChordBoard | 4cee6b069569717fc04a40084edd5e310d16d41b | [
"Apache-2.0"
] | 2 | 2017-08-17T08:48:43.000Z | 2018-07-30T02:31:34.000Z | src/components/SongKeyDialog.js | justinlawrence/ChordBoard | 4cee6b069569717fc04a40084edd5e310d16d41b | [
"Apache-2.0"
] | 2 | 2022-02-15T01:19:51.000Z | 2022-02-27T23:33:15.000Z | src/components/SongKeyDialog.js | justinlawrence/ChordBoard | 4cee6b069569717fc04a40084edd5e310d16d41b | [
"Apache-2.0"
] | null | null | null | import React from 'react'
import { useAtom } from 'jotai'
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
Switch,
Typography,
} from '@mui/material'
import {
AddOutlined as AddIcon,
RemoveOutlined as RemoveIcon,
} from '@mui/icons-material'
import { isNashvilleAtom, wordSizeAtom } from './SongViewer'
const SongKeyDialog = ({ onClose, ...other }) => {
const [isNashville, setIsNashville] = useAtom(isNashvilleAtom)
const [setWordSize] = useAtom(wordSizeAtom)
const handleToggleNashville = event => setIsNashville(event.target.checked)
const handleWordSizeDown = () => setWordSize(prevState => prevState - 1)
const handleWordSizeUp = () => setWordSize(prevState => prevState + 1)
return (
<Dialog aria-labelledby={'songkey-dialog-title'} dividers {...other}>
<DialogTitle id={'songkey-dialog-title'}>Song Settings</DialogTitle>
<DialogContent
dividers
sx={{
width: theme => theme.spacing(8 * 7),
}}
>
<Box
sx={{
alignItems: 'center',
display: 'flex',
justifyContent: 'space-between',
}}
>
<Typography>Word and Chord Size</Typography>
<Box>
<IconButton
aria-label={'Word size down'}
onClick={handleWordSizeDown}
size={'large'}
>
<RemoveIcon />
</IconButton>
<IconButton
aria-label={'Word size up'}
onClick={handleWordSizeUp}
size={'large'}
>
<AddIcon />
</IconButton>
</Box>
</Box>
<Box
sx={{
alignItems: 'center',
display: 'flex',
justifyContent: 'space-between',
mt: 2,
}}
>
<Box>
<Typography>Nashville Numbering</Typography>
<Typography color={'textSecondary'} variant={'body2'}>
Show numbers instead of chords
</Typography>
</Box>
<Switch
aria-label={'Toggle Nashville Numbering'}
checked={isNashville}
onClick={handleToggleNashville}
>
Toggle
</Switch>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Close</Button>
</DialogActions>
</Dialog>
)
}
export default SongKeyDialog
| 21.74 | 76 | 0.621435 |
3c3d3b62e7cbb7d1826ee3c64d057678b1752787 | 2,941 | js | JavaScript | services/user.service.js | umutyilmaz44/NodeJs-WebApp-Api-JWT- | c3449f4e5ceb04138293927b0a26528f4cff2352 | [
"MIT"
] | null | null | null | services/user.service.js | umutyilmaz44/NodeJs-WebApp-Api-JWT- | c3449f4e5ceb04138293927b0a26528f4cff2352 | [
"MIT"
] | null | null | null | services/user.service.js | umutyilmaz44/NodeJs-WebApp-Api-JWT- | c3449f4e5ceb04138293927b0a26528f4cff2352 | [
"MIT"
] | 1 | 2022-02-10T11:45:37.000Z | 2022-02-10T11:45:37.000Z | const db = require("../repository/db");
//db.sequelize.sync();
const authHelper = require('../helpers/auth.helper');
async function findUser(email, password){
let user;
try{
user = await db.models.user.findAll({ where: { email_address: email, deleted: false } });
if(user.length > 0)
user = user[0].dataValues;
} catch(error){
return Promise.reject(error.message);
}
if (!user)
return Promise.reject('Username or password is incorrect');
const match = await authHelper.compareHashedValue(password, user.password);
if (!match)
return Promise.reject('Username or password is incorrect');
return Promise.resolve(user);
}
async function findById(id){
let user;
try{
user = await db.models.user.findByPk(id);
} catch(error){
user = null;
}
if (!user)
return Promise.reject('User not found!');
return Promise.resolve(user.dataValues);
}
async function getAll() {
let users;
try{
let dataList = await db.models.user.findAll({ where: { deleted: false } });
users = [];
dataList.forEach(element => {
users.push(element.dataValues);
});
} catch(error){
users = null;
}
return Promise.resolve(users);
}
async function addUser(user){
let createdUser;
let err;
try{
createdUser = await db.models.user.create(user);
} catch(error){
err = error;
createdUser = null;
}
if (!createdUser)
return Promise.reject(err);
return Promise.resolve(createdUser);
}
async function updateUser(user, id){
let effectedCount;
let err;
try{
if(!user || !user.email_address || !user.first_name || !user.last_name){
return Promise.reject('User info invalid!');
}
effectedCount = await db.models.user.update(user, {
where: {id: id}
});
} catch(error){
err = error;
effectedCount = 0;
}
if (effectedCount != 1)
return Promise.reject(err);
return Promise.resolve();
}
async function deleteUser(user, id){
let effectedCount;
let err;
try{
effectedCount = await db.models.user.destroy({
where: {id: id}
});
} catch(error){
err = error;
effectedCount = 0;
}
if (effectedCount != 1)
return Promise.reject(err);
return Promise.resolve();
}
async function findByFilter(filter){
let users;
try{
users = await db.models.user.findAll({ where: filter });
} catch(error){
return Promise.reject(error.message);
}
return Promise.resolve(users);
}
module.exports = {
findUser,
findById,
getAll,
addUser,
updateUser,
deleteUser,
findByFilter
}; | 22.450382 | 97 | 0.564774 |
3c3d75720a6491e99ff7c8c566de37081ce4415b | 316 | js | JavaScript | springlong-client/src/api/moving.js | 1960533658/spring_long-client | 57ced2325738154fc82fef8014e0b467df533061 | [
"MIT"
] | null | null | null | springlong-client/src/api/moving.js | 1960533658/spring_long-client | 57ced2325738154fc82fef8014e0b467df533061 | [
"MIT"
] | null | null | null | springlong-client/src/api/moving.js | 1960533658/spring_long-client | 57ced2325738154fc82fef8014e0b467df533061 | [
"MIT"
] | null | null | null | import { requestWithToken } from "../utils/request";
// 初始化获取好友动态
export const getFriendMoving = (myId) => {
return requestWithToken(`/chatmoving/getmoving/${myId}`, "get");
};
// 更新好友动态
export const uploadMovingDataAPI = (formdata) => {
return requestWithToken("/chatmoving/uploadmoving", "post", formdata);
};
| 31.6 | 72 | 0.712025 |
3c3d75d504c2286902c7b63f1f51cade9661d400 | 121 | js | JavaScript | FundamentalsModule/DataTypesandVariablesMoreExercise/Biggestof3Numbers.js | DPlamenov/Homework-tasks | 81e7316d23b4b182d67e09278004e88d1bfc2023 | [
"Apache-2.0"
] | null | null | null | FundamentalsModule/DataTypesandVariablesMoreExercise/Biggestof3Numbers.js | DPlamenov/Homework-tasks | 81e7316d23b4b182d67e09278004e88d1bfc2023 | [
"Apache-2.0"
] | null | null | null | FundamentalsModule/DataTypesandVariablesMoreExercise/Biggestof3Numbers.js | DPlamenov/Homework-tasks | 81e7316d23b4b182d67e09278004e88d1bfc2023 | [
"Apache-2.0"
] | null | null | null | function solve(a, b, c) {
let firstMax = Math.max(a, b);
let max = Math.max(firstMax, c);
console.log(max);
} | 24.2 | 36 | 0.586777 |
3c3e3cbbbf8830e4bafd8b4aa392abc9d5643b0e | 282 | js | JavaScript | server/routes/date.js | HBTghost/vuejs0x005 | e8207e47d20e38595d787a93fa8de618201009df | [
"MIT"
] | null | null | null | server/routes/date.js | HBTghost/vuejs0x005 | e8207e47d20e38595d787a93fa8de618201009df | [
"MIT"
] | null | null | null | server/routes/date.js | HBTghost/vuejs0x005 | e8207e47d20e38595d787a93fa8de618201009df | [
"MIT"
] | 1 | 2021-06-08T16:45:49.000Z | 2021-06-08T16:45:49.000Z | import express from 'express';
import { genResultedDates } from '../tools/date.js';
const timeRouter = express.Router();
timeRouter.get('/genDates/:region/:quantity', (req, res) => {
res.json(genResultedDates(req.params.region, req.params.quantity));
});
export { timeRouter }; | 28.2 | 69 | 0.712766 |
3c3e746b2835a60842990ebcb1e74080735a89e7 | 3,281 | js | JavaScript | src/components/organisms/header/header.js | averysmithproductions/faithinventory-com-platinumenoch | c6dbbcac20e343fa84153a256d852e971e266b48 | [
"MIT"
] | 1 | 2020-06-24T02:31:21.000Z | 2020-06-24T02:31:21.000Z | src/components/organisms/header/header.js | averysmithproductions/faithinventory-com-platinumenoch | c6dbbcac20e343fa84153a256d852e971e266b48 | [
"MIT"
] | 3 | 2021-09-02T08:57:38.000Z | 2022-02-19T04:16:06.000Z | src/components/organisms/header/header.js | averysmithproductions/faithinventory-com-platinumenoch | c6dbbcac20e343fa84153a256d852e971e266b48 | [
"MIT"
] | null | null | null | import React from "react"
import { Link, navigate, graphql, useStaticQuery } from 'gatsby'
import PropTypes from "prop-types"
import { Button, Logo } from "atoms"
import { MainNav } from "molecules"
import { isEmpty } from 'lodash'
import styles from './header.module.scss'
import './header.scss'
const Header = ({ inventoryItemEvent, location, rightColElement, sectionTitle, siteDescription, siteTitle }) => {
const data = useStaticQuery(graphql`
query {
allInventoryItems(filter: {id: {ne: "dummy"}}) {
edges {
node {
alternative_id
}
}
}
}
`)
const inventoryItemIds = []
data.allInventoryItems.edges.forEach( edge => {
inventoryItemIds.push(edge.node.alternative_id)
})
let localStorageItemIds = []
if (typeof window !== `undefined` && window.localStorage.getItem('itemIds')) {
// get ids from local storage and filter out any that don't exist in the database anymore.
localStorageItemIds = window.localStorage.getItem('itemIds').split(',').filter( itemId => inventoryItemIds.includes(itemId) )
}
const currentView = location.pathname
const shouldShowListButton = (currentView === '/' || currentView.includes('/i/') || currentView.includes('/category/') || currentView === '/items/list/')
return (
<header className={styles.header}>
<div className="container-fluid">
<div className="row">
<div className="col-sm-2 col-md-3">
<Logo />
</div>
<div className="col-sm-6 col-md-5">
<div id="hero-text" className={styles.heroText}>
<h1><Link to="/">{siteTitle}</Link></h1>
<p>{siteDescription}</p>
</div>
</div>
<div className="col-sm-offset-1 col-sm-3 col-md-offset-1 col-md-2">
{rightColElement || <MainNav currentView={currentView} />}
</div>
</div>
</div>
<div className="container-fluid">
<div className="row">
<div className="col-xs-9 col-sm-offset-2 col-sm-8 col-md-offset-3 col-md-8">
{shouldShowListButton && <div className={styles.listButton}>
{localStorageItemIds.length > 0 && <div className={styles.amount} onClick={ e => {
e.preventDefault()
navigate('/items/list/')
}}>{localStorageItemIds.length}</div>}
<Button
cn={currentView === '/items/list/' ? styles.tabbed : ''}
label="Your List"
fontIcon='school-backpack'
onClick={ e => {
e.preventDefault()
navigate('/items/list/')
}}
/>
</div>}
{!shouldShowListButton && sectionTitle && <div className={styles.sectionTitle}>
<h1>{sectionTitle}</h1>
</div>}
</div>
</div>
</div>
</header>
)
}
Header.propTypes = {
locaton: PropTypes.object,
rightColElement: PropTypes.object,
siteTitle: PropTypes.string,
siteDescription: PropTypes.string
}
Header.defaultProps = {
location: { pathname: '' },
rightColElement: null,
siteTitle: ``,
siteDescription: ``
}
export default Header
| 34.904255 | 155 | 0.573301 |
3c3f29bdda552a7e46cf15c0a7bd5160c80c34c6 | 1,874 | js | JavaScript | web/assets_game/js/script.js | kurraz-soft/prj-jack | 8962c1551cff0a0c32b9c900ffbde37162b7a89f | [
"MIT"
] | 1 | 2017-09-22T11:00:10.000Z | 2017-09-22T11:00:10.000Z | web/assets_game/js/script.js | kurraz-soft/prj-jack | 8962c1551cff0a0c32b9c900ffbde37162b7a89f | [
"MIT"
] | null | null | null | web/assets_game/js/script.js | kurraz-soft/prj-jack | 8962c1551cff0a0c32b9c900ffbde37162b7a89f | [
"MIT"
] | null | null | null | $(function () {
$('#loading-wrapper').remove();
$('.character-select-lnk').click(function (e) {
e.preventDefault();
$('.character-select-list').hide();
$('.character-select-detail').hide();
$($(this).attr('href')).show();
});
$('body').on('click','.g-tab',function () {
var id = $(this).attr('href');
var $tabs_wrap = $(this).parents('.g-tabs-wrap');
$tabs_wrap.find('.g-tab > .g-checkbox.checked').removeClass('checked');
$(this).find('.g-checkbox').addClass('checked');
$(id).parents('.g-tab-content').find('.g-tab-panel.active').removeClass('active');
$(id).addClass('active');
});
$('body').tooltip({
//selector: '[data-toggle="tooltip"]'
selector: '[title]'
});
$('body').on('click', '.g-checkbox.g-ajax-link:not(.disabled)', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
if($(this).hasClass('g-radio'))
{
$('.g-radio[rel="'+$(this).attr('rel')+'"].checked').removeClass('checked');
}
$(this).toggleClass('checked');
if($(this).is('[data-info-id]'))
{
var info_id;
if($(this).is('.checked'))
{
info_id = $(this).data('infoId') + '-' + 1;
}else
{
info_id = $(this).data('infoId') + '-' + 0;
}
$('.g-info-text-content:visible').html($('#' + info_id).html());
}
$.ajax({
url: $(this).attr('href'),
success: function (data) {
}
});
});
checkTabHash();
});
function checkTabHash() {
var hash = window.location.hash;
if(hash.indexOf('#tab-') === 0)
{
$('.g-tab[href="' + hash + '"]').click();
}
} | 27.558824 | 90 | 0.453042 |
3c3f47bb6550dd04d3f425da8c7a4ebf0b67fa9a | 2,802 | js | JavaScript | dist/testing/ivm_helper.js | ekoleda-codaio/packs-sdk | 83ba23e0a09e5f1e689d7df9c6e46233c461b0d4 | [
"MIT"
] | 1 | 2022-02-03T19:09:44.000Z | 2022-02-03T19:09:44.000Z | dist/testing/ivm_helper.js | erickoledadevrel/packs-sdk | c633718703897d2d28a65089a890b1c06ab746bc | [
"MIT"
] | null | null | null | dist/testing/ivm_helper.js | erickoledadevrel/packs-sdk | c633718703897d2d28a65089a890b1c06ab746bc | [
"MIT"
] | null | null | null | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupIvmContext = void 0;
const build_1 = require("../cli/build");
const bootstrap_1 = require("../runtime/bootstrap");
const fs_1 = __importDefault(require("fs"));
const bootstrap_2 = require("../runtime/bootstrap");
const bootstrap_3 = require("../runtime/bootstrap");
const isolated_vm_1 = __importDefault(require("isolated-vm"));
const path_1 = __importDefault(require("path"));
const bootstrap_4 = require("../runtime/bootstrap");
const IsolateMemoryLimit = 128;
// execution_helper_bundle.js is built by esbuild (see Makefile)
// which puts it into the same directory: dist/testing/
const CompiledHelperBundlePath = bootstrap_2.getThunkPath();
const HelperTsSourceFile = `${__dirname}/../runtime/thunk/thunk.ts`;
async function setupIvmContext(bundlePath, executionContext) {
// creating an isolate with 128M memory limit.
const isolate = new isolated_vm_1.default.Isolate({ memoryLimit: IsolateMemoryLimit });
const ivmContext = await bootstrap_1.createIsolateContext(isolate);
const bundleFullPath = bundlePath.startsWith('/') ? bundlePath : path_1.default.join(process.cwd(), bundlePath);
// If the ivm helper is running by node, the compiled execution_helper bundle should be ready at the
// dist/ directory described by CompiledHelperBundlePath. If the ivm helper is running by mocha, the
// bundle file may not be available or update-to-date, so we'd always compile it first from
// HelperTsSourceFile.
//
// TODO(huayang): this is not efficient enough and needs optimization if to be used widely in testing.
if (fs_1.default.existsSync(CompiledHelperBundlePath)) {
await bootstrap_4.registerBundles(isolate, ivmContext, bundleFullPath, CompiledHelperBundlePath);
}
else if (fs_1.default.existsSync(HelperTsSourceFile)) {
const bundlePath = await build_1.build(HelperTsSourceFile);
await bootstrap_4.registerBundles(isolate, ivmContext, bundleFullPath, bundlePath);
}
else {
throw new Error('cannot find the execution helper');
}
await bootstrap_3.injectExecutionContext({
context: ivmContext,
fetcher: executionContext.fetcher,
temporaryBlobStorage: executionContext.temporaryBlobStorage,
logger: console,
endpoint: executionContext.endpoint,
invocationLocation: executionContext.invocationLocation,
timezone: executionContext.timezone,
invocationToken: executionContext.invocationToken,
sync: executionContext.sync,
});
return ivmContext;
}
exports.setupIvmContext = setupIvmContext;
| 50.945455 | 116 | 0.737687 |