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
d3fbbb7c6a2206b5db9272ffe2ea67c127e612d4
564
js
JavaScript
app/redux/civilityTitle/actions.js
aitfriha/internalSystemFront
eda74a248c031a1154ed6eaf7d7292d53e4f29a6
[ "MIT" ]
1
2021-06-23T16:19:05.000Z
2021-06-23T16:19:05.000Z
app/redux/civilityTitle/actions.js
aitfriha/internalSystemFront
eda74a248c031a1154ed6eaf7d7292d53e4f29a6
[ "MIT" ]
null
null
null
app/redux/civilityTitle/actions.js
aitfriha/internalSystemFront
eda74a248c031a1154ed6eaf7d7292d53e4f29a6
[ "MIT" ]
null
null
null
import { ADD_CIVILITYTITLE, DELETE_CIVILITYTITLE, GET_ALL_CIVILITYTITLES, UPDATE_CIVILITYTITLE } from './constants'; export const addCivilityTitleStatus = (civilityTitle) => ({ type: ADD_CIVILITYTITLE, civilityTitle }); export const updateCivilityTitleStatus = (civilityTitleWithId) => ({ type: UPDATE_CIVILITYTITLE, civilityTitleWithId }); export const deleteCivilityTitleStatus = (civilityTitleId) => ({ type: DELETE_CIVILITYTITLE, civilityTitleId }); export const getAllCivilityTitleStatus = () => ({ type: GET_ALL_CIVILITYTITLES, });
21.692308
68
0.758865
d3fc96317eda70eee1bb44b40539be0bdb08a8f3
743
js
JavaScript
src/orders/ordersArray.js
ar4sdoteth/Crypto-Katamari
a4746864cea46be06f620a166b5d54b0fc0aba05
[ "MIT" ]
1
2021-10-31T10:46:04.000Z
2021-10-31T10:46:04.000Z
src/orders/ordersArray.js
ar4sdoteth/Crypto-Katamari
a4746864cea46be06f620a166b5d54b0fc0aba05
[ "MIT" ]
1
2021-02-12T19:47:33.000Z
2021-02-12T19:47:33.000Z
src/orders/ordersArray.js
ar4sdoteth/Crypto-Katamari
a4746864cea46be06f620a166b5d54b0fc0aba05
[ "MIT" ]
null
null
null
const orders = require('./orderIndex'); const { weiToEthUsd } = require('../helpers/convertWei') const ordersArray = []; for (const order in orders) { if (orders[order][order].asset) { ordersArray.push({ eth_price: weiToEthUsd(orders[order][order].current_price, 0), usd_price: weiToEthUsd(orders[order][order].current_price, 1), image_thumbnail: orders[order][order].asset.image_thumbnail_url, image_preview: orders[order][order].asset.image_preview_url, image: orders[order][order].asset.image_url, name: orders[order][order].asset.name, perma: orders[order][order].asset.permalink, description: orders[order][order].asset.description }); } } module.exports = { ordersArray };
33.772727
70
0.693136
d3fd14040b87c51d11010f99fd9ea2be105fc3b0
147
js
JavaScript
src/log/log.js
calbatr0ss/election-money-api
f206760aa4bd8092c5d1cd2e1adfd866d63d5a75
[ "MIT" ]
2
2019-04-12T13:50:50.000Z
2019-05-29T19:07:20.000Z
src/log/log.js
calbatr0ss/election-money-api
f206760aa4bd8092c5d1cd2e1adfd866d63d5a75
[ "MIT" ]
null
null
null
src/log/log.js
calbatr0ss/election-money-api
f206760aa4bd8092c5d1cd2e1adfd866d63d5a75
[ "MIT" ]
6
2018-11-24T16:31:06.000Z
2019-05-26T15:42:25.000Z
import { db } from "../db/db.js" export const submit = (level, message) => db.log.create({ EventTime: Date(), Level: level, Message: message })
29.4
70
0.646259
d3fd2ff5e366dc61453f41f2c0a4a04133b2797e
40
js
JavaScript
test/input/import-with-duplicate.js
asg017/oak-parser
ccef230f50671efd2789a2004873e0146aa905bd
[ "ISC" ]
146
2018-12-12T03:41:30.000Z
2022-03-17T18:08:57.000Z
test/input/import-with-duplicate.js
asg017/oak-parser
ccef230f50671efd2789a2004873e0146aa905bd
[ "ISC" ]
126
2018-12-12T02:41:50.000Z
2022-02-13T01:43:20.000Z
test/input/import-with-duplicate.js
asg017/oak-parser
ccef230f50671efd2789a2004873e0146aa905bd
[ "ISC" ]
25
2018-12-12T12:17:51.000Z
2022-02-01T15:51:24.000Z
import {} with {foo, foo} from "module"
20
39
0.65
d3ff98f3093bb20251e91bfa0ec558fe2e72700d
2,013
js
JavaScript
public/directives.js
machaad/AdmonPedidos
62aef030ec1cbd02fbf486764fb8322f5b98ae34
[ "Apache-2.0" ]
null
null
null
public/directives.js
machaad/AdmonPedidos
62aef030ec1cbd02fbf486764fb8322f5b98ae34
[ "Apache-2.0" ]
null
null
null
public/directives.js
machaad/AdmonPedidos
62aef030ec1cbd02fbf486764fb8322f5b98ae34
[ "Apache-2.0" ]
null
null
null
(function(){ var app = angular.module('app.common.directives', []); app.directive('ixTableToolbar', [ "UserAction", function(UserAction) { return { templateUrl : 'template/ix.table.toolbar.html', scope: { selected : '=', query : '=', onEdit :'&?', onDelete :'&?', title : '@', deletePermission : "@", editPermission : "@" }, link: function(scope, element) { scope.action = { edit : angular.isDefined(scope.onEdit) && UserAction.isAllowed(scope.editPermission), delete : angular.isDefined(scope.onDelete) && UserAction.isAllowed(scope.deletePermission) }; scope.query.search = ''; scope._toolbar = {}; scope._toolbar.showSearch = false; scope._toolbar.toggleSearch = function(){ scope._toolbar.showSearch = !scope._toolbar.showSearch; } } }; }]); app.directive('passwordConfirm', [ function () { return { restrict: 'A', scope: { matchTarget: '=' }, require: 'ngModel', link: function link(scope, elem, attrs, ctrl) { var validator = function (value) { ctrl.$setValidity('match', value === scope.matchTarget); return value; }; ctrl.$parsers.unshift(validator); ctrl.$formatters.push(validator); // This is to force validator when the original password gets changed scope.$watch('matchTarget', function(newval, oldval) { validator(ctrl.$viewValue); }); } }; }]); }());
33.55
112
0.441629
31000ff3cf0946041f2797b350a850046614af39
114
js
JavaScript
web/assets/js/example.js
chloecorfmat/into-the-woods-webapp
e49e5af38c515f52c80b2a7e1661d92b8580315f
[ "MIT" ]
1
2019-02-13T11:02:27.000Z
2019-02-13T11:02:27.000Z
web/assets/js/example.js
chloecorfmat/into-the-woods-webapp
e49e5af38c515f52c80b2a7e1661d92b8580315f
[ "MIT" ]
1
2019-11-20T19:22:33.000Z
2019-11-20T19:22:33.000Z
web/assets/js/example.js
chloecorfmat/into-the-woods-webapp
e49e5af38c515f52c80b2a7e1661d92b8580315f
[ "MIT" ]
null
null
null
window.addEventListener('load', initialiser) function initialiser (event) { console.log('Welcome on Raidy'); }
19
44
0.745614
31004d2303cd09e36e2f56ae33891be3e1c43630
2,238
js
JavaScript
src/components/AboutMaizuo/Employ.js
skydaya/react-sell
f1bb2a47ffc96cca3c5df548e592ee90c2ee9436
[ "MIT" ]
6
2017-08-24T09:46:56.000Z
2017-10-18T01:32:22.000Z
src/components/AboutMaizuo/Employ.js
skydaya/react-sell
f1bb2a47ffc96cca3c5df548e592ee90c2ee9436
[ "MIT" ]
null
null
null
src/components/AboutMaizuo/Employ.js
skydaya/react-sell
f1bb2a47ffc96cca3c5df548e592ee90c2ee9436
[ "MIT" ]
null
null
null
/** * Created by dllo on 17/8/29. */ import React, {Component} from 'react' import '../../assets/about/employ.styl' class Employ extends Component { render() { return ( <div id="about"> <div id='about-nav-title'> <ul id='about-ul'> <li><a href='about.html'>关于卖座</a></li> <li><a href='contact.html'>联系我们</a></li> <li><a href='business.html'>商务合作</a></li> <li><a href='teamwork.html'>合作伙伴</a></li> <li><a href='sincere.html'>诚聘英才</a></li> <li><a href='employ.html'>使用帮助</a></li> <li><a href='refund.html'>退票服务</a></li> <li><a href='clause.html'>服务条款</a></li> <li><a href='community.html'>社区管理</a></li> </ul> </div> <div id="employ-right-content"> <h1>使用帮助</h1> <p className="employ-title">一、什么是卖座卡</p> <p className="employ-content">卖座卡是卖座网的金牌产品,是作为员工福利、赠送客户和回馈会员的理想选择,方便实用,服务尊享。 适用于卖座网平台上可预订及支付的项目,包含电影票、影院小食、电影周边。</p> <p className="employ-title">二、卖座卡可不可以延期?</p> <p className="employ-content">卖座卡背面是印有有效期的,只能在有效期内使用 ,根据购卡协议目前暂不支持延期。</p> <p className="employ-title">三、我购买了你们的通兑电子票,请问有效期是多久?</p> <p className="employ-content">有效期根据影城不同,有效期也不同,一般是60-90天,购票时都有写明有效期,购票成功后短信也有说明。</p> <p className="employ-title">四、我买了某影城的订座票,但是临时有事不能去看可以退吗?</p> <p className="employ-content">详情请见「退票服务」。</p> <p className="employ-title">五、想在你们官网购买5张卖座卡,请问可以开发票吗?</p> <p className="employ-content">可以的,麻烦您在收货地址后面写上发票抬头即可。</p> <p className="employ-title">六、我有一张卖座网面额为100元的电影卡,请问可以去哪些影城使用?</p> <p className="employ-content">在全国范围内,只要跟卖座网有合作的影城都可以使用。</p> <p className="employ-title">七、我购买了一张某影城的通兑票,请问可以在线订座吗?</p> <p className="employ-content">通兑票是需要凭短信取票码到影城前台兑换的,不支持网上订座。</p> <p className="employ-title">八、我购买了某家影城的通兑票,没有时间去看,请问可以退掉吗?</p> <p className="employ-content">如果您的通兑票在有效期内未使用兑换,可以通过卖座电影APP进行自助退款。</p> <p className="employ-title">九、公司刚发的卡,找不到了,请问怎么办?</p> <p className="employ-content">建议您第一时间联系卖座客服4001808400进行挂失,避免资金流失。</p> </div> </div> ) } } export default Employ
43.882353
94
0.594281
3100abbb4bf1201b58451afc0803c7896d891b5d
11,302
js
JavaScript
spec/auth_accounts.spec.js
nobitlost/imp-central-api
a8a8c3368d58e24b836d4c5c507948e95917f2a0
[ "MIT" ]
2
2017-12-09T15:07:47.000Z
2021-06-25T08:26:12.000Z
spec/auth_accounts.spec.js
nobitlost/imp-central-api
a8a8c3368d58e24b836d4c5c507948e95917f2a0
[ "MIT" ]
1
2017-04-27T09:54:17.000Z
2017-04-27T21:10:39.000Z
spec/auth_accounts.spec.js
electricimp/imp-central-api
94afbf52afc5ac646c391dc3a307e672e07322f8
[ "MIT" ]
4
2017-07-28T19:49:31.000Z
2020-02-13T15:03:15.000Z
// MIT License // // Copyright 2017 Electric Imp // // SPDX-License-Identifier: MIT // // 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. 'use strict'; require('jasmine-expect'); const ImpCentralApi = require('../lib/ImpCentralApi'); const util = require('./util'); const Errors = require('../lib/Errors'); const config = require('./config'); describe('impCentralAPI.auth and impCentralAPI.accounts test suite', () => { let impCentralApi = util.impCentralApi; let accountId; let refreshTokenId; let loginKey; let loginKeyDescr; beforeAll(util.init, util.TIMEOUT); it('should refresh access token', (done) => { impCentralApi.auth.login(config.email, config.password). then((res) => { if ('refresh_token' in res) { impCentralApi.auth.refreshAccessToken(res.refresh_token). then((res) => { expect('access_token' in res).toBeTruthy(); done(); }). catch((error) => { done.fail(error); }); } else { done.fail('No refresh_token in login response'); } }). catch((error) => { done.fail(error); }); }); it('should not login with empty email', (done) => { impCentralApi.auth.login('', 'pwd'). then((res) => { done.fail('login with empty email'); }). catch((error) => { if (!(error instanceof Errors.InvalidDataError)) { done.fail('unexpected error'); } done(); }); }); it('should not login with wrong email or password', (done) => { impCentralApi.auth.login(config.email, config.password + '123'). then((res) => { done.fail('login with wrong email or password'); }). catch((error) => { if (!(error instanceof Errors.ImpCentralApiError)) { done.fail('unexpected error'); } done(); }); }); it('should get refresh tokens', (done) => { impCentralApi.auth.getRefreshTokens(). then((res) => { expect(res.data.length).toBeGreaterThan(0); if (res.data.length > 0) { refreshTokenId = res.data[0].id; } done(); }). catch((error) => { done.fail(error); }); }); it('should delete refresh token', (done) => { if (refreshTokenId) { impCentralApi.auth.deleteRefreshToken(refreshTokenId). then((res) => { done(); }). catch((error) => { done.fail(error); }); } else { done(); } }); it('should not delete refresh token with empty id', (done) => { if (refreshTokenId) { impCentralApi.auth.deleteRefreshToken(''). then((res) => { done.fail('delete refresh token with empty id'); }). catch((error) => { if (!(error instanceof Errors.InvalidDataError)) { done.fail('unexpected error'); } done(); }); } else { done(); } }); it('should get "me" account', (done) => { impCentralApi.accounts.get('me'). then((res) => { expect(res.data.type).toBe('account'); accountId = res.data.id; done(); }). catch((error) => { done.fail(error); }); }); it('should get a specific account', (done) => { impCentralApi.accounts.get(accountId). then((res) => { expect(res.data.type).toBe('account'); expect(res.data.id).toBe(accountId); done(); }). catch((error) => { done.fail(error); }); }); it('should not get an account with wrong id', (done) => { impCentralApi.accounts.get('wrong-id'). then((res) => { done.fail('account with wrong id obtained successfully'); }). catch((error) => { if (!(error instanceof Errors.ImpCentralApiError)) { done.fail('unexpected error'); } done(); }); }); it('should create login key', (done) => { loginKeyDescr = 'test description'; impCentralApi.accounts.createLoginKey(config.password, { 'description' : loginKeyDescr }). then((res) => { expect(res.data.type).toBe('login_key'); expect(res.data.attributes.description).toBe(loginKeyDescr); loginKey = res.data.id; done(); }). catch((error) => { done.fail(error); }); }); it('should get list of login keys', (done) => { impCentralApi.accounts.listLoginKeys(). then((res) => { expect(res.data.length).toBeGreaterThan(0); done(); }). catch((error) => { done.fail(error); }); }); it('should get list of login keys with pagination', (done) => { impCentralApi.accounts.listLoginKeys(1, 1). then((res) => { expect(res.data.length).toBe(1); done(); }). catch((error) => { done.fail(error); }); }); it('should get a specific login key', (done) => { impCentralApi.accounts.getLoginKey(loginKey). then((res) => { expect(res.data.id).toBe(loginKey); expect(res.data.attributes.description).toBe(loginKeyDescr); done(); }). catch((error) => { done.fail(error); }); }); it('should not get login key with wrong id', (done) => { impCentralApi.accounts.getLoginKey(accountId). then((res) => { done.fail('login key with wrong id obtained successfully'); }). catch((error) => { if (!(error instanceof Errors.ImpCentralApiError)) { done.fail('unexpected error'); } done(); }); }); it('should update a specific login key', (done) => { loginKeyDescr = 'updated test description'; impCentralApi.accounts.updateLoginKey(loginKey, config.password, { description : loginKeyDescr}). then((res) => { expect(res.data.attributes.description).toBe(loginKeyDescr); done(); }). catch((error) => { done.fail(error); }); }); it('should not update a specific login key with wrong attributes', (done) => { impCentralApi.accounts.updateLoginKey(loginKey, config.password, { name : 'test name' }). then((res) => { done.fail('login key updated successfully with wrong attributes'); }). catch((error) => { if (!(error instanceof Errors.InvalidDataError)) { done.fail('unexpected error'); } done(); }); }); it('should not update login key with wrong id', (done) => { impCentralApi.products.update(loginKey + '123', { description: 'test description' }). then((res) => { done.fail('login key with wrong id updated successfully'); }). catch((error) => { if (!(error instanceof Errors.ImpCentralApiError)) { done.fail('unexpected error'); } done(); }); }); it('should get access token by login key', (done) => { impCentralApi.auth.getAccessToken(loginKey). then((res) => { expect('access_token' in res).toBeTruthy(); done(); }). catch((error) => { done.fail(error); }); }); it('should not get access token by empty login key', (done) => { impCentralApi.auth.getAccessToken(''). then((res) => { done.fail('get access token by empty login key'); }). catch((error) => { if (!(error instanceof Errors.InvalidDataError)) { done.fail('unexpected error'); } done(); }); }); it('should not get access token by wrong login key', (done) => { impCentralApi.auth.getAccessToken('wrong_login_key'). then((res) => { done.fail('get access token by wrong login key'); }). catch((error) => { if (!(error instanceof Errors.ImpCentralApiError)) { done.fail('unexpected error'); } done(); }); }); it('should delete a specific login key', (done) => { impCentralApi.accounts.deleteLoginKey(loginKey, config.password). then((res) => { done(); }). catch((error) => { done.fail(error); }); }); it('should not delete nonexistent login key', (done) => { impCentralApi.accounts.deleteLoginKey(loginKey, config.password). then((res) => { done.fail('nonexistent login key deleted successfully'); }). catch((error) => { if (!(error instanceof Errors.ImpCentralApiError)) { done.fail('unexpected error'); } done(); }); }); });
33.838323
105
0.48195
310168b9363cfdae327c0d1ef1e9a5b5d4a014d4
903
js
JavaScript
app/plugins/controls/bar.js
kornalius/openvision
675367d80c6e1b29ba3f08b331b39faa6a6ed642
[ "Apache-2.0" ]
null
null
null
app/plugins/controls/bar.js
kornalius/openvision
675367d80c6e1b29ba3f08b331b39faa6a6ed642
[ "Apache-2.0" ]
null
null
null
app/plugins/controls/bar.js
kornalius/openvision
675367d80c6e1b29ba3f08b331b39faa6a6ed642
[ "Apache-2.0" ]
null
null
null
export default class Bar extends Plugin { constructor () { super() this.name = 'bar' this.desc = 'Container that has sections.' this.author = 'Alain Deschenes' this.version = '1.0.0' this.dependencies = ['control', 'flow'] app.Bar = (options = {}) => { let b = new app.Rectangle(_.get(options, 'width', 0), _.get(options, 'height', 24)) b.fill = _.get(options, 'fill', true) b.color = _.get(options, 'color', 0xb3b3b3) b.borderColor = _.get(options, 'borderColor', 0xFFFFFF) b.borderAlpha = _.get(options, 'borderAlpha', 1) b.borderSize = _.get(options, 'borderSize', 0.5) b.plug('bar', options) return b } } addSection (container) { this.$.addChild(container) this.$.update() return this } removeSection (container) { this.$.removeChild(container) this.$.update() return this } }
24.405405
89
0.596899
31019bf25edcea404d4f7570feb7b17700bbe189
2,933
js
JavaScript
src/view/screens/SignupScreen.js
DanQuan1/shopping-app
bf02c9f5dc8763d1ac1808ad0af0bf7077c65cc9
[ "MIT" ]
null
null
null
src/view/screens/SignupScreen.js
DanQuan1/shopping-app
bf02c9f5dc8763d1ac1808ad0af0bf7077c65cc9
[ "MIT" ]
null
null
null
src/view/screens/SignupScreen.js
DanQuan1/shopping-app
bf02c9f5dc8763d1ac1808ad0af0bf7077c65cc9
[ "MIT" ]
null
null
null
import React from 'react'; import {Text, StyleSheet, View, TextInput, TouchableOpacity, ScrollView } from "react-native"; const SignupScreen = ({navigation})=>{ return( <View> <ScrollView style={styles.BottomView}> <Text style={styles.Heading}> Join {"\n"} Us Today </Text> <View style={styles.FormView}> <TextInput placeholder={"Full Name"} placeholderTextColor={"black"} style={styles.TextInput}/> <TextInput placeholder={"Email Address"} placeholderTextColor={"black"} style={styles.TextInput}/> <TextInput placeholder={"Mobile"} placeholderTextColor={"black"} style={styles.TextInput}/> <TextInput placeholder={"Password"} secureTextEntry= {true} placeholderTextColor={"black"} style={styles.TextInput}/> <TextInput placeholder={"Confirm Password"} secureTextEntry= {true} placeholderTextColor={"black"} style={styles.TextInput}/> <TouchableOpacity style={styles.Button}> <Text style={styles.ButtonText}>Sign Up</Text> </TouchableOpacity> </View> <TouchableOpacity style={styles.TextButton} onPress= {() => {navigation.navigate("Login"); }}> <Text style={styles.SignUpText}> <Text style={styles.login}> Have an account?</Text> Login </Text> </TouchableOpacity> </ScrollView> </View> ) } const styles = StyleSheet.create({ BottomView:{ width:"100%", height:"100%", backgroundColor: "white", borderTopLeftRadius: 30, borderTopRightRadius: 30, }, Heading:{ color:"black", fontSize: 40, fontWeight: "bold", marginLeft: 30, marginTop: 60, }, FormView:{ width:"100%", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", marginTop: 40, }, TextInput:{ width: "90%", borderWidth: 1, borderColor: "black", height: 52, borderRadius: 10, paddingLeft: 5, marginTop: 20, }, Button:{ width:"90%", color: "#000", height: 52, backgroundColor: "black", borderRadius: 10, marginTop: 20, display: "flex", justifyContent:"center", alignItems: "center", }, ButtonText:{ fontWeight: "bold", fontSize: 18, color: "white", }, Question:{ color: "black", textAlign: "center", fontWeight: "bold", fontSize: 18, }, SignUpText:{ color: "black", }, TextButton:{ width: "100%", display: "flex", alignItems: "center", marginTop: 20, }, login:{ color: "black", }, icons:{ width: "60%", height: 35, borderWidth: 1, borderRadius:20, marginTop: 30, flexDirection: "row", alignItems: "center", alignSelf: "center", paddingHorizontal: "9%", } }) export default SignupScreen
23.464
139
0.584385
31026539db9a2a0f323c5a4a2202879bb86915c1
81,298
js
JavaScript
Office-ProPlus-Deployment/CTROfficeXmlWebEditor/CTROfficeXmlWebEditor/Scripts/main.js
cvvamsi/Office-IT-Pro-Deployment-Scripts
e0283abbde0f5d322403acc4868c3d3c57b50c8e
[ "MIT" ]
6
2021-08-05T09:13:37.000Z
2021-11-02T04:54:32.000Z
Office-ProPlus-Deployment/CTROfficeXmlWebEditor/CTROfficeXmlWebEditor/Scripts/main.js
golfkinguk/Office-IT-Pro-Deployment-Scripts
e0283abbde0f5d322403acc4868c3d3c57b50c8e
[ "MIT" ]
null
null
null
Office-ProPlus-Deployment/CTROfficeXmlWebEditor/CTROfficeXmlWebEditor/Scripts/main.js
golfkinguk/Office-IT-Pro-Deployment-Scripts
e0283abbde0f5d322403acc4868c3d3c57b50c8e
[ "MIT" ]
1
2020-07-07T16:30:38.000Z
2020-07-07T16:30:38.000Z
 var selectDate; $(document).ready(function () { $('#txtDeadline').datetimepicker({ sideBySide: true }).on("dp.change", function (e) { var date = e.date; //e.date is a moment object if (date) { selectDate = date.format("MM/DD/YYYY HH:mm"); var target = $(e.target).attr('name'); } }); var finput = document.getElementById('fileInput'); finput.addEventListener('change', function (e) { fileUploaded(e); document.getElementById("fileUploadForm").reset(); }); document.getElementById("collapseOne").style.display = "block"; document.getElementById("collapseProperties").style.display = "block"; document.getElementById("pidkeySignal").style.display = "none"; document.getElementById("targetversionSignal").style.display = "none"; document.getElementById("updatepathSignal").style.display = "none"; if (isInternetExplorer()) { document.getElementById("txtVersion").style.lineHeight = "0px"; document.getElementById("txtTargetVersion").style.lineHeight = "0px"; } $("#btRemoveProduct").prop("disabled", true); $("#btAddLanguage").prop("disabled", true); $("#btRemoveLanguage").prop("disabled", true); toggleTextBox("txtUpdatePath", false); toggleTextBox("txtTargetVersion", false); $("#inputDeadline").prop("disabled", true); var collapse = $.cookie("optionalcollapse"); if (collapse == "true") { $("#toggleExpand").removeClass('glyphicon-collapse-down'); $("#toggleExpand").addClass('glyphicon-collapse-up'); $("#collapseOne").collapse('show'); $("#collapseOne").css("height", ""); } else { $("#toggleExpand").removeClass('glyphicon-collapse-up'); $("#toggleExpand").addClass('glyphicon-collapse-down'); $("#collapseOne").collapse('hide'); $("#collapseOne").css("height", "0"); } var collapseProperties = $.cookie("propertiescollapse"); if (collapseProperties == "true") { $("#togglePropertiesExpand").removeClass('glyphicon-collapse-down'); $("#togglePropertiesExpand").addClass('glyphicon-collapse-up'); $("#collapseProperties").collapse('show'); $("#collapseProperties").css("height", ""); } else { $("#togglePropertiesExpand").removeClass('glyphicon-collapse-up'); $("#togglePropertiesExpand").addClass('glyphicon-collapse-down'); $("#collapseProperties").collapse('hide'); $("#collapseProperties").css("height", "0"); } $('#templateList li').click(function (e) { e.preventDefault(); var $that = $(this); var url = document.getElementById(this.id).getAttribute("href"); var rawFile = new XMLHttpRequest(); rawFile.open("GET", url, true); rawFile.onreadystatechange = function () { if (rawFile.readyState === 4) { var allText = rawFile.responseText; if (allText) { $('textarea#xmlText').val(allText); loadUploadXmlFile(); } } } rawFile.send(); }); $("#collapseOne").prop("height", "auto"); $("#collapseProperties").prop("height", "auto"); setActiveTab(); resizeWindow(); var xmlOutput = $.cookie("xmlcache"); $('textarea#xmlText').val(xmlOutput); loadUploadXmlFile(); $(window).resize(function () { resizeWindow(); }); //$(".alert").addClass("in").fadeOut(4500); $('#txtPidKey').keydown(function (e) { var currentText = this.value; var code = e.keyCode || e.which; var start = document.getElementById("txtPidKey").selectionStart; var end = document.getElementById("txtPidKey").selectionEnd; if (code == 189) { if (start != 5 && start != 11 && start != 17 && start != 23) { e.preventDefault(); } } if (code == 8 || code == 46) { if (end < currentText.length) { var selPart = currentText.substring(start - 1, end); if (selPart.indexOf("-") > -1) { e.preventDefault(); } } } if (code == 8 || (code >= 37 && code <= 40)) return; if (code == 46 || code == 16) return; var strSplit = currentText.split('-'); for (var t = 0; t < strSplit.length; t++) { var part = strSplit[t]; if (part.length > 5) { //e.preventDefault(); } } if (currentText.length > 28) { e.preventDefault(); } }); $('#txtPidKey').keyup(function () { validatePidKey(this); var currentText = this.value; if (currentText.length >= 27) { while (currentText.indexOf("-") > -1) { currentText = currentText.replace("-", ""); } var newCode = currentText.substring(0, 5) + "-" + currentText.substring(5, 10) + "-" + currentText.substring(10, 15) + "-" + currentText.substring(15, 20) + "-" + currentText.substring(20, 25); var start = document.getElementById("txtPidKey").selectionStart; var end = document.getElementById("txtPidKey").selectionEnd; this.value = newCode; document.getElementById("txtPidKey").selectionStart = start; document.getElementById("txtPidKey").selectionEnd = end; } }); $('#txtPACKAGEGUID').keydown(function (e) { var currentText = this.value; var code = e.keyCode || e.which; var start = document.getElementById("txtPACKAGEGUID").selectionStart; var end = document.getElementById("txtPACKAGEGUID").selectionEnd; if (code == 189) { if (start != 5 && start != 11 && start != 17 && start != 23) { e.preventDefault(); } } if (code == 8 || code == 46) { if (end < currentText.length) { var selPart = currentText.substring(start - 1, end); if (selPart.indexOf("-") > -1) { e.preventDefault(); } } } if (code == 8 || (code >= 37 && code <= 40)) return; if (code == 46 || code == 16) return; var strSplit = currentText.split('-'); for (var t = 0; t < strSplit.length; t++) { var part = strSplit[t]; if (part.length > 5) { //e.preventDefault(); } } if (currentText.length > 36) { e.preventDefault(); } }); $('#txtPACKAGEGUID').keyup(function () { validatePackageGuid(this); var currentText = this.value; if (currentText.length >= 31) { while (currentText.indexOf("-") > -1) { currentText = currentText.replace("-", ""); } var newCode = currentText.substring(0, 8) + "-" + currentText.substring(8, 12) + "-" + currentText.substring(12, 16) + "-" + currentText.substring(16, 20) + "-" + currentText.substring(20, 32); var start = document.getElementById("txtPACKAGEGUID").selectionStart; var end = document.getElementById("txtPACKAGEGUID").selectionEnd; this.value = newCode; document.getElementById("txtPACKAGEGUID").selectionStart = start; document.getElementById("txtPACKAGEGUID").selectionEnd = end; } }); $('txtPidKey').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("pidkeySignal").style.display = "none"; } else { document.getElementById("pidkeySignal").style.display = "block"; } }); $('#txtVersion').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("versionSignal").style.display = "none"; } else { document.getElementById("versionSignal").style.display = "block"; } }); $('#txtPACKAGEGUID').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("PACKAGEGUIDSignal").style.display = "none"; } else { document.getElementById("PACKAGEGUIDSignal").style.display = "block"; } }); $('#txtSourcePath').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("sourcepathSignal").style.display = "none"; } else { document.getElementById("sourcepathSignal").style.display = "block"; } }); $('#txtUpdatePath').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("updatepathSignal").style.display = "none"; } else { document.getElementById("updatepathSignal").style.display = "block"; } }); $('#txtTargetVersion').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("targetversionSignal").style.display = "none"; } else { document.getElementById("targetversionSignal").style.display = "block"; } }); $('#txtLoggingUpdatePath').on('input propertychange paste focus click', function () { if (this.value.length == 0) { document.getElementById("logupdatepathSignal").style.display = "none"; } else { document.getElementById("logupdatepathSignal").style.display = "block"; } }); $("#btAddProduct").button().click(function () { var xmlDoc = getXmlDocument(); odtAddProduct(xmlDoc); displayXml(xmlDoc); $("#btAddProduct").text('Edit Product'); return false; }); $("#btRemoveProduct").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveProduct(xmlDoc); displayXml(xmlDoc); return false; }); $("#btAddLanguage").button().click(function () { var xmlDoc = getXmlDocument(); odtAddLanguage(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemoveLanguage").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveLanguage(xmlDoc); displayXml(xmlDoc); return false; }); $("#cbProduct").change(function () { var end = this.value; changeSelectedProduct(); }); $("#cbLanguage").change(function () { var end = this.value; changeSelectedLanguage(); }); $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { //e.target // activated tab //e.relatedTarget // previous tab scrollXmlEditor(); $.cookie("activeTab", e.target); var mainTabs = document.getElementById("myTab"); if (mainTabs) { var target = $(e.target).attr("href"); var liItems = mainTabs.getElementsByTagName("li"); if (liItems) { for (var i = 0; i < liItems.length; i++) { var liItem = liItems[i]; if ($("#" + liItem.id).hasClass("active")) { } } } } }); $("#btAddExcludeApp").button().click(function () { var xmlDoc = getXmlDocument(); odtAddExcludeApp(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemoveExcludeApp").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveExcludeApp(xmlDoc); displayXml(xmlDoc); return false; }); $("#btAddRemoveProduct").button().click(function () { var xmlDoc = getXmlDocument(); odtAddRemoveApp(xmlDoc); displayXml(xmlDoc); return false; }); $("#btDeleteRemoveProduct").button().click(function () { var xmlDoc = getXmlDocument(); odtDeleteRemoveApp(xmlDoc); displayXml(xmlDoc); return false; }); $("#btAddRemoveLanguage").button().click(function () { var xmlDoc = getXmlDocument(); odtAddRemoveLanguage(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemoveRemoveLanguage").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveRemoveLanguage(xmlDoc); displayXml(xmlDoc); return false; }); $("#btSaveUpdates").button().click(function () { var xmlDoc = getXmlDocument(); odtSaveUpdates(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemovesUpdates").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveUpdates(xmlDoc); displayXml(xmlDoc); return false; }); $("#btSaveDisplay").button().click(function () { var xmlDoc = getXmlDocument(); odtSaveDisplay(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemoveDisplay").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveDisplay(xmlDoc); displayXml(xmlDoc); return false; }); $("#btSaveLogging").button().click(function () { var xmlDoc = getXmlDocument(); odtSaveLogging(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemoveLogging").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveLogging(xmlDoc); displayXml(xmlDoc); return false; }); $("#btSaveProperties").button().click(function () { var xmlDoc = getXmlDocument(); odtSaveProperties(xmlDoc); displayXml(xmlDoc); return false; }); $("#btRemoveProperties").button().click(function () { var xmlDoc = getXmlDocument(); odtRemoveProperties(xmlDoc); displayXml(xmlDoc); return false; }); $("#btViewOnGitHub").button().click(function () { window.open("https://github.com/OfficeDev/Office-IT-Pro-Deployment-Scripts/tree/master/Office-ProPlus-Deployment/CTROfficeXmlWebEditor"); return false; }); $(window).scroll(function() { scrollXmlEditor(); }); $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'versions', source: substringMatcher(versions) }); $('#txtVersion').keydown(function (e) { restrictToVersion(e); }); $('#txtTargetVersion').keydown(function (e) { restrictToVersion(e); }); setScrollBar(); }); function setScrollBar() { var optionDiv = document.getElementById("optionDiv"); if (optionDiv) { var optionDivHeight = optionDiv.clientHeight; var bodyHeight = window.innerHeight; if (optionDivHeight > bodyHeight - 100) { document.body.style.overflow = "auto"; } else { if (isInternetExplorer()) { document.body.style.overflow = "hidden"; } } } } function scrollXmlEditor() { var scrollTop = $(window).scrollTop(); var bodyWidth = window.innerWidth; var xmlEditorDiv = document.getElementById("xmlEditorDiv"); if (xmlEditorDiv) { var clientLeft = getPos(xmlEditorDiv).x; if (clientLeft > 50) { if (scrollTop > 50) { xmlEditorDiv.style.top = (scrollTop - 50) + "px"; } else { xmlEditorDiv.style.top = (0) + "px"; } } else { xmlEditorDiv.style.top = (0) + "px"; } } } function getPos(el) { // yay readability for (var lx = 0, ly = 0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent); return { x: lx, y: ly }; } function isInternetExplorer() { if (window.ActiveXObject || "ActiveXObject" in window) { return true; } return false; } var substringMatcher = function (strs) { return function findMatches(q, cb) { try { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push(str); } }); cb(matches); } catch(ex) {} }; }; function restrictToVersion(e) { var currentText = this.value; var code = e.keyCode || e.which; var start = document.getElementById("txtPidKey").selectionStart; var end = document.getElementById("txtPidKey").selectionEnd; if ((code >= 48 && code <= 57) || code == 190 || code == 8 || code == 46 || (e.ctrlKey && code == 67) || code == 17 || (e.ctrlKey && code == 86) || (code >= 37 && code <= 40)) { } else { e.preventDefault(); } } function setActiveTab() { var activeTab = $.cookie("activeTab"); if (activeTab) { if (activeTab.indexOf('#') > -1) { var tabSplit = activeTab.split('#'); activeTab = tabSplit[tabSplit.length - 1]; } $('[data-toggle="tab"][href="#' + activeTab + '"]').tab('show'); } } function clickUpload() { var finput = document.getElementById('fileInput'); finput.click(); } function fileUploaded(e) { var control = document.getElementById('fileInput'); var i = 0, files = control.files; var file = files[i]; var reader = new FileReader(); reader.onload = function (event) { var contents = event.target.result; var xmlOutput = vkbeautify.xml(contents); $('textarea#xmlText').val(xmlOutput); loadUploadXmlFile(); }; reader.onerror = function (event) { throw "File could not be read! Code " + event.target.error.code; }; reader.readAsText(file); } function toggleExpandOptional(source) { if ($("#toggleExpand").hasClass('glyphicon-collapse-up')) { $("#toggleExpand").removeClass('glyphicon-collapse-up'); $("#toggleExpand").addClass('glyphicon-collapse-down'); $.cookie("optionalcollapse", "false"); } else { $("#toggleExpand").addClass('glyphicon-collapse-up'); $("#toggleExpand").removeClass('glyphicon-collapse-down'); $.cookie("optionalcollapse", "true"); } setTimeout(setScrollBar, 500); } function toggleExpandProperties(source) { if ($("#togglePropertiesExpand").hasClass('glyphicon-collapse-up')) { $("#togglePropertiesExpand").removeClass('glyphicon-collapse-up'); $("#togglePropertiesExpand").addClass('glyphicon-collapse-down'); $.cookie("propertiescollapse", "false"); } else { $("#togglePropertiesExpand").addClass('glyphicon-collapse-up'); $("#togglePropertiesExpand").removeClass('glyphicon-collapse-down'); $.cookie("propertiescollapse", "true"); } setTimeout(setScrollBar, 500); } function download() { var xmlDoc = getXmlDocument(); var xmlString = (new XMLSerializer().serializeToString(xmlDoc.documentElement)); var xmlOutput = vkbeautify.xml(xmlString); xmlOutput = xmlOutput.replace(/\n/g, "\r\n"); var blob = new Blob([xmlOutput], { type: "text/xml" }); saveAs(blob, "configuration.xml"); } function validatePidKey(t) { //if (!this.value.match(/[0-9]/)) { // this.value = this.value.replace(/[^0-9]/g, ''); //} var firstPart = ""; var secondPart = ""; var thirdPart = ""; var fourthPart = ""; var fifthPart = ""; var currentText = t.value; if (currentText.indexOf("--") > -1) { var start = document.getElementById("txtPidKey").selectionStart; var end = document.getElementById("txtPidKey").selectionEnd; t.value = t.value.replace("--", "-"); document.getElementById("txtPidKey").selectionStart = start; document.getElementById("txtPidKey").selectionEnd = end; return; } if (currentText.length > 5) { firstPart = currentText.substring(0, 5); if (firstPart.indexOf("-") > -1) return; var dash1 = currentText.substring(5, 6); if (dash1 != "-") { var firstPart1 = currentText.substring(0, 5); var restPart1 = currentText.substring(5, currentText.length); firstPart1 = firstPart1.replace("-", ""); firstPart = firstPart1 + "-" + restPart1; var startPos = document.getElementById("txtPidKey").selectionStart; t.value = firstPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPidKey").selectionStart = startPos + 1; document.getElementById("txtPidKey").selectionEnd = startPos + 1; } } if (currentText.length > 11) { secondPart = currentText.substring(6, 11); if (secondPart.indexOf("-") > -1) return; var dash2 = currentText.substring(11, 12); if (dash2 != "-" & dash2 != "") { var firstPart2 = currentText.substring(11, 15); var restPart2 = currentText.substring(15, currentText.length); if (restPart2) { thirdPart = firstPart2 + "-" + restPart2; } else { thirdPart = firstPart2; } var startPos = document.getElementById("txtPidKey").selectionStart; t.value = firstPart + "-" + secondPart + "-" + thirdPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPidKey").selectionStart = startPos + 1; document.getElementById("txtPidKey").selectionEnd = startPos + 1; } } if (currentText.length > 17) { thirdPart = currentText.substring(12, 17);; if (thirdPart.indexOf("-") > -1) return; var dash3 = currentText.substring(17, 18); if (dash3 != "-" & dash3 != "") { var firstPart3 = currentText.substring(17, 21); var restPart3 = currentText.substring(21, currentText.length); if (restPart3) { fourthPart = firstPart3 + "-" + restPart3; } else { fourthPart = firstPart3; } var startPos = document.getElementById("txtPidKey").selectionStart; t.value = firstPart + "-" + secondPart + "-" + thirdPart + "-" + fourthPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPidKey").selectionStart = startPos + 1; document.getElementById("txtPidKey").selectionEnd = startPos + 1; } } if (currentText.length > 23) { fourthPart = currentText.substring(18, 23);; if (fourthPart.indexOf("-") > -1) return; var dash4 = currentText.substring(23, 24); if (dash4 != "-" & dash4 != "") { var firstPart4 = currentText.substring(23, 27); var restPart4 = currentText.substring(27, currentText.length); if (restPart4) { fifthPart = firstPart4 + "-" + restPart4; } else { fifthPart = firstPart4; } var startPos = document.getElementById("txtPidKey").selectionStart; t.value = firstPart + "-" + secondPart + "-" + thirdPart + "-" + fourthPart + "-" + fifthPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPidKey").selectionStart = startPos + 1; document.getElementById("txtPidKey").selectionEnd = startPos + 1; } } } function validatePackageGuid(t) { //if (!this.value.match(/[0-9]/)) { // this.value = this.value.replace(/[^0-9]/g, ''); //} var firstPart = ""; var secondPart = ""; var thirdPart = ""; var fourthPart = ""; var fifthPart = ""; var currentText = t.value; if (currentText.indexOf("--") > -1) { var start = document.getElementById("txtPACKAGEGUID").selectionStart; var end = document.getElementById("txtPACKAGEGUID").selectionEnd; t.value = t.value.replace("--", "-"); document.getElementById("txtPACKAGEGUID").selectionStart = start; document.getElementById("txtPACKAGEGUID").selectionEnd = end; return; } if (currentText.length > 8) { firstPart = currentText.substring(0, 8); if (firstPart.indexOf("-") > -1) return; var dash1 = currentText.substring(8, 9); if (dash1 != "-") { var firstPart1 = currentText.substring(0, 8); var restPart1 = currentText.substring(8, currentText.length); firstPart1 = firstPart1.replace("-", ""); firstPart = firstPart1 + "-" + restPart1; var startPos = document.getElementById("txtPACKAGEGUID").selectionStart; t.value = firstPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPACKAGEGUID").selectionStart = startPos + 1; document.getElementById("txtPACKAGEGUID").selectionEnd = startPos + 1; } } if (currentText.length > 13) { secondPart = currentText.substring(9, 13); if (secondPart.indexOf("-") > -1) return; var dash2 = currentText.substring(13, 14); if (dash2 != "-" & dash2 != "") { var firstPart2 = currentText.substring(13, 17); var restPart2 = currentText.substring(17, currentText.length); if (restPart2) { thirdPart = firstPart2 + "-" + restPart2; } else { thirdPart = firstPart2; } var startPos = document.getElementById("txtPACKAGEGUID").selectionStart; t.value = firstPart + "-" + secondPart + "-" + thirdPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPACKAGEGUID").selectionStart = startPos + 1; document.getElementById("txtPACKAGEGUID").selectionEnd = startPos + 1; } } if (currentText.length > 18) { thirdPart = currentText.substring(14, 18);; if (thirdPart.indexOf("-") > -1) return; var dash3 = currentText.substring(18, 19); if (dash3 != "-" & dash3 != "") { var firstPart3 = currentText.substring(18, 22); var restPart3 = currentText.substring(22, currentText.length); if (restPart3) { fourthPart = firstPart3 + "-" + restPart3; } else { fourthPart = firstPart3; } var startPos = document.getElementById("txtPACKAGEGUID").selectionStart; t.value = firstPart + "-" + secondPart + "-" + thirdPart + "-" + fourthPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPACKAGEGUID").selectionStart = startPos + 1; document.getElementById("txtPACKAGEGUID").selectionEnd = startPos + 1; } } if (currentText.length > 23) { fourthPart = currentText.substring(19, 23); if (fourthPart.indexOf("-") > -1) return; var dash4 = currentText.substring(23, 24); if (dash4 != "-" & dash4 != "") { var firstPart4 = currentText.substring(23, 27); var restPart4 = currentText.substring(27, currentText.length); if (restPart4) { fifthPart = firstPart4 + "-" + restPart4; } else { fifthPart = firstPart4; } var startPos = document.getElementById("txtPACKAGEGUID").selectionStart; t.value = firstPart + "-" + secondPart + "-" + thirdPart + "-" + fourthPart + "-" + fifthPart; t.value = t.value.replace("--", "-"); document.getElementById("txtPACKAGEGUID").selectionStart = startPos + 1; document.getElementById("txtPACKAGEGUID").selectionEnd = startPos + 1; } } } function changeSelectedLanguage() { var selectedProduct = $("#cbProduct").val(); var selectLanguage = $("#cbLanguage").val(); var xmlDoc = getXmlDocument(); $("#btAddLanguage").prop("disabled", false); var addNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; } if (addNode) { var productNode = getProductNode(addNode, selectedProduct); var langNode = getLanguageNode(productNode, selectLanguage); if (langNode) { $("#btAddLanguage").prop("disabled", true); } } } function changeSelectedProduct() { var productId = $('#cbProduct').val(); var xmlDoc = getXmlDocument(); $("#txtPidKey").val(""); var productCount = getAddProductCount(xmlDoc); if (productCount > 0) { var productNode = getProductNode(xmlDoc, productId); if (productNode) { $("#btAddProduct").text('Edit Product'); $("#btRemoveProduct").prop("disabled", false); var pidKey = productNode.getAttribute("PIDKEY"); if (pidKey) { $("#txtPidKey").val(pidKey); } var excludeApps = productNode.getElementsByTagName("ExcludeApp"); if (excludeApps.length == 0) { $("#btRemoveExcludeApp").prop("disabled", true); $("select#cbExcludeApp").prop('selectedIndex', 0); } else { $("#btRemoveExcludeApp").prop("disabled", false); var excludeApp = excludeApps[0]; if (excludeApp) { $("#cbExcludeApp").val(excludeApp.getAttribute("ID")); } } } else { $("#btAddProduct").text('Add Product'); //$("#btRemoveProduct").prop("disabled", true); $("#btRemoveExcludeApp").prop("disabled", true); $("select#cbExcludeApp").prop('selectedIndex', 0); } } else { $("#btRemoveProduct").prop("disabled", true); } var langCount = getLanguageNodeCount(xmlDoc, productId); $("#btRemoveLanguage").prop("disabled", !(langCount > 1)); } function resizeWindow() { var bodyHeight = window.innerHeight; var bodyWidth = window.innerWidth; var leftPaneHeight = bodyHeight - 180; var rightPaneHeight = bodyHeight - 100; var scrollTop = $(window).scrollTop(); if (scrollTop > 50) { rightPaneHeight = rightPaneHeight + 50; } $("#xmlText").height(rightPaneHeight - 90); setScrollBar(); } function cacheNodes(xmlDoc) { var propertyNameList = ["Remove", "Display", "Logging", "Property", "Updates"]; var nodeList = []; for (var p = 0; p < propertyNameList.length; p++) { var propertyName = propertyNameList[p]; var nodes = xmlDoc.documentElement.getElementsByTagName(propertyName); if (nodes.length > 0) { var nodeCount = nodes.length; for (var n = 0; n < nodeCount; n++) { var propNode = xmlDoc.documentElement.getElementsByTagName(propertyName)[0]; nodeList.push(propNode); xmlDoc.documentElement.removeChild(propNode); } } } return nodeList; } function readdNodes(xmlDoc, nodeList) { for (var t = 0; t < nodeList.length; t++) { var addPropNode = nodeList[t]; xmlDoc.documentElement.appendChild(addPropNode); } } function odtAddProduct(xmlDoc) { var selectedProduct = $("#cbProduct").val(); var selectBitness = $("#cbEdition").val(); var selectVersion = $("#txtVersion").val(); var selectSourcePath = $("#txtSourcePath").val(); var selectLanguage = $("#cbLanguage").val(); var selectPidKey = $("#txtPidKey").val(); var addNode = xmlDoc.createElement("Add"); var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; } else { var nodeList = cacheNodes(xmlDoc); xmlDoc.documentElement.appendChild(addNode); readdNodes(xmlDoc, nodeList); } if (selectSourcePath) { addNode.setAttribute("SourcePath", selectSourcePath); } else { addNode.removeAttribute("SourcePath"); } if (selectVersion) { addNode.setAttribute("Version", selectVersion); } else { addNode.removeAttribute("Version"); } addNode.setAttribute("OfficeClientEdition", selectBitness); var productNode = getProductNode(addNode, selectedProduct); if (!(productNode)) { productNode = xmlDoc.createElement("Product"); productNode.setAttribute("ID", selectedProduct); addNode.appendChild(productNode); } if (selectPidKey) { productNode.setAttribute("PIDKEY", selectPidKey); } else { productNode.removeAttribute("PIDKEY"); } var langNode = getLanguageNode(productNode, selectLanguage); if (!(langNode)) { langNode = xmlDoc.createElement("Language"); langNode.setAttribute("ID", selectLanguage); productNode.appendChild(langNode); } var removeNode = null; var removeNodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (removeNodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; } if (removeNode) { var existingRemoveProduct = checkForRemoveProductNode(xmlDoc, selectedProduct); if (existingRemoveProduct) { removeNode.removeChild(existingRemoveProduct); } if (removeNode.childElementCount == 0) { xmlDoc.documentElement.removeChild(removeNode); } } var productCount = getAddProductCount(xmlDoc); if (productCount == 0) { $("#btRemoveProduct").prop("disabled", true); $("#btAddLanguage").prop("disabled", true); $("#btRemoveLanguage").prop("disabled", true); } else { $("#btRemoveProduct").prop("disabled", false); $("#btAddLanguage").prop("disabled", true); } } function odtRemoveProduct(xmlDoc) { var selectedProduct = $("#cbProduct").val(); var addNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, selectedProduct); if (productNode) { addNode.removeChild(productNode); } var products = addNode.getElementsByTagName("Product"); if (products.length == 0) { addNode.parentNode.removeChild(addNode); } } var productCount = getAddProductCount(xmlDoc); if (productCount == 0) { $("#btRemoveProduct").prop("disabled", true); $("#btAddLanguage").prop("disabled", true); $("#btRemoveLanguage").prop("disabled", true); } else { $("#btRemoveProduct").prop("disabled", false); $("#btAddLanguage").prop("disabled", false); } //$("#removeAllProducts").removeClass('btn-primary'); //$("#removeSelectProducts").removeClass('btn-primary'); //$("#removeAllProducts").removeClass('active'); //$("#removeSelectProducts").removeClass('active'); $("#btAddProduct").text('Add Product'); } function odtAddLanguage(xmlDoc) { var selectedProduct = $("#cbProduct").val(); var selectLanguage = $("#cbLanguage").val(); var addNode = xmlDoc.createElement("Add"); var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, selectedProduct); if (productNode) { var langNode = getLanguageNode(productNode, selectLanguage); if (!(langNode)) { var langs = productNode.getElementsByTagName("Language"); var lastLang = langs[langs.length - 1]; var langList = []; for (var p = 0; p < langs.length; p++) { var langChkNode1 = langs[p]; langList.push(langChkNode1); } for (var l = 0; l < langs.length; l++) { var langChkNode2 = langs[l]; productNode.removeChild(langChkNode2); } for (var t = 0; t < langList.length ; t++) { var langChkNode = langList[t]; productNode.appendChild(langChkNode); } langNode = xmlDoc.createElement("Language"); langNode.setAttribute("ID", selectLanguage); productNode.appendChild(langNode, lastLang); $("#btAddLanguage").prop("disabled", true); } } } var langCount = getLanguageNodeCount(xmlDoc, selectedProduct); $("#btRemoveLanguage").prop("disabled", !(langCount > 1)); } function odtRemoveLanguage(xmlDoc) { var selectedProduct = $("#cbProduct").val(); var selectLanguage = $("#cbLanguage").val(); var addNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, selectedProduct); if (productNode) { if (getLanguageNodeCount(xmlDoc, selectedProduct) > 1) { var langNode = getLanguageNode(productNode, selectLanguage); if (langNode) { productNode.removeChild(langNode); $("#btAddLanguage").prop("disabled", false); } } } } var langCount = getLanguageNodeCount(xmlDoc, selectedProduct); $("#btRemoveLanguage").prop("disabled", !(langCount > 1)); } function odtAddRemoveLanguage(xmlDoc) { var selectedProduct = $("#cbRemoveProduct").val(); var selectLanguage = $("#cbRemoveLanguage").val(); var removeNode = xmlDoc.createElement("Remove"); var nodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (nodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; var productNode = getProductNode(removeNode, selectedProduct); if (productNode) { var langNode = getLanguageNode(productNode, selectLanguage); if (!(langNode)) { var langs = productNode.getElementsByTagName("Language"); var lastLang = langs[langs.length - 1]; langNode = xmlDoc.createElement("Language"); langNode.setAttribute("ID", selectLanguage); productNode.insertBefore(langNode, lastLang); } } } var langCount = getRemoveLanguageNodeCount(xmlDoc, selectedProduct); $("#btRemoveRemoveLanguage").prop("disabled", !(langCount > 1)); } function odtRemoveRemoveLanguage(xmlDoc) { var selectedProduct = $("#cbRemoveProduct").val(); var selectLanguage = $("#cbRemoveLanguage").val(); var removeNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (nodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; var productNode = getProductNode(removeNode, selectedProduct); if (productNode) { if (getRemoveLanguageNodeCount(xmlDoc, selectedProduct) > 1) { var langNode = getLanguageNode(productNode, selectLanguage); if (langNode) { productNode.removeChild(langNode); } } } } var langCount = getRemoveLanguageNodeCount(xmlDoc, selectedProduct); $("#btRemoveLanguage").prop("disabled", !(langCount > 1)); } function removeAllSections() { document.getElementById("btRemoveDisplay").click(); document.getElementById("btRemoveExcludeApp").click(); document.getElementById("btRemoveLanguage").click(); document.getElementById("btRemoveLogging").click(); document.getElementById("btRemoveProduct").click(); document.getElementById("btRemoveProperties").click(); document.getElementById("btRemoveRemoveLanguage").click(); document.getElementById("btRemovesUpdates").click(); } function odtAddRemoveApp(xmlDoc) { var selectedProduct = $("#cbRemoveProduct").val(); var selectLanguage = $("#cbRemoveLanguage").val(); var $removeAll = $("#removeAllProducts"); if ($removeAll.hasClass('btn-primary')) { } var removeNode = xmlDoc.createElement("Remove"); var nodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (nodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; } else { xmlDoc.documentElement.appendChild(removeNode); } var removeAll = false; var $removeSelect = $("#removeSelectProducts"); if ($removeSelect.hasClass('btn-primary')) { removeNode.removeAttribute("All"); var productNode = getProductNode(removeNode, selectedProduct); if (!(productNode)) { productNode = xmlDoc.createElement("Product"); productNode.setAttribute("ID", selectedProduct); removeNode.appendChild(productNode); } var langNode = getLanguageNode(productNode, selectLanguage); if (!(langNode)) { langNode = xmlDoc.createElement("Language"); langNode.setAttribute("ID", selectLanguage); productNode.appendChild(langNode); } } else { removeAll = true; removeNode.setAttribute("All", "TRUE"); if (removeNode.childElementCount > 0) { var products = removeNode.getElementsByTagName("Product"); var prodLength = products.length; for (var v = 0; v < prodLength; v++) { removeNode.removeChild(products[0]); } } } var addNode = null; var addNodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (addNodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; } if (addNode) { var existingAddProduct = checkForAddProductNode(xmlDoc, selectedProduct); if (existingAddProduct) { addNode.removeChild(existingAddProduct); } if (addNode.childElementCount == 0 || removeAll) { xmlDoc.documentElement.removeChild(addNode); } } } function odtDeleteRemoveApp(xmlDoc) { var selectedProduct = $("#cbRemoveProduct").val(); var selectLanguage = $("#cbRemoveLanguage").val(); var removeNode = xmlDoc.createElement("Remove"); var nodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (nodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; } else { xmlDoc.documentElement.appendChild(removeNode); } var $removeSelect = $("#removeSelectProducts"); if ($removeSelect.hasClass('btn-primary')) { removeNode.removeAttribute("All"); var productNode = getProductNode(removeNode, selectedProduct); if (productNode) { removeNode.removeChild(productNode); } } var products = removeNode.getElementsByTagName("Product"); if (products.length == 0) { removeNode.parentNode.removeChild(removeNode); } } function odtAddExcludeApp(xmlDoc) { var selectedProduct = $("#cbProduct").val(); var selectExcludeApp = $("#cbExcludeApp").val(); var addNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, selectedProduct); if (productNode) { var exNode = getExcludeAppNode(productNode, selectExcludeApp); if (!(exNode)) { var excludeApps = productNode.getElementsByTagName("ExcludeApp"); var excludeNode = excludeApps[excludeApps.length - 1]; exNode = xmlDoc.createElement("ExcludeApp"); exNode.setAttribute("ID", selectExcludeApp); if (excludeNode) { productNode.insertBefore(exNode, excludeNode); } else { productNode.appendChild(exNode); } } } } var exCount = getExcludeAppNodeCount(xmlDoc, selectedProduct); $("#btRemoveExcludeApp").prop("disabled", !(exCount > 0)); } function odtRemoveExcludeApp(xmlDoc) { var selectedProduct = $("#cbProduct").val(); var selectExcludeApp = $("#cbExcludeApp").val(); var addNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, selectedProduct); if (productNode) { if (getExcludeAppNodeCount(xmlDoc, selectedProduct) > 0) { var exNode = getExcludeAppNode(productNode, selectExcludeApp); if (exNode) { productNode.removeChild(exNode); } } } } var langCount = getExcludeAppNodeCount(xmlDoc, selectedProduct); $("#btRemoveExcludeApp").prop("disabled", !(langCount > 0)); } function getExcludeAppNode(excludeAppNode, selectedExcludeApp) { var exNode = null; var excludeApps = excludeAppNode.getElementsByTagName("ExcludeApp"); for (var i = 0; i < excludeApps.length; i++) //looping xml childnodes { var excludeApp = excludeApps[i]; var excludeAppId = excludeApp.getAttribute("ID"); if (excludeAppId == selectedExcludeApp) { exNode = excludeApp; } } return exNode; } function getExcludeAppNodeCount(xmlDoc, productId) { var addNode = xmlDoc.createElement("Add"); var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, productId); if (productNode) { var excludeApps = productNode.getElementsByTagName("ExcludeApp"); return excludeApps.length; } } return 0; } function odtSaveUpdates(xmlDoc) { var selectUpdatePath = $("#txtUpdatePath").val(); var selectTargetVersion = $("#txtTargetVersion").val(); var $btUpdatesEnabled = $("#btupdatesEnabled"); var $btUpdatesDisabled = $("#btupdatesDisabled"); if (!$btUpdatesEnabled.hasClass('btn-primary') && !$btUpdatesDisabled.hasClass('btn-primary')) { $btUpdatesEnabled.addClass('btn-primary'); $("#txtUpdatePath").prop("disabled", false); //$("#txtTargetVersion").prop("disabled", false); $("#inputDeadline").prop("disabled", false); } if ($btUpdatesEnabled.hasClass('btn-primary') || $btUpdatesDisabled.hasClass('btn-primary')) { var updateNode = xmlDoc.createElement("Updates"); var nodes = xmlDoc.documentElement.getElementsByTagName("Updates"); if (nodes.length > 0) { updateNode = xmlDoc.documentElement.getElementsByTagName("Updates")[0]; } else { xmlDoc.documentElement.appendChild(updateNode); } if (selectUpdatePath) { updateNode.setAttribute("UpdatePath", selectUpdatePath); } else { updateNode.removeAttribute("UpdatePath"); } if (selectTargetVersion) { updateNode.setAttribute("TargetVersion", selectTargetVersion); } else { updateNode.removeAttribute("TargetVersion"); } if (selectDate) { updateNode.setAttribute("Deadline", selectDate); } else { updateNode.removeAttribute("Deadline"); } if ($btUpdatesEnabled.hasClass('btn-primary')) { updateNode.setAttribute("Enabled", "TRUE"); } if ($btUpdatesDisabled.hasClass('btn-primary')) { updateNode.setAttribute("Enabled", "FALSE"); updateNode.removeAttribute("UpdatePath"); updateNode.removeAttribute("TargetVersion"); updateNode.removeAttribute("Deadline"); } } } function odtRemoveUpdates(xmlDoc) { var addNode = xmlDoc.createElement("Updates"); var nodes = xmlDoc.documentElement.getElementsByTagName("Updates"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Updates")[0]; if (addNode) { xmlDoc.documentElement.removeChild(addNode); } } $("#btupdatesDisabled").removeClass('btn-primary'); $("#btupdatesEnabled").removeClass('btn-primary'); $("#btupdatesDisabled").removeClass('active'); $("#btupdatesEnabled").removeClass('active'); $("#inputDeadline").prop("disabled", true); toggleTextBox("txtUpdatePath", false); toggleTextBox("txtTargetVersion", false); } function odtSaveDisplay(xmlDoc) { var addNode = xmlDoc.createElement("Display"); var nodes = xmlDoc.documentElement.getElementsByTagName("Display"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Display")[0]; } else { xmlDoc.documentElement.appendChild(addNode); } var $displayLevelNone = $("#btLevelNone"); var $displayLevelFull = $("#btLevelFull"); var $AcceptEulaEnabled = $("#btAcceptEULAEnabled"); var $AcceptEulaDisabled = $("#btAcceptEULADisabled"); if (!$displayLevelNone.hasClass('btn-primary') && !$displayLevelFull.hasClass('btn-primary') && !$AcceptEulaEnabled.hasClass('btn-primary') && !$AcceptEulaDisabled.hasClass('btn-primary')) { $displayLevelNone.addClass('btn-primary'); $AcceptEulaEnabled.addClass('btn-primary'); } if ($displayLevelNone.hasClass('btn-primary')) { addNode.setAttribute("Level", "None"); } if ($displayLevelFull.hasClass('btn-primary')) { addNode.setAttribute("Level", "Full"); } if ($AcceptEulaEnabled.hasClass('btn-primary')) { addNode.setAttribute("AcceptEULA", "TRUE"); } if ($AcceptEulaDisabled.hasClass('btn-primary')) { addNode.setAttribute("AcceptEULA", "FALSE"); } } function odtRemoveDisplay(xmlDoc) { var addNode = xmlDoc.createElement("Display"); var nodes = xmlDoc.documentElement.getElementsByTagName("Display"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Display")[0]; if (addNode) { xmlDoc.documentElement.removeChild(addNode); } } $("#btLevelNone").removeClass('btn-primary'); $("#btLevelFull").removeClass('btn-primary'); $("#btLevelNone").removeClass('active'); $("#btLevelFull").removeClass('active'); $("#btAcceptEULAEnabled").removeClass('btn-primary'); $("#btAcceptEULAEnabled").removeClass('active'); $("#btAcceptEULADisabled").removeClass('btn-primary'); $("#btAcceptEULADisabled").removeClass('active'); } function odtSaveProperties(xmlDoc) { var autoActivateNode = null; var forceShutDownNode = null; var sharedComputerLicensingNode = null; var packageguidNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Property"); if (nodes.length > 0) { for (var n = 0; n < nodes.length; n++) { propNode = xmlDoc.documentElement.getElementsByTagName("Property")[n]; if (propNode) { var attrValue = propNode.getAttribute("Name"); if (attrValue) { if (propNode.getAttribute("Name").toUpperCase() == "AUTOACTIVATE") { autoActivateNode = propNode; } if (propNode.getAttribute("Name").toUpperCase() == "FORCEAPPSHUTDOWN") { forceShutDownNode = propNode; } if (propNode.getAttribute("Name").toUpperCase() == "SHAREDCOMPUTERLICENSING") { sharedComputerLicensingNode = propNode; } if (propNode.getAttribute("Name").toUpperCase() == "PACKAGEGUID") { packageguidNode = propNode; } } } } } var $btAutoActivateYes = $("#btAutoActivateYes"); var $btAutoActivateNo = $("#btAutoActivateNo"); var $btForceAppShutdownTrue = $("#btForceAppShutdownTrue"); var $btForceAppShutdownFalse = $("#btForceAppShutdownFalse"); var $btSharedComputerLicensingYes = $("#btSharedComputerLicensingYes"); var $btSharedComputerLicensingNo = $("#btSharedComputerLicensingNo"); var packageguidVal = $("#txtPACKAGEGUID").val(); if (packageguidVal) { if (packageguidVal.length > 0) { if (IsGuid(packageguidVal)) { if (!(packageguidNode)) { packageguidNode = xmlDoc.createElement("Property"); xmlDoc.documentElement.appendChild(packageguidNode); } packageguidNode.setAttribute("Name", "PACKAGEGUID"); packageguidNode.setAttribute("Value", packageguidVal); } } } if ($btAutoActivateYes.hasClass('btn-primary') || $btAutoActivateNo.hasClass('btn-primary')) { if (!(autoActivateNode)) { autoActivateNode = xmlDoc.createElement("Property"); xmlDoc.documentElement.appendChild(autoActivateNode); } if ($btAutoActivateYes.hasClass('btn-primary')) { autoActivateNode.setAttribute("Name", "AUTOACTIVATE"); autoActivateNode.setAttribute("Value", "1"); } if ($btAutoActivateNo.hasClass('btn-primary')) { autoActivateNode.setAttribute("Name", "AUTOACTIVATE"); autoActivateNode.setAttribute("Value", "0"); } } if ($btForceAppShutdownTrue.hasClass('btn-primary') || $btForceAppShutdownFalse.hasClass('btn-primary')) { if (!(forceShutDownNode)) { forceShutDownNode = xmlDoc.createElement("Property"); xmlDoc.documentElement.appendChild(forceShutDownNode); } if ($btForceAppShutdownTrue.hasClass('btn-primary')) { forceShutDownNode.setAttribute("Name", "FORCEAPPSHUTDOWN"); forceShutDownNode.setAttribute("Value", "TRUE"); } if ($btForceAppShutdownFalse.hasClass('btn-primary')) { forceShutDownNode.setAttribute("Name", "FORCEAPPSHUTDOWN"); forceShutDownNode.setAttribute("Value", "FALSE"); } } if ($btSharedComputerLicensingYes.hasClass('btn-primary') || $btSharedComputerLicensingNo.hasClass('btn-primary')) { if (!(sharedComputerLicensingNode)) { sharedComputerLicensingNode = xmlDoc.createElement("Property"); xmlDoc.documentElement.appendChild(sharedComputerLicensingNode); } if ($btSharedComputerLicensingYes.hasClass('btn-primary')) { sharedComputerLicensingNode.setAttribute("Name", "SharedComputerLicensing"); sharedComputerLicensingNode.setAttribute("Value", "1"); } if ($btSharedComputerLicensingNo.hasClass('btn-primary')) { sharedComputerLicensingNode.setAttribute("Name", "SharedComputerLicensing"); sharedComputerLicensingNode.setAttribute("Value", "0"); } } } function odtRemoveProperties(xmlDoc) { var propNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Property"); if (nodes.length > 0) { var nodeCount = nodes.length; for (var n = 0; n < nodeCount; n++) { propNode = xmlDoc.documentElement.getElementsByTagName("Property")[0]; if (propNode) { xmlDoc.documentElement.removeChild(propNode); } } } $("#btAutoActivateYes").removeClass('btn-primary'); $("#btAutoActivateNo").removeClass('btn-primary'); $("#btAutoActivateYes").removeClass('active'); $("#btAutoActivateNo").removeClass('active'); $("#btForceAppShutdownTrue").removeClass('btn-primary'); $("#btForceAppShutdownTrue").removeClass('active'); $("#btForceAppShutdownFalse").removeClass('btn-primary'); $("#btForceAppShutdownFalse").removeClass('active'); $("#btSharedComputerLicensingYes").removeClass('btn-primary'); $("#btSharedComputerLicensingYes").removeClass('active'); $("#btSharedComputerLicensingNo").removeClass('btn-primary'); $("#btSharedComputerLicensingNo").removeClass('active'); } function odtSaveLogging(xmlDoc) { var loggingUpdatePath = $("#txtLoggingUpdatePath").val(); var $displayLevelNone = $("#btLoggingLevelOff"); var $displayLevelStandard = $("#btLoggingLevelStandard"); if (!$displayLevelNone.hasClass('btn-primary') && !$displayLevelStandard.hasClass('btn-primary')) { $displayLevelNone.addClass('btn-primary'); $("#txtLoggingUpdatePath").prop("disabled", true); } if ($displayLevelNone.hasClass('btn-primary') || $displayLevelStandard.hasClass('btn-primary')) { var addNode = xmlDoc.createElement("Logging"); var nodes = xmlDoc.documentElement.getElementsByTagName("Logging"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Logging")[0]; } else { xmlDoc.documentElement.appendChild(addNode); } if ($displayLevelNone.hasClass('btn-primary')) { addNode.setAttribute("Level", "Off"); addNode.removeAttribute("Path"); } if ($displayLevelStandard.hasClass('btn-primary')) { addNode.setAttribute("Level", "Standard"); if (loggingUpdatePath) { addNode.setAttribute("Path", loggingUpdatePath); } } } } function odtRemoveLogging(xmlDoc) { var addNode = xmlDoc.createElement("Logging"); var nodes = xmlDoc.documentElement.getElementsByTagName("Logging"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Logging")[0]; if (addNode) { xmlDoc.documentElement.removeChild(addNode); } } $("#btLoggingLevelOff").removeClass('btn-primary'); $("#btLoggingLevelOff").removeClass('active'); $("#btLoggingLevelStandard").removeClass('btn-primary'); $("#btLoggingLevelStandard").removeClass('active'); } function getProductNode(addNode, selectedProduct) { var productNode = null; var products = addNode.getElementsByTagName("Product"); for (var i = 0; i < products.length; i++) //looping xml childnodes { var product = products[i]; var productId = product.getAttribute("ID"); if (productId == selectedProduct) { productNode = product; } } return productNode; } function getAddProductCount(xmlDoc) { var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { var addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var products = addNode.getElementsByTagName("Product"); return products.length; } return 0; } function checkForAddProductNode(xmlDoc, selectedProduct) { var addNode = xmlDoc.createElement("Add"); var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; } else { xmlDoc.documentElement.appendChild(addNode); } var productNode = getProductNode(addNode, selectedProduct); return productNode; } function checkForRemoveProductNode(xmlDoc, selectedProduct) { var removeNode = xmlDoc.createElement("Remove"); var nodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (nodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; } else { xmlDoc.documentElement.appendChild(removeNode); } var productNode = getProductNode(removeNode, selectedProduct); return productNode; } function getLanguageNode(productNode, selectedLanguage) { var langNode = null; var languages = productNode.getElementsByTagName("Language"); for (var i = 0; i < languages.length; i++) //looping xml childnodes { var language = languages[i]; var languageId = language.getAttribute("ID"); if (languageId == selectedLanguage) { langNode = language; } } return langNode; } function getLanguageNodeCount(xmlDoc, productId) { var addNode = xmlDoc.createElement("Add"); var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var productNode = getProductNode(addNode, productId); if (productNode) { var languages = productNode.getElementsByTagName("Language"); return languages.length; } } return 0; } function getRemoveLanguageNodeCount(xmlDoc, productId) { var addNode = xmlDoc.createElement("Remove"); var nodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; var productNode = getProductNode(addNode, productId); if (productNode) { var languages = productNode.getElementsByTagName("Language"); return languages.length; } } return 0; } function loadUploadXmlFile(inXmlDoc) { var xmlDoc = inXmlDoc; if (!(xmlDoc)) { xmlDoc = getXmlDocument(); } var addNode = null; var nodes = xmlDoc.documentElement.getElementsByTagName("Add"); if (nodes.length > 0) { addNode = xmlDoc.documentElement.getElementsByTagName("Add")[0]; var selectBitness = addNode.getAttribute("OfficeClientEdition"); $("#cbEdition").val(selectBitness); var products = addNode.getElementsByTagName("Product"); if (products.length > 0) { var product = products[0]; var productId = product.getAttribute("ID"); $("#cbProduct").val(productId); var pidKey = product.getAttribute("PIDKEY"); $("#txtPidKey").val(pidKey); var exApps = product.getElementsByTagName("ExcludeApp"); if (exApps.length > 0) { var exApp = exApps[0]; var excludeAppId = exApp.getAttribute("ID"); $("#cbExcludeApp").val(excludeAppId); $("#btRemoveExcludeApp").prop("disabled", false); } else { $("#btRemoveExcludeApp").prop("disabled", true); } } var version = addNode.getAttribute("Version"); $("#txtVersion").val(version); var version = addNode.getAttribute("SourcePath"); $("#txtSourcePath").val(version); } var removeNode = null; var remvoeNodes = xmlDoc.documentElement.getElementsByTagName("Remove"); if (remvoeNodes.length > 0) { removeNode = xmlDoc.documentElement.getElementsByTagName("Remove")[0]; if (removeNode) { var removeProducts = removeNode.getElementsByTagName("Product"); if (removeProducts.length > 0) { var removeproduct = removeProducts[0]; var removeproductId = removeproduct.getAttribute("ID"); $("#cbRemoveProduct").val(removeproductId); var removeLangs = removeproduct.getElementsByTagName("Language"); if (removeLangs.length > 0) { var removeLangId = removeLangs[0].getAttribute("ID"); $("#cbRemoveLanguage").val(removeLangId); } toggleRemove("removeSelectProducts"); } else { toggleRemove("removeallproducts"); } } } var updateNodes = xmlDoc.documentElement.getElementsByTagName("Updates"); if (updateNodes.length > 0) { var updateNode = xmlDoc.documentElement.getElementsByTagName("Updates")[0]; var updatesEnabled = updateNode.getAttribute("Enabled"); var selectUpdatePath = updateNode.getAttribute("UpdatePath"); var selectTargetVersion = updateNode.getAttribute("TargetVersion"); var selectDeadline = updateNode.getAttribute("Deadline"); if (updatesEnabled == "TRUE") { toggleUpdatesEnabled("btupdatesEnabled"); $("#txtUpdatePath").val(selectUpdatePath); $("#txtTargetVersion").val(selectTargetVersion); $("#txtDeadline").val(selectDeadline); } else { toggleUpdatesEnabled("btupdatesDisabled"); $("#txtUpdatePath").val(""); $("#txtTargetVersion").val(""); $("#txtDeadline").val(""); } } var displayNodes = xmlDoc.documentElement.getElementsByTagName("Display"); if (displayNodes.length > 0) { var displayNode = xmlDoc.documentElement.getElementsByTagName("Display")[0]; var logLevel = displayNode.getAttribute("Level"); var acceptEula = displayNode.getAttribute("AcceptEULA"); if (logLevel == "None") { toggleDisplayLevelEnabled("btLevelNone"); } else { toggleDisplayLevelEnabled("btLevelFull"); } if (acceptEula == "TRUE") { toggleDisplayEULAEnabled("btAcceptEULAEnabled"); } else { toggleDisplayEULAEnabled("btAcceptEULADisabled"); } } var propertyNodes = xmlDoc.documentElement.getElementsByTagName("Property"); if (propertyNodes.length > 0) { var autoActivateNode = null; var forceShutDownNode = null; var sharedComputerLicensingNode = null; var packageguidNode = null; nodes = xmlDoc.documentElement.getElementsByTagName("Property"); if (nodes.length > 0) { for (var n = 0; n < nodes.length; n++) { var propNode = xmlDoc.documentElement.getElementsByTagName("Property")[n]; if (propNode) { var attrValue = propNode.getAttribute("Name"); if (attrValue) { if (propNode.getAttribute("Name").toUpperCase() == "AUTOACTIVATE") { autoActivateNode = propNode; } if (propNode.getAttribute("Name").toUpperCase() == "FORCEAPPSHUTDOWN") { forceShutDownNode = propNode; } if (propNode.getAttribute("Name").toUpperCase() == "SHAREDCOMPUTERLICENSING") { sharedComputerLicensingNode = propNode; } if (propNode.getAttribute("Name").toUpperCase() == "PACKAGEGUID") { packageguidNode = propNode; } } } } } var autoActivate = ""; if (autoActivateNode) { autoActivate = autoActivateNode.getAttribute("Value"); } var forceShutDown = ""; if (forceShutDownNode) { forceShutDown = forceShutDownNode.getAttribute("Value"); } var sharedComputerLicensing = ""; if (sharedComputerLicensingNode) { sharedComputerLicensing = sharedComputerLicensingNode.getAttribute("Value"); } var packageguid = ""; if (packageguidNode) { packageguid = packageguidNode.getAttribute("Value"); } if (packageguid) { if (packageguid.length > 0) { $("#txtPACKAGEGUID").val(packageguid); } } if (autoActivate == "1") { toggleAutoActivateEnabled("btAutoActivateYes"); } else { toggleAutoActivateEnabled("btAutoActivateNo"); } if (forceShutDown == "TRUE") { toggleForceAppShutdownEnabled("btForceAppShutdownTrue"); } else { toggleForceAppShutdownEnabled("btForceAppShutdownFalse"); } if (sharedComputerLicensing == "1") { toggleSharedComputerLicensing("btSharedComputerLicensingYes"); } else { toggleSharedComputerLicensing("btSharedComputerLicensingNo"); } } else { document.getElementById("btRemoveProduct").click(); } var loggingNodes = xmlDoc.documentElement.getElementsByTagName("Logging"); if (loggingNodes.length > 0) { var loggingNode = xmlDoc.documentElement.getElementsByTagName("Logging")[0]; var logLevel = loggingNode.getAttribute("Level"); var path = loggingNode.getAttribute("Path"); if (logLevel == "Off") { toggleLoggingEnabled("btLoggingLevelOff"); } else { toggleLoggingEnabled("btLoggingLevelStandard"); } $("#txtLoggingUpdatePath").val(path); } var productCount = getAddProductCount(xmlDoc); if (productCount == 0) { $("#btRemoveProduct").prop("disabled", true); } else { $("#btRemoveProduct").prop("disabled", false); } } function sendMail() { var xmlSource = $('textarea#xmlText').val(); var link = "mailto:" + "&subject=" + escape("Office Click-To-Run Configuration XML") + "&body=" + escape(xmlSource) ; window.location.href = link; } function clearXml() { $('textarea#xmlText').val(""); $("#txtDeadline").val(""); $("#txtLoggingUpdatePath").val(""); $("#txtPidKey").val(""); $("#txtSourcePath").val(""); $("#txtTargetVersion").val(""); $("#txtUpdatePath").val(""); $("#txtVersion").val(""); var resetDropDowns = document.getElementsByTagName("select"); for (var t = 0; t < resetDropDowns.length; t++) { var dropDown = resetDropDowns[t]; $("#" + dropDown.id).prop('selectedIndex', 0); } toggleRemove("removeAllProducts"); var clearButtons = ["#btLevelNone", "#btLevelFull", "#btLoggingLevelOff", "#btLoggingLevelStandard", "#btAcceptEULAEnabled", "#btAcceptEULADisabled", "#btLoggingLevelOff", "#btLoggingLevelStandard", "#btAutoActivateYes", "#btAutoActivateNo", "#btForceAppShutdownTrue", "#btForceAppShutdownFalse", "#btSharedComputerLicensingYes", "#btSharedComputerLicensingNo"]; for (var b = 0; b < clearButtons.length; b++) { var buttonName = clearButtons[b]; $(buttonName).removeClass('active'); $(buttonName).removeClass('btn-primary'); } $.cookie("xmlcache", ""); $("#btAddProduct").text('Add Product'); } function getXmlDocument() { var xmlSource = $('textarea#xmlText').val(); if (!(xmlSource)) { xmlSource = "<Configuration></Configuration>"; } var xmlDoc = createXmlDocument(xmlSource); return xmlDoc; } function createXmlDocument(string) { var doc; if (window.DOMParser) { parser = new DOMParser(); doc = parser.parseFromString(string, "application/xml"); } else // Internet Explorer { doc = new ActiveXObject("Microsoft.XMLDOM"); doc.async = "false"; doc.loadXML(string); } return doc; } function displayXml(xmlDoc) { var xmlString = (new XMLSerializer().serializeToString(xmlDoc.documentElement)); var xmlOutput = vkbeautify.xml(xmlString); $('textarea#xmlText').val(xmlOutput); $.cookie("xmlcache", xmlOutput); } function toggleRemove(sourceId) { if (sourceId.toLowerCase() == "removeallproducts") { $("#removeSelectProducts").removeClass('active'); $("#removeSelectProducts").removeClass('btn-primary'); var $this = $("#removeAllProducts"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } $("#cbRemoveProduct").prop("disabled", true); $("#cbRemoveLanguage").prop("disabled", true); $("#btAddRemoveLanguage").prop("disabled", true); } else { $("#removeAllProducts").removeClass('active'); $("#removeAllProducts").removeClass('btn-primary'); var $this = $("#removeSelectProducts"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } $("#cbRemoveProduct").prop("disabled", false); $("#cbRemoveLanguage").prop("disabled", false); $("#btAddRemoveLanguage").prop("disabled", false); } } function toggleUpdatesEnabled(sourceId) { if (sourceId.toLowerCase() == "btupdatesenabled") { //$("#btupdatesDisabled").removeClass('active'); $("#btupdatesDisabled").removeClass('btn-primary'); var $this = $("#btupdatesEnabled"); //if (!$this.hasClass('active')) { // $this.addClass('active'); //} if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } $("#inputDeadline").prop("disabled", false); toggleTextBox("txtUpdatePath", true); toggleTextBox("txtTargetVersion", true); } else { //$("#btupdatesEnabled").removeClass('active'); $("#btupdatesEnabled").removeClass('btn-primary'); var $this = $("#btupdatesDisabled"); //if (!$this.hasClass('active')) { // $this.addClass('active'); //} if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } $("#inputDeadline").prop("disabled", true); toggleTextBox("txtUpdatePath", false); toggleTextBox("txtTargetVersion", false); } return false; } function toggleTextBox(id, enabled) { if (enabled) { $("#" + id).prop("disabled", false); $("#" + id).css("background-color", ""); $("#" + id).css("border-color", ""); } else { $("#" + id).prop("disabled", true); $("#" + id).css("background-color", "#eeeeee"); $("#" + id).css("border-color", "#e1e1e1"); } } function toggleAutoActivateEnabled(sourceId) { if (sourceId.toLowerCase() == "btautoactivateyes") { $("#btAutoActivateNo").removeClass('active'); $("#btAutoActivateNo").removeClass('btn-primary'); var $this = $("#btAutoActivateYes"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } else { $("#btAutoActivateYes").removeClass('active'); $("#btAutoActivateYes").removeClass('btn-primary'); var $this = $("#btAutoActivateNo"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } } function toggleForceAppShutdownEnabled(sourceId) { if (sourceId.toLowerCase() == "btforceappshutdowntrue") { $("#btForceAppShutdownFalse").removeClass('active'); $("#btForceAppShutdownFalse").removeClass('btn-primary'); var $this = $("#btForceAppShutdownTrue"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } else { $("#btForceAppShutdownTrue").removeClass('active'); $("#btForceAppShutdownTrue").removeClass('btn-primary'); var $this = $("#btForceAppShutdownFalse"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } } function toggleSharedComputerLicensing(sourceId) { if (sourceId.toLowerCase() == "btsharedcomputerlicensingyes") { $("#btSharedComputerLicensingNo").removeClass('active'); $("#btSharedComputerLicensingNo").removeClass('btn-primary'); var $this = $("#btSharedComputerLicensingYes"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } else { $("#btSharedComputerLicensingYes").removeClass('active'); $("#btSharedComputerLicensingYes").removeClass('btn-primary'); var $this = $("#btSharedComputerLicensingNo"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } } function toggleDisplayLevelEnabled(sourceId) { if (sourceId.toLowerCase() == "btlevelnone") { $("#btLevelFull").removeClass('active'); $("#btLevelFull").removeClass('btn-primary'); var $this = $("#btLevelNone"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } else { $("#btLevelNone").removeClass('active'); $("#btLevelNone").removeClass('btn-primary'); var $this = $("#btLevelFull"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } } function toggleDisplayEULAEnabled(sourceId) { if (sourceId.toLowerCase() == "btaccepteulaenabled") { $("#btAcceptEULADisabled").removeClass('active'); $("#btAcceptEULADisabled").removeClass('btn-primary'); var $this = $("#btAcceptEULAEnabled"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } else { $("#btAcceptEULAEnabled").removeClass('active'); $("#btAcceptEULAEnabled").removeClass('btn-primary'); var $this = $("#btAcceptEULADisabled"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } } } function toggleLoggingEnabled(sourceId) { if (sourceId.toLowerCase() == "btloggingleveloff") { $("#btLoggingLevelStandard").removeClass('active'); $("#btLoggingLevelStandard").removeClass('btn-primary'); var $this = $("#btLoggingLevelOff"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } $("#txtLoggingUpdatePath").prop("disabled", true); } else { $("#btLoggingLevelOff").removeClass('active'); $("#btLoggingLevelOff").removeClass('btn-primary'); var $this = $("#btLoggingLevelStandard"); if (!$this.hasClass('active')) { $this.addClass('active'); } if (!$this.hasClass('btn-primary')) { $this.addClass('btn-primary'); } $("#txtLoggingUpdatePath").prop("disabled", false); } } function IsGuid(value) { var rGx = new RegExp("\\b(?:[A-F0-9]{8})(?:-[A-F0-9]{4}){3}-(?:[A-F0-9]{12})\\b"); return rGx.exec(value) != null; } var versions = [ '15.0.4745.1001', '15.0.4727.1003', '15.0.4719.1002', '15.0.4711.1003', '15.0.4701.1002', '15.0.4693.1002', '15.0.4693.1001', '15.0.4675.1002', '15.0.4667.1002', '15.0.4659.1001', '15.0.4649.1003', '15.0.4649.1001', '15.0.4641.1003', '15.0.4631.1004', '15.0.4631.1002', '15.0.4623.1003', '15.0.4615.1002', '15.0.4605.1003', '15.0.4569.1508', '15.0.4569.1507', '15.0.4551.1512', '15.0.4551.1011', '15.0.4551.1005', '15.0.4535.1511', '15.0.4535.1004', '15.0.4517.1509', '15.0.4517.1005', '15.0.4505.1510', '15.0.4505.1006', '15.0.4481.1510' ];
31.969328
145
0.584393
31054c54107b04330d616835f4c7a5b72dc05d8b
104
js
JavaScript
webpackEnv/src/main.js
alien-house/Front-End-Developer-Environment-Setup
17bc263dbf11f92a0814278f90868e3d12519859
[ "MIT" ]
null
null
null
webpackEnv/src/main.js
alien-house/Front-End-Developer-Environment-Setup
17bc263dbf11f92a0814278f90868e3d12519859
[ "MIT" ]
null
null
null
webpackEnv/src/main.js
alien-house/Front-End-Developer-Environment-Setup
17bc263dbf11f92a0814278f90868e3d12519859
[ "MIT" ]
null
null
null
// import 文を使って sub.js ファイルを読み込む。 import {hello} from './sub'; // sub.jsに定義されたJavaScriptを実行する。 hello();
20.8
33
0.711538
31063f147caa367673ce21d0113b55eeceddd252
311
js
JavaScript
src/create.js
teleology-io/teleology-dynamo
956e82164965576349259bc11b3cd0d17855da76
[ "MIT" ]
null
null
null
src/create.js
teleology-io/teleology-dynamo
956e82164965576349259bc11b3cd0d17855da76
[ "MIT" ]
1
2020-08-14T07:17:25.000Z
2020-08-14T07:17:25.000Z
src/create.js
icarus-sullivan/teleology-dynamo
5dd8a8aac060088623f917476552ba254eb88db1
[ "MIT" ]
null
null
null
const get = require('./get'); const put = require('./put'); module.exports = async ({ ddb, table, key, value, item }) => { const exists = await get({ ddb, table, key, value, item }); if (exists) { throw new Error(`A record already exists with that ${key}`); } return put({ ddb, table, item }); };
25.916667
64
0.598071
3106f791b63e0d90691915d8fd98727367ebf4ec
1,785
js
JavaScript
event-twister.js
kt3k/event-twister
009f6138014e78fa542ab2548b4f181dd676bab9
[ "MIT" ]
null
null
null
event-twister.js
kt3k/event-twister
009f6138014e78fa542ab2548b4f181dd676bab9
[ "MIT" ]
null
null
null
event-twister.js
kt3k/event-twister
009f6138014e78fa542ab2548b4f181dd676bab9
[ "MIT" ]
null
null
null
/** * event-twister.js v2.0.0 * author: Yoshiya Hinosawa ( https://github.com/kt3k ) * license: MIT */ (function ($) { 'use strict'; $.registerClassComponent('event-twister', function (){ var twister = new EventTwister(this); twister.bindEvents(); }); /** * EventTwister handles the initialization of `.event-twister` class element. */ function EventTwister(elem) { this.$elem = $(elem); } var pt = EventTwister.prototype; /** * Binds events to the element. */ pt.bindEvents = function () { var $elem = this.$elem; var handleBubble = this.handleBubble(); this.getTwists().forEach(function (twist) { $elem.on(twist.original, function (e) { if (!handleBubble && e.target !== $elem.get(0)) { return; } $elem.trigger(twist.twist); }); }); }; pt.getTwists = function () { var twist = this.$elem.attr('twist') || this.$elem.attr('twists'); if (!twist) { return []; } var twists = twist.split(';'); return twists.map(function (twist) { var map = twist.split(':', 2); if (map.length < 2) { return; } map = map.map(function (event) { return event.replace(/^\s*|\s*$/g, ''); // trim() }); return { original: map[0], twist: map[1] }; }).filter(function (twist) { return !!twist; }); // filter out undefined }; pt.handleBubble = function () { return !!this.$elem.attr('handle-bubble'); }; }(window.jQuery));
17.330097
81
0.473389
310794497edf0457760709f744b55cfee370be33
2,283
js
JavaScript
services/drone_racing/frontend/src/components/Header.js
vient/proctf-2019
b7b954fff2396a7a7a83c90ec55d75bce4a3485c
[ "MIT" ]
2
2020-04-22T19:36:16.000Z
2020-09-16T07:45:54.000Z
services/drone_racing/frontend/src/components/Header.js
vient/proctf-2019
b7b954fff2396a7a7a83c90ec55d75bce4a3485c
[ "MIT" ]
3
2021-03-31T19:21:51.000Z
2021-06-08T20:31:48.000Z
services/drone_racing/frontend/src/components/Header.js
leetchicken/proctf-2019
b7b954fff2396a7a7a83c90ec55d75bce4a3485c
[ "MIT" ]
3
2019-10-26T00:25:03.000Z
2019-11-23T21:10:10.000Z
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import {AccountCircle} from "@material-ui/icons"; import {Link} from "react-router-dom"; const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, }, menuButton: { color: 'white', marginRight: theme.spacing(2), }, usernameContainer: { display: 'inline-flex', justifyContent: 'center', alignContent: 'center', alignItems: 'center', padding: '8px 11px', textTransform: 'uppercase', boxSizing: 'border-box', verticalAlign: 'middle', fontSize: '0.9375rem', }, username: { fontWeight: '500', paddingLeft: '8px', }, title: { flexGrow: 1, }, titleLink: { color: 'inherit', textDecoration: 'none', cursor: 'pointer', fontSize: 'inherit', fontWeight: 'inherit', } })); export default function Header(props) { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <Typography variant="h6" className={classes.title}> <Link to="/" className={classes.titleLink}>Drone racing</Link> </Typography> <div style={{"position": "relative"}}> <div className={classes.usernameContainer}> <AccountCircle/> <div className={classes.username}> { props.user.name } </div> </div> <Button size="large" className={classes.menuButton} onClick={props.onLogoutButtonClick} > Logout </Button> </div> </Toolbar> </AppBar> </div> ); }
30.039474
86
0.483136
31079af0b1d71b79621d6887456c1ea3e9b81a4a
1,407
js
JavaScript
public/out/node_modules/style-sherpa/index.js
html5col/honey
38babb809fa2e87eaebcf02d83e556a44c2ead8f
[ "MIT" ]
1
2016-07-20T03:10:44.000Z
2016-07-20T03:10:44.000Z
public/out/node_modules/style-sherpa/index.js
html5col/honey
38babb809fa2e87eaebcf02d83e556a44c2ead8f
[ "MIT" ]
null
null
null
public/out/node_modules/style-sherpa/index.js
html5col/honey
38babb809fa2e87eaebcf02d83e556a44c2ead8f
[ "MIT" ]
null
null
null
var extend = require('util')._extend; var fs = require('fs'); var handlebars = require('handlebars'); var hljs = require('highlight.js'); var marked = require('marked'); var path = require('path'); var renderer = require('./lib/marked'); module.exports = function(input, options, cb) { options = extend({ template: path.join(__dirname, 'template.html') }, options); // Read input file var inputFile = fs.readFileSync(path.join(process.cwd(), input)); // The divider for pages is four newlines var pages = inputFile.toString().replace(/(?:\r\n)/mg, "\n").split('\n\n\n\n'); // Process each page pages = pages.map(function(page, i) { // Convert Markdown to HTML var body = marked(page, { renderer: renderer }); // Find the title of the page by identifying the <h1> // The second match is the inner group var foundHeadings = body.match('<h1.*>(.*)</h1>'); var title = foundHeadings && foundHeadings[1] || 'Page ' + (i + 1); var anchor = title.toLowerCase().replace(/[^\w]+/g, '-'); return { title: title, anchor: anchor, body: body } }); // Write file to disk var templateFile = fs.readFileSync(path.join(process.cwd(), options.template)); var template = handlebars.compile(templateFile.toString(), { noEscape: true }); var outputPath = path.join(process.cwd(), options.output); fs.writeFile(outputPath, template({ pages: pages }), cb); }
35.175
81
0.653873
31090356f5b6732f0838e7eda1ef7cf49b4e84d5
15,236
js
JavaScript
server.js
tormentedhollow/pmis2019
67f3253538953f8b2463bae440c21afb942a192b
[ "MIT" ]
null
null
null
server.js
tormentedhollow/pmis2019
67f3253538953f8b2463bae440c21afb942a192b
[ "MIT" ]
null
null
null
server.js
tormentedhollow/pmis2019
67f3253538953f8b2463bae440c21afb942a192b
[ "MIT" ]
null
null
null
const express = require('express'); const compression = require('compression'); const mysql = require('mysql'); const bodyParser = require("body-parser"); // Body parser for fetch posted data const async = require('async'); const path = require('path'); var staticRoot = __dirname + './dist'; const CONTEXT = '/angular-ngrx-material-starter'; const PORT = 3115; const app = express(); app.use(compression()); app.use(require('cors')()); app.use(CONTEXT, express.static(__dirname + '/dist')); app.use('/', express.static(__dirname + '/dist')); app.use(bodyParser.json()); // Body parser use JSON data app.use(bodyParser.urlencoded({ extended: false })); //app.listen(PORT, '172.16.130.8', () => console.log(`App running on localhost:${PORT}/${CONTEXT}`)); app.listen(PORT, '0.0.0.0', () => console.log(`App running on localhost:${PORT}/${CONTEXT}`)); const connection = mysql.createConnection({ host : '172.16.130.8', user : 'pmis', password : 'pmis', database : 'raw_dasystem2019', }); connection.connect(); app.get('/', (req, res) => res.send('Hello World!')); app.get('/dashboard', function(req, res) { data = []; function delay() { return new Promise(resolve => setTimeout(resolve, 500)); } async function delayedLog(item) { // notice that we can await a function // that returns a promise connection.query(` SELECT sum(janft) as janft FROM tbl_mfo where program_id =`+item, function (error, results) { if (error) throw error; results.id = item; data.push(results); }); await delay(); console.log(data); } async function processArray(array) { const promises = array.map(delayedLog); // wait until all promises are resolved await Promise.all(promises); res.send(data); console.log('Done!'); } processArray([1, 2, 3, 4, 5]); }); app.post('/login',function(req,res){ console.log(req.body); var query = "SELECT * FROM ?? WHERE ??=? and ??=?"; var table = ["users", "username", req.body.username, "password", req.body.password]; query = mysql.format(query,table); console.log(query); connection.query(query,function(err, rows, fields){ if(rows.length != 0){ res.status(200).json({ user_id: rows[0].user_id, pid: rows[0].program_id, b: rows[0].budget, username: rows[0].username, token: 'dacaraga'}); }else{ res.status(400).json('Invalid Username or Password'); } }); }); app.post('/mfos',function(req,res){ var query = ` SELECT *, tbl_mfo.mfo_id FROM tbl_mfo left JOIN tbl_allotment on tbl_mfo.mfo_id = tbl_allotment.mfo_id LEFT JOIN tbl_object on tbl_allotment.object_id=tbl_object.object_id where program_id = ?`; var data = [req.body.pid]; query = mysql.format(query,data); console.log(query); connection.query(query, function (error, results) { if (error) throw error; res.json(results); }); }); app.post('/mfosPhysical',function(req,res){ connection.query(` SELECT * FROM tbl_mfo where program_id =`+req.body.pid, function (error, results) { if (error) throw error; res.json(results); }); }); app.post('/getLogs', function(req, res){ var query = "SELECT * FROM tbl_logs where pid = ? and beds = ? order by date DESC"; var data = [req.body.pid, req.body.beds]; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); res.json(rows); }) }); app.post('/getDistrict', function(req, res){ var query = "SELECT * FROM tbl_mfo INNER JOIN tbl_district on tbl_mfo.mfo_id = tbl_district.mfo_id WHERE tbl_mfo.program_id = ? group by tbl_mfo.mfo_id"; var data = [req.body.pid]; var datares={}; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ var province = ["Agusan del Norte", "Agusan del Sur", "Surigao del Norte", "Surigao del Sur", "Province of Dinagat Islands", "Butuan City"]; var itemsProcessed = 0; async.each(rows, function(row, callback){ var mfo_id = row.mfo_id; //console.log(mfo_id); var districtFunction =function(prov, callback){ var arr = []; async.parallel({ one: function(callback) { var sql = `SELECT mfo_id,province,district,sum(target) as target ,cost, sum(accomp) as accomp, GROUP_CONCAT(CONCAT(municipal, '(', target,')') SEPARATOR ", ") as text, GROUP_CONCAT(CASE WHEN accomp>0 THEN CONCAT(municipal, '(', accomp,')') ELSE NULL END SEPARATOR ", " ) as text2 FROM tbl_district where mfo_id = ? and province= ? and district=1 GROUP BY mfo_id,province,district`; connection.query(String(sql),[mfo_id, prov,],function(k_err,k_rows){ if(k_err) console.error(k_err); if(k_rows[0] === undefined){ callback(null, {accomp: null, cost: null, target: null, text: null, text2: null}) }else{ callback(null, k_rows[0]); } }); }, two: function(callback) { var sql = `SELECT mfo_id,province,district,sum(target) as target ,cost, sum(accomp) as accomp, GROUP_CONCAT(CONCAT(municipal, '(', target,')') SEPARATOR ", ") as text, GROUP_CONCAT(CASE WHEN accomp>0 THEN CONCAT(municipal, '(', accomp,')') ELSE NULL END SEPARATOR ", " ) as text2 FROM tbl_district where mfo_id = ? and province=? and district=2 GROUP BY mfo_id,province,district`; console.log(sql); connection.query(String(sql),[mfo_id, prov,],function(k_err,k_rows){ if(k_err) console.error(k_err); if(k_rows[0] === undefined){ callback(null, {accomp: null, cost: null, target: null, text: null}) }else{ callback(null, k_rows[0]); } }); }, // three: function(callback) { // var sql = `SELECT mfo_id,province,district,sum(accomp) as accomp , // GROUP_CONCAT(CONCAT(municipal, '(', accomp,')') SEPARATOR ", ") as text // FROM tbl_district where mfo_id = ? and province=? and district=1 and accomp>0 GROUP BY mfo_id,province,district`; // connection.query(String(sql),[mfo_id, prov,],function(k_err,k_rows){ // if(k_err) console.error(k_err); // callback(null, k_rows[0]); // }); // }, // four: function(callback) { // var sql = `SELECT mfo_id,province,district,sum(accomp) as accomp , // GROUP_CONCAT(CONCAT(municipal, '(', accomp,')') SEPARATOR ", ") as text // FROM tbl_district where mfo_id = ? and province=? and district=2 and accomp>0 GROUP BY mfo_id,province,district`; // connection.query(String(sql),[mfo_id, prov,],function(k_err,k_rows){ // if(k_err) console.error(k_err); // callback(null, k_rows[0]); // }); // } }, function(err, results) { return callback(null, results); }); } async.map(province, districtFunction, function(err, result){ console.log(result); itemsProcessed++; row.dist = result; if(itemsProcessed === rows.length) { datares["data"] = rows; res.json(rows); } /*row.area=result; itemsProcessed++; if(itemsProcessed === rows.length) { datares["data"] = rows; res.json(datares); }*/ }); }) if(rows.length<=0) res.json(rows); if (err) throw res.status(400).json(err); //res.json(rows); }) }); app.post('/getDistrictDetails', function(req, res){ var query = "SELECT * FROM tbl_district left join tbl_mfo on tbl_district.mfo_id = tbl_mfo.mfo_id WHERE province like(?) and district = ? and tbl_district.mfo_id = ?"; var data = req.body.data; console.log(data); query = mysql.format(query,[data.province,data.district,data.mfo_id]); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.length > 0){ res.json(rows); } }) }); app.post('/addDistrictDetails', function(req, res){ var query = "INSERT INTO tbl_district (mfo_id, province,district,municipal,target,accomp,cost) values (?,?,?,?,?,?,?)"; var data = req.body.data; console.log(data); query = mysql.format(query,[data.mfo_id, data.province, data.district, data.municipal, data.target,data.accomp, data.cost]); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.affectedRows > 0){ console.log(rows); res.json(rows); } }) }); app.post('/updateDistrictDetailsTarget', function(req, res){ var query = "UPDATE tbl_district SET ? WHERE id = ?"; var data = req.body.data; //console.log(data); query = mysql.format(query,[data.data,data.id]); console.log(query); connection.query(query, function(err, rows){ console.log(rows); if (err) throw res.status(400).json(err); if (rows.affectedRows > 0){ console.log(rows); res.json(rows); } }) }); app.post('/updateDistrictDetails', function(req, res){ var query = "UPDATE tbl_district SET accomp = ? WHERE id = ?"; var data = req.body.data; //console.log(data); query = mysql.format(query,[Number(data.accomp),data.id]); console.log(query); connection.query(query, function(err, rows){ console.log(rows); if (err) throw res.status(400).json(err); if (rows.affectedRows > 0){ console.log(rows); res.json(rows); } }) }); app.post('/lastUpdated', function(req, res){ var query = "SELECT date FROM tbl_logs where pid = ? and beds = ? ORDER BY date DESC LIMIT 1 "; var data = [req.body.pid, req.body.beds]; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.length > 0){ res.json(rows[0].date); }else{ res.json(null); } }) }); app.post('/addObject', function(req, res){ var query = "INSERT INTO tbl_allotment (mfo_id, object_id, pid) VALUES (?,?,?)"; var data = [req.body.mfo_id, req.body.object_id, req.body.pid]; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.insertId){ res.status(200).json("Successfully Object Added!") } }) }); app.post('/addLogs', function(req, res){ var query = "INSERT INTO tbl_logs (pid, mfo_id, message, date, beds) VALUES (?, ?, ?, NOW(), ?)"; var data = [req.body.uid, req.body.mfo_id, req.body.message, req.body.beds]; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.insertId){ res.status(200).json("Successfully Logs Added!") } }) }); app.post('/updateAllotment', function(req, res){ var query = "UPDATE tbl_allotment SET ?? = ? WHERE id = ?"; var data = [req.body.col, req.body.value, req.body.id]; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.changedRows){ res.status(200).json("Successfully Updated!") } }) }); app.post('/updatePhysical', function(req, res){ var query = "UPDATE tbl_mfo SET ?? = ? WHERE mfo_id = ?"; var data = [req.body.col, req.body.value, req.body.id]; query = mysql.format(query,data); console.log(query); connection.query(query, function(err, rows){ if (err) throw res.status(400).json(err); if (rows.changedRows){ res.status(200).json("Successfully Updated!") } }) }); app.post('/summaryObject', function(req, res){ connection.query(` SELECT a.object_id, b.name, b.type, b.header, SUM(budget) as budget, SUM(adjustment) as adj, SUM(jan) as jan, SUM(feb) as feb, SUM(mar) as mar, SUM(apr) as apr, SUM(may) as may, SUM(jun) as jun, SUM(jul) as jul, SUM(aug) as aug, SUM(sep) as sep, SUM(oct) as oct, SUM(nov) as nov, SUM(decm) as decm, SUM(jan_da) as jan_da, SUM(feb_da) as feb_da, SUM(mar_da) as mar_da, SUM(apr_da) as apr_da, SUM(may_da) as may_da, SUM(jun_da) as jun_da, SUM(jul_da) as jul_da, SUM(aug_da) as aug_da, SUM(sep_da) as sep_da, SUM(oct_da) as oct_da, SUM(nov_da) as nov_da, SUM(dec_da) as dec_da FROM tbl_allotment a LEFT JOIN tbl_object b ON a.object_id = b.object_id where pid =`+req.body.pid+` GROUP BY a.object_id `, function(error, results){ if (error) throw error; res.json(results); }) }) //connection.end(); app.get('/', function (req, res) { res.sendFile(path.join(staticRoot,'index.html')) }); app.get('*', function (req, res) { res.sendFile(path.join(staticRoot,'index.html')); });
41.972452
654
0.529929
310a18c59418d7cd7f3ee627af3af0cbad652ccb
208
js
JavaScript
app/bootstrap/index.js
jhnns/webpack-with-common-libs
617e7757868653854a7f32a73293efb4454c707d
[ "MIT" ]
357
2015-01-07T17:05:02.000Z
2021-11-08T11:03:31.000Z
app/bootstrap/index.js
lucascherifi/webpack-with-common-libs
82e87e1cd13a76678d0ee0f4a87d4ce5dcd370b0
[ "MIT" ]
4
2015-02-16T19:50:52.000Z
2017-10-18T21:10:38.000Z
app/bootstrap/index.js
lucascherifi/webpack-with-common-libs
82e87e1cd13a76678d0ee0f4a87d4ce5dcd370b0
[ "MIT" ]
186
2015-01-29T12:37:25.000Z
2021-02-07T02:33:37.000Z
// twbs/bootstrap is included in the webpack.config.js // as multi-module entry $("#myModal").modal({ show: false }); $("#save-button").click(function() { alert("Saved"); $("#myModal").modal("hide"); });
18.909091
54
0.629808
310a6b1a51c0cd14ee1f7f1cf7a5c593f62a7b35
236
js
JavaScript
tests/browser/features/aspect-ratio.js
itsViney/css-feature-toggle-devtools-extension
8ff0b4a3e5577f635effa04e6a7eae42d01e70c0
[ "MIT" ]
null
null
null
tests/browser/features/aspect-ratio.js
itsViney/css-feature-toggle-devtools-extension
8ff0b4a3e5577f635effa04e6a7eae42d01e70c0
[ "MIT" ]
null
null
null
tests/browser/features/aspect-ratio.js
itsViney/css-feature-toggle-devtools-extension
8ff0b4a3e5577f635effa04e6a7eae42d01e70c0
[ "MIT" ]
null
null
null
addTest({ name: 'aspect-ratio', group: 'Aspect ratio', css: `<indicator-selector>::before { content: ''; display: block; background: <supported-color>; width: 100%; aspect-ratio: 1 / 1; }` });
21.454545
41
0.542373
310b137947bc59036357278ec1a74f45c49f8a4b
200
js
JavaScript
lib/runner/targetRunner.js
gitter-badger/ecmake
bb8b67d1723c2b760331e992eb886357239ec062
[ "MIT" ]
null
null
null
lib/runner/targetRunner.js
gitter-badger/ecmake
bb8b67d1723c2b760331e992eb886357239ec062
[ "MIT" ]
null
null
null
lib/runner/targetRunner.js
gitter-badger/ecmake
bb8b67d1723c2b760331e992eb886357239ec062
[ "MIT" ]
null
null
null
const { getTarget } = require('../model/toolBox'); module.exports = class TargetRunner { constructor(root) { this.root = root; } go(target) { getTarget(this.root, target).go(); } };
16.666667
50
0.615
310b56ce01433ec98a24e60c20b440b1c5b6e2b8
130
js
JavaScript
src/models/index.js
motyar/quotable
4a3cb4e02197e0ec5ed913e32116eb3b839e2c39
[ "MIT" ]
730
2019-06-23T23:48:23.000Z
2022-03-31T10:04:30.000Z
src/models/index.js
motyar/quotable
4a3cb4e02197e0ec5ed913e32116eb3b839e2c39
[ "MIT" ]
59
2019-09-05T11:47:34.000Z
2022-03-17T00:59:57.000Z
src/models/index.js
motyar/quotable
4a3cb4e02197e0ec5ed913e32116eb3b839e2c39
[ "MIT" ]
122
2019-08-01T02:25:59.000Z
2022-03-31T11:13:05.000Z
import Quotes from './Quotes' import Authors from './Authors' import Tags from './Tags' export default { Quotes, Authors, Tags }
21.666667
40
0.723077
310d454e191cadcef4c190dd1e878f58b9cdbd6a
2,454
js
JavaScript
Craftyy/js/addons/screenwrite/ScreenwriteCamera.js
ncase/cuttingedge-craftyy
1600cc6981e6f04b13b71f4ab6c53a19760dfe0a
[ "MIT" ]
1
2021-11-08T09:45:24.000Z
2021-11-08T09:45:24.000Z
Craftyy/js/addons/screenwrite/ScreenwriteCamera.js
ncase/cuttingedge-craftyy
1600cc6981e6f04b13b71f4ab6c53a19760dfe0a
[ "MIT" ]
null
null
null
Craftyy/js/addons/screenwrite/ScreenwriteCamera.js
ncase/cuttingedge-craftyy
1600cc6981e6f04b13b71f4ab6c53a19760dfe0a
[ "MIT" ]
null
null
null
(function(exports){ /**** Screenwrite: Pan & Zoom UI */ var EditCam = { initialize: function(){ EditCam.reset(); // Events News.subscribe("tick",EditCam.update); News.subscribe("scroll",EditCam.onScroll); }, reset: function(){ // Matrices EditCam.mtx = new Matrix2D(); EditCam.pan = new Matrix2D(); EditCam.zoom = new Matrix2D(); // Helper info EditCam.zoomLevel = 0; EditCam.vel = {x:0,y:0,scroll:0}; }, update: function(){ if(!Screenplay.scene) return; // Update matrices EditCam.updateScroll(); EditCam.updatePan(); // Deselect if moving cam if( Math.abs(EditCam.vel.scroll)>0.01 || Key.left||Key.right||Key.up||Key.down){ News.publish("edit.Deselected"); } // Apply matrices EditCam.mtx.identity(); EditCam.mtx.appendMatrix(EditCam.pan); EditCam.mtx.appendMatrix(EditCam.zoom); EditCam.mtx.invert(); EditCam.mtx.decompose(Screenplay.scene.art); }, updateScroll: function(){ var prevScale = Math.exp(EditCam.zoomLevel); EditCam.vel.scroll *= 0.5; EditCam.zoomLevel -= EditCam.vel.scroll; // Bounce if(EditCam.zoomLevel<-0.69){ EditCam.zoomLevel=-0.69; EditCam.vel.scroll *= -0.5; } if(EditCam.zoomLevel>1.10){ EditCam.zoomLevel=1.10; EditCam.vel.scroll *= -0.5; } // Zoom onto Mouse position var tmpMtx = new Matrix2D(); tmpMtx.appendMatrix(EditCam.zoom); tmpMtx.append(1,0,0,1,Mouse.x,Mouse.y); var regX = tmpMtx.tx; var regY = tmpMtx.ty; var currScale = Math.exp(EditCam.zoomLevel); var relativeScale = currScale/prevScale; // Matrix EditCam.zoom.translate(-regX,-regY); EditCam.zoom.scale(relativeScale,relativeScale); EditCam.zoom.translate(regX,regY); }, updatePan: function(){ // TODO: CLICK & DRAG // Keys if(Key.left) EditCam.vel.x = (EditCam.vel.x-20)/2; if(Key.right) EditCam.vel.x = (EditCam.vel.x+20)/2; if(Key.up) EditCam.vel.y = (EditCam.vel.y-20)/2; if(Key.down) EditCam.vel.y = (EditCam.vel.y+20)/2; // With Inertia if(!Key.left && !Key.right){ EditCam.vel.x *= 0.5; } if(!Key.up && !Key.down){ EditCam.vel.y *= 0.5; } // Matrix var scale = Math.exp(EditCam.zoomLevel); EditCam.pan.tx += EditCam.vel.x * scale; EditCam.pan.ty += EditCam.vel.y * scale; }, onScroll: function(event){ EditCam.vel.scroll += event.scroll; } }; ////////////////// // SINGLETON exports.EditCam = EditCam; News.subscribe("screenplay.Init",EditCam.initialize); })(window);
19.95122
82
0.651182
310d7cc3cda92a39c49461067f314cca6802d60c
835
js
JavaScript
app/scripts/mt.ui/controllers/createAccountModal.js
tunguski/matsuo-ng-ui
724767bed1a47df57ffa91e5f1f6e639e2b26bd1
[ "MIT" ]
null
null
null
app/scripts/mt.ui/controllers/createAccountModal.js
tunguski/matsuo-ng-ui
724767bed1a47df57ffa91e5f1f6e639e2b26bd1
[ "MIT" ]
null
null
null
app/scripts/mt.ui/controllers/createAccountModal.js
tunguski/matsuo-ng-ui
724767bed1a47df57ffa91e5f1f6e639e2b26bd1
[ "MIT" ]
null
null
null
'use strict'; angular.module('mt.ui') /** * @ngdoc function * @name mt.ui.controller:CreateAccountModalCtrl * @description * # CreateAccountModalCtrl * Controller of the mt.ui */ .controller('CreateAccountModalCtrl', function ($scope, $http, $uibModalInstance) { $scope.loginData = {}; $scope.createAccount = function(isValid) { if (isValid) { $http.post('/api/login/createAccount', $scope.loginData) .success(function (data) { toastr.success($scope.translate('dialog.createAccount.success') + '\n' + data); $uibModalInstance.close(); }); } else { $scope.errorClass = 'text-red'; } }; $scope.close = function() { $uibModalInstance.close(); }; }) ;
26.935484
95
0.548503
310db5df087cd6018c9e72c4c82bbd3ea635b3c3
3,317
js
JavaScript
index.js
realToadtoad/public-gcal-fetch
cc30e0c4b82edb5ad664c9df35926812839c93a1
[ "0BSD" ]
null
null
null
index.js
realToadtoad/public-gcal-fetch
cc30e0c4b82edb5ad664c9df35926812839c93a1
[ "0BSD" ]
null
null
null
index.js
realToadtoad/public-gcal-fetch
cc30e0c4b82edb5ad664c9df35926812839c93a1
[ "0BSD" ]
null
null
null
// var request = require('request'); // Credits to https://gist.github.com/marcelotmelo/b67f58a08bee6c2468f8 var RFC_3339_regex = /^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))$/; function PublicGcal(options) { options = options || {}; if (!options.API_key) { throw new Error("API_key must be specified!"); } if (!options.calendarId) { throw new Error("calendarId must be specified!"); } this.API_key = options.API_key; this.calendarId = options.calendarId; } PublicGcal.prototype.getEvents = async function (options, callback) { // thanks to user RichardLitt for following code options.singleEvents = "singleEvents" in options ? options.singleEvents : true; // default true options.orderBy = options.orderBy || "startTime"; if (options.timeMin && !options.timeMin.match(RFC_3339_regex)) { return callback( new Error( "timeMin must be an RFC3339 timestamp with mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z." ) ); } if (options.timeMax && !options.timeMax.match(RFC_3339_regex)) { return callback( new Error( "timeMax must be an RFC3339 timestamp with mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z." ) ); } if (options.q && typeof options.q !== "string") { return callback(new Error("q must be a string!")); } if ( options.orderBy && options.orderBy !== "startTime" && options.orderBy !== "updated" ) { return callback( new Error("orderBy must be either 'startTime' or 'updated'!") ); } if (options.singleEvents && typeof options.singleEvents !== "boolean") { return callback(new Error("singleEvents must be boolean!")); } var url = "https://www.googleapis.com/calendar/v3/calendars/" + this.calendarId + "/events?key=" + this.API_key; if (options.singleEvents) { url = url + "&singleEvents=True"; } if (options.timeMin) { url = url + "&timeMin=" + options.timeMin; } if (options.timeMax) { url = url + "&timeMax=" + options.timeMax; } if (options.q) { url = url + "&q=" + options.q; } if (options.orderBy) { if (options.singleEvents || options.orderBy === "updated") { url = url + "&orderBy=" + options.orderBy; } } console.log(url); var gcalOutput = await fetch(url); gcalOutput = await gcalOutput.json(); return await gcalOutput.items; //original code /* request.get(url, function (error, response, data) { if (error) { return callback(error); } data = JSON.parse(data); if ('error' in data) { return callback(new Error('Error from Google: ' + JSON.stringify(data.error.errors))); } var events = data.items; result = events.filter(function (item) { return item.status && !item.status.match(/cancelled/i); }).map(function (item) { return { summary: item.summary, description: item.description ? item.description : '', location: item.location ? item.location : '', start: item.start, end: item.end }; }); callback(null, result); }); //*/ }; module.exports = PublicGcal;
26.75
184
0.611697
310e03f33cb0bff4de6fbab70907fbec07086f8d
392
js
JavaScript
node_modules/newtype-ts/lib/NonZeroInteger.js
alwanof/tc-cucu
f5ad2107e47c023879d7be69494d2c814dd66019
[ "MIT" ]
null
null
null
node_modules/newtype-ts/lib/NonZeroInteger.js
alwanof/tc-cucu
f5ad2107e47c023879d7be69494d2c814dd66019
[ "MIT" ]
null
null
null
node_modules/newtype-ts/lib/NonZeroInteger.js
alwanof/tc-cucu
f5ad2107e47c023879d7be69494d2c814dd66019
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _1 = require("."); var Integer_1 = require("./Integer"); var NonZero_1 = require("./NonZero"); /** * @since 0.2.0 */ exports.isNonZeroInteger = function (n) { return NonZero_1.isNonZero(n) && Integer_1.isInteger(n); }; /** * @since 0.2.0 */ exports.prismNonZeroInteger = _1.prism(exports.isNonZeroInteger);
28
101
0.681122
310ff6c1da997906761c8d044b1d41b476b7fbdd
86
js
JavaScript
abbreviate-a-two-word-name/solution.js
ErmineNotyours/code-wars
3bcca56572ccdf9c1fb8b92f8ffedd03d84d1b9d
[ "MIT" ]
null
null
null
abbreviate-a-two-word-name/solution.js
ErmineNotyours/code-wars
3bcca56572ccdf9c1fb8b92f8ffedd03d84d1b9d
[ "MIT" ]
null
null
null
abbreviate-a-two-word-name/solution.js
ErmineNotyours/code-wars
3bcca56572ccdf9c1fb8b92f8ffedd03d84d1b9d
[ "MIT" ]
null
null
null
function abbrevName(name){ return name.match(/\b[^ ]/g).join('.').toUpperCase(); }
28.666667
57
0.627907
311085523ffd13cec299878c19d326cce57d749b
782
js
JavaScript
ProgettoLube/frontend/dashboard/node_modules/react-map-gl/dist/es5/utils/crisp-pixel.js
Lube-Project/ProgettoLube
cbf33971e2c2e865783ec1a2302625539186a338
[ "MIT" ]
null
null
null
ProgettoLube/frontend/dashboard/node_modules/react-map-gl/dist/es5/utils/crisp-pixel.js
Lube-Project/ProgettoLube
cbf33971e2c2e865783ec1a2302625539186a338
[ "MIT" ]
1
2021-09-10T18:20:18.000Z
2021-09-10T18:20:18.000Z
ProgettoLube/frontend/dashboard/node_modules/react-map-gl/dist/es5/utils/crisp-pixel.js
Lube-Project/ProgettoLube
cbf33971e2c2e865783ec1a2302625539186a338
[ "MIT" ]
2
2021-07-18T20:23:48.000Z
2021-09-14T20:08:11.000Z
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.crispPercentage = exports.crispPixel = void 0; var pixelRatio = typeof window !== 'undefined' && window.devicePixelRatio || 1; var crispPixel = function crispPixel(size) { return Math.round(size * pixelRatio) / pixelRatio; }; exports.crispPixel = crispPixel; var crispPercentage = function crispPercentage(el, percentage) { var dimension = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'x'; if (el === null) { return percentage; } var origSize = dimension === 'x' ? el.offsetWidth : el.offsetHeight; return crispPixel(percentage / 100 * origSize) / origSize * 100; }; exports.crispPercentage = crispPercentage; //# sourceMappingURL=crisp-pixel.js.map
28.962963
90
0.710997
3110fe5b9128d7060207599ae05448fa3b7a37a6
3,590
js
JavaScript
Frontend/dist/static/js/6.785db00faf76511ddd5e.js
17320692835RGF/buptoj
3d1e4719d757b4f0199e4451be7c0bee28e7c3ca
[ "MIT" ]
null
null
null
Frontend/dist/static/js/6.785db00faf76511ddd5e.js
17320692835RGF/buptoj
3d1e4719d757b4f0199e4451be7c0bee28e7c3ca
[ "MIT" ]
null
null
null
Frontend/dist/static/js/6.785db00faf76511ddd5e.js
17320692835RGF/buptoj
3d1e4719d757b4f0199e4451be7c0bee28e7c3ca
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[6],{0:function(e,t){},1:function(e,t){},2:function(e,t){},"3jW1":function(e,t){},xbUP:function(e,t,s){"use strict";s.r(t);var a=s("Iab2"),o=s.n(a),r=s("EUZL"),n=s.n(r),c={name:"givechoiceproblemscore",data:function(){return{singalscore:"",studentcount:"",type:1,isadmin:!1,canshow:!1,standardanswer:"",tableData:[],contestid:"",scoreform:{ContestId:"",ChoiceProblemAnswer:"",one_pro_score:""}}},methods:{exportExcel:function(){var e=n.a.utils.table_to_book(document.querySelector("#out-table")),t=n.a.write(e,{bookType:"xlsx",bookSST:!0,type:"array"});try{o.a.saveAs(new Blob([t],{type:"application/octet-stream"}),"ChoiceProblemScores.xlsx")}catch(e){"undefined"!=typeof console&&this.$message.error(e)}return t},SubmitScore:function(){var e=this;this.$confirm("确定提交评阅分数吗?数据库中学生分数将在后台完成更新。",{confirmButtonText:"确定",cancelButtonText:"取消",type:"warning"}).then(function(){e.scoreform.ContestId=e.$route.query.contestid,e.scoreform.ChoiceProblemAnswer=e.standardanswer,e.scoreform.one_pro_score=e.singalscore,e.$axios.post("/scorecontestchoiceproblems",e.scoreform).then(function(t){e.$message({message:t.data,type:"success"})}).catch(function(t){e.$message.error("提交评阅失败!请再提交一次。可能是你没有登录,或者后台出错,请联系管理员查看后台输出日志以获取错误信息("+JSON.stringify(t.response.data)+")")})})},Score:function(){for(var e=this.standardanswer.toUpperCase(),t=0;t<this.studentcount;t++){for(var s=this.tableData[t].answer,a=Number(0),o=0;o<e.length;o++)s[o]===e[o]&&(a+=Number(this.singalscore));this.tableData[t].score=Number(a)}}},created:function(){var e=this;if(this.type=sessionStorage.type,2!=this.type&&3!=this.type)return this.$message.error("非法访问!"),void(this.canshow=!1);this.canshow=!0,3==this.type&&(this.isadmin=!0),this.contestid=this.$route.query.contestid,this.$axios.get("/conteststudentchoiceanswer/?contestid="+this.contestid).then(function(t){e.tableData=t.data,e.studentcount=t.data.length})}},i=s("JFUb"),l=Object(i.a)(c,function(){var e=this,t=e.$createElement,s=e._self._c||t;return s("el-tabs",{directives:[{name:"show",rawName:"v-show",value:e.canshow,expression:"canshow"}],attrs:{type:"border-card"}},[s("el-row",[s("el-row",[s("el-input",{attrs:{placeholder:"请输入一道题的分值(一题多少分)",clearable:""},model:{value:e.singalscore,callback:function(t){e.singalscore=t},expression:"singalscore"}}),e._v(" "),s("el-col",[s("el-input",{attrs:{placeholder:"请输入正确答案(不区分大小写)",clearable:""},model:{value:e.standardanswer,callback:function(t){e.standardanswer=t},expression:"standardanswer"}})],1)],1),e._v(" "),s("el-row",[s("el-button",{attrs:{type:"success",disabled:!e.isadmin},on:{click:e.Score}},[e._v("评阅")])],1),e._v(" "),s("el-row",[s("el-table",{staticStyle:{width:"100%"},attrs:{data:e.tableData,id:"out-table"}},[s("el-table-column",{attrs:{prop:"username",label:"用户名",width:"180"}}),e._v(" "),s("el-table-column",{attrs:{prop:"realname",label:"真实姓名",width:"180"}}),e._v(" "),s("el-table-column",{attrs:{prop:"number",label:"学号",width:"180"}}),e._v(" "),s("el-table-column",{attrs:{prop:"answer",label:"学生答案",width:"400"}}),e._v(" "),s("el-table-column",{attrs:{prop:"score",label:"分数",width:"180"}})],1)],1),e._v(" "),s("el-row"),e._v(" "),s("el-button",{attrs:{type:"success",disabled:!e.isadmin},on:{click:e.SubmitScore}},[e._v("提交评阅")]),e._v(" "),s("el-button",{attrs:{type:"primary",disabled:!e.isadmin},on:{click:e.exportExcel}},[e._v("导出表格")]),e._v(" "),s("el-alert",{attrs:{title:"数据库中保存有学生答题的详细信息,包含了学生选的选项描述,选择题题目,选择题id,学生用户名,真实姓名,最后一次提交答案的时间",type:"info"}})],1)],1)},[],!1,function(e){s("3jW1")},"data-v-eaf6ca96",null);t.default=l.exports}}]);
3,590
3,590
0.701114
3112a6ecdfc4a9eadb207d3856ec6a6cd1584097
997
js
JavaScript
src/js/animacoes.js
arthurprioli/projeto-scifi
3073e2407c4deec7bf43b9a2c110d4be65b55d1e
[ "MIT" ]
null
null
null
src/js/animacoes.js
arthurprioli/projeto-scifi
3073e2407c4deec7bf43b9a2c110d4be65b55d1e
[ "MIT" ]
null
null
null
src/js/animacoes.js
arthurprioli/projeto-scifi
3073e2407c4deec7bf43b9a2c110d4be65b55d1e
[ "MIT" ]
null
null
null
$('.botoes1').hover(function() { $('.botoes1').removeClass('bg-white') $('.text1').removeClass('text-muted') $('.botoes1').addClass('bg-secondary') $('.text1').addClass('text-white') }, function() { $('.botoes1').removeClass('bg-secondary') $('.text1').removeClass('text-white') $('.botoes1').addClass('bg-white') $('.text1').addClass('text-muted') }) $('.botoes2').hover(function() { $('.botoes2').removeClass('bg-white') $('.text2').removeClass('text-muted') $('.botoes2').addClass('bg-secondary') $('.text2').addClass('text-white') }, function() { $('.botoes2').removeClass('bg-secondary') $('.text2').removeClass('text-white') $('.botoes2').addClass('bg-white') $('.text2').addClass('text-muted') }) $('header').hover(function() { $('header').css('background-color', 'black') $('#bicolor').addClass('text-white') }, function() { $('header').css('background-color', '') $('#bicolor').addClass('text-warning') })
31.15625
48
0.579739
3112f3e33a6ee6c08a084b3b53a48f085cc0f237
618
js
JavaScript
src/state/ledgers/selectors.js
checho651/bfx-report-ui
66594a651344d9e9902d1c5d4e94f6a8fd589456
[ "Apache-2.0" ]
9
2019-01-29T16:02:40.000Z
2021-11-10T19:08:56.000Z
src/state/ledgers/selectors.js
checho651/bfx-report-ui
66594a651344d9e9902d1c5d4e94f6a8fd589456
[ "Apache-2.0" ]
11
2019-02-06T11:24:18.000Z
2022-01-27T14:06:44.000Z
src/state/ledgers/selectors.js
checho651/bfx-report-ui
66594a651344d9e9902d1c5d4e94f6a8fd589456
[ "Apache-2.0" ]
13
2019-01-25T16:43:52.000Z
2022-02-24T15:50:10.000Z
export const getLedgers = state => state.ledgers export const getExistingCoins = state => getLedgers(state).existingCoins export const getTargetCategory = state => getLedgers(state).targetCategory export const getTargetSymbols = state => getLedgers(state).targetSymbols export const getDataReceived = state => getLedgers(state).dataReceived export const getEntries = state => getLedgers(state).entries export const getPageLoading = state => getLedgers(state).pageLoading export default { getDataReceived, getEntries, getExistingCoins, getLedgers, getPageLoading, getTargetCategory, getTargetSymbols, }
32.526316
74
0.797735
3113d248f2b13559d0509d05409bb63055fbbd5f
3,667
js
JavaScript
tests/helpers/fixture-data.js
zeke/emberfire
a99f2867eb1886b04d4cd5e61e18c229ab332664
[ "MIT" ]
1
2021-01-05T16:48:36.000Z
2021-01-05T16:48:36.000Z
tests/helpers/fixture-data.js
zeke/emberfire
a99f2867eb1886b04d4cd5e61e18c229ab332664
[ "MIT" ]
null
null
null
tests/helpers/fixture-data.js
zeke/emberfire
a99f2867eb1886b04d4cd5e61e18c229ab332664
[ "MIT" ]
null
null
null
export default { "blogs": { "normalized": { "users": { "aputinski": { "firstName": "Adam", "created": 1395162147634, "posts": { "post_1": true, "post_2": true } } }, "posts": { "post_1": { "published": 1395162147646, "user": "aputinski", "body": "This is the first FireBlog post!", "comments": { "comment_1": true, "comment_2": true }, "title": "Post 1" }, "post_2": { "published": 1395162147646, "user": "aputinski", "body": "This is the second FireBlog post!", "comments": { "comment_3": true, "comment_4": true }, "title": "Post 2" } }, "comments": { "comment_1": { "published": 1395176007623, "user": "aputinski", "body": "This is a comment" }, "comment_2": { "published": 1395176007624, "user": "aputinski", "body": "This is a second comment" }, "comment_3": { "published": 1395176007625, "user": "aputinski", "body": "This is a third comment" }, "comment_4": { "published": 1395176007626, "user": "aputinski", "body": "This is a fourth comment" } } }, "denormalized": { "posts": { "post_1": { "published": 1395162147646, "user": "aputinski", "body": "This is the first FireBlog post!", "comments": { "comment_1": { "published": 1395176007623, "user": "aputinski", "body": "This is a comment" }, "comment_2": { "published": 1395176007624, "user": "aputinski", "body": "This is a second comment" } }, "title": "Post 1" }, "post_2": { "published": 1395162147646, "user": "aputinski", "body": "This is the second FireBlog post!", "comments": { "comment_3": { "published": 1395176007625, "user": "aputinski", "body": "This is a third comment" }, "comment_4": { "published": 1395176007626, "user": "aputinski", "body": "This is a fourth comment" } }, "title": "Post 2" } } }, "double_denormalized": { "posts": { "post_1": { "published": 1395162147646, "user": "aputinski", "body": "This is the first FireBlog post!", "embeddedComments": { "comment_1": { "published": "32", "embeddedUser": { "id": "aputinski", "firstName": "Adam" }, "body": "This is a comment" }, }, "title": "Post 1" }, }, }, "invalid": { "posts": { "post_1": { "published": 1395162147646, "user": "aputinski", "body": "This is the first FireBlog post!", "comments": ["comment_1", "comment_2"], "title": "Post 1" }, "post_2": { "published": 1395162147646, "user": "aputinski", "body": "This is the second FireBlog post!", "comments": ["comment_3", "comment_4"], "title": "Post 2" } } } } };
26.381295
54
0.406872
31169ec421afd97df564edd40615dd29ab30d893
712
js
JavaScript
src/aid/convert/bytestring/array.js
bookmoons/cashshufflejs
651cf41f97356750784b693e7edad37e29bf4985
[ "Unlicense" ]
3
2018-09-13T19:18:53.000Z
2018-10-12T18:29:21.000Z
src/aid/convert/bytestring/array.js
bookmoons/cashshufflejs
651cf41f97356750784b693e7edad37e29bf4985
[ "Unlicense" ]
32
2018-07-16T10:31:27.000Z
2019-04-19T04:51:36.000Z
src/aid/convert/bytestring/array.js
bookmoons/cashshufflejs
651cf41f97356750784b693e7edad37e29bf4985
[ "Unlicense" ]
null
null
null
import validateByteString from '/aid/validate/bytestring' /** * Convert `ByteString` to `Array` of `Byte`. * * @memberof module:cashshuffle/aid/convert * * @param {ByteString} byteString - `ByteString` to convert. * * @return {Array<Byte>} New `Array` containing bytes in `byteString`. * * @throws {(FormatError|ValueError)} If `byteString` is not * a valid `ByteString`. Message starts with `'invalid byte string'`. */ function byteStringToArray (byteString) { validateByteString(byteString) const bytesArray = [] for (const character of byteString) { const codePoint = character.codePointAt() bytesArray.push(codePoint) } return bytesArray } export default byteStringToArray
27.384615
73
0.719101
3116bc3754e236ec21d8329b13bd807de9ab92d4
143
js
JavaScript
simple/index.js
domui/examples
41ccc1fd132fae07e78b2ee441010fd0e3c04216
[ "MIT" ]
null
null
null
simple/index.js
domui/examples
41ccc1fd132fae07e78b2ee441010fd0e3c04216
[ "MIT" ]
null
null
null
simple/index.js
domui/examples
41ccc1fd132fae07e78b2ee441010fd0e3c04216
[ "MIT" ]
null
null
null
import { Text, render } from '@domui/core'; const Main = () => ({ render: () => [Text('Hello World').padding('14px')], }); render(Main());
17.875
54
0.552448
3119779818baf68450c17c68c70fbed58b9ef66f
316
js
JavaScript
repositories/drunk.js
FomaLSSJ/drunk-server
fb089625823e1d0611920a4449253e1c1875c35a
[ "WTFPL" ]
null
null
null
repositories/drunk.js
FomaLSSJ/drunk-server
fb089625823e1d0611920a4449253e1c1875c35a
[ "WTFPL" ]
4
2021-03-02T01:36:02.000Z
2022-03-08T23:29:17.000Z
repositories/drunk.js
FomaLSSJ/drunk-server
fb089625823e1d0611920a4449253e1c1875c35a
[ "WTFPL" ]
null
null
null
const DrunkModel = require('../models/drunk'); class Drunkrepositories extends DrunkModel { static async create(doc) { const item = new this(doc); return item.save(); } static pagination(params) { const items = this.paginate(params); return items; } } module.exports = Drunkrepositories;
18.588235
46
0.683544
3119d840217fb50f0bdc6d3932125630fc50ef60
423
js
JavaScript
app/script/routers.js
huanrum/xinyuweb
3551a2c3b0d1e3be4e8ceb8cc74f376d6ba48c79
[ "CC0-1.0" ]
null
null
null
app/script/routers.js
huanrum/xinyuweb
3551a2c3b0d1e3be4e8ceb8cc74f376d6ba48c79
[ "CC0-1.0" ]
null
null
null
app/script/routers.js
huanrum/xinyuweb
3551a2c3b0d1e3be4e8ceb8cc74f376d6ba48c79
[ "CC0-1.0" ]
null
null
null
var main = require('./modules/main'); var login = require('./modules/login'); //所有的路由信息都写在这里 //name,path,component 是自带的icon,title是用于菜单的,会根据path来进行子菜单分级 module.exports = function routers() { return [ { name: 'login', path: '/login', component: login }, { name: 'main', path: '/', component: main, title: '主页', icon: '', children: main.routers } ]; }
20.142857
100
0.55792
311af2b295ec27695ca52ccda62cd46d30958a8a
5,917
js
JavaScript
Shorthand.VKMinus.Node/routes/index.js
karl-sjogren/vkminus
2ac919c51cb6fc1685a10564e5a2ba4e6da7ba45
[ "MIT" ]
1
2015-01-08T12:45:22.000Z
2015-01-08T12:45:22.000Z
Shorthand.VKMinus.Node/routes/index.js
karl-sjogren/vkminus
2ac919c51cb6fc1685a10564e5a2ba4e6da7ba45
[ "MIT" ]
null
null
null
Shorthand.VKMinus.Node/routes/index.js
karl-sjogren/vkminus
2ac919c51cb6fc1685a10564e5a2ba4e6da7ba45
[ "MIT" ]
null
null
null
/* * GET home page. */ exports.index = function(req, res){ if (process.argv[2] === "vsdebug") { // Go for test-data instead since VS won't load mongodb for some reason return res.render('index', { title: 'VK-', links: 161, plusLinks: 161, percentage: 34, latestMainLinks: 47, latestMainPlusLinks: 27, latestMainPercentage: 57, latestNewsLinks: 98, latestNewsPlusLinks: 21, latestNewsPercentage: 21, lastUpdated: '2013-12-12 14:02:00', block0: { links: 6, pluslinks: 2, percentage: 33 }, block1: { links: 7, pluslinks: 5, percentage: 71 }, block2: { links: 10, pluslinks: 7, percentage: 70 }, block3: { links: 10, pluslinks: 7, percentage: 70 }, block4: { links: 7, pluslinks: 4, percentage: 57 }, block5: { links: 8, pluslinks: 6, percentage: 75 } }); } var mongoClient = require('mongodb').MongoClient; var moment = require('moment'); var percentage = function(val, total) { var res = parseFloat(val / total).toFixed(2); return Math.floor(res * 100); }; mongoClient.connect(process.env.mongodb, function(err, db) { if (err) throw err; console.log("Connected to Database"); var collection = db.collection('statistics'); var cMain = collection.find(); cMain.sort({ 'createdAt': 1 }).limit(1); cMain.nextObject(function(err, results) { if (err) throw err; var model = { title: 'VK-', links: results.TotalLinks, plusLinks: results.TotalPlusLinks, percentage: percentage(results.TotalPlusLinks, results.TotalLinks), latestMainLinks: results.TotalMainLinks, latestMainPlusLinks: results.TotalMainPlusLinks, latestMainPercentage: percentage(results.TotalMainPlusLinks, results.TotalMainLinks), latestNewsLinks: results.TotalLatestNewsLinks, latestNewsPlusLinks: results.TotalLatestNewsPlusLinks, latestNewsPercentage: percentage(results.TotalLatestNewsPlusLinks, results.TotalLatestNewsLinks), lastUpdated: moment(results.CreatedAt).format('YYYY-MM-DD HH:mm:ss'), block0: { links: results.Blocks[0].TotalLinks, pluslinks: results.Blocks[0].TotalPlusLinks, percentage: percentage(results.Blocks[0].TotalPlusLinks, results.Blocks[0].TotalLinks) }, block1: { links: results.Blocks[1].TotalLinks, pluslinks: results.Blocks[1].TotalPlusLinks, percentage: percentage(results.Blocks[1].TotalPlusLinks, results.Blocks[1].TotalLinks) }, block2: { links: results.Blocks[2].TotalLinks, pluslinks: results.Blocks[2].TotalPlusLinks, percentage: percentage(results.Blocks[2].TotalPlusLinks, results.Blocks[2].TotalLinks) }, block3: { links: results.Blocks[3].TotalLinks, pluslinks: results.Blocks[3].TotalPlusLinks, percentage: percentage(results.Blocks[3].TotalPlusLinks, results.Blocks[3].TotalLinks) }, block4: { links: results.Blocks[4].TotalLinks, pluslinks: results.Blocks[4].TotalPlusLinks, percentage: percentage(results.Blocks[4].TotalPlusLinks, results.Blocks[4].TotalLinks) }, block5: { links: results.Blocks[5].TotalLinks, pluslinks: results.Blocks[5].TotalPlusLinks, percentage: percentage(results.Blocks[5].TotalPlusLinks, results.Blocks[5].TotalLinks) } }; var cMainAverage = collection.find(); cMainAverage.sort({ 'createdAt': 1 }).limit(30); cMainAverage.toArray(function(err, results) { if (err) throw err; var values = []; var labels = []; for (var i = 0; i < results.length; i++) { var item = results[i]; values.push(percentage(item.TotalMainPlusLinks, item.TotalMainLinks)); labels.push(moment(item.CreatedAt).format('HHmm')); } values.reverse(); labels.reverse(); model.mainChart = { labels: labels.join(', '), values: values.join(', ') }; values = []; labels = []; for (var i = 0; i < results.length; i++) { var item = results[i]; values.push(percentage(item.TotalPlusLinks, item.TotalLinks)); labels.push(moment(item.CreatedAt).format('HHmm')); } values.reverse(); labels.reverse(); model.totalChart = { labels: labels.join(', '), values: values.join(', ') }; console.dir(model); res.render('index', model); db.close(); }); }); }); };
36.300613
113
0.482677
311b5c43639af7fd14b8c2bbc399a8bdfc669e73
307
js
JavaScript
packages/esrun/lib/dts-builder-thread.js
SalvatorePreviti/balsamic
d96032690bb0c2e1594227dae786b4ebd7bbfd67
[ "MIT" ]
null
null
null
packages/esrun/lib/dts-builder-thread.js
SalvatorePreviti/balsamic
d96032690bb0c2e1594227dae786b4ebd7bbfd67
[ "MIT" ]
null
null
null
packages/esrun/lib/dts-builder-thread.js
SalvatorePreviti/balsamic
d96032690bb0c2e1594227dae786b4ebd7bbfd67
[ "MIT" ]
null
null
null
'use strict' const { parentPort, workerData } = require('worker_threads') require('v8-compile-cache') const tscBuilder = require('./dts-builder') tscBuilder .buildDts(workerData) .then((result) => { parentPort.postMessage(result) }) .catch((error) => { parentPort.postMessage(error) })
19.1875
60
0.680782
311cbc70ed910d2215a78c0973a3c207c28f2ce7
4,204
js
JavaScript
src/components/Layout/Navbar.js
gayaIn/FrontEnd_Web
bd83397abdd459fff90e3179e3066d1ccbf7d30d
[ "Xnet", "X11" ]
1
2021-01-17T07:39:58.000Z
2021-01-17T07:39:58.000Z
src/components/Layout/Navbar.js
gayaIn/FrontEnd_Web
bd83397abdd459fff90e3179e3066d1ccbf7d30d
[ "Xnet", "X11" ]
1
2021-02-15T22:17:40.000Z
2021-02-15T22:18:02.000Z
src/components/Layout/Navbar.js
gayaIn/gayaIn-Frontend-Web
bd83397abdd459fff90e3179e3066d1ccbf7d30d
[ "Xnet", "X11" ]
3
2020-03-16T02:03:25.000Z
2020-04-06T16:36:28.000Z
import React, { Component, Fragment } from "react"; import { connect } from "react-redux"; import { Link, withRouter } from "react-router-dom"; import { getProducts } from "../redux/actions/product"; class NewNavbar extends Component { state = { name: "", category: "", hidden: false, activePage: 1, searchName: "", }; searchProduct = (event) => { this.setState({ searchName: event.target.value }); this.props.history.push(`?name=${event.target.value}`); const data = { activePage: 1, searchName: event.target.value, }; this.props.dispatch(getProducts(data)); }; render() { const { onClick, onhidden } = this.props; const ValidasiForm = () => { return ( <Fragment> <li className="nav-item dropdown"> <Link className="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > <i class="fa fa-fw fa-cogs"></i> </Link> <div className="dropdown-menu" aria-labelledby="navbarDropdown"> <span className="dropdown-item"> <Link to="/Category" className="nav-item nav-link"> Category </Link>{" "} </span> <span className="dropdown-item"> <Link to="/" className="nav-item nav-link"> Product </Link> </span> <span className="dropdown-item"> <Link to="/history" className="nav-item nav-link"> History </Link> </span> </div> </li> </Fragment> ); }; return ( <Fragment> <nav className="navbarTop navbar sticky-top navbar-expand-lg navbar-light bg-ligh" style={{ width: "100rem", height: "50px", marginLeft: "1%", position: "fixed", boxShadow: "0px 5px 10px #2222228c", }} > <span className="navbar-brand">Gaya-In</span> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarNavAltMarkup"> <div className="navbar-nav"> <ValidasiForm /> <span> <Link to="/user" className="nav-item nav-link"> <i className="fas fa-user-cog"></i> </Link> </span> <span> <Link to="/login" className="nav-item nav-link" onClick={onClick} > <i className="fas fa-sign-out-alt"></i> </Link> </span> <div className="search form-inline"> <input onChange={this.searchProduct} hidden={onhidden} value={this.state.searchName} className="search form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" /> </div> <div className="input-group mb-3" style={{ marginLeft: "13rem", height: "30px", marginTop: "9px", }} > <div className="input-group-prepend"></div> </div> </div> </div> </nav> </Fragment> ); } } const mapStateToProps = (state) => { return { products: state.products.products, auth: state.auth, }; }; export default withRouter(connect(mapStateToProps)(NewNavbar));
29.605634
87
0.465271
311cfb5d098a849beda68473cc05ab5476103cf1
1,356
js
JavaScript
front/tree.js
Alienero/Rambo
b26f8fd5f0ff1d0e5756fda46b2716ff57f9b103
[ "Apache-2.0" ]
7
2016-01-17T05:58:22.000Z
2017-06-29T15:42:59.000Z
front/tree.js
Alienero/Rambo
b26f8fd5f0ff1d0e5756fda46b2716ff57f9b103
[ "Apache-2.0" ]
3
2016-04-18T16:43:05.000Z
2016-05-19T18:34:07.000Z
front/tree.js
Alienero/Rambo
b26f8fd5f0ff1d0e5756fda46b2716ff57f9b103
[ "Apache-2.0" ]
null
null
null
var nodes = [] var links = [] var depths_nodes = [] function addNode(node,parent){ } var option = { title : { text: 'Force', subtext: 'Force-directed tree', x:'right', y:'bottom' }, tooltip : { trigger: 'item', formatter: '{a} : {b}' }, toolbox: { show : true, feature : { restore : {show: true}, saveAsImage : {show: true} } }, legend: { x: 'left', data:['叶子节点','非叶子节点', '根节点'] }, series : [ { type:'force', name : "SQL AST Tree", categories : [ { name: '叶子节点', itemStyle: { normal: { color : '#ff7f50' } } }, { name: '非叶子节点', itemStyle: { normal: { color : '#6f57bc' } } }, { name: '根节点', itemStyle: { normal: { color : '#af0000' } } } ], itemStyle: { normal: { label: { show: false }, nodeStyle : { brushType : 'both', strokeColor : 'rgba(255,215,0,0.6)', lineWidth : 1 } } }, // minRadius : 2, // maxRadius : 10, nodes : nodes, links : links } ] };
16.95
48
0.365044
311d3cb243b51f21f98e08cae3858a5144198b1e
739
js
JavaScript
src/assets/text/Login.text.js
ajcper/DesignSystem
d3a580d5b3e4911396aca170ef9ff8a3cb3007ac
[ "MIT" ]
null
null
null
src/assets/text/Login.text.js
ajcper/DesignSystem
d3a580d5b3e4911396aca170ef9ff8a3cb3007ac
[ "MIT" ]
8
2019-12-28T06:33:31.000Z
2022-02-26T10:24:25.000Z
src/assets/text/Login.text.js
ajcper/DesignSystem
d3a580d5b3e4911396aca170ef9ff8a3cb3007ac
[ "MIT" ]
null
null
null
export const LoginCarouselText = [ { heading: `A proactive way to combat academic piracy.`, body: `Perlego addresses the root cause of academic piracy by delivering affordable and convenient access on one platform.`, }, { heading: `Providing data that empowers publishers.`, body: `Perlego collates a rapidly-growing, granular dataset that can be used to optimise marketing and commissioning decisions.`, }, { heading: `Content curation that helps find new audiences.`, body: `Perlego carefully curates content with BISAC infrastructure and synaptic pathways to ensure engagement from previously inaccessible readers.` }, ] export const LoginHeaderText = [ '' ]
38.894737
156
0.703654
311d833ae7ed56c020c97f8b884e53e99f32e66c
7,929
js
JavaScript
fe-mock/src/App.js
de4a-wp5/de4a-connector-mock
dfb4f48c2d3ffdbc90ca6b690681352ddabc575c
[ "Apache-2.0" ]
1
2021-03-31T13:35:53.000Z
2021-03-31T13:35:53.000Z
fe-mock/src/App.js
de4a-wp5/de4a-connector-mock
dfb4f48c2d3ffdbc90ca6b690681352ddabc575c
[ "Apache-2.0" ]
5
2021-03-03T08:58:49.000Z
2022-02-21T10:25:28.000Z
fe-mock/src/App.js
de4a-wp5/de4a-connector-mock
dfb4f48c2d3ffdbc90ca6b690681352ddabc575c
[ "Apache-2.0" ]
1
2022-02-18T11:54:37.000Z
2022-02-18T11:54:37.000Z
import React, {useEffect, useState, useRef} from "react"; import {useLocation} from "react-router-dom" import Containter from 'react-bootstrap/Container' import axios from "axios"; import ClipLoader from 'react-spinners/ClipLoader' import * as SockJS from 'sockjs-client' import { Client } from "@stomp/stompjs"; import translate from 'translate-js' import trans_en from './translate/en' import Preview from "./Preview" import RequestList from "./RequestList"; import {Col, Row} from "react-bootstrap"; translate.add(trans_en, 'en') translate.whenUndefined = (key, locale) => { return `${key}:undefined:${locale}` } const EvidenceStatus = { Accepted: 'Accepted', Rejected: 'Rejected', Processing: 'Processing', Unanswered: 'Unanswered', FetchingEvidence: 'FetchingEvidence', NoSuchEvidence: 'NoSuchEvidence', NoEvidenceChosen: 'NoEvidenceChosen', Error: 'Error', } const format = (str, args) => { console.log("args", args) var formatted = str; for (var prop in args) { var regexp = new RegExp('\\{' + prop + '\\}', 'gi'); formatted = formatted.replace(regexp, args[prop]); } return formatted; } const App = () => { const [evidence, setEvidence] = useState("") const [evidenceStatus, setEvidenceStatus] = useState(EvidenceStatus.FetchingEvidence) const [evidencesList, setEvidencesList] = useState([]) const [requestId, setRequestId] = useState("") const evidencesListRef = useRef(evidencesList) const setEvidencesListRef = useRef(setEvidencesList) const search = useLocation().search const urlParams = new URLSearchParams(search) const requestIdParam = urlParams.get('requestId') const pathName = useLocation().pathname const acceptEvidence = () => { setEvidenceStatus(EvidenceStatus.Processing) axios.get(format(window.DO_CONST['previewAcceptEndpoint'], {requestId: requestId})) .then(response => { let locationUrl = response.data setEvidenceStatus(EvidenceStatus.Accepted) if (locationUrl === "") { console.error("no back url provided") setEvidenceStatus(EvidenceStatus.Error) return } window.location.replace(locationUrl); }) .catch(error => { console.error("error: ", error) setEvidenceStatus(EvidenceStatus.Error) }) } const rejectEvidence = () => { setEvidenceStatus(EvidenceStatus.Processing) axios.get(format(window.DO_CONST['previewRejectEndpoint'], {requestId: requestId})) .then(response => { let locationUrl = response.data setEvidenceStatus(EvidenceStatus.Rejected) if (locationUrl === "" ) { console.error("no back url provided") setEvidenceStatus(EvidenceStatus.Error) return } window.location.replace(locationUrl); }) .catch(error => { setEvidenceStatus(EvidenceStatus.Error) console.log(error) }) } const fetchEvidence = (requestId) => { if (requestId && requestId !== "") { axios.get( format(window.DO_CONST['previewEndpoint'], {requestId: requestId})) .then(response => { setEvidence(response.data) setRequestId(requestId) setEvidenceStatus(EvidenceStatus.Unanswered) console.log(response) }) .catch(error => { setEvidenceStatus(EvidenceStatus.NoSuchEvidence) setRequestId(requestId) console.error(error) }) } else { setEvidenceStatus(EvidenceStatus.NoEvidenceChosen) } } const fetchPreviewEvidences = () => axios.get(window.DO_CONST['previewIdsEndpoint']) .then(response => { setEvidencesList(response.data) }) const updatePreviewEvidences = (message) => { console.log("message: ", message) console.log("evidencesList: ", evidencesListRef.current) switch (message.action) { case("RM"): { console.log("rm") setEvidencesListRef.current(evidencesListRef.current .filter(value => value !== message.payload)) break } case("ADD"): { console.log("add") if (!evidencesListRef.current.includes(message.payload)) { console.log("inner") setEvidencesListRef.current([...evidencesListRef.current, message.payload]) } break } default: break } console.log("evidencesList: ", evidencesList.current) } const newMessage = (message) => { console.log("message: ", message.body) updatePreviewEvidences(JSON.parse(message.body)) } const client = new Client(); client.webSocketFactory = () => { return new SockJS(`${window.DO_CONST['previewWebsocket']}`) } client.debug = (str) => { console.log(str) } client.onConnect = function (frame) { client.subscribe(`${pathName.replace(/index$/, window.DO_CONST['previewMessages'])}`, newMessage) }; client.onStompError = function (frame) { console.log('Broker reported error: ' + frame.headers['message']); console.log('Additional details: ' + frame.body); }; const subscribeRequestId = () => { client.activate() } useEffect(() => { fetchEvidence(requestIdParam) fetchPreviewEvidences() subscribeRequestId() // eslint-disable-next-line react-hooks/exhaustive-deps }, []) useEffect(() => { evidencesListRef.current = evidencesList setEvidencesListRef.current = setEvidencesList }, [evidenceStatus, evidencesList]) const renderSwitch = (evidenceStatus) => { switch (evidenceStatus) { case EvidenceStatus.FetchingEvidence: return <ClipLoader/> case EvidenceStatus.NoEvidenceChosen: return <RequestList requestIds={evidencesList} onSelect={fetchEvidence} translate={translate}/> case EvidenceStatus.NoSuchEvidence: return <p>no evidence found for request with id: {requestId}</p> case EvidenceStatus.Unanswered: return <Preview evidence={evidence} evidenceRoot="//*[local-name() = 'CanonicalEvidence']" evidenceIgnore={[]} acceptEvidence={acceptEvidence} rejectEvidence={rejectEvidence} translate={translate}/> case EvidenceStatus.Accepted: return <p>Evidence accepted</p> case EvidenceStatus.Rejected: return <p>Evidence rejected</p> case EvidenceStatus.Processing: return <Row> <Col> <ClipLoader/> </Col> <Col> <p>Processing answer</p> </Col> </Row> case EvidenceStatus.Error: default: return <p>Error occurred</p> } } return <Containter> <Row> <Col><h1>{translate('doTitle')}</h1></Col> </Row> <Row> <Col> {renderSwitch(evidenceStatus)} </Col> </Row> </Containter> } export default App;
34.324675
115
0.555177
311d974e9dc0869ef2f5c6ada3ddb503a704bc35
508
js
JavaScript
demo/src/pages/bigTree/updaters.js
serchavalos/react-recollect
388e96311c19b136ed81810ffc856158053c19d5
[ "MIT" ]
413
2018-10-29T20:51:57.000Z
2022-01-05T23:06:43.000Z
demo/src/pages/bigTree/updaters.js
serchavalos/react-recollect
388e96311c19b136ed81810ffc856158053c19d5
[ "MIT" ]
92
2018-11-08T19:02:59.000Z
2022-02-27T21:11:55.000Z
demo/src/pages/bigTree/updaters.js
serchavalos/react-recollect
388e96311c19b136ed81810ffc856158053c19d5
[ "MIT" ]
13
2018-11-03T16:00:19.000Z
2021-12-12T08:58:38.000Z
import { TYPES } from '../../shared/constants'; export const deleteChild = (parent, child) => { if (parent.childrenType === TYPES.OBJ) { delete parent.children[child.id]; } else if (parent.childrenType === TYPES.ARR) { parent.children = parent.children.filter( (childItem) => childItem.id !== child.id ); } else if (parent.childrenType === TYPES.MAP) { parent.children.delete(child.id); } else if (parent.childrenType === TYPES.SET) { parent.children.delete(child); } };
31.75
49
0.643701
311dab16205ff267c83c7afea4c7f184ed67eb7d
325
js
JavaScript
src/services/appointment/storeAppointmentsService.js
kovmat86/celmegvalositas.com-services
b70e496565262ab33622a224e1bc0fe6dbab0482
[ "MIT" ]
null
null
null
src/services/appointment/storeAppointmentsService.js
kovmat86/celmegvalositas.com-services
b70e496565262ab33622a224e1bc0fe6dbab0482
[ "MIT" ]
null
null
null
src/services/appointment/storeAppointmentsService.js
kovmat86/celmegvalositas.com-services
b70e496565262ab33622a224e1bc0fe6dbab0482
[ "MIT" ]
null
null
null
import { save } from "./appointmentManager.js"; const Service = { urlPattern: "/store/appointments", type: "post", run: (req, res) => { const appointments = req.body; console.log("storeAppointments: " + JSON.stringify(appointments)); save(appointments); } }; export { Service }; export default Service;
21.666667
70
0.661538
9448e4071ed735ef019afb30bf505072946f5faa
225
js
JavaScript
app/home-page/home-page.component.js
nicknielsen86/teacher-tools
ffe3298dadfc6a3bee1a50f6c7964603116a908d
[ "MIT" ]
null
null
null
app/home-page/home-page.component.js
nicknielsen86/teacher-tools
ffe3298dadfc6a3bee1a50f6c7964603116a908d
[ "MIT" ]
1
2017-05-25T20:25:06.000Z
2017-05-25T21:25:25.000Z
app/home-page/home-page.component.js
nicknielsen86/teacher-tools
ffe3298dadfc6a3bee1a50f6c7964603116a908d
[ "MIT" ]
null
null
null
'use strict'; 'use strict'; angular.module('homePage', ['navigationBar']). component('homePage', { templateUrl: 'home-page/home-page.template.html', controller: [homePageController] }); function homePageController() { }
20.454545
51
0.72
94491e6e5a5b707e0b4806734fd99d99c8a7ba2c
1,610
js
JavaScript
public/js/dollhouse.js
ncreel/gamez4grrrlz
105365758f10b92e080be80deed7a70ba05ffbe3
[ "MIT" ]
1
2021-02-14T02:32:02.000Z
2021-02-14T02:32:02.000Z
public/js/dollhouse.js
ncreel/gamez4grrrlz
105365758f10b92e080be80deed7a70ba05ffbe3
[ "MIT" ]
null
null
null
public/js/dollhouse.js
ncreel/gamez4grrrlz
105365758f10b92e080be80deed7a70ba05ffbe3
[ "MIT" ]
null
null
null
function handleClick(id){ $("#kitchendialog").dialog({ autoOpen: false, modal: true, width:400}); $("#bedroomdialog").dialog({ autoOpen: false, modal: true, width:400}); $("#bathroomdialog").dialog({ autoOpen: false, modal: true, width:400 }); $("#closetdialog").dialog({ autoOpen: false, modal: true, width:400 }); const element = document.getElementById(id); switch (id) { case "kitchen": if(element.src ="../assets/images/dollhouse/cleankitchen.png"){ element.src = "../assets/images/dollhouse/corruptkitchen.png"; }else{ element.src = "../assets/images/dollhouse/cleankitchen.png"; }; $("#kitchendialog").dialog("open"); break; case "bathroom": if(element.src ="../assets/images/dollhouse/cleanbathroom.png"){ element.src = "../assets/images/dollhouse/corruptbathroom.png"; }else{ element.src = "../assets/images/dollhouse/cleanbathroom.png"; }; $("#bathroomdialog").dialog("open"); break; case "bedroom": if(element.src ="../assets/images/dollhouse/cleanbedroom.png"){ element.src = "../assets/images/dollhouse/corruptbedroom.png"; }else{ element.src = "../assets/images/dollhouse/cleanbedroom.png"; }; $("#bedroomdialog").dialog("open"); break; case "closet": if(element.src ="../assets/images/dollhouse/cleancloset.png"){ element.src = "../assets/images/dollhouse/corruptcloset.png"; }else{ element.src = "../assets/images/dollhouse/cleancloset.png"; }; $("#closetdialog").dialog("open"); } }
39.268293
75
0.618634
9449736334458b1f60fa0d182fd4ec0afa80734b
1,273
js
JavaScript
resources/js/admin/dashboard.js
TripleSD/moring
3b37e69f61f155adcf2ebbbd265f5ae1997df43f
[ "MIT" ]
6
2019-11-08T15:51:54.000Z
2021-06-04T12:08:13.000Z
resources/js/admin/dashboard.js
TripleSD/moring
3b37e69f61f155adcf2ebbbd265f5ae1997df43f
[ "MIT" ]
16
2019-12-04T14:54:09.000Z
2022-02-26T19:59:05.000Z
resources/js/admin/dashboard.js
TripleSD/moring
3b37e69f61f155adcf2ebbbd265f5ae1997df43f
[ "MIT" ]
null
null
null
/* * Author: Abdullah A Almsaeed * Date: 4 Jan 2014 * Description: * This is a demo file used only for the main dashboard (index.html) **/ $(function () { 'use strict' // Make the dashboard widgets sortable Using jquery UI $('.connectedSortable').sortable({ placeholder : 'sort-highlight', connectWith : '.connectedSortable', handle : '.card-header, .nav-tabs', forcePlaceholderSize: true, zIndex : 999999 }) $('.connectedSortable .card-header, .connectedSortable .nav-tabs-custom').css('cursor', 'move') // jQuery UI sortable for the todo list $('.todo-list').sortable({ placeholder : 'sort-highlight', handle : '.handle', forcePlaceholderSize: true, zIndex : 999999 }) $('.connectedSortable').sortable({ stop: function() { $.ajax({ url: 'admin/panel/items/sort/ ', method: 'post', data: $('.connectedSortable').sortable('serialize'), beforeSend: function(request) { return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content')); }, }); } }); })
28.931818
114
0.538099
944979e3ca8e540b677375b38349e461c0ddec2b
3,201
js
JavaScript
front/src/store/index.js
revenue-hack/satellite-puzzle
82fee1bf9c5daa99d931d3b5895c8fb030b0cf49
[ "Apache-2.0" ]
5
2019-02-21T10:16:11.000Z
2020-03-19T18:36:26.000Z
front/src/store/index.js
revenue-hack/satellite-puzzle
82fee1bf9c5daa99d931d3b5895c8fb030b0cf49
[ "Apache-2.0" ]
null
null
null
front/src/store/index.js
revenue-hack/satellite-puzzle
82fee1bf9c5daa99d931d3b5895c8fb030b0cf49
[ "Apache-2.0" ]
4
2019-02-21T01:51:10.000Z
2019-10-19T04:50:55.000Z
import { cpus } from 'os'; const state = () => ({ puzzles: {}, // puzzle.jsonから取得した情報 min: 0, // パズルにかかった時間(分) sec: 0, // パズルにかかった時間(秒) bestRecords: [], // 自己記録 bestRecord: {}, // 今回プレイしたマップ・難易度の自己記録 isNewRecord: false, // 新記録かどうか version: -1, // 現在プレイ中のパズルの初期配置番号 }) const getters = { puzzles: state => state.puzzles, min: state => state.min, sec: state => state.sec, bestRecords: state => state.bestRecords, bestRecord: state => state.bestRecord, isNewRecord: state => state.isNewRecord, version: state => state.version, } const mutations = { SET_PUZZLE_SETTING(state, json) { state.puzzles = json }, RESET_MIN(state) { state.min = 0 }, RESET_SEC(state) { state.sec = 0 }, INCLEMENT_MIN(state) { state.min++ }, INCLEMENT_SEC(state) { state.sec++ }, SET_BEST_RECORDS(state, record) { state.bestRecords = record }, SET_BEST_RECORD(state, record) { state.bestRecord = record }, SET_IS_NEW_RECORD(state, isNewRecord) { state.isNewRecord = isNewRecord }, SET_VERSION(state, version) { state.version = version } } const actions = { async nuxtServerInit({ commit, state }, { app }) { const path = require('path') const sprintf = require('sprintf-js').vsprintf const puzzleSettings = require('../puzzle.json') commit('SET_PUZZLE_SETTING', puzzleSettings.puzzles) let promises = [] puzzleSettings.puzzles.forEach(e => { e.parameters.forEach(p => { // FIXME: このやり方かなりイケてないので、修正したい // TODO: hostを環境変数で制御する const imageUrl = sprintf("%s/images/%s/%d-%d-%d-%d/completed.png", [`${process.env.CLIENT_URL}`, p.kind, p.z, p.x, p.y, p.split_n]) this.$axios.get(imageUrl) .catch((err) => { promises.push(this.$axios.get(`${process.env.API_URL}`, { params: p })) }) }) }) // アプリケーション起動時にパズルの設定ファイルを読み込み、画像を分割する処理をリクエストする try { promises && await Promise.all(promises) } catch (err) { throw err } }, resetMin({ commit }) { commit('RESET_MIN') }, resetSec({ commit }) { commit('RESET_SEC') }, inclementMin({ commit }) { commit('INCLEMENT_MIN') }, inclementSec({ commit }) { commit('INCLEMENT_SEC') }, updateBestRecords({ commit }, record) { // bestRecordsを更新する // bestRecordsを全て取得 let bestRecords = this.state.bestRecords.concat() // recordの難易度・マップに対応するindexをbestRecordsから取得 const i = bestRecords.findIndex(v => { return v.difficulty === record.difficulty && v.map === record.map }) if (i > -1) { // 対応するindexが見つかった場合 bestRecords[i] = record // 記録を更新する } else { // 対応するindexが見つからなかった場合 bestRecords.push({ // 記録を追加する difficulty: record.difficulty, map: record.map, min: record.min, sec: record.sec }) } commit('SET_BEST_RECORDS', bestRecords) // 修正した値を新たなbestRecordsとして保存する }, setBestRecord({ commit }, record) { commit('SET_BEST_RECORD', record) }, setIsNewRecord({ commit }, isNewRecord) { commit('SET_IS_NEW_RECORD', isNewRecord) }, setVersion({ commit }, version) { commit('SET_VERSION', version) } } export default { state, getters, mutations, actions, }
28.078947
83
0.628554
9449af7ec0cdff48c1159dae36d2c7e69ba1a789
713
js
JavaScript
routerapp/src/shopcar/store/shopcar/shopcar.action.js
123844114/react-master
19b88a2c6528e6f5122cd238642e9975250a01da
[ "Zlib" ]
null
null
null
routerapp/src/shopcar/store/shopcar/shopcar.action.js
123844114/react-master
19b88a2c6528e6f5122cd238642e9975250a01da
[ "Zlib" ]
null
null
null
routerapp/src/shopcar/store/shopcar/shopcar.action.js
123844114/react-master
19b88a2c6528e6f5122cd238642e9975250a01da
[ "Zlib" ]
null
null
null
import axios from 'axios'; export const INIT_DATA = 'INIT_DATA' //初始化获取数据 export const CHANGE_COUNT = 'CHANGE_COUNT' //点击加减改变数量 export const CHANGE_CHECK = 'CHANGE_CHECK' //点击checkbox export default { getdata:()=>{ return (dispatch)=>{ axios.get('/api/shopcar').then(res=>{ dispatch({type:INIT_DATA,data:res.data.car}); }) } }, changeCount(count,groupIndex,itemIndex){ return { type:CHANGE_COUNT, count, groupIndex, itemIndex } }, changeCheck(isCheck,groupIndex,itemIndex){ return { type:CHANGE_CHECK,isCheck,groupIndex,itemIndex } } }
24.586207
61
0.56662
944a7356dd7b900c4758e411e4f4b77de1d3db00
1,138
js
JavaScript
src/js/components/Heading.js
slavapavlutin/pavlutin-node
28d8744fbcea168fae82d7d1f19f581e4622dbd2
[ "MIT" ]
2
2017-04-11T10:26:06.000Z
2017-04-16T01:55:34.000Z
src/js/components/Heading.js
slavapavlutin/pavlutin-node
28d8744fbcea168fae82d7d1f19f581e4622dbd2
[ "MIT" ]
null
null
null
src/js/components/Heading.js
slavapavlutin/pavlutin-node
28d8744fbcea168fae82d7d1f19f581e4622dbd2
[ "MIT" ]
null
null
null
import { kebabCase } from 'lodash'; import React, { Children } from 'react'; import Icon from 'react-fontawesome'; function Heading({ level, children }) { const Component = matchHeadingLevel(level); const id = generateId(children); if (id === '') { return <Component>{ children }</Component>; } return ( <Component id={id} className="heading"> { children } <a href={id} className="heading__anchor"> {' '} <Icon name="link" /> </a> </Component> ); } function matchHeadingLevel(level) { switch (level) { case 1: return props => <h1 {...props} />; case 2: return props => <h2 {...props} />; case 3: return props => <h3 {...props} />; case 4: return props => <h4 {...props} />; case 5: return props => <h5 {...props} />; case 6: return props => <h6 {...props} />; default: return props => <h1 {...props} />; } } function generateId(children) { if (Children.count(children) === 1) { return `#${kebabCase(children)}`; } if (Children.count(children) > 1) { return `#${kebabCase(children[0])}`; } return ''; } export default Heading;
25.288889
47
0.575571
944a95e5131a17000dbe7d5808eab0f6adab0c75
5,506
js
JavaScript
src/scripts/dojo/release/dojox/embed/Flash.js
Anirudradabas/dojo-website
f222da8256a48081771ba7626febe2d977563afc
[ "CC0-1.0" ]
4
2016-01-22T11:13:41.000Z
2017-03-22T11:09:30.000Z
src/scripts/dojo/release/dojox/embed/Flash.js
jains1234567890/dojo-website
371f39db94f86032bd5844add44436a5c17a97a4
[ "CC0-1.0" ]
34
2015-08-14T15:56:18.000Z
2021-09-17T05:06:46.000Z
src/scripts/dojo/release/dojox/embed/Flash.js
jains1234567890/dojo-website
371f39db94f86032bd5844add44436a5c17a97a4
[ "CC0-1.0" ]
23
2015-08-28T13:29:38.000Z
2021-05-18T07:28:10.000Z
//>>built define("dojox/embed/Flash","dojo/_base/lang dojo/_base/unload dojo/_base/array dojo/query dojo/has dojo/dom dojo/on dojo/window dojo/string".split(" "),function(d,p,l,q,r,k,s,m,e){function n(a){a=d.delegate(t,a);if(!("path"in a))return null;"id"in a||(a.id=u+v++);return a}var h,g,u="dojox-embed-flash-",v=0,t={expressInstall:!1,width:320,height:240,swLiveConnect:"true",allowScriptAccess:"sameDomain",allowNetworking:"all",style:null,redirect:null};r("ie")?(h=function(a){a=n(a);if(!a)return null;var b, c=a.path;if(a.vars){var d=[];for(b in a.vars)d.push(encodeURIComponent(b)+"\x3d"+encodeURIComponent(a.vars[b]));a.params.FlashVars=d.join("\x26");delete a.vars}c='\x3cobject id\x3d"'+e.escape(String(a.id))+'" classid\x3d"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width\x3d"'+e.escape(String(a.width))+'" height\x3d"'+e.escape(String(a.height))+'"'+(a.style?' style\x3d"'+e.escape(String(a.style))+'"':"")+'\x3e\x3cparam name\x3d"movie" value\x3d"'+e.escape(String(c))+'" /\x3e';if(a.params)for(b in a.params)c+= '\x3cparam name\x3d"'+e.escape(b)+'" value\x3d"'+e.escape(String(a.params[b]))+'" /\x3e';return{id:a.id,markup:c+"\x3c/object\x3e"}},g=function(){for(var a=10,b=null;!b&&7<a;)try{b=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+a--)}catch(c){}return b?(a=b.GetVariable("$version").split(" ")[1].split(","),{major:null!=a[0]?parseInt(a[0]):0,minor:null!=a[1]?parseInt(a[1]):0,rev:null!=a[2]?parseInt(a[2]):0}):{major:0,minor:0,rev:0}}(),p.addOnWindowUnload(function(){var a=function(){};q("object").reverse().style("display", "none").forEach(function(b){for(var c in b)if("FlashVars"!=c&&"function"==typeof b[c])try{b[c]=a}catch(e){}})})):(h=function(a){a=n(a);if(!a)return null;var b,c=a.path;if(a.vars){var d=[];for(b in a.vars)d.push(encodeURIComponent(b)+"\x3d"+encodeURIComponent(a.vars[b]));a.params.flashVars=d.join("\x26");delete a.vars}c='\x3cembed type\x3d"application/x-shockwave-flash" src\x3d"'+e.escape(String(c))+'" id\x3d"'+e.escape(String(a.id))+'" width\x3d"'+e.escape(String(a.width))+'" height\x3d"'+e.escape(String(a.height))+ '"'+(a.style?' style\x3d"'+e.escape(String(a.style))+'" ':"")+'pluginspage\x3d"'+window.location.protocol+'//www.adobe.com/go/getflashplayer" ';if(a.params)for(b in a.params)c+=" "+e.escape(b)+'\x3d"'+e.escape(String(a.params[b]))+'"';return{id:a.id,markup:c+" /\x3e"}},g=function(){var a=navigator.plugins["Shockwave Flash"];return a&&a.description?(a=a.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."),{major:null!=a[0]?parseInt(a[0]):0,minor:null!=a[1]?parseInt(a[1]): 0,rev:null!=a[2]?parseInt(a[2]):0}):{major:0,minor:0,rev:0}}());var f=function(a,b){if(-1<location.href.toLowerCase().indexOf("file://"))throw Error("dojox.embed.Flash can't be run directly from a file. To instatiate the required SWF correctly it must be run from a server, like localHost.");this.available=g.major;this.minimumVersion=a.minimumVersion||9;this.domNode=this.movie=this.id=null;b&&(b=k.byId(b));setTimeout(d.hitch(this,function(){if(a.expressInstall||this.available&&this.available>=this.minimumVersion)if(a&& b)this.init(a,b);else this.onError("embed.Flash was not provided with the proper arguments.");else if(this.available)this.onError("Flash version detected: "+this.available+" is out of date. Minimum required: "+this.minimumVersion);else this.onError("Flash is not installed.")}),100)};d.extend(f,{onReady:function(a){},onLoad:function(a){},onError:function(a){},_onload:function(){clearInterval(this._poller);delete this._poller;delete this._pollCount;delete this._pollMax;this.onLoad(this.movie)},init:function(a, b){this.destroy();b=k.byId(b||this.domNode);if(!b)throw Error("dojox.embed.Flash: no domNode reference has been passed.");var c=0;this._poller=null;this._pollCount=0;this._pollMax=15;this.pollTime=100;f.initialized&&(this.id=f.place(a,b),this.domNode=b,setTimeout(d.hitch(this,function(){this.movie=this.byId(this.id,a.doc);this.onReady(this.movie);this._poller=setInterval(d.hitch(this,function(){try{c=this.movie.PercentLoaded()}catch(a){}if(100==c)this._onload();else if(0==c&&this._pollCount++>this._pollMax)throw clearInterval(this._poller), Error("Building SWF failed.");}),this.pollTime)}),1))},_destroy:function(){try{this.domNode.removeChild(this.movie)}catch(a){}this.id=this.movie=this.domNode=null},destroy:function(){if(this.movie){var a=d.delegate({id:!0,movie:!0,domNode:!0,onReady:!0,onLoad:!0}),b;for(b in this)a[b]||delete this[b];this._poller?s(this,"Load",this,"_destroy"):this._destroy()}},byId:function(a,b){b=b||document;return b.embeds[a]?b.embeds[a]:b[a]?b[a]:window[a]?window[a]:document[a]?document[a]:null}});d.mixin(f,{minSupported:8, available:g.major,supported:g.major>=g.required,minimumRequired:g.required,version:g,initialized:!1,onInitialize:function(){f.initialized=!0},__ie_markup__:function(a){return h(a)},proxy:function(a,b){l.forEach(b instanceof Array?b:[b],function(a){this[a]=d.hitch(this,function(){return function(){return eval(this.movie.CallFunction('\x3cinvoke name\x3d"'+a+'" returntype\x3d"javascript"\x3e\x3carguments\x3e'+l.map(arguments,function(a){return __flash__toXML(a)}).join("")+"\x3c/arguments\x3e\x3c/invoke\x3e"))}.apply(this, arguments||[])})},a)}});f.place=function(a,b){var c=h(a);b=k.byId(b);b||(b=m.doc.createElement("div"),b.id=c.id+"-container",m.body().appendChild(b));return c?(b.innerHTML=c.markup,c.id):null};f.onInitialize();d.setObject("dojox.embed.Flash",f);return f}); //# sourceMappingURL=Flash.js.map
423.538462
546
0.711224
944b4f1d411bed14c1189a746e758e1c18011d17
171
js
JavaScript
src/fragments/forms/map-form/components/print/i18n/print.i18n.pt-br.js
whpai/eeee
e5e425bb92110f3b3728414f2120b19d72c8cd92
[ "Apache-2.0" ]
45
2020-07-08T16:56:00.000Z
2022-03-13T12:42:23.000Z
src/fragments/forms/map-form/components/print/i18n/print.i18n.pt-br.js
whpai/eeee
e5e425bb92110f3b3728414f2120b19d72c8cd92
[ "Apache-2.0" ]
217
2020-07-16T17:13:31.000Z
2022-03-29T19:05:32.000Z
src/fragments/forms/map-form/components/print/i18n/print.i18n.pt-br.js
whpai/eeee
e5e425bb92110f3b3728414f2120b19d72c8cd92
[ "Apache-2.0" ]
17
2020-09-30T20:19:44.000Z
2022-03-23T20:49:26.000Z
export default { print: { print: 'Imprimir', segment: 'Segmento', preparingPrinting: 'Preparando impressão', readyToPrint: 'Pronta para imprimir' } }
17.1
46
0.654971
944b8b74171dcf1c660589795b73a86c831f522d
311
js
JavaScript
javascript/0765.valid-triangle.js
Ubastic/lintcode
9f600eece075410221a24859331a810503c76014
[ "MIT" ]
null
null
null
javascript/0765.valid-triangle.js
Ubastic/lintcode
9f600eece075410221a24859331a810503c76014
[ "MIT" ]
null
null
null
javascript/0765.valid-triangle.js
Ubastic/lintcode
9f600eece075410221a24859331a810503c76014
[ "MIT" ]
1
2020-08-27T11:58:03.000Z
2020-08-27T11:58:03.000Z
/** * @param a: a integer represent the length of one edge * @param b: a integer represent the length of one edge * @param c: a integer represent the length of one edge * @return: whether three edges can form a triangle */ const isValidTriangle = function (a, b, c) { return a+b>c && a+c>b && b+c>a; }
31.1
55
0.66881
944be6801f16c6aea0cd5d74683b503658e59323
1,324
js
JavaScript
src/tests/utils/index.js
mattcarlotta/Testing-Practice
62b3be9dfd941d506fdda553d8f8516cca5319e1
[ "MIT" ]
null
null
null
src/tests/utils/index.js
mattcarlotta/Testing-Practice
62b3be9dfd941d506fdda553d8f8516cca5319e1
[ "MIT" ]
null
null
null
src/tests/utils/index.js
mattcarlotta/Testing-Practice
62b3be9dfd941d506fdda553d8f8516cca5319e1
[ "MIT" ]
null
null
null
import React from 'react'; import { shallow } from 'enzyme'; import checkPropTypes from 'check-prop-types'; /** * Factory function to create a ShallowWrapper for the Home component * @function setup * @param {node} Component - Component to be shallowed * @param {object} props - Component props specific to this setup. * @param {object} state - initial state for setup. * @returns {ShallowWrapper} */ export const setup = (Component, props = {}, state = null) => { const wrapper = shallow(<Component {...props} />); if (state) wrapper.setState(state); return wrapper; }; /** * Return ShallowWrapper containing node(s) with the given data-test val. * @param {ShallowWrapper} wrapper - Enzyme shallow wrapper to search within. * @param {string} val - Value of data-test attribute for search. * @returns {ShallowWrapper} */ export const findByTestAttr = (wrapper, val) => wrapper.find(`[data-test="${val}"]`); /** * Component PropType error checking * @param {node} Component - Component to be checked. * @param {conformingProps} object - Component props to be checked against. */ export const checkProps = (Component, conformingProps) => { const propError = checkPropTypes( Component.propTypes, conformingProps, 'prop', Component.name, ); expect(propError).toBeUndefined(); };
31.52381
77
0.701662
944c03240d1dca52b5ad4a1e1971df90b39291aa
10,153
js
JavaScript
src/containers/Signup.js
ks510/bounce-admin-portal-frontend
2e785239528e1010f5fd9b58977468eb8d9c4cf5
[ "MIT" ]
1
2020-11-27T22:00:15.000Z
2020-11-27T22:00:15.000Z
src/containers/Signup.js
ks510/bounce-admin-portal-frontend
2e785239528e1010f5fd9b58977468eb8d9c4cf5
[ "MIT" ]
10
2020-09-04T11:54:48.000Z
2022-03-08T22:30:21.000Z
src/containers/Signup.js
ks510/bounce-admin-portal-frontend
2e785239528e1010f5fd9b58977468eb8d9c4cf5
[ "MIT" ]
null
null
null
import React, { Component } from "react"; import { HelpBlock, FormGroup, FormControl, ControlLabel, Checkbox } from "react-bootstrap"; import { Link } from "react-router-dom"; import { Auth } from "aws-amplify"; import LoaderButton from "../components/LoaderButton"; import "./Signup.css"; import { API } from "aws-amplify"; /** * Two-page Sign Up with verification by code for Bounce Portal */ export default class Signup extends Component { constructor(props) { super(props); this.state = { isLoading: false, email: "", password: "", confirmPassword: "", confirmationCode: "", firstName: "", lastName: "", companyName: "", agreeChecked: false, newUser: null, pageOneComplete: false }; } /** * Validates page 1 of Sign Up form by checking all fields are filled in, * both password fields match exactly and the agreement checkbox is checked. */ validateFormPageOne() { return ( this.state.email.length > 0 && this.state.password.length > 0 && this.state.password === this.state.confirmPassword && this.state.agreeChecked ); } /** * Validates page 2 of Sign Up by checking all fields are filled in. */ validateFormPageTwo() { return ( this.state.firstName.length > 0 && this.state.lastName.length > 0 && this.state.companyName.length > 0 ); } /** * Validates confirmation code by checking it is filled in. */ validateConfirmationForm() { return this.state.confirmationCode.length > 0; } /** * Updates the state of form text fields. **/ handleChange = event => { this.setState({ [event.target.id]: event.target.value }); } /** * Updates the state of the checkbox. **/ handleChangeCheckbox = event => { this.setState({ [event.target.id]: event.target.checked }); } /** * Updates the state of sign up progression (after submitting page 1). */ handleSubmitPageOne = async event => { event.preventDefault(); this.setState({ isLoading: true, pageOneComplete: true }); this.setState({ isLoading: false }); } /** * Makes request to AWS Cognito to sign up user. Sign up progression is updated * upon error to redirect user back to page 1 of Sign up and make changes. * Since the state of fields are stored, the user only needs to make changes to * the fields with errors e.g. email already exists */ handleSubmitPageTwo = async event => { event.preventDefault(); this.setState({ isLoading: true }); try { const newUser = await Auth.signUp({ username: this.state.email, password: this.state.password, attributes: { 'email': this.state.email, 'given_name': this.state.firstName, 'family_name': this.state.lastName, 'custom:company_name': this.state.companyName, 'custom:customer_ID': '' } }); this.setState({ newUser }); } catch (e) { // currently all errors will redirect user back to page 1 of sign up form alert(e.message); this.setState({ pageOneComplete: false }); /* For more specific error handling e.g. email already exists: if (e.message === "An account with the given email already exists.") { this.setState({ pageOneComplete: false }); } */ } this.setState({ isLoading: false }); } /** * Confirms user account with code and automatically signs them in and redirects * to homepage for authenticated users (management portal landing). A Stripe * customer object is also created and stores the ID in Cognito custom attribute. **/ handleConfirmationSubmit = async event => { event.preventDefault(); this.setState({ isLoading: true }); try { await Auth.confirmSignUp(this.state.email, this.state.confirmationCode); await Auth.signIn(this.state.email, this.state.password); // create a new customer object for this account in Stripe const stripeCustomer = await this.createStripeCustomer({ email: this.state.email }); // store the unique stripe customer ID in Cognito const user = await Auth.currentAuthenticatedUser(); await Auth.updateUserAttributes(user, { "custom:customer_ID": stripeCustomer.customerID }); // redirect user to homepage / management portal landing this.props.userHasAuthenticated(true); this.props.history.push("/"); } catch (e) { alert(e.message); this.setState({ isLoading: false }); } } /** * Calls backend API for creating a Stripe customer object. **/ createStripeCustomer(email) { return API.post("notes", "/createCustomer", { body: email }); } /** * Renders page 1 of Sign Up form with the following fields: * - Email * - */ renderForm1() { return ( <div className="signupform1"> <form onSubmit={this.handleSubmitPageOne}> <h3>Improve your team today.</h3> <FormGroup controlId="email" bsSize="large"> <ControlLabel>Email</ControlLabel> <FormControl autoFocus type="email" value={this.state.email} onChange={this.handleChange} placeholder="johnsmith@bouncebot.io" /> </FormGroup> <FormGroup controlId="password" bsSize="large"> <ControlLabel>Create a Password</ControlLabel> <FormControl value={this.state.password} onChange={this.handleChange} type="password" placeholder="Minimum 8 characters" /> </FormGroup> <FormGroup controlId="confirmPassword" bsSize="large"> <ControlLabel>Confirm your Password</ControlLabel> <FormControl value={this.state.confirmPassword} onChange={this.handleChange} type="password" placeholder="Retype your password" /> </FormGroup> <Checkbox id="agreeChecked" checked={this.state.agreeChecked} onChange={this.handleChangeCheckbox} title="agreeChecked"> I have read and agree to Bounce&#39;s <Link to="/termsofservice">Terms of Service </Link> and <Link to="/privacypolicy">Privacy Policy</Link>. </Checkbox> <LoaderButton block bsSize="large" disabled={!this.validateFormPageOne()} type="submit" isLoading={this.state.isLoading} text="Sign Up" loadingText="Signing up…" /> </form> </div> ); } /** * Renders page 2 of Sign Up with the following fields: * - First Name * - Last Name * - Company Name * These are stored as attributes with user sign up profile in Cognito. */ renderForm2() { return ( <div className="signupform2"> <form onSubmit={this.handleSubmitPageTwo}> <h3>Almost there.</h3> <FormGroup controlId="firstName" bsSize="large"> <ControlLabel>First Name</ControlLabel> <FormControl value={this.state.firstName} onChange={this.handleChange} type="firstName" placeholder="John" /> </FormGroup> <FormGroup controlId="lastName" bsSize="large"> <ControlLabel>First Name</ControlLabel> <FormControl value={this.state.lastName} onChange={this.handleChange} type="lastName" placeholder="Smith" /> </FormGroup> <FormGroup controlId="companyName" bsSize="large"> <ControlLabel>Company Name</ControlLabel> <FormControl value={this.state.companyName} onChange={this.handleChange} type="companyName" placeholder="Bounce Technologies" /> </FormGroup> <LoaderButton block bsSize="large" disabled={!this.validateFormPageTwo()} type="submit" isLoading={this.state.isLoading} text="Sign Up" loadingText="Signing up…" /> </form> </div> ) } /** * Renders verification page for user to input confirmation code from their email */ renderConfirmationForm() { return ( <div className="signup-verification"> <form onSubmit={this.handleConfirmationSubmit}> <h3>One last step.</h3> <p id="verify">You&#39;ll receive an email within a few minutes to verify your account with a confirmation code. Please enter the code below.</p> <FormGroup controlId="confirmationCode" bsSize="large"> <ControlLabel>Confirmation Code</ControlLabel> <FormControl autoFocus type="tel" value={this.state.confirmationCode} onChange={this.handleChange} /> <HelpBlock>Please check your email for the code.</HelpBlock> </FormGroup> <LoaderButton block bsSize="large" disabled={!this.validateConfirmationForm()} type="submit" isLoading={this.state.isLoading} text="Verify" loadingText="Verifying…" /> </form> </div> ); } /** * Decision for rendering page 1 or page 2 of sign up based on progression. */ renderForm() { return ( <div className="signup-form"> {this.state.pageOneComplete ? this.renderForm2() : this.renderForm1()} </div> ); } /** * Decision for rendering sign up form or verification based on progression. **/ render() { return ( <div className="Signup"> {this.state.newUser === null ? this.renderForm() : this.renderConfirmationForm()} </div> ); } }
28.360335
101
0.58495
944c668fbd478c03c2cd0b00bf102e7b29e0ff1d
341
js
JavaScript
chai-example/chai-test.js
segrey/mocha-sample-tests
8d88af9f8ee126258fce4d87ba24e8c060a10da4
[ "Apache-2.0" ]
null
null
null
chai-example/chai-test.js
segrey/mocha-sample-tests
8d88af9f8ee126258fce4d87ba24e8c060a10da4
[ "Apache-2.0" ]
null
null
null
chai-example/chai-test.js
segrey/mocha-sample-tests
8d88af9f8ee126258fce4d87ba24e8c060a10da4
[ "Apache-2.0" ]
null
null
null
var chai = require('chai'); var expect = chai.expect; var assert = chai.assert; var should = chai.should(); //actually call the function describe('chai', function () { it('should check indexOf', function () { [1, 2, 3].indexOf(4).should.equal(-1); }); it('should pass', function () { expect(true).to.be.equal(true); }); });
24.357143
56
0.621701
944ca5085ff71e22c540837b7c29f2338c84399d
350
js
JavaScript
.storybook/preview.js
Tiamat-Tech/react-intersection-observer
e59d9c2199384c82e9d0b8d653136944a699e30d
[ "MIT" ]
null
null
null
.storybook/preview.js
Tiamat-Tech/react-intersection-observer
e59d9c2199384c82e9d0b8d653136944a699e30d
[ "MIT" ]
null
null
null
.storybook/preview.js
Tiamat-Tech/react-intersection-observer
e59d9c2199384c82e9d0b8d653136944a699e30d
[ "MIT" ]
null
null
null
import 'intersection-observer'; import 'tailwindcss/tailwind.css'; import { themes } from '@storybook/theming'; import { ignoreErrorMessages } from './utils/ignore-errors'; export const parameters = { docs: { theme: themes.dark, }, controls: { expanded: true, }, }; if (process.env.NODE_ENV !== 'test') { ignoreErrorMessages(); }
19.444444
60
0.671429
944e6a12fa743ffaeff1ddb7433e5eb062c09e89
2,604
js
JavaScript
ui/src/pages/index.js
gabrielclaudino/descomplica-technical-challenge
d693911e52bfb99766cee89ab69afc72d3c70cf5
[ "MIT" ]
null
null
null
ui/src/pages/index.js
gabrielclaudino/descomplica-technical-challenge
d693911e52bfb99766cee89ab69afc72d3c70cf5
[ "MIT" ]
4
2021-12-09T17:17:56.000Z
2022-01-29T01:33:15.000Z
ui/src/pages/index.js
gabrielclaudino/descomplica-technical-challenge
d693911e52bfb99766cee89ab69afc72d3c70cf5
[ "MIT" ]
null
null
null
import * as React from 'react'; import { Box, Container, Fab, Typography } from '@mui/material'; import AddIcon from '@mui/icons-material/Add'; import { useMutation, useQuery } from '@apollo/client'; import { addApolloState, initializeApollo } from '../lib/apollo'; import { ALL_STUDENTS_QUERY } from '../lib/graphql/allStudents'; import { UPDATE_STUDENT_MUTATION } from '../lib/graphql/updateStudent'; import Header from '../components/Header'; import StudentsDataGrid from '../components/StudentsDataGrid'; const Index = () => { const { data, loading, error, refetch } = useQuery(ALL_STUDENTS_QUERY, {}); const [ updateStudent, { error: mutErrro }, ] = useMutation(UPDATE_STUDENT_MUTATION); const columns = [ { field: 'name', headerName: 'Nome do Aluno', width: 200, editable: true, }, { field: 'cpf', headerName: 'CPF', width: 150, editable: true, }, { field: 'email', headerName: 'Email', width: 200, editable: true, }, ]; const rows = data?.allStudents || []; const handleEditCommit = ({ field, id, value }) => { updateStudent({ variables: { id, student: { [field]: value }, }, }); }; if (mutErrro) { console.error('Error', mutErrro); } return ( <> <Header /> <Container maxWidth={'md'}> <Typography pt={1} variant="h3" component="h1" align="center" sx={{ fontWeight: 'bold' }} > Lista de Alunos </Typography> <Typography align="center" pt={3} pb={2}> Visualize ou edite seus estudantes </Typography> <Box sx={{ flexGrow: 1 }}> <StudentsDataGrid rows={rows} columns={columns} loading={loading} error={error} onEditCommit={handleEditCommit} /> </Box> </Container> <Box sx={{ display: { xs: 'none', md: 'none' }, position: 'fixed', width: '100%', justifyContent: 'center', bottom: '3vh', }} > <Fab color="primary" aria-label="Adicionar"> <AddIcon /> </Fab> </Box> </> ); }; export const getStaticProps = async () => { const client = initializeApollo(); try { await client.query({ query: ALL_STUDENTS_QUERY }); return addApolloState(client, { props: {}, revalidate: 1, }); } catch { return { props: {}, }; } }; export default Index;
22.067797
77
0.531874
944ef00f79d012abe0cca399870c4b96b5891178
726
js
JavaScript
index.js
johnotander/rework-only-child
048b9d44a9e32fdd184d17bba41e2f7714ad37f4
[ "MIT" ]
null
null
null
index.js
johnotander/rework-only-child
048b9d44a9e32fdd184d17bba41e2f7714ad37f4
[ "MIT" ]
null
null
null
index.js
johnotander/rework-only-child
048b9d44a9e32fdd184d17bba41e2f7714ad37f4
[ "MIT" ]
null
null
null
'use strict'; var walk = require('rework-walk'); var PROPERTY_IDENTIFIER = ':only-child'; var PROPERTY_REPLACEMENT = ':first-child:last-child'; module.exports = function reworkOnlyChild() { return function reworkOnlyChild(css) { walk(css, function(rule, node) { if (!rule.selectors) return rule; rule.selectors = rule.selectors.map(function(selector) { // See if it's a selector with the :only-child pseudo-class if (selector.indexOf(PROPERTY_IDENTIFIER) !== -1) { // Replace :only-child with :first-child:last-child return selector.split(PROPERTY_IDENTIFIER).join(PROPERTY_REPLACEMENT); } else { return selector; } }); }); }; };
29.04
80
0.643251
944f3cc0246b45c93a96e249802d36140e1ef7bb
391
js
JavaScript
src/components/UsersList.js
danielkermode/hiplee-application
c9f52d9de7755a98e3e062fdb911d8308012ed1f
[ "MIT" ]
null
null
null
src/components/UsersList.js
danielkermode/hiplee-application
c9f52d9de7755a98e3e062fdb911d8308012ed1f
[ "MIT" ]
null
null
null
src/components/UsersList.js
danielkermode/hiplee-application
c9f52d9de7755a98e3e062fdb911d8308012ed1f
[ "MIT" ]
null
null
null
import React from 'react'; const UsersList = props => { return ( <div className='userlist'> {props.users.map(user => { return ( <div className='userbox' key={user.id} onClick={() => { props.selectActiveUser(user) }}> <div>{user.first_name} {user.last_name}</div> </div> ) })} </div> ) } export default UsersList;
19.55
63
0.534527
94503d68d2faef3bb25959bf68e4ec51028fc6cb
191
js
JavaScript
src/commands/imageManipulation/bongocat.js
Neutronboi345/Dank-Memer-1
6d4a0b4ca8ba926f83e53cb8e1e8efbc3954269c
[ "MIT" ]
25
2020-07-19T10:41:33.000Z
2022-03-04T19:54:13.000Z
src/commands/imageManipulation/bongocat.js
Neutronboi345/Dank-Memer-1
6d4a0b4ca8ba926f83e53cb8e1e8efbc3954269c
[ "MIT" ]
null
null
null
src/commands/imageManipulation/bongocat.js
Neutronboi345/Dank-Memer-1
6d4a0b4ca8ba926f83e53cb8e1e8efbc3954269c
[ "MIT" ]
40
2020-08-26T21:16:09.000Z
2022-03-12T14:27:48.000Z
const GenericImageCommand = require('../../models/GenericImageCommand.js'); module.exports = new GenericImageCommand({ triggers: ['bongocat', 'bongo'], description: 'smack smack...' });
27.285714
75
0.706806
9450b165aa27aba0b76d91ca37740782c24790a2
902
js
JavaScript
client/components/forms/AddReview.js
autarky-nomoi/Starships
30fe622a66d8bdbd791344d33d69c6cade4b8e76
[ "MIT" ]
null
null
null
client/components/forms/AddReview.js
autarky-nomoi/Starships
30fe622a66d8bdbd791344d33d69c6cade4b8e76
[ "MIT" ]
22
2018-07-25T20:46:50.000Z
2018-08-01T00:12:20.000Z
client/components/forms/AddReview.js
autarky-nomoi/Starships
30fe622a66d8bdbd791344d33d69c6cade4b8e76
[ "MIT" ]
3
2018-07-25T19:48:53.000Z
2018-07-25T20:03:34.000Z
import React from 'react' import {connect} from 'react-redux'; import {addReviews} from '../../store/review' import ReviewForm from './ReviewForm' require('../style/singleUser.css') const AddReviewForm = ({handleSubmit, ship, user}) => ( <React.Fragment> <h1>Add a new Review</h1> <ReviewForm handleSubmit={handleSubmit} ship={ship} user={user} /> </React.Fragment> ) const mapStateToprops = (state) => ({ ship: state.ship.singleShip, user: state.user }); const mapDispatchToProps = (dispatch, ownProps) => ({ handleSubmit: async (event, reviewData) =>{ event.preventDefault(); const starshipAction = await dispatch(addReviews(reviewData, ownProps)); const theId = starshipAction.payload.starshipId ownProps.history.push(`/starships/${theId}`) } }) const AddReview = connect(mapStateToprops, mapDispatchToProps)(AddReviewForm) export default AddReview;
26.529412
77
0.707317
9450cea1b3e40e883cd456eb6d32bc0c666038f3
100
js
JavaScript
vsdoc/search--/s_461.js
asiboro/asiboro.github.io
a2e56607dca65eed437b6a666dcbc3f586492d8c
[ "MIT" ]
null
null
null
vsdoc/search--/s_461.js
asiboro/asiboro.github.io
a2e56607dca65eed437b6a666dcbc3f586492d8c
[ "MIT" ]
null
null
null
vsdoc/search--/s_461.js
asiboro/asiboro.github.io
a2e56607dca65eed437b6a666dcbc3f586492d8c
[ "MIT" ]
null
null
null
search_result['461']=["topic_00000000000000E1_props--.html","TleceBaseResponseModel Properties",""];
100
100
0.8
9451e0a45dd945f777517749e37fbbe57bec4508
933
js
JavaScript
08. Text-Processing/More-Exercises/04. Melrah Shake.js
tsvdimitrov/SoftUni-JS-Fundamentals
1e9f7e8713be1f8865a41a526fa164cd164b2840
[ "MIT" ]
null
null
null
08. Text-Processing/More-Exercises/04. Melrah Shake.js
tsvdimitrov/SoftUni-JS-Fundamentals
1e9f7e8713be1f8865a41a526fa164cd164b2840
[ "MIT" ]
null
null
null
08. Text-Processing/More-Exercises/04. Melrah Shake.js
tsvdimitrov/SoftUni-JS-Fundamentals
1e9f7e8713be1f8865a41a526fa164cd164b2840
[ "MIT" ]
null
null
null
function melrahShake(input) { let text = input.shift(); let pattern = input.shift(); while (pattern.length > 0) { let firstMatch = text.indexOf(pattern); let secondMatch = text.lastIndexOf(pattern); if (firstMatch > -1 && secondMatch > -1 && firstMatch !== secondMatch) { text = text.split(""); text.splice(firstMatch, pattern.length); text = text.join(""); secondMatch = text.lastIndexOf(pattern); text = text.split(""); text.splice(secondMatch, pattern.length); let removeFromPat = pattern[Math.floor(pattern.length / 2)]; pattern = pattern.replace(removeFromPat, ""); text = text.join(""); console.log('Shaked it.'); } else { break; } } console.log('No shake.'); console.log(text); } melrahShake(['astalavista baby', 'sta', '']);
31.1
80
0.546624
9454eecfad1d11e9617f2560e8d99c4079bff562
1,537
js
JavaScript
@gip-recia/subject-infos/src/subject-infos-style.js
slafon51/esup-publisher-webcomponents
e3b7377ec9a6241e7f644fd3cedc7a04121a2a9c
[ "Apache-2.0" ]
null
null
null
@gip-recia/subject-infos/src/subject-infos-style.js
slafon51/esup-publisher-webcomponents
e3b7377ec9a6241e7f644fd3cedc7a04121a2a9c
[ "Apache-2.0" ]
14
2022-03-14T09:08:55.000Z
2022-03-31T15:57:14.000Z
@gip-recia/subject-infos/src/subject-infos-style.js
slafon51/esup-publisher-webcomponents
e3b7377ec9a6241e7f644fd3cedc7a04121a2a9c
[ "Apache-2.0" ]
1
2022-01-24T08:46:38.000Z
2022-01-24T08:46:38.000Z
import { css } from 'lit' export const subjectInfosStyle = css` a:hover, a:focus, a:link { text-decoration: none; outline: none; } a { color: var(--subject-infos-text-color, #000) } a:hover, a:focus, a:hover>div, a:focus>div { color: var(--subject-infos-focus-text-color, #25B2F3); background-color: var(--subject-infos-focus-background-color, transparent); } .icon:before { -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; display: inline-block; font-style: normal; font-variant: normal; text-rendering: auto; line-height: 1; margin: 0px 2px; font-family: 'Font Awesome 5 Free'; font-weight: 900; content: '\\f128'; } .icon-question:before { font-family: var(--icon-question-font-family, 'Font Awesome 5 Free'); font-weight: var(--icon-question-font-weight, 900); content: var(--icon-question-content, '\\f128'); } .icon-users:before { font-family: var(--icon-users-font-family, 'Font Awesome 5 Free'); font-weight: var(--icon-users-font-weight, 900); content: var(--icon-users-content, '\\f0c0'); } .icon-user:before { font-family: var(--icon-user-font-family, 'Font Awesome 5 Free'); font-weight: var(--icon-user-font-weight, 900); content: var(--icon-user-content, '\\f007'); } [data-tooltip] { position: relative; } `
29
83
0.575146
9455367023665c3c22c25c66d6e93e16d2d95198
128
js
JavaScript
config.js
linanaliu51k/weixintest
fb42172e2f6f5c4f0ca3975e857d42bac20da466
[ "MIT" ]
null
null
null
config.js
linanaliu51k/weixintest
fb42172e2f6f5c4f0ca3975e857d42bac20da466
[ "MIT" ]
null
null
null
config.js
linanaliu51k/weixintest
fb42172e2f6f5c4f0ca3975e857d42bac20da466
[ "MIT" ]
null
null
null
module.exports = { appID:"wxd9ac82842f1d8fa7", appsecret:"86101d04882d294d3182d1096a767cf8", Token:'zhufengpeixun' }
25.6
49
0.742188
94565aeb27664839763503c9ee9a525a5fb349b5
11,155
js
JavaScript
vst3sdk/doc/vstsdk/search/classes_7.js
MOAMaster/AudioPlugSharp-SamplePlugins
dbe3cc445a7834e7e0f922f53a35973d6d9b583a
[ "MIT" ]
null
null
null
vst3sdk/doc/vstsdk/search/classes_7.js
MOAMaster/AudioPlugSharp-SamplePlugins
dbe3cc445a7834e7e0f922f53a35973d6d9b583a
[ "MIT" ]
null
null
null
vst3sdk/doc/vstsdk/search/classes_7.js
MOAMaster/AudioPlugSharp-SamplePlugins
dbe3cc445a7834e7e0f922f53a35973d6d9b583a
[ "MIT" ]
null
null
null
var searchData= [ ['iattributelist_2622',['IAttributeList',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IAttributeList.html',1,'Steinberg::Vst']]], ['iattributes_2623',['IAttributes',['../../base/classSteinberg_1_1IAttributes.html',1,'Steinberg']]], ['iattributes2_2624',['IAttributes2',['../../base/classSteinberg_1_1IAttributes2.html',1,'Steinberg']]], ['iaudiopresentationlatency_2625',['IAudioPresentationLatency',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IAudioPresentationLatency.html',1,'Steinberg::Vst']]], ['iaudioprocessor_2626',['IAudioProcessor',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IAudioProcessor.html',1,'Steinberg::Vst']]], ['iautomationstate_2627',['IAutomationState',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IAutomationState.html',1,'Steinberg::Vst']]], ['ibstream_2628',['IBStream',['../../base/classSteinberg_1_1IBStream.html',1,'Steinberg']]], ['icloneable_2629',['ICloneable',['../../base/classSteinberg_1_1ICloneable.html',1,'Steinberg']]], ['icomponent_2630',['IComponent',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IComponent.html',1,'Steinberg::Vst']]], ['icomponenthandler_2631',['IComponentHandler',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IComponentHandler.html',1,'Steinberg::Vst']]], ['icomponenthandler2_2632',['IComponentHandler2',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IComponentHandler2.html',1,'Steinberg::Vst']]], ['icomponenthandler3_2633',['IComponentHandler3',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IComponentHandler3.html',1,'Steinberg::Vst']]], ['icomponenthandlerbusactivation_2634',['IComponentHandlerBusActivation',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IComponentHandlerBusActivation.html',1,'Steinberg::Vst']]], ['iconnectionpoint_2635',['IConnectionPoint',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IConnectionPoint.html',1,'Steinberg::Vst']]], ['icontextmenu_2636',['IContextMenu',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IContextMenu.html',1,'Steinberg::Vst']]], ['icontextmenuitem_2637',['IContextMenuItem',['../../vstinterfaces/structSteinberg_1_1Vst_1_1IContextMenuItem.html',1,'Steinberg::Vst']]], ['icontextmenutarget_2638',['IContextMenuTarget',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IContextMenuTarget.html',1,'Steinberg::Vst']]], ['idependent_2639',['IDependent',['../../base/classSteinberg_1_1IDependent.html',1,'Steinberg']]], ['ieditcontroller_2640',['IEditController',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IEditController.html',1,'Steinberg::Vst']]], ['ieditcontroller2_2641',['IEditController2',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IEditController2.html',1,'Steinberg::Vst']]], ['ieditcontrollerhostediting_2642',['IEditControllerHostEditing',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IEditControllerHostEditing.html',1,'Steinberg::Vst']]], ['ierrorcontext_2643',['IErrorContext',['../../base/classSteinberg_1_1IErrorContext.html',1,'Steinberg']]], ['ieventhandler_2644',['IEventHandler',['../../base/classSteinberg_1_1Linux_1_1IEventHandler.html',1,'Steinberg::Linux']]], ['ieventlist_2645',['IEventList',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IEventList.html',1,'Steinberg::Vst']]], ['ihostapplication_2646',['IHostApplication',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IHostApplication.html',1,'Steinberg::Vst']]], ['iinfolistener_2647',['IInfoListener',['../../vstinterfaces/classSteinberg_1_1Vst_1_1ChannelContext_1_1IInfoListener.html',1,'Steinberg::Vst::ChannelContext']]], ['iinterappaudioconnectionnotification_2648',['IInterAppAudioConnectionNotification',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IInterAppAudioConnectionNotification.html',1,'Steinberg::Vst']]], ['iinterappaudiohost_2649',['IInterAppAudioHost',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IInterAppAudioHost.html',1,'Steinberg::Vst']]], ['iinterappaudiopresetmanager_2650',['IInterAppAudioPresetManager',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IInterAppAudioPresetManager.html',1,'Steinberg::Vst']]], ['ikeyswitchcontroller_2651',['IKeyswitchController',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IKeyswitchController.html',1,'Steinberg::Vst']]], ['imagedesc_2652',['ImageDesc',['../structVST3_1_1Hosting_1_1Module_1_1Snapshot_1_1ImageDesc.html',1,'VST3::Hosting::Module::Snapshot']]], ['imessage_2653',['IMessage',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IMessage.html',1,'Steinberg::Vst']]], ['imidilearn_2654',['IMidiLearn',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IMidiLearn.html',1,'Steinberg::Vst']]], ['imidimapping_2655',['IMidiMapping',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IMidiMapping.html',1,'Steinberg::Vst']]], ['inoteexpressioncontroller_2656',['INoteExpressionController',['../../vstinterfaces/classSteinberg_1_1Vst_1_1INoteExpressionController.html',1,'Steinberg::Vst']]], ['inoteexpressionphysicaluimapping_2657',['INoteExpressionPhysicalUIMapping',['../../vstinterfaces/classSteinberg_1_1Vst_1_1INoteExpressionPhysicalUIMapping.html',1,'Steinberg::Vst']]], ['iparameterchanges_2658',['IParameterChanges',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IParameterChanges.html',1,'Steinberg::Vst']]], ['iparameterfinder_2659',['IParameterFinder',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IParameterFinder.html',1,'Steinberg::Vst']]], ['iparameterfunctionname_2660',['IParameterFunctionName',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IParameterFunctionName.html',1,'Steinberg::Vst']]], ['iparamvaluequeue_2661',['IParamValueQueue',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IParamValueQueue.html',1,'Steinberg::Vst']]], ['ipersistent_2662',['IPersistent',['../../base/classSteinberg_1_1IPersistent.html',1,'Steinberg']]], ['iplugframe_2663',['IPlugFrame',['../../base/classSteinberg_1_1IPlugFrame.html',1,'Steinberg']]], ['ipluginbase_2664',['IPluginBase',['../../base/classSteinberg_1_1IPluginBase.html',1,'Steinberg']]], ['ipluginfactory_2665',['IPluginFactory',['../../base/classSteinberg_1_1IPluginFactory.html',1,'Steinberg']]], ['ipluginfactory2_2666',['IPluginFactory2',['../../base/classSteinberg_1_1IPluginFactory2.html',1,'Steinberg']]], ['ipluginfactory3_2667',['IPluginFactory3',['../../base/classSteinberg_1_1IPluginFactory3.html',1,'Steinberg']]], ['ipluginterfacesupport_2668',['IPlugInterfaceSupport',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IPlugInterfaceSupport.html',1,'Steinberg::Vst']]], ['iplugview_2669',['IPlugView',['../../base/classSteinberg_1_1IPlugView.html',1,'Steinberg']]], ['iplugviewcontentscalesupport_2670',['IPlugViewContentScaleSupport',['../../base/classSteinberg_1_1IPlugViewContentScaleSupport.html',1,'Steinberg']]], ['iprefetchablesupport_2671',['IPrefetchableSupport',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IPrefetchableSupport.html',1,'Steinberg::Vst']]], ['iprocesscontextrequirements_2672',['IProcessContextRequirements',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IProcessContextRequirements.html',1,'Steinberg::Vst']]], ['iprogramlistdata_2673',['IProgramListData',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IProgramListData.html',1,'Steinberg::Vst']]], ['iprogress_2674',['IProgress',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IProgress.html',1,'Steinberg::Vst']]], ['iptr_2675',['IPtr',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['iptr_3c_20steinberg_3a_3aibstream_20_3e_2676',['IPtr&lt; Steinberg::IBStream &gt;',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['iptr_3c_20steinberg_3a_3aipluginfactory_20_3e_2677',['IPtr&lt; Steinberg::IPluginFactory &gt;',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['iptr_3c_20steinberg_3a_3avst_3a_3aicomponent_20_3e_2678',['IPtr&lt; Steinberg::Vst::IComponent &gt;',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['iptr_3c_20steinberg_3a_3avst_3a_3aiconnectionpoint_20_3e_2679',['IPtr&lt; Steinberg::Vst::IConnectionPoint &gt;',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['iptr_3c_20steinberg_3a_3avst_3a_3aieditcontroller_20_3e_2680',['IPtr&lt; Steinberg::Vst::IEditController &gt;',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['iptr_3c_20steinberg_3a_3avst_3a_3apluginterfacesupport_20_3e_2681',['IPtr&lt; Steinberg::Vst::PlugInterfaceSupport &gt;',['../../base/classSteinberg_1_1IPtr.html',1,'Steinberg']]], ['irunloop_2682',['IRunLoop',['../../base/classSteinberg_1_1Linux_1_1IRunLoop.html',1,'Steinberg::Linux']]], ['isizeablestream_2683',['ISizeableStream',['../../base/classSteinberg_1_1ISizeableStream.html',1,'Steinberg']]], ['istreamattributes_2684',['IStreamAttributes',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IStreamAttributes.html',1,'Steinberg::Vst']]], ['istring_2685',['IString',['../../base/classSteinberg_1_1IString.html',1,'Steinberg']]], ['istringresult_2686',['IStringResult',['../../base/classSteinberg_1_1IStringResult.html',1,'Steinberg']]], ['itest_2687',['ITest',['../../vstinterfaces/classSteinberg_1_1ITest.html',1,'Steinberg']]], ['itestfactory_2688',['ITestFactory',['../../vstinterfaces/classSteinberg_1_1ITestFactory.html',1,'Steinberg']]], ['itestplugprovider_2689',['ITestPlugProvider',['../../vstinterfaces/classSteinberg_1_1Vst_1_1ITestPlugProvider.html',1,'Steinberg::Vst']]], ['itestplugprovider2_2690',['ITestPlugProvider2',['../../vstinterfaces/classSteinberg_1_1Vst_1_1ITestPlugProvider2.html',1,'Steinberg::Vst']]], ['itestresult_2691',['ITestResult',['../../vstinterfaces/classSteinberg_1_1ITestResult.html',1,'Steinberg']]], ['itestsuite_2692',['ITestSuite',['../../vstinterfaces/classSteinberg_1_1ITestSuite.html',1,'Steinberg']]], ['itimerhandler_2693',['ITimerHandler',['../../base/classSteinberg_1_1Linux_1_1ITimerHandler.html',1,'Steinberg::Linux']]], ['iunitdata_2694',['IUnitData',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IUnitData.html',1,'Steinberg::Vst']]], ['iunithandler_2695',['IUnitHandler',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IUnitHandler.html',1,'Steinberg::Vst']]], ['iunithandler2_2696',['IUnitHandler2',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IUnitHandler2.html',1,'Steinberg::Vst']]], ['iunitinfo_2697',['IUnitInfo',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IUnitInfo.html',1,'Steinberg::Vst']]], ['iupdatehandler_2698',['IUpdateHandler',['../../base/classSteinberg_1_1IUpdateHandler.html',1,'Steinberg']]], ['ivst3toaaxwrapper_2699',['IVst3ToAAXWrapper',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IVst3ToAAXWrapper.html',1,'Steinberg::Vst']]], ['ivst3toauwrapper_2700',['IVst3ToAUWrapper',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IVst3ToAUWrapper.html',1,'Steinberg::Vst']]], ['ivst3tovst2wrapper_2701',['IVst3ToVst2Wrapper',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IVst3ToVst2Wrapper.html',1,'Steinberg::Vst']]], ['ivst3wrappermpesupport_2702',['IVst3WrapperMPESupport',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IVst3WrapperMPESupport.html',1,'Steinberg::Vst']]], ['ixmlrepresentationcontroller_2703',['IXmlRepresentationController',['../../vstinterfaces/classSteinberg_1_1Vst_1_1IXmlRepresentationController.html',1,'Steinberg::Vst']]] ];
129.709302
199
0.764142
9456b68c6de5dcbed920e9147e3829c464213548
448
js
JavaScript
CSF.Screenplay.Selenium.JavaScriptWorkarounds/ScriptResources/GetALocalisedDate.js
csf-dev/CSF.Screenplay.Selenium
0644e7883d5ebc91dcebaa0fab4a20925f967eda
[ "MIT" ]
2
2021-01-20T16:00:04.000Z
2021-03-19T16:35:29.000Z
CSF.Screenplay.Selenium.JavaScriptWorkarounds/ScriptResources/GetALocalisedDate.js
csf-dev/CSF.Screenplay.Selenium
0644e7883d5ebc91dcebaa0fab4a20925f967eda
[ "MIT" ]
63
2018-02-01T23:10:16.000Z
2019-05-01T07:13:08.000Z
CSF.Screenplay.Selenium.JavaScriptWorkarounds/ScriptResources/GetALocalisedDate.js
csf-dev/CSF.Screenplay.Selenium
0644e7883d5ebc91dcebaa0fab4a20925f967eda
[ "MIT" ]
null
null
null
function executeScript(argsArray) { 'use strict'; argumentsArrayValidator.validate(argsArray, 3); var year = argsArray[0], month = argsArray[1], day = argsArray[2], theDate; if(typeof year !== 'number' || typeof month !== 'number' || typeof day !== 'number') throw new Error('The supplied year, month and day must all be numbers.'); theDate = new Date(year, month, day); return theDate.toLocaleDateString(); }
26.352941
86
0.65625
9456eae8b9f13431702202693ab8fd6bfe16dd0a
1,512
js
JavaScript
pages/_app.js
abelofficial/nextjs-material-ui_Boiler
bad3becc4ab62979dc5df42684c3ed817bdf702b
[ "MIT" ]
null
null
null
pages/_app.js
abelofficial/nextjs-material-ui_Boiler
bad3becc4ab62979dc5df42684c3ed817bdf702b
[ "MIT" ]
null
null
null
pages/_app.js
abelofficial/nextjs-material-ui_Boiler
bad3becc4ab62979dc5df42684c3ed817bdf702b
[ "MIT" ]
null
null
null
// Core components import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; import Head from 'next/head'; import { DefaultSeo } from 'next-seo'; // Material ui import { CssBaseline, ThemeProvider, useMediaQuery, responsiveFontSizes } from '@material-ui/core'; // Local import SEO from '@local/src/utils/next-seo.config'; import theme from '@local-utils/globalTheme'; export default function MyApp(props) { const { Component, pageProps } = props; // Auto detect browser theme mode const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)'); const globalTheme = responsiveFontSizes( theme(prefersDarkMode ? 'dark' : 'light') ); useEffect(() => { // Remove the server-side injected CSS. const jssStyles = document.querySelector('#jss-server-side'); if (jssStyles) { jssStyles.parentElement.removeChild(jssStyles); } }, []); return ( <> <Head> <DefaultSeo {...SEO} /> {/* // Cookie based redirect <script dangerouslySetInnerHTML={{ __html: `if (document.cookie && document.cookie.includes('${__COOKIE_NAME__}')) { window.location.href = "${__REDIRECT_URL__}" }` }} /> */} </Head> <ThemeProvider theme={globalTheme}> <CssBaseline /> <Component {...pageProps} /> </ThemeProvider> </> ); } MyApp.propTypes = { Component: PropTypes.elementType.isRequired, pageProps: PropTypes.object.isRequired };
24.387097
91
0.634921
945ad753056aa20f97da7ea7fab03ed9dc34a5a1
1,421
js
JavaScript
public/assets/app.js
speedDeveloper/Team-Sport
6bb42a10d9428cbd3171be168e2efe4fa624ab5d
[ "MIT" ]
4
2015-09-12T08:16:21.000Z
2015-09-14T14:29:41.000Z
public/assets/app.js
speedDeveloper/Team-Sport
6bb42a10d9428cbd3171be168e2efe4fa624ab5d
[ "MIT" ]
null
null
null
public/assets/app.js
speedDeveloper/Team-Sport
6bb42a10d9428cbd3171be168e2efe4fa624ab5d
[ "MIT" ]
null
null
null
var app = angular.module('runningApp', [ 'ngMaterial', 'ngRoute', 'ngMap', 'ngCookies', 'mainCtrl.runningApp', 'loginCtrl.runningApp', 'registerCtrl.runningApp' ]) .config(function($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/pLogin.html', controller: 'loginCtrl' }) .when('/main', { templateUrl: 'views/pMain.html', controller: 'mainCtrl' }) .when('/register', { templateUrl: 'views/pRegister.html', controller: 'registerCtrl' }) .when("/addevent", { templateUrl: "views/pAddEvent.html", controller: "addeventCtrl.runningApp" }) .when("/findevent", { templateUrl: "views/pFindEvent.html", controller: "findevent.runningApp" }); }).factory('types', function() { var types = ['Joggen', 'Rennen', 'Spazieren', 'Biken', 'Sudoku']; return types; }) .service('coordinates', function() { var longitude = 0; var latitude = 0; var setCoordinates = function(long, lat) { longitude = long; latitude = lat; }; var getLongitude = function() { return longitude; }; var getLatitude = function() { return latitude; }; return { getLongitude: getLongitude, getLatitude: getLatitude, setCoordinates: setCoordinates }; });
24.5
69
0.57354
945fa594f7dc317da767459d0dc1a7f9fc55989b
1,800
js
JavaScript
src/Commands/Install/index.js
un-versed/adonis-cli
1e698919332d65e629b73a0ea8a800274e9e1cf1
[ "MIT" ]
147
2015-09-20T18:59:44.000Z
2021-09-08T10:01:09.000Z
src/Commands/Install/index.js
un-versed/adonis-cli
1e698919332d65e629b73a0ea8a800274e9e1cf1
[ "MIT" ]
161
2016-01-15T06:11:52.000Z
2021-04-09T05:48:13.000Z
src/Commands/Install/index.js
un-versed/adonis-cli
1e698919332d65e629b73a0ea8a800274e9e1cf1
[ "MIT" ]
81
2015-12-09T03:43:05.000Z
2022-03-07T15:12:12.000Z
'use strict' /* * adonis-cli * * (c) Harminder Virk <virk@adonisjs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const path = require('path') const BaseCommand = require('../Base') class Install extends BaseCommand { constructor () { super() const FakeHelpers = require('@adonisjs/ignitor/src/Helpers') this.Helpers = new FakeHelpers(process.cwd()) } /** * The command signature * * @method signature * * @return {String} */ static get signature () { return ` install { module : Npm module name } { --as=@value : Name of the module, required when installing from github or local file system } { --yarn: Use yarn over npm for installation } { --cnpm: Use cnpm over npm for installation } { -s, --skip-instructions: Do not run post install instructions } { --raw : Disable animations and colored output } ` } /** * The command description * * @method description * * @return {String} */ static get description () { return 'Install Adonisjs provider from npm/yarn and run post install instructions' } async handle ({ module: packageName }, options) { const name = options.as || packageName const stepsCounter = this.initiateSteps(1, options) await this.invoke(async () => { await this.ensureInProjectRoot() await require('../../Services/install')(options.yarn ? 'yarn' : (options.cnpm ? 'cnpm' : 'npm'), stepsCounter, packageName) if (options.skipInstructions) { return } const directory = path.join(process.cwd(), 'node_modules', name) await this.call('run:instructions', { directory }, { name }) }) } } module.exports = Install
25.352113
129
0.642222
94600aa1bf09d95604005406b2ee1bec5883f6cc
119
js
JavaScript
API/regioes/sudeste/index.js
danilosilvadev/CidadesBrasileirasAPI
17b2266c083fa47e86818ab0353c712bfbadf7c6
[ "MIT" ]
1
2018-08-11T23:37:13.000Z
2018-08-11T23:37:13.000Z
API/regioes/sudeste/index.js
danilosilvadev/CidadesBrasileirasAPI
17b2266c083fa47e86818ab0353c712bfbadf7c6
[ "MIT" ]
1
2018-08-13T13:35:33.000Z
2018-08-13T13:35:33.000Z
API/regioes/sudeste/index.js
danilosilvadev/CidadesBrasileirasAPI
17b2266c083fa47e86818ab0353c712bfbadf7c6
[ "MIT" ]
null
null
null
import ES from './API/ES'; import RJ from './API/RJ'; import SP from './API/SP'; export default { ES, RJ, SP, };
13.222222
26
0.588235
946065ebacd08de83d06266de6d8bf661e5ec09d
765
js
JavaScript
test/index.test.js
jolicode/tabto
43eb3bbd9be536a2a48d20ddb632d139debd7b7a
[ "MIT" ]
2
2018-09-28T12:35:58.000Z
2020-11-13T15:46:04.000Z
test/index.test.js
jolicode/tabto
43eb3bbd9be536a2a48d20ddb632d139debd7b7a
[ "MIT" ]
11
2018-09-28T12:32:31.000Z
2018-10-08T12:01:44.000Z
test/index.test.js
jolicode/tabto
43eb3bbd9be536a2a48d20ddb632d139debd7b7a
[ "MIT" ]
2
2018-10-02T04:48:54.000Z
2018-10-06T16:10:30.000Z
/* eslint-env jest */ 'use strict' import tabto from '../index' test('focus on the next field', () => { document.body.innerHTML = '<input id="one" data-tab-target="#two" maxlength="10" />\n' + '<input id="two" />' let firstInput = document.getElementById('one') let event = new window.Event('input') tabto(firstInput) firstInput.focus() expect(document.activeElement.id).toEqual(firstInput.id) // Length = 9 firstInput.value = '123456789' // Fire keyup firstInput.dispatchEvent(event) // Still "one" expect(document.activeElement.id).toEqual(firstInput.id) // Length = 11 firstInput.value = '12345678911' firstInput.dispatchEvent(event) // Jumped to "two" \o/ expect(document.activeElement.id).toEqual('two') })
21.25
66
0.671895
9460dd6b3ad863c536f233476d3466a0e1d21250
307
js
JavaScript
examples/index.js
validate-io/function-array
9110bf5338eadd8602534401c11e7227d1714476
[ "MIT" ]
3
2015-05-10T23:56:59.000Z
2015-11-04T12:58:17.000Z
examples/index.js
validate-io/function-array
9110bf5338eadd8602534401c11e7227d1714476
[ "MIT" ]
null
null
null
examples/index.js
validate-io/function-array
9110bf5338eadd8602534401c11e7227d1714476
[ "MIT" ]
null
null
null
'use strict'; var isFunctionArray = require( './../lib' ); function beep(){} function boop(){} function bap(){} console.log( isFunctionArray( [beep,boop,bap] ) ); // returns true console.log( isFunctionArray( [] ) ); // returns false console.log( isFunctionArray( [beep,null,bap] ) ); // returns false
18.058824
50
0.664495
946193537bd2bc6a163e2287eb602cca9d5920be
4,825
js
JavaScript
src/model/TlsConfigurationResponseData.js
fastly/fastly-js
177c07a92ea82c160341aae2c7d36ad835c20dbd
[ "MIT" ]
1
2022-03-23T02:55:29.000Z
2022-03-23T02:55:29.000Z
src/model/TlsConfigurationResponseData.js
fastly/fastly-js
177c07a92ea82c160341aae2c7d36ad835c20dbd
[ "MIT" ]
null
null
null
src/model/TlsConfigurationResponseData.js
fastly/fastly-js
177c07a92ea82c160341aae2c7d36ad835c20dbd
[ "MIT" ]
1
2022-03-23T08:17:27.000Z
2022-03-23T08:17:27.000Z
/** * Fastly API * Via the Fastly API you can perform any of the operations that are possible within the management console, including creating services, domains, and backends, configuring rules or uploading your own application code, as well as account operations such as user administration and billing reports. The API is organized into collections of endpoints that allow manipulation of objects related to Fastly services and accounts. For the most accurate and up-to-date API reference content, visit our [Developer Hub](https://developer.fastly.com/reference/api/) * * The version of the OpenAPI document: 1.0.0 * Contact: oss@fastly.com * * NOTE: This class is auto generated. * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import RelationshipsForTlsConfiguration from './RelationshipsForTlsConfiguration'; import TlsConfigurationData from './TlsConfigurationData'; import TlsConfigurationResponseAttributes from './TlsConfigurationResponseAttributes'; import TlsConfigurationResponseDataAllOf from './TlsConfigurationResponseDataAllOf'; import TypeTlsConfiguration from './TypeTlsConfiguration'; /** * The TlsConfigurationResponseData model module. * @module model/TlsConfigurationResponseData * @version 3.0.0-beta3 */ class TlsConfigurationResponseData { /** * Constructs a new <code>TlsConfigurationResponseData</code>. * @alias module:model/TlsConfigurationResponseData * @implements module:model/TlsConfigurationData * @implements module:model/TlsConfigurationResponseDataAllOf */ constructor() { TlsConfigurationData.initialize(this);TlsConfigurationResponseDataAllOf.initialize(this); TlsConfigurationResponseData.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>TlsConfigurationResponseData</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/TlsConfigurationResponseData} obj Optional instance to populate. * @return {module:model/TlsConfigurationResponseData} The populated <code>TlsConfigurationResponseData</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new TlsConfigurationResponseData(); TlsConfigurationData.constructFromObject(data, obj); TlsConfigurationResponseDataAllOf.constructFromObject(data, obj); if (data.hasOwnProperty('type')) { obj['type'] = TypeTlsConfiguration.constructFromObject(data['type']); } if (data.hasOwnProperty('attributes')) { obj['attributes'] = TlsConfigurationResponseAttributes.constructFromObject(data['attributes']); } if (data.hasOwnProperty('relationships')) { obj['relationships'] = RelationshipsForTlsConfiguration.constructFromObject(data['relationships']); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } } return obj; } } /** * @member {module:model/TypeTlsConfiguration} type */ TlsConfigurationResponseData.prototype['type'] = undefined; /** * @member {module:model/TlsConfigurationResponseAttributes} attributes */ TlsConfigurationResponseData.prototype['attributes'] = undefined; /** * @member {module:model/RelationshipsForTlsConfiguration} relationships */ TlsConfigurationResponseData.prototype['relationships'] = undefined; /** * @member {String} id */ TlsConfigurationResponseData.prototype['id'] = undefined; // Implement TlsConfigurationData interface: /** * @member {module:model/TypeTlsConfiguration} type */ TlsConfigurationData.prototype['type'] = undefined; /** * @member {module:model/TlsConfigurationDataAttributes} attributes */ TlsConfigurationData.prototype['attributes'] = undefined; /** * @member {module:model/RelationshipsForTlsConfiguration} relationships */ TlsConfigurationData.prototype['relationships'] = undefined; // Implement TlsConfigurationResponseDataAllOf interface: /** * @member {String} id */ TlsConfigurationResponseDataAllOf.prototype['id'] = undefined; /** * @member {module:model/TlsConfigurationResponseAttributes} attributes */ TlsConfigurationResponseDataAllOf.prototype['attributes'] = undefined; export default TlsConfigurationResponseData;
38.293651
557
0.731813
9461e431703ca02e84c36d0bf9175487cb2a1097
5,189
js
JavaScript
app/controllers/usermessages.server.controller.js
eliavmaman/joakes
5771b47065491085c3b294a67701700b7e9821ed
[ "MIT" ]
null
null
null
app/controllers/usermessages.server.controller.js
eliavmaman/joakes
5771b47065491085c3b294a67701700b7e9821ed
[ "MIT" ]
1
2015-09-07T00:36:47.000Z
2015-09-07T00:36:47.000Z
app/controllers/usermessages.server.controller.js
eliavmaman/joakes
5771b47065491085c3b294a67701700b7e9821ed
[ "MIT" ]
null
null
null
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Usermessage = mongoose.model('Usermessage'), _ = require('lodash'); var q = require('q'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var nodemailer = require('nodemailer'); var config = require('../../config/config'); var User = mongoose.model('User'); /** * Create a Usermessage */ exports.create = function (user) { var defered = q.defer(); var usermessage = new Usermessage({ user: user, messages: [] }); usermessage.save(function (err) { if (err) { defered.reject(err); } else { user.messages = usermessage; user.save(function (err, user) { if (err) { defered.reject(err); } else { defered.resolve(usermessage); } }) } }); return defered.promise; }; /** * Show the current Usermessage */ exports.read = function (req, res) { console.log('--------------------' + req.user._id); Usermessage.find({user:req.user._id}).exec(function(err,messages) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(messages); } }); //getByUserId(req.user._id).then(function (user) { // // if (userMessages === null) { // exports.create(req.user).then(function (data) { // res.jsonp(data); // }, function (err) { // res.status(400).send(err); // }); // } else { // var messages = userMessages.messages.reverse(); // res.jsonp(messages); // } //}, function (err) { // res.status(400).send(err); //}); }; exports.countUnread = function (req, res) { Usermessage.findById(req.user.messages).exec(function (err, messages) { if (err) { res.status(400).send(err); } else { var count = messages.messages.filter(function (item) { return !item.viewed; }).length; res.send({'count': count}) } }); }; exports.markAsViewed = function (req, res) { Usermessage.findById(req.user.messages).exec(function (err, messages) { if (err) { res.status(400).send(err); } else { var message = messages.messages.filter(function (item) { return item._id.toString() === req.params.messageId; })[0]; if (!message) { res.status(400).send('message was not found. '); } else { message.viewed = true; messages.save(function (err, data) { res.status(200).send('saved'); }) } } }); }; exports.addMessage = function (req, res) { User.findById(req.params.userId) .exec(function (err, user) { var message = new Usermessage(req.body); message.user = req.params.userId; message.save(function (err) { if (err) { res.status(400).send(err); } else { console.log('userMessage saved'); //var message = user.messages[user.messages.length - 1]; res.render('templates/message-received', { url: 'http://' + req.headers.host + '/#!/profile/messages/' + message._id }, function (err, emailHTML) { var smtpTransport = nodemailer.createTransport(config.mailer.options); var mailOptions = { to: user.email, from: config.mailer.from, subject: 'התקבלה הודעה חדשה', html: emailHTML }; smtpTransport.sendMail(mailOptions, function (err) { res.status(201).send('message created'); }); }); } }); }); //User.findById(req.params.userId) // .populate('messages') // .exec(function (err, user) { // user = user._doc; // user.messages=new Usermessage(); // var userMessages = user.messages; // // try { // // // old users dont have a messages array // if (!userMessages.messages) { // userMessages.messages = []; // } // userMessages.messages.push(req.body); // } catch (e) { // console.log('invalid message'); // res.status(400).send('invalid message'); // return; // } // // // }, function (err) { // res.status(400).send(err); // }); }; /** * Usermessage middleware */ exports.usermessageByID = function (req, res, next, id) { Usermessage.findById(id).populate('user', 'displayName').exec(function (err, usermessage) { if (err) return next(err); if (!usermessage) return next(new Error('Failed to load Usermessage ' + id)); req.usermessage = usermessage; next(); }); }; /** * Usermessage authorization middleware */ exports.hasAuthorization = function (req, res, next) { if (req.usermessage.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); }; function getByUserId(userId) { var deferred = q.defer(); Usermessage.where('user').equals(userId).findOne(function (err, userMessages) { if (err) { deferred.reject(err); } else { deferred.resolve(userMessages); } }); return deferred.promise; }
24.947115
93
0.568703
9463073f9a657dfe7f0d18d35dc9b28073266cf3
572
js
JavaScript
webpack-entry.js
ttsuchiya/codap
4f81a6e083e118db85f8d4c9c349652b2445278c
[ "MIT" ]
null
null
null
webpack-entry.js
ttsuchiya/codap
4f81a6e083e118db85f8d4c9c349652b2445278c
[ "MIT" ]
null
null
null
webpack-entry.js
ttsuchiya/codap
4f81a6e083e118db85f8d4c9c349652b2445278c
[ "MIT" ]
null
null
null
/*global require:true, React:true, ReactDOM:true, iframePhone:true, Papa:true */ /*global L:true, deepEqual:true, Promise:true, pluralize:true, moment:true */ /* exported React, ReactDOM, iframePhone, Papa, deepEqual, Promise, pluralize, moment */ React = require('react'); ReactDOM = require('react-dom'); iframePhone = require('iframe-phone'); Papa = require('papaparse'); L = require('leaflet'); L.esri = require('esri-leaflet'); deepEqual = require('deep-equal'); Promise = require('es6-promise').Promise; pluralize = require('pluralize'); moment = require('moment');
40.857143
88
0.722028
94637da90cecb65fdc1a2b34cdcbbbebe92b0858
2,942
js
JavaScript
lib/save_cache.js
mango-chutney/mango-actions-google-cache
dac58c1466460d76b17e913bfcc351876a39ed18
[ "MIT" ]
null
null
null
lib/save_cache.js
mango-chutney/mango-actions-google-cache
dac58c1466460d76b17e913bfcc351876a39ed18
[ "MIT" ]
10
2019-08-22T05:05:44.000Z
2022-01-22T08:44:09.000Z
lib/save_cache.js
mango-chutney/mango-actions-google-cache
dac58c1466460d76b17e913bfcc351876a39ed18
[ "MIT" ]
null
null
null
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const exec = __importStar(require("@actions/exec")); const compressAndUpload = (bucket, cache_file, directory, paths, threshold) => __awaiter(this, void 0, void 0, function* () { console.log(`Compressing cache to ${cache_file}`); yield exec.exec(`tar cpzf ${cache_file} -C ${directory} ${paths} -P`); console.log('Uploading cache to Google Cloud Storage...'); yield exec.exec(`gsutil -o GSUtil:parallel_composite_upload_threshold=${threshold}M cp -r ${cache_file} gs://${bucket}`); }); const save_cache = ({ bucket, directory, key, overwrite, paths, threshold, }) => __awaiter(this, void 0, void 0, function* () { try { const cache_file = `${directory}/${key}.tgz`; if (overwrite === 'no') { const bucket_file = `gs://${bucket}/${key}.tgz`; let out = ''; let err = ''; const options = { listeners: { stdout: (data) => { out += data.toString(); }, stderr: (data) => { err += data.toString(); }, }, ignoreReturnCode: true, }; yield exec.exec(`gsutil ls ${bucket_file}`, undefined, options); console.log(out.trim()); console.log(err.trim()); if (out.trim() === bucket_file) { throw new Error('Cache file exists, exiting save_cache without over-writing cache file.'); } if (err.trim() === 'CommandException: One or more URLs matched no objects.') { console.log('Object does not exist, uploading new file'); compressAndUpload(bucket, cache_file, directory, paths, threshold); } } else { compressAndUpload(bucket, cache_file, directory, paths, threshold); } } catch (err) { console.log(err); } }); exports.default = save_cache;
46.698413
151
0.561523
9464fd16c751de6e4ca1cd93ef5c19897d2742c8
2,686
js
JavaScript
src/route/weiboDetail.js
keisei77/micro-backend
89c2ee02d40713c26d9b33d1ee2bf8b0d65e9bfb
[ "MIT" ]
1
2020-03-10T12:05:46.000Z
2020-03-10T12:05:46.000Z
src/route/weiboDetail.js
keisei77/micro-backend
89c2ee02d40713c26d9b33d1ee2bf8b0d65e9bfb
[ "MIT" ]
null
null
null
src/route/weiboDetail.js
keisei77/micro-backend
89c2ee02d40713c26d9b33d1ee2bf8b0d65e9bfb
[ "MIT" ]
null
null
null
const cheerio = require('cheerio'); const fetch = require('node-fetch'); module.exports = async (req, res) => { const link = req.query.link.replace(/#/g, '%23') || ''; console.log(link); const topicInfo = {}; try { if (link) { const topic = await fetch(link).then((res) => res.text()); const $_topic = cheerio.load(topic); const feedList = $_topic('#pl_feedlist_index .card-wrap'); // 导语 有可能为空 const lead = feedList.find('.card-topic-lead p').text(); const feedItems = feedList.filter( (_index, element) => $_topic(element).attr('action-type') === 'feed_list_item' ); const feedContent = []; feedItems.each((_index, element) => { const avatar = $_topic('.avator img', element).attr('src'); const nickname = $_topic( 'p[node-type=feed_list_content]', element ).attr('nick-name'); const content = $_topic('p[node-type=feed_list_content_full]', element) .text() .trim() .slice(0, -6) || $_topic('p[node-type=feed_list_content]', element).text().trim(); const images = []; const imageSource = $_topic( 'div[node-type=feed_list_media_prev] li', element ); const mid = $_topic(element).attr('mid'); imageSource.each((_imageIdx, imageEl) => { const imgEl = $_topic('img', imageEl); const actionData = imgEl .attr('action-data') .split('&') .reduce((acc, curr) => { const [key, value] = curr.split('='); acc[key] = value; return acc; }, {}); const { uid, pic_id: pid } = actionData; const thumbSrc = imgEl.attr('src'); const originSrc = thumbSrc.replace(/orj480|orj360|thumb150/, 'large'); images.push({ thumbSrc, originSrc }); }); let video = ''; try { const videoSource = $_topic('a[node-type=fl_h5_video]', element); const videoData = videoSource.attr('action-data'); video = videoData ? videoData .split('&') .find((_) => _.startsWith('video_src')) .slice('video_src'.length + 1) : ''; } catch (err) {} feedContent.push({ userInfo: { avatar, nickname }, content, images, video, }); }); topicInfo['lead'] = lead; topicInfo['feedContent'] = feedContent; } res.json(topicInfo); } catch (error) { res.status(400).json({ error: error.message, }); } };
30.873563
80
0.511169
9465ab62b6cb4ee687214e8dc2c1b5e40679200b
990
js
JavaScript
src/gatsby-plugin-theme-ui/index.js
AlexNti/eat-a-pie
558e326f51eab1e88374919042d6eb3622599258
[ "RSA-MD" ]
null
null
null
src/gatsby-plugin-theme-ui/index.js
AlexNti/eat-a-pie
558e326f51eab1e88374919042d6eb3622599258
[ "RSA-MD" ]
null
null
null
src/gatsby-plugin-theme-ui/index.js
AlexNti/eat-a-pie
558e326f51eab1e88374919042d6eb3622599258
[ "RSA-MD" ]
null
null
null
export default { colors: { text: '#fff', background: '#F5E0E0', winningMessage: '#015FCF', }, fontSizes: { small: '0.8em', mediumg: '1em', large: '1.7em', veryLarge: '2.7em', }, fonts: { heading: 'montserrat', }, styles: { root: { // uses the theme values provided above fontFamily: 'montserrat', fontWeight: 400, }, }, text: { loginText: { fontSize: '20px', textAlign: 'center', width: '292px', }, default: { fontFamily: 'heading', color: 'text', fontSize: 'veryLarge', }, winningMessage: { fontWeight: 700, fontSize: '20px', lineHeight: '24.38px', textAlign: 'center', color: 'winningMessage', width: '298px', height: '24px', }, cheerMessage: { fontFamily: 'heading', width: '298px', height: '20px', fontWeight: 400, textAlign: 'center', color: 'winningMessage', }, }, };
18.333333
71
0.518182
9465dff34dd3c98815ef3d46cdc3bbe917c387fa
1,694
js
JavaScript
models/user.js
nieka/webs5
45b7aafee52b85e9c182505572730f1d9c46d23f
[ "Apache-2.0" ]
null
null
null
models/user.js
nieka/webs5
45b7aafee52b85e9c182505572730f1d9c46d23f
[ "Apache-2.0" ]
null
null
null
models/user.js
nieka/webs5
45b7aafee52b85e9c182505572730f1d9c46d23f
[ "Apache-2.0" ]
null
null
null
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); function init(){ console.log('Iniializing user schema'); var userSchema = new mongoose.Schema( { local : { email : String, password : String, voornaam : String, achternaam : String }, google : { id : String, token : String, email : String, name : String } }, { toObject: { virtuals: true }, toJSON: { virtuals: true } }); userSchema.virtual('fullname') .get(function () { if(this.local.email){ return this.local.voornaam + ' ' + this.local.achternaam; }else { return this.google.name; } }); userSchema.virtual('email') .get(function () { if(this.local.email){ return this.local.email; }else { return this.google.email; } }); // methods ====================== // generating a hash userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.local.password); }; return mongoose.model("User",userSchema); } module.exports = init();
26.888889
73
0.453955
9466bace8cdb8bc0682b086fe526ccea07f59444
22,564
js
JavaScript
app/containers/WorkForcePages/FloorStatus/index.js
devpao26/hcmwebapp
39fd535c3d95a6059e2380095c3680a06cafc2df
[ "MIT" ]
1
2019-09-11T14:20:20.000Z
2019-09-11T14:20:20.000Z
app/containers/WorkForcePages/FloorStatus/index.js
devpao26/hcmwebapp
39fd535c3d95a6059e2380095c3680a06cafc2df
[ "MIT" ]
null
null
null
app/containers/WorkForcePages/FloorStatus/index.js
devpao26/hcmwebapp
39fd535c3d95a6059e2380095c3680a06cafc2df
[ "MIT" ]
null
null
null
/* * Floor Status * */ import React from 'react'; import PropTypes from 'prop-types'; import { Helmet } from 'react-helmet'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { compose } from 'redux'; import moment from 'moment'; import ReactPaginate from 'react-paginate'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import { faCaretLeft, faTh, faList, faCaretDown } from '@fortawesome/fontawesome-free-solid'; /* Global injectSaga and injectReducer */ import injectSaga from 'utils/injectSaga'; import injectReducer from 'utils/injectReducer'; /* Global Components */ import PageWrap from 'components/PageWrap'; import Header from 'components/Header'; import Footer from 'components/Footer'; import Main from 'components/Main'; import Sidebar from 'components/Sidebar'; import PageContent from 'components/Main/PageContent'; import Avatar from 'components/Img/Avatar'; import Calendar from 'components/Calendar'; import ImageModal from 'components/Img/ImageModal'; import Pagination from 'components/Pagination'; import ExportButton from 'components/ExportButton'; /* Section Components */ import H2 from 'components/Section/H2'; import Back from 'components/Section/Back'; import Flex from 'components/SectionFlex'; /* Own Components */ import Left from './Left'; import Right from './Right'; import Wrapper from './WhiteBox'; import Employee from './Employee'; import DisplayButton from './DisplayButton'; import CalendarWrapper from './CalendarWrapper'; // import Graph from './Graph'; // import Sample from 'images/sample_graph.png'; import ShiftSummaryList from './ShiftSummaryList'; import ShiftAppList from './ShiftAppList'; import ShiftUrlList from './ShiftUrlList'; import ScreenshotsList from './ScreenshotList'; /* selectors, reducer, saga and actions */ import { makeSelectEmpId, // makeSelectEmpData, makeSelectSummaryData, makeSelectLoading, makeSelectError, makeSelectPages, makeSelectDtrUri, } from './selectors'; import { GET_SHIFTREC, GET_SSHOT, GET_ACTIVEAPP, GET_BROWSERURL, } from './constants'; import reducer from './reducer'; import saga from './saga'; import { writeIdDate, getPagination, dtrExport, clearDtrUri, } from './actions'; export class FloorStatus extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { empId: this.props.location.emp.id, empData: this.props.location.emp.detail, viewImage: false, imagePath: '', workStatus: false, calendar: false, displayClass: 'grid', displayDate: moment().startOf('days'), currentStatus: 'No Available Status', displayBy: 'Date', filterBy: true, }; } componentDidMount() { const emp = this.props.location.emp; const id = emp.id; // Retrieve Initial data this.props.retrieveInitialData(id, moment().startOf('days').format('M/DD/YYYY'), true); } componentWillReceiveProps(nextProps) { if (nextProps.dtrUri !== false) { location.assign(nextProps.dtrUri); this.props.clearUri(); } } toggleCalendar = () => { this.setState({ calendar: !this.state.calendar, workStatus: false, }); } showImageModal = (path) => { this.setState({ viewImage: !this.state.viewImage, imagePath: path, }); } hideImageModal = () => { this.setState({ viewImage: false, }); } selectedDate = (date) => { this.setState({ // calendar: false, displayDate: date, }); this.props.retrieveInitialData(this.state.empId, moment(date).format('MM/DD/YYYY'), this.state.filterBy); } showWorkStatus = () => { this.setState({ calendar: false, workStatus: !this.state.workStatus, }); } changeDisplay = (e) => { e.preventDefault(); const display = e.currentTarget.getAttribute('data-display'); this.setState({ displayClass: display, }); } filterBy = (e) => { e.preventDefault(); const filter = (e.currentTarget.innerText === 'Date') || false; this.setState({ displayBy: e.currentTarget.innerText, filterBy: filter, }); this.props.retrieveInitialData(this.state.empId, moment(this.state.displayDate).format('MM/DD/YYYY'), filter); } mobileToggleDisplay = (e) => { // get our parent container const parent = e.currentTarget.parentNode.parentNode; // toggle our class parent.classList.toggle('toggle'); } render() { const { empId, displayDate, empData, } = this.state; const { shiftRecData, screenShotData, activeAppsData, browserUrlData, // workStatData, shiftRecLoading, shiftRecError, screenShotLoading, screenShotError, activeAppLoading, activeAppError, browserUrlLoading, browserUrlError, shiftRecPages, screenShotPages, activeAppsPages, browserUrlPages, // workStatPages, gotoPage, generateDtr, } = this.props; // Shift Summary Props const shiftSummaryList = { loading: shiftRecLoading, error: shiftRecError, shiftRec: shiftRecData, }; // Shift App/URL Summary Props const shiftAppList = { loading: activeAppLoading, error: activeAppError, activeApp: activeAppsData, }; const shiftUrlList = { loading: browserUrlLoading, error: browserUrlError, browserUrl: browserUrlData, }; // Screenshots Props const screenshotList = { loading: screenShotLoading, error: screenShotError, screenShots: screenShotData, }; // Retrieval of Employee Details // let empList; let userData; let avatar; if (empData) { avatar = (empData.EmpAvatarAttachs != null) ? <Avatar bgImage={`url('${empData.EmpAvatarAttachs.Path}')`} /> : <Avatar />; userData = ( <div className="details"> <div className="info"> <h4>{empData.FirstName} {empData.LastName}</h4> <p>{empData.JobRole.Name}</p> <p>Department: {(empData.WorkGroup.length !== 0) && empData.WorkGroup[0].Department.Name}</p> <p>Workgroup: {(empData.WorkGroup.length !== 0) && empData.WorkGroup[0].Team.Name}</p> <p> {(empData.WorkGroup.length !== 0) && <i className="fa fa-sitemap" />} {(empData.WorkGroup.length !== 0) && <i className="fa fa-group" />} </p> </div> </div> ); } // Declare Max Pages for the summaries let activeAppMaxPage = 1; let browserUrlMaxPage = 1; let screenShotMaxPage = 1; let shiftRecMaxPage = 1; if (activeAppsPages) { activeAppMaxPage = activeAppsPages.MaxPageIndex; } if (browserUrlPages) { browserUrlMaxPage = browserUrlPages.MaxPageIndex; } if (screenShotPages) { screenShotMaxPage = screenShotPages.MaxPageIndex; } if (shiftRecPages) { shiftRecMaxPage = shiftRecPages.MaxPageIndex; } // Get user current status // if (shiftRecData) { // const dateToday = moment().startOf('days').format('YYYY-MM-DD'); // shiftRecData.map((item, index) => { // if (index === 0 && item.Date === dateToday && displayDate === dateToday) { // // console.log('matched'); // this.setState({ // currentStatus: (item.TemplateWorkStatusDetails != null) ? item.TemplateWorkStatusDetails.WorkStatus.Name : item.SystemStatusType.Name // }); // } // }); // } return ( <PageWrap> <Helmet> <title>WorkForce Floor Status</title> </Helmet> <Header /> <Sidebar location={this.props.location} /> <Main> <PageContent> <Back onClick={this.props.history.goBack}><FontAwesomeIcon icon={faCaretLeft} /> BACK TO EMPLOYEE FLOOR STATUS LIST</Back> <Flex> <Left> <Employee> {avatar} {userData} <div className="options"> <div className="select"> <label htmlFor="chooseDate">Choose Date</label> <div className="data"> <span role="presentation" className="content" onClick={this.toggleCalendar}>{moment(displayDate).format('LL')}</span> <button className="fa fa-caret-down" onClick={this.toggleCalendar} /> { this.state.calendar && <CalendarWrapper className="negtop"> <H2>Select Date</H2> <Calendar selectedDate={this.selectedDate} hideCal={this.toggleCalendar} displayDate={displayDate} /> </CalendarWrapper> } </div> <label htmlFor="currentStatus">Display By:</label> <div className="filter"> <button onClick={this.filterBy} className={(this.state.displayBy === 'Date') && 'active'}>Date</button> <button onClick={this.filterBy} className={(this.state.displayBy === 'Shift Schedule') && 'active'}>Shift Schedule</button> </div> {/* <label htmlFor="currentStatus">Current Status</label> <div className="data"> <span className="content">{this.state.currentStatus}</span> <OptionMenu title="Work Status" position="bottom" width="150px"> <label> <input type="checkbox" /> Select All </label> <label> <input type="checkbox" defaultChecked="checked" /> Available </label> <label> <input type="checkbox" /> Research </label> <label> <input type="checkbox" /> After Call Work </label> <label> <input type="checkbox" /> Lunch </label> <label> <input type="checkbox" /> BioBreak </label> <label> <input type="checkbox" /> 15 Min Break </label> <label> <input type="checkbox" /> Meeting </label> <label> <input type="checkbox" /> Coaching </label> <label> <input type="checkbox" /> Training </label> <label> <input type="checkbox" /> Admin </label> <label> <input type="checkbox" /> Floorwalk </label> <label> <input type="checkbox" /> Others </label> <label> <input type="checkbox" /> End of Day </label> </OptionMenu> </div> */} <ExportButton onClick={() => { generateDtr(moment(displayDate).format('YYYY-MM-DD'), empId); }} text="Export DTR" /> </div> </div> </Employee> {/* <Wrapper className="expand"> <Graph> <select> <option>Weekly Status</option> </select> <Img src={Sample} alt="Sample Graph" /> </Graph> </Wrapper> */} <Wrapper className="toggle"> <H2>Shift Summary <button onClick={this.mobileToggleDisplay}><FontAwesomeIcon icon={faCaretDown} /></button></H2> <ShiftSummaryList {...shiftSummaryList} /> { (shiftRecPages && shiftRecMaxPage !== 1) && <Pagination> <ReactPaginate previousLabel={'Previous'} nextLabel={'Next'} breakLabel={<span>...</span>} breakClassName={'break-me'} pageCount={shiftRecMaxPage} marginPagesDisplayed={1} pageRangeDisplayed={4} onPageChange={(e) => { gotoPage(e, GET_SHIFTREC); }} activeClassName={'active'} /> </Pagination> } </Wrapper> <Wrapper> <H2> Screenshots { (screenShotData) && <DisplayButton> <button onClick={this.changeDisplay} data-display="grid" className={(this.state.displayClass === 'grid') && 'active'}><FontAwesomeIcon icon={faTh} /></button> | <button onClick={this.changeDisplay} data-display="list" className={(this.state.displayClass === 'list') && 'active'}><FontAwesomeIcon icon={faList} /></button> </DisplayButton> } <button onClick={this.mobileToggleDisplay}><FontAwesomeIcon icon={faCaretDown} /></button> </H2> <ScreenshotsList {...screenshotList} display={this.state.displayClass} imgPath={this.showImageModal} /> { (screenShotPages && screenShotMaxPage !== 1) && <Pagination> <ReactPaginate previousLabel={'Previous'} nextLabel={'Next'} breakLabel={<span>...</span>} breakClassName={'break-me'} pageCount={screenShotMaxPage} marginPagesDisplayed={1} pageRangeDisplayed={4} onPageChange={(e) => { gotoPage(e, GET_SSHOT); }} activeClassName={'active'} /> </Pagination> } </Wrapper> </Left> <Right> {/* <Wrapper> <H2>Workgroup Name <button onClick={this.mobileToggleDisplay} className="fa fa-caret-down" /></H2> <EMPList className="list"> <dl> <dt><Avatar bgImage="url('https://picsum.photos/100/?random')" /></dt> <dd> <p> Tony Stark <span>stark@marvel.com</span> </p> <OptionMenu title="Options" position="left"> <button>Transfer</button> <button>View Profile</button> <button>Assign Calendar Template</button> <button>Assign Shift Schedule Template</button> <button data-user="Tony Stark" onClick={this.showDisable}>Disable Account</button> </OptionMenu> </dd> </dl> <dl> <dt><Avatar /></dt> <dd> <p> Tony Stark <span>stark@marvel.com</span> </p> <OptionMenu title="Options" position="left"> <button>Transfer</button> <button>View Profile</button> <button>Assign Calendar Template</button> <button>Assign Shift Schedule Template</button> <button data-user="Tony Stark" onClick={this.showDisable}>Disable Account</button> </OptionMenu> </dd> </dl> </EMPList> </Wrapper> */} <Wrapper> <H2>Shift Active Apps <button onClick={this.mobileToggleDisplay}><FontAwesomeIcon icon={faCaretDown} /></button></H2> <ShiftAppList {...shiftAppList} /> { (activeAppsPages && activeAppMaxPage !== 1) && <Pagination> <ReactPaginate previousLabel={'Previous'} nextLabel={'Next'} breakLabel={<span>...</span>} breakClassName={'break-me'} pageCount={activeAppMaxPage} marginPagesDisplayed={1} pageRangeDisplayed={4} onPageChange={(e) => { gotoPage(e, GET_ACTIVEAPP); }} activeClassName={'active'} /> </Pagination> } </Wrapper> <Wrapper> <H2>Shift Browser URLs <button onClick={this.mobileToggleDisplay}><FontAwesomeIcon icon={faCaretDown} /></button></H2> <ShiftUrlList {...shiftUrlList} /> { (browserUrlPages && browserUrlMaxPage !== 1) && <Pagination> <ReactPaginate previousLabel={'Previous'} nextLabel={'Next'} breakLabel={<span>...</span>} breakClassName={'break-me'} pageCount={browserUrlMaxPage} marginPagesDisplayed={1} pageRangeDisplayed={4} onPageChange={(e) => { gotoPage(e, GET_BROWSERURL); }} activeClassName={'active'} /> </Pagination> } </Wrapper> </Right> </Flex> </PageContent> </Main> <Footer /> <ImageModal show={this.state.viewImage} onClose={this.hideImageModal} imagePath={this.state.imagePath} /> </PageWrap> ); } } FloorStatus.defaultProps = { dtrUri: false, }; FloorStatus.propTypes = { location: PropTypes.object, history: PropTypes.object, // empId: PropTypes.oneOfType([ // PropTypes.bool, // PropTypes.string, // ]), // empData: PropTypes.array, shiftRecData: PropTypes.oneOfType([ PropTypes.array, PropTypes.bool, ]), screenShotData: PropTypes.oneOfType([ PropTypes.array, PropTypes.bool, ]), activeAppsData: PropTypes.oneOfType([ PropTypes.array, PropTypes.bool, ]), browserUrlData: PropTypes.oneOfType([ PropTypes.array, PropTypes.bool, ]), // workStatData: PropTypes.oneOfType([ // PropTypes.array, // PropTypes.bool, // ]), shiftRecLoading: PropTypes.bool, screenShotLoading: PropTypes.bool, activeAppLoading: PropTypes.bool, browserUrlLoading: PropTypes.bool, // workStatLoading: PropTypes.bool, shiftRecError: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), screenShotError: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), activeAppError: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), browserUrlError: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), // workStatError: PropTypes.oneOfType([ // PropTypes.object, // PropTypes.bool, // ]), shiftRecPages: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), screenShotPages: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), activeAppsPages: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), browserUrlPages: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool, ]), // workStatPages: PropTypes.oneOfType([ // PropTypes.object, // PropTypes.bool, // ]), dtrUri: PropTypes.oneOfType([ PropTypes.bool, PropTypes.string, ]), // Function dispatch props retrieveInitialData: PropTypes.func, gotoPage: PropTypes.func, generateDtr: PropTypes.func, clearUri: PropTypes.func, }; const mapStateToProps = createStructuredSelector({ empId: makeSelectEmpId(), // empData: makeSelectEmpData(), shiftRecData: makeSelectSummaryData('shiftRec'), screenShotData: makeSelectSummaryData('screenShot'), activeAppsData: makeSelectSummaryData('activeApps'), browserUrlData: makeSelectSummaryData('browserUrl'), workStatData: makeSelectSummaryData('workStat'), shiftRecLoading: makeSelectLoading('shiftRec'), screenShotLoading: makeSelectLoading('screenShot'), activeAppLoading: makeSelectLoading('activeApps'), browserUrlLoading: makeSelectLoading('browserUrl'), workStatLoading: makeSelectLoading('workStat'), shiftRecError: makeSelectError('shiftRec'), screenShotError: makeSelectError('screenShot'), activeAppError: makeSelectError('activeApps'), browserUrlError: makeSelectError('browserUrl'), workStatError: makeSelectError('workStat'), shiftRecPages: makeSelectPages('shiftRec'), screenShotPages: makeSelectPages('screenShot'), activeAppsPages: makeSelectPages('activeApps'), browserUrlPages: makeSelectPages('browserUrl'), workStatPages: makeSelectPages('workStat'), dtrUri: makeSelectDtrUri(), }); function mapDispatchToProps(dispatch) { return { retrieveInitialData: (id, date, filter) => dispatch(writeIdDate(id, date, filter)), gotoPage: (evt, action) => { const page = evt.selected + 1; dispatch(getPagination(page, action)); }, generateDtr: (date, id) => dispatch(dtrExport(date, id)), clearUri: () => dispatch(clearDtrUri()), }; } const withConnect = connect(mapStateToProps, mapDispatchToProps); const withReducer = injectReducer({ key: 'wfadmin', reducer }); const withSaga = injectSaga({ key: 'wfadmin', saga }); export default compose( withReducer, withSaga, withConnect, )(FloorStatus);
34.239757
184
0.538823
94679ed9cc104f4eeac997237f4aeefdb7a0dbe3
146
js
JavaScript
app/models/index.js
alwaysmavs/duty
32431aeb0afbb6069c578888abac775e162706a4
[ "MIT" ]
null
null
null
app/models/index.js
alwaysmavs/duty
32431aeb0afbb6069c578888abac775e162706a4
[ "MIT" ]
null
null
null
app/models/index.js
alwaysmavs/duty
32431aeb0afbb6069c578888abac775e162706a4
[ "MIT" ]
null
null
null
import router from './router'; import shot from './shots/index'; export function registerModels(app) { app.model(router); app.model(shot); }
18.25
37
0.705479
9467b60b3a00c6ebc98f892b3035199bdef47f6f
2,076
js
JavaScript
src/components/Form/oldone.js
Fatensamman/resty
61b7f77eeafe7fb0f11f8c091fbc1f6c82f1a6da
[ "MIT" ]
null
null
null
src/components/Form/oldone.js
Fatensamman/resty
61b7f77eeafe7fb0f11f8c091fbc1f6c82f1a6da
[ "MIT" ]
null
null
null
src/components/Form/oldone.js
Fatensamman/resty
61b7f77eeafe7fb0f11f8c091fbc1f6c82f1a6da
[ "MIT" ]
null
null
null
// import './Form.scss' // import React from 'react' // class Form extends React.Component { // constructor(props) { // super(props) // this.state = { // url: '', // method: 'get', // }; // } // handleSubmit = async (e) => { // e.preventDefault(); // try { // let raw = await fetch(this.state.url); // let data = await raw.json(); // let headers ={}; // // console.log(raw.headers); // raw.headers.forEach((item,key)=>{ // return headers[key]=item}); // this.props.handleClick(headers,data.count,data.results) // } catch (error) { // console.error(error) // } // } // urlHandle = e => { // const url = e.target.value; // this.setState({ url }) // } // handleMethod = (e) => { // const method = e.target.value; // this.setState({ method }) // } // render() { // return ( // <main> // <form> // <label>URL: </label> // <input onChange = {this.urlHandle} type="url" name="url" className="url" placeholder="Enter request URL" /> // <input type="submit" value="Go!" onClick={this.handleSubmit} /> // <br /> // <label className="methodLabel">Get</label> // <input onChange = {this.handleMethod} type="radio" name="method" className="method" value="get" /> // <label className="methodLabel">Post</label> // <input onChange = {this.handleMethod} type="radio" name="method" className="method" value="post" /> // <label className="methodLabel">Put</label> // <input onChange = {this.handleMethod} type="radio" name="method" className="method" value="put" /> // <label className="methodLabel">Delete</label> // <input onChange = {this.handleMethod} type="radio" name="method" className="method" value="delete" /> // </form> // <div> // <h3>{this.state.method}&nbsp; &nbsp; &nbsp;{this.state.url}</h3> // </div> // </main> // ) // } // } // export default Form;
31.938462
121
0.52842
94687379ebb08a5ab88f16cf7214b941f29bb2df
6,222
js
JavaScript
JavaScript/SimpleGame/scripts/Components/Base.js
ProfPorkins/GameTech
aa45062d9003c593bf19f65708efcb99a13063c3
[ "MIT" ]
13
2016-07-14T16:27:25.000Z
2021-03-31T23:32:46.000Z
JavaScript/SimpleGame/scripts/Components/Base.js
ProfPorkins/GameTech
aa45062d9003c593bf19f65708efcb99a13063c3
[ "MIT" ]
5
2018-03-22T16:11:39.000Z
2021-05-30T16:34:06.000Z
JavaScript/SimpleGame/scripts/Components/Base.js
ProfPorkins/GameTech
aa45062d9003c593bf19f65708efcb99a13063c3
[ "MIT" ]
6
2018-03-22T16:00:02.000Z
2020-04-11T12:46:23.000Z
//------------------------------------------------------------------ // // Defines a Base component. A Base contains a sprite. // The spec is defined as: // { // imageName: // Asset name to use for the base // center: { x: , y: } // In world coordinates // radius: // In world coordinates // orientation: // In Radians // rotateRate: // Radians per second // vicinity: // In world coordinates // missile: { // delay: // How long (milliseconds) between firing missiles // lifetime: // How long (milliseconds) a missle lives // rotateRate: // How fast (radians/millisecond) a missile can turn // hitPoints: { // max: // Maximum hit points for the base // }, // shield: { // regenerationDelay: // How long (milliseconds) between shield regeneration // thickness: // In world coordinates // max: // Maximum value for the shield, also the starting strength // } // } // //------------------------------------------------------------------ Demo.components.Base = function(spec) { 'use strict'; let that = Demo.components.Entity(spec, spec.imageName); let shield = { get radius() { return spec.radius + spec.shield.thickness; }, get strength() { return spec.shield.strength; }, get max() { return spec.shield.max; } }; let regenerationTime = 0; let lastMissileFired = 0; Object.defineProperty(that, 'type', { get: function() { return Demo.components.Types.Base; }, enumerable: true, configurable: false }); // // Set the initial shield strengths spec.shield.strength = spec.shield.max; Object.defineProperty(that, 'shield', { get: function() { return shield; }, enumerable: true, configurable: false }); //------------------------------------------------------------------ // // Tell the sprite to update and continue to rotate the base. // //------------------------------------------------------------------ that.update = function(elapsedTime) { that.sprite.update(elapsedTime); spec.orientation += (spec.rotateRate * elapsedTime); // // Shields regenerate every 1 second regenerationTime += elapsedTime; if (regenerationTime >= spec.shield.regenerationDelay) { spec.shield.strength = Math.min(spec.shield.strength + 1, spec.shield.max); regenerationTime -= spec.shield.regenerationDelay; } // // Update how long since last missle was fired lastMissileFired += elapsedTime; return true; }; //------------------------------------------------------------------ // // Called when another entity gets within the 'vicinity' of this entity. // //------------------------------------------------------------------ that.vicinity = function(entity, report) { // // If the other entity is a spaceship and is within our vicinity, then // fire a missle if we haven't fired one in the last X milliseconds. if (entity.type === Demo.components.Types.SpaceShip) { let distance = Math.sqrt(Math.pow(entity.center.x - that.center.x, 2) + Math.pow(entity.center.y - that.center.y, 2)); if (distance <= spec.vicinity && lastMissileFired > spec.missile.delay) { lastMissileFired = 0; let direction = { x: entity.center.x - that.center.x, y: entity.center.y - that.center.y }; let magnitude = Math.sqrt(Math.pow(direction.x, 2) + Math.pow(direction.y, 2)); direction.x = (direction.x / magnitude) / 4000; direction.y = (direction.y / magnitude) / 4000; let missile = Demo.components.TrackingMissile({ center : { x: that.center.x, y: that.center.y }, target: entity, momentum: { x: direction.x, y: direction.y }, rotateRate: spec.missile.rotateRate, lifetime: spec.missile.lifetime }); // // Report the firing of the missle back to the calling code. report(missile, Demo.renderer.Missile); } } }; //------------------------------------------------------------------ // // Handle the collision behavior for when the Base collides with another entity. // //------------------------------------------------------------------ that.collide = function(entity) { let keepAlive = true; let damageLeft = entity.damage; if (that.shield.strength > 0) { spec.shield.strength -= damageLeft; if (spec.shield.strength < 0) { damageLeft = Math.abs(spec.shield.strength); spec.shield.strength = 0; } } if (spec.shield.strength === 0 && damageLeft > 0) { spec.hitPoints.strength = Math.max(spec.hitPoints.strength - damageLeft, 0); if (spec.hitPoints.strength <= 0) { keepAlive = false; // // Make a nice big explosion when this happens! Demo.components.ParticleSystem.createEffectExplosion({ center: { x: that.center.x, y: that.center.y }, howMany: 1000 }); // // Make a sound! Demo.assets['audio-base-explosion'].currentTime = 0.5; // Start it a little into the effect because there is a dead spot at the start of it Demo.assets['audio-base-explosion'].play(); } } // // No matter what happens, reset the next shield regeneration time. regenerationTime = 0; return keepAlive; }; return that; };
40.141935
158
0.482642
9469e6e1975e7430e9c081474cff0a3411d9ce7e
5,505
js
JavaScript
example/mockData.js
JackEasons/re-echarts
78ef2ad2c0a0c485d8e3fd19bf861fa2adb66e7d
[ "MIT" ]
40
2016-04-05T06:02:19.000Z
2021-11-12T04:16:56.000Z
example/mockData.js
JackEasons/re-echarts
78ef2ad2c0a0c485d8e3fd19bf861fa2adb66e7d
[ "MIT" ]
5
2016-04-21T03:59:23.000Z
2019-05-28T08:59:45.000Z
example/mockData.js
JackEasons/re-echarts
78ef2ad2c0a0c485d8e3fd19bf861fa2adb66e7d
[ "MIT" ]
17
2016-04-05T04:42:06.000Z
2021-12-15T02:44:50.000Z
/** * Created by liekkas on 16/4/4. */ export function mockMapData() { return { title : { text: '全国故障投诉情况', subtext: '点击任意省份,右侧图表随之联动', left: 'center' }, tooltip : { trigger: 'item' }, legend: { orient: 'vertical', left: 'left', data:['白天','晚上'] }, visualMap: { min: 0, max: 2500, left: 'left', top: 'bottom', text:['高','低'], // 文本,默认为数值文本 calculable : true }, series : [ { name: '白天', type: 'map', mapType: 'china', roam: false, itemStyle:{ normal:{label:{show:true}}, emphasis:{label:{show:true}} }, data:[ {name: '北京',value: Math.round(Math.random() * 1000)}, {name: '天津',value: Math.round(Math.random() * 1000)}, {name: '上海',value: Math.round(Math.random() * 1000)}, {name: '重庆',value: Math.round(Math.random() * 1000)}, {name: '河北',value: Math.round(Math.random() * 1000)}, {name: '河南',value: Math.round(Math.random() * 1000)}, {name: '云南省',value: Math.round(Math.random() * 1000)}, {name: '辽宁',value: Math.round(Math.random() * 1000)}, {name: '黑龙江',value: Math.round(Math.random() * 1000)}, {name: '湖南',value: Math.round(Math.random() * 1000)}, {name: '安徽',value: Math.round(Math.random() * 1000)}, {name: '山东',value: Math.round(Math.random() * 1000)}, {name: '新疆',value: Math.round(Math.random() * 1000)}, {name: '江苏',value: Math.round(Math.random() * 1000)}, {name: '浙江',value: Math.round(Math.random() * 1000)}, {name: '江西',value: Math.round(Math.random() * 1000)}, {name: '湖北',value: Math.round(Math.random() * 1000)}, {name: '广西',value: Math.round(Math.random() * 1000)}, {name: '甘肃',value: Math.round(Math.random() * 1000)}, {name: '山西',value: Math.round(Math.random() * 1000)}, {name: '内蒙古',value: Math.round(Math.random() * 1000)}, {name: '陕西',value: Math.round(Math.random() * 1000)}, {name: '吉林',value: Math.round(Math.random() * 1000)}, {name: '福建',value: Math.round(Math.random() * 1000)}, {name: '贵州',value: Math.round(Math.random() * 1000)}, {name: '广东',value: Math.round(Math.random() * 1000)}, {name: '青海',value: Math.round(Math.random() * 1000)}, {name: '西藏',value: Math.round(Math.random() * 1000)}, {name: '四川',value: Math.round(Math.random() * 1000)}, {name: '宁夏',value: Math.round(Math.random() * 1000)}, {name: '海南',value: Math.round(Math.random() * 1000)}, {name: '台湾',value: Math.round(Math.random() * 1000)}, {name: '香港',value: Math.round(Math.random() * 1000)}, {name: '澳门',value: Math.round(Math.random() * 1000)} ] }, { name: '晚上', type: 'map', mapType: 'china', itemStyle:{ normal:{label:{show:true}}, emphasis:{label:{show:true}} }, data:[ {name: '北京',value: Math.round(Math.random() * 1000)}, {name: '天津',value: Math.round(Math.random() * 1000)}, {name: '上海',value: Math.round(Math.random() * 1000)}, {name: '重庆',value: Math.round(Math.random() * 1000)}, {name: '河北',value: Math.round(Math.random() * 1000)}, {name: '安徽',value: Math.round(Math.random() * 1000)}, {name: '新疆',value: Math.round(Math.random() * 1000)}, {name: '浙江',value: Math.round(Math.random() * 1000)}, {name: '江西',value: Math.round(Math.random() * 1000)}, {name: '山西',value: Math.round(Math.random() * 1000)}, {name: '内蒙古',value: Math.round(Math.random() * 1000)}, {name: '吉林',value: Math.round(Math.random() * 1000)}, {name: '福建',value: Math.round(Math.random() * 1000)}, {name: '广东',value: Math.round(Math.random() * 1000)}, {name: '西藏',value: Math.round(Math.random() * 1000)}, {name: '四川',value: Math.round(Math.random() * 1000)}, {name: '宁夏',value: Math.round(Math.random() * 1000)}, {name: '香港',value: Math.round(Math.random() * 1000)}, {name: '澳门',value: Math.round(Math.random() * 1000)} ] } ] } } export function mockLineData(region='全国',time) { let data = [] for (let i = 0; i < 7; i++) { data.push(Math.ceil(Math.random()*20)) } return { title: { text: region + time + '一周投诉情况', subtext: time === '白天' ? '主题动态切换效果' : '加载过渡效果' }, tooltip: { trigger: 'axis' }, legend: { show: false, data:[time] }, toolbox: { show: true, feature: { dataZoom: {}, dataView: {readOnly: false}, magicType: {type: ['line', 'bar']}, restore: {}, saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: ['周一','周二','周三','周四','周五','周六','周日'] }, yAxis: { type: 'value', axisLabel: { formatter: '{value} 件' } }, series: [ { name:time, type:'line', data, markPoint: { data: [ {type: 'max', name: '最大值'}, {type: 'min', name: '最小值'} ] }, markLine: { data: [ {type: 'average', name: '平均值'} ] } }, ] } }
32.573964
64
0.48247
946c237e926e441d44b876e16d3466d6637cecda
4,437
js
JavaScript
plugin/scripts/options.js
artemut/chrome-ext-tc-build-checker-for-tfs
adb4b26d088f64a2b2ca9345cbc13ac0f086d130
[ "MIT" ]
null
null
null
plugin/scripts/options.js
artemut/chrome-ext-tc-build-checker-for-tfs
adb4b26d088f64a2b2ca9345cbc13ac0f086d130
[ "MIT" ]
null
null
null
plugin/scripts/options.js
artemut/chrome-ext-tc-build-checker-for-tfs
adb4b26d088f64a2b2ca9345cbc13ac0f086d130
[ "MIT" ]
null
null
null
(function() { function OptionManager() { var table = $('#options-table'); var statusBlock = $('#status'); this.addRow = function() { var firstRow = $('tr.data:first', table); var newRow = firstRow.clone(); $('input.tfs-hostname', newRow).val(''); $('input.tc-url', newRow).val(''); table.append(newRow); $('button.remove', newRow).click(function() { var removeBtn = $(this); removeRow(removeBtn); }); // enable 'Remove' buttons (because now there are at least 2 rows) $('tr.data button.remove[disabled="disabled"]', table).removeAttr('disabled'); }; var removeRow = function(removeBtn) { var rowCountBeforeRemoval = $('tr.data', table).length; var currentRow = removeBtn.closest('tr'); currentRow.remove(); if (rowCountBeforeRemoval === 2) { // disable 'Remove' button for the remaining row $('tr.data button.remove', table).attr('disabled', 'disabled'); } }; var validate = function(tfsHostnameInput, tcUrlInput) { var valid = true; if (tfsHostnameInput.val() == '') { tfsHostnameInput.css({ borderColor: 'red' }); valid = false; } else { tfsHostnameInput.css({ borderColor: '' }); } if (tcUrlInput.val() == 0) { tcUrlInput.css({ borderColor: 'red' }); valid = false; } else { tcUrlInput.css({ borderColor: '' }); } return valid; }; this.saveOptions = function() { statusBlock.html(''); var options = []; var isValidGlobal = true; $('tr.data', table).each(function() { var row = $(this); var tfsHostnameInput = $('input.tfs-hostname', row); var tcUrlInput = $('input.tc-url', row); var isValidCurrent = validate(tfsHostnameInput, tcUrlInput); if (isValidCurrent === true) { var tfsHostname = tfsHostnameInput.val(); var tcUrl = tcUrlInput.val(); var isDuplicate = options.some(function(value) { return value.tfsHostname === tfsHostname && value.tcUrl === tcUrl; }); if (!isDuplicate) { options.push({ tfsHostname: tfsHostname, tcUrl: tcUrl }); } } else { isValidGlobal = false; } }); if (isValidGlobal !== true) { return; } var items = { 'options': options }; chrome.storage.sync.set(items, function() { chrome.runtime.sendMessage({ code: 'options_changed' }); var statusBlock = $('#status'); statusBlock.html('Options saved!'); setTimeout(function() { statusBlock.html(''); }, 2000); }); }; this.restoreOptions = function() { var self = this; if (chrome.storage) { chrome.storage.sync.get({ options: [] }, function(items) { $.each(items.options, function(i, current) { if (i > 0) { self.addRow(); } var lastRow = $('tr.data:last', table); $('input.tfs-hostname', lastRow).val(current.tfsHostname); $('input.tc-url', lastRow).val(current.tcUrl); }); // bind remove event on the first row $('tr.data:first button.remove', table).click(function() { var removeBtn = $(this); removeRow(removeBtn); }); }); } }; } $(document).ready(function() { var optionManager = new OptionManager(); optionManager.restoreOptions(); $('#add').click(optionManager.addRow); $('#save').click(optionManager.saveOptions); }); })()
36.669421
90
0.446022
946d7467584e058f5c28df8e543e5642cbe13aac
167
js
JavaScript
src/index.js
VladimirKukolovich/reverse-int
d7b19d6a0e4b7c0d1df1bcaa73929c377f87ab1e
[ "MIT" ]
null
null
null
src/index.js
VladimirKukolovich/reverse-int
d7b19d6a0e4b7c0d1df1bcaa73929c377f87ab1e
[ "MIT" ]
null
null
null
src/index.js
VladimirKukolovich/reverse-int
d7b19d6a0e4b7c0d1df1bcaa73929c377f87ab1e
[ "MIT" ]
null
null
null
module.exports = function reverse (n) { x = Math.abs(n) arrN = Array.of(x); let res = (''+ arrN).split('').reverse().map(Number).join('') return res; };
23.857143
66
0.562874
946dbe621e900d8ba7767ec71b57cf407774287e
339
js
JavaScript
src/views/layouts/Header/Menu/__tests__/component.spec.js
Rammfall/themoviedb
02dd573a400446fed24024fbac6736fbf414a411
[ "MIT" ]
null
null
null
src/views/layouts/Header/Menu/__tests__/component.spec.js
Rammfall/themoviedb
02dd573a400446fed24024fbac6736fbf414a411
[ "MIT" ]
357
2021-01-11T02:47:50.000Z
2022-03-31T05:13:27.000Z
src/views/layouts/Header/Menu/__tests__/component.spec.js
Rammfall/themoviedb
02dd573a400446fed24024fbac6736fbf414a411
[ "MIT" ]
1
2021-03-02T20:39:22.000Z
2021-03-02T20:39:22.000Z
import React from 'react' import { shallow } from 'enzyme' import MenuComponent from '../component' describe('MenuComponent', () => { const defaultProps = { onLogout: jest.fn() } it('matches snapshot', () => { const component = shallow(<MenuComponent {...defaultProps} />) expect(component).toMatchSnapshot() }) })
19.941176
66
0.648968
946e2db4f7035759261d2d22926d6b2ba3875675
491
js
JavaScript
src/category.js
AnaBetancourt/beatitudinem-frontend
88e3bb0f8a3b32602444c35a3ad91b592e9d9601
[ "MIT" ]
null
null
null
src/category.js
AnaBetancourt/beatitudinem-frontend
88e3bb0f8a3b32602444c35a3ad91b592e9d9601
[ "MIT" ]
null
null
null
src/category.js
AnaBetancourt/beatitudinem-frontend
88e3bb0f8a3b32602444c35a3ad91b592e9d9601
[ "MIT" ]
null
null
null
class Category { static all = [] constructor({id, name}){ this.id = id this.name = name Category.all.push(this) } allItems(){ return Item.all.filter(item => parseInt(item.category_id) === parseInt(this.id)) } addToDropdown(){ const newOption = document.createElement('option') newOption.value = this.id newOption.innerText = this.name document.getElementById('dropdown').append(newOption) } }
22.318182
88
0.592668
946ec6b5a19b15b9199f5bc504b165954c451c53
1,659
js
JavaScript
packages/frontend/src/components/TweetsBody/TweetsBody.js
H-isaac23/V-Updates
2c157e272f25e5e6b30133e7e0e7fb7d119e0b87
[ "MIT" ]
null
null
null
packages/frontend/src/components/TweetsBody/TweetsBody.js
H-isaac23/V-Updates
2c157e272f25e5e6b30133e7e0e7fb7d119e0b87
[ "MIT" ]
22
2021-07-27T10:45:57.000Z
2021-10-01T16:18:11.000Z
packages/frontend/src/components/TweetsBody/TweetsBody.js
H-isaac23/V-Updates
2c157e272f25e5e6b30133e7e0e7fb7d119e0b87
[ "MIT" ]
null
null
null
import styles from "./TweetsBody.module.scss"; import TweetCard from "./TweetsCard"; import { useEffect, useState } from "react"; import services from "../../services/Bodies"; const TweetsBody = () => { const [tweets, setTweets] = useState([]); useEffect(() => { services.getTweets().then((response) => { setTweets( response.data .sort((a, b) => new Date(b.date) - new Date(a.date)) .slice(0, 10) ); }); }, []); // for getting new tweets, will implement the functionality later // useEffect(() => { // services.getAccounts().then((accounts) => { // console.log(accounts); // services.reloadTweets(accounts.data).then((_) => { // services.getTweets().then((response) => { // setTweets( // response.data // .sort((a, b) => new Date(b.date) - new Date(a.date)) // .slice(0, 10) // ); // }); // }); // }); // }, []); // useEffect(() => { // services.getAccounts().then((response) => { // console.log(response.data); // }); // }); return ( <section className={styles.mainBody}> <div className={styles.titleContainer}> <div className={styles.sectionTitle}>Recent Tweets</div> </div> <div className={styles.tweetUpdates}> {tweets.map((t, i) => ( <TweetCard imageSrc={t.profile_image_url} handle={t.handle} date={t.date} content={t.content} tweet_id={t.tweet_id} key={i} /> ))} </div> </section> ); }; export default TweetsBody;
26.333333
69
0.512357
946ee6fa79f676536955aa5cdb0b80c956892f85
944
js
JavaScript
web/js/pixel-editor-master/js/components/palette.js
heltru/mirovid_web
4008c4b5039f195c9008e71186f64de21e4c0bc1
[ "BSD-3-Clause" ]
null
null
null
web/js/pixel-editor-master/js/components/palette.js
heltru/mirovid_web
4008c4b5039f195c9008e71186f64de21e4c0bc1
[ "BSD-3-Clause" ]
null
null
null
web/js/pixel-editor-master/js/components/palette.js
heltru/mirovid_web
4008c4b5039f195c9008e71186f64de21e4c0bc1
[ "BSD-3-Clause" ]
null
null
null
import {palettes} from './palettes/palettes.js'; import {Color} from './color.js'; export class Palette { constructor(parent) { this.parent = parent; this.parent.palette = this; this.element = document.createElement('aside'); this.element.setAttribute('id', 'palette'); parent.element.appendChild(this.element); } get current() { return this.currentPalette; } set current(paletteIndex) { this.currentPalette = paletteIndex; for(let colorIndex = 0; colorIndex < palettes[paletteIndex].colors.length; colorIndex++) { this['color' + colorIndex] = new Color(this, palettes[paletteIndex].colors, colorIndex); this.element.appendChild(this['color' + colorIndex]['element']); this.color = palettes[paletteIndex].colors[colorIndex].replace(/[^\d,]/g, '').split(','); } } set color(color) { this.parent.color = color; } set tool(tool) { this.parent.tool = tool; } }
27.764706
95
0.662076
946eed7f0de8724a7b1c0201834db8df59e3caad
16,339
js
JavaScript
tests/dummy_observation.test.js
arcman7/jssc2
fea1cceebcbbe3ecc83520f4fd6694d4dedcca82
[ "Apache-2.0" ]
3
2020-09-09T23:21:44.000Z
2021-06-13T20:36:07.000Z
tests/dummy_observation.test.js
arcman7/jssc2
fea1cceebcbbe3ecc83520f4fd6694d4dedcca82
[ "Apache-2.0" ]
4
2020-09-09T21:27:15.000Z
2020-09-23T23:13:06.000Z
tests/dummy_observation.test.js
arcman7/jssc2
fea1cceebcbbe3ecc83520f4fd6694d4dedcca82
[ "Apache-2.0" ]
1
2020-10-31T22:54:45.000Z
2020-10-31T22:54:45.000Z
const path = require('path') //eslint-disable-line const { performance } = require('perf_hooks') //eslint-disable-line const s2clientprotocol = require('s2clientprotocol') //eslint-disable-line const dummy_observation = require(path.resolve(__dirname, './dummy_observation.js')) const features = require(path.resolve(__dirname, '..', 'lib', 'features.js')) const point = require(path.resolve(__dirname, '..', 'lib', 'point.js')) const actions = require(path.resolve(__dirname, '..', 'lib', 'actions.js')) const units = require(path.resolve(__dirname, '..', 'lib', 'units.js')) const pythonUtils = require(path.resolve(__dirname, '..', 'lib', 'pythonUtils.js')) const { common_pb } = s2clientprotocol const { assert } = pythonUtils const { getattr } = dummy_observation const msToS = 1 / 1000 const _PROBE = new dummy_observation.Unit({ unit_type: units.Protoss.Probe, player_relative: features.PlayerRelative.SELF, health: 20, shields: 20, energy: 0, transport_slots_taken: 0, build_progress: 1.0, }) const _ZEALOT = new dummy_observation.Unit({ unit_type: units.Protoss.Zealot, player_relative: features.PlayerRelative.SELF, health: 100, shields: 50, energy: 0, transport_slots_taken: 0, build_progress: 1.0, }) const _MOTHERSHIP = new dummy_observation.Unit({ unit_type: units.Protoss.Probe, player_relative: features.PlayerRelative.SELF, health: 350, shields: 7, energy: 200, transport_slots_taken: 0, build_progress: 1.0, }) class TestCase { constructor() { this._features = new features.Features( new features.AgentInterfaceFormat({ feature_dimensions: new features.Dimensions({ screen: [64, 60], minimap: [32, 28], }), rgb_dimensions: new features.Dimensions({ screen: [128, 124], minimap: [64, 60], }), action_space: actions.ActionSpace.FEATURES, use_feature_units: true, }), new point.Point(256, 256) ) this._obs_spec = this._features.observation_spec() this._builder = new dummy_observation.Builder(this._obs_spec) } _get_obs() { return this._builder.build().getObservation() } _check_layer(layer, x, y, bits) { //eslint-disable-line assert(layer.getSize().getX() === x, 'layer.getSize().getX() === x') assert(layer.getSize().getY() === y, 'layer.getSize().getY() === y') assert(layer.getBitsPerPixel() === bits, 'layer.getBitsPerPixel() === bits') } _check_attributes_match(a, b, attributes) {//eslint-disable-line for (let i = 0; i < attributes.length; i++) { const attribute = attributes[i] const aVal = getattr(a, attribute) !== undefined ? getattr(a, attribute) : a[attribute] const bVal = getattr(b, attribute) !== undefined ? getattr(b, attribute) : b[attribute] assert(aVal == bVal, `aVal == bVal, attribute: ${attribute}\n aVal: ${aVal}, bVal: ${bVal}`) } } _check_unit(proto, builder) { return this._check_attributes_match(proto, builder, Object.keys(builder)) } _check_feature_unit(proto, builder) { return this._check_attributes_match(proto, builder, [ 'unit_type', 'alliance', 'owner', 'pos', 'radius', 'health', 'health_max', 'is_on_screen', 'shield', 'shield_max' ]) } } function DummyObservationTest() { console.log('DummyObservationTest:') const start_timer = performance.now() * msToS let testState let count = 0 function getFuncName() { return getFuncName.caller.name } function testFeaturesScreenMatchesSpec() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const obs = testState._get_obs() for (let i = 0; i < features.SCREEN_FEATURES.length; i++) { const f = features.SCREEN_FEATURES[i] const layer = obs.getFeatureLayerData().getRenders() testState._check_layer(getattr(layer, f.name), 64, 60, 8) } count += 1 } testFeaturesScreenMatchesSpec() function testFeatureMinimapMatchesSpec() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const obs = testState._get_obs() for (let i = 0; i < features.MINIMAP_FEATURES.length; i++) { const f = features.MINIMAP_FEATURES[i] const layer = obs.getFeatureLayerData().getMinimapRenders() testState._check_layer(getattr(layer, f.name), 32, 28, 8) } count += 1 } testFeatureMinimapMatchesSpec() function testRgbScreenMatchesSpec() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const obs = testState._get_obs() testState._check_layer(obs.getRenderData().getMap(), 128, 124, 24) count += 1 } testRgbScreenMatchesSpec() function testGameLoopCanBeSet() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() testState._builder.game_loop(1234) const obs = testState._get_obs() assert(obs.getGameLoop() === 1234, 'obs.getGameLoop() === 1234') count += 1 } testGameLoopCanBeSet() function testPlayerCommonCanBeSet() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() testState._builder.player_common({ minerals: 1000, vespene: 200, food_cap: 200, food_used: 198, food_army: 140, food_workers: 58, army_count: 92, warp_gate_count: 7, larva_count: 15, }) const obs = testState._get_obs() assert(getattr(obs.getPlayerCommon(), 'player_id') === 1) // (we didn't set it) assert(getattr(obs.getPlayerCommon(), 'minerals') === 1000) assert(getattr(obs.getPlayerCommon(), 'vespene') === 200) assert(getattr(obs.getPlayerCommon(), 'food_cap') === 200) assert(getattr(obs.getPlayerCommon(), 'food_used') === 198) assert(getattr(obs.getPlayerCommon(), 'food_army') === 140) assert(getattr(obs.getPlayerCommon(), 'food_workers') === 58) assert(getattr(obs.getPlayerCommon(), 'idle_worker_count') === 2) // (didn't set it) assert(getattr(obs.getPlayerCommon(), 'army_count') === 92) assert(getattr(obs.getPlayerCommon(), 'warp_gate_count') === 7) assert(getattr(obs.getPlayerCommon(), 'larva_count') === 15) } testPlayerCommonCanBeSet() function testScoreCanBeSet() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() testState._builder.score(54321) const obs = testState._get_obs() assert(obs.getScore().getScore() === 54321, 'obs.getScore().getScore() === 54321') count += 1 } testScoreCanBeSet() function testScoreDetailsCanBeSet() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() testState._builder.score_details({ idle_production_time: 1, idle_worker_time: 2, total_value_units: 3, killed_value_units: 5, killed_value_structures: 6, collected_minerals: 7, collected_vespene: 8, collection_rate_minerals: 9, collection_rate_vespene: 10, spent_minerals: 11, spent_vespene: 12, }) const obs = testState._get_obs() assert(getattr(obs.getScore().getScoreDetails(), 'idle_production_time') === 1) assert(getattr(obs.getScore().getScoreDetails(), 'idle_worker_time') === 2) assert(getattr(obs.getScore().getScoreDetails(), 'total_value_units') === 3) assert(getattr(obs.getScore().getScoreDetails(), 'total_value_structures') === 230) assert(getattr(obs.getScore().getScoreDetails(), 'killed_value_units') === 5) assert(getattr(obs.getScore().getScoreDetails(), 'killed_value_structures') === 6) assert(getattr(obs.getScore().getScoreDetails(), 'collected_minerals') === 7) assert(getattr(obs.getScore().getScoreDetails(), 'collected_vespene') === 8) assert(getattr(obs.getScore().getScoreDetails(), 'collection_rate_minerals') === 9) assert(getattr(obs.getScore().getScoreDetails(), 'collection_rate_vespene') === 10) assert(getattr(obs.getScore().getScoreDetails(), 'spent_minerals') === 11) assert(getattr(obs.getScore().getScoreDetails(), 'spent_vespene') === 12) count += 1 } testScoreDetailsCanBeSet() function testScoreByCategorySpec() { //Note that if these dimensions are changed, client code is liable to break.// console.log(` running test "${getFuncName()}"`) testState = new TestCase() const score = testState._obs_spec.score_by_category assert(score[0] === 11, 'testState._obs_spec.score_by_category[0] === 11') assert(score[1] === 5, 'testState._obs_spec.score_by_category[1] === 5') count += 1 } testScoreByCategorySpec() function testScoreByCategory() { console.log(` running test "${getFuncName()}"`) const arr = features.ScoreByCategory.toArray() for (let i = 0; i < arr.length; i++) { testState = new TestCase() const entry_name = arr[i].key testState._builder.score_by_category({ entry_name, none: 10, army: 1200, economy: 400, technology: 100, upgrade: 200, }) const response_observation = testState._builder.build() const obs = response_observation.getObservation() const entry = getattr(obs.getScore().getScoreDetails(), entry_name) assert(entry.getNone() === 10, 'entry.getNone() === 10') assert(entry.getArmy() === 1200, 'entry.getArmy() === 1200') assert(entry.getEconomy() === 400, 'entry.getEconomy() === 400') assert(entry.getTechnology() === 100, 'entry.getTechnology() === 100') assert(entry.getUpgrade() === 200, 'entry.getUpgrade() === 200') // Check the transform_obs does what we expect, too. const transformed_obs = testState._features.transform_obs(response_observation) const transformed_entry = transformed_obs.score_by_category[entry_name] assert(transformed_entry.none === 10, 'transformed_obs.none === 10') assert(transformed_entry.army === 1200, 'transformed_entry.army === 1200') assert(transformed_entry.economy === 400, 'transformed_entry.economy === 400') assert(transformed_entry.technology === 100, 'transformed_entry.technology === 100') assert(transformed_entry.upgrade === 200, 'transformed_entry.upgrade === 200') } count += 1 } testScoreByCategory() function testScoreByVitalSpec() { //Note that if these dimensions are changed, client code is liable to break. console.log(` running test "${getFuncName()}"`) testState = new TestCase() const scoreVital = testState._obs_spec.score_by_vital assert(scoreVital[0] === 3, 'scoreVital[0] === 3') assert(scoreVital[1] === 3, 'scoreVital[1] === 3') count += 1 } testScoreByVitalSpec() function testScoreByVital() { console.log(` running test "${getFuncName()}"`) const arr = features.ScoreByVital.toArray() for (let i = 0; i < arr.length; i++) { testState = new TestCase() const entry_name = arr[i].key testState._builder.score_by_vital({ entry_name, life: 1234, shields: 45, energy: 423, }) const response_observation = testState._builder.build() const obs = response_observation.getObservation() const entry = getattr(obs.getScore().getScoreDetails(), entry_name) assert(entry.getLife() === 1234, 'entry.getLife() === 1234') assert(entry.getShields() === 45, 'entry.getShields() === 45') assert(entry.getEnergy() === 423, 'entry.getEnergy() === 423') // Check the transform_obs does what we expect, too. const transform_obs = testState._features.transform_obs(response_observation) const transformed_entry = transform_obs.score_by_vital[entry_name] assert(transformed_entry.life === 1234, 'transformed_entry.life === 1234') assert(transformed_entry.shields === 45, 'transformed_entry.shields === 45') assert(transformed_entry.energy === 423, 'transformed_entry.energy === 423') } count += 1 } testScoreByVital() function testRgbMinimapMatchesSpec() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const obs = testState._get_obs() testState._check_layer(obs.getRenderData().getMinimap(), 64, 60, 24) count += 1 } testRgbMinimapMatchesSpec() function testNoSingleSelect() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const obs = testState._get_obs() assert(obs.getUiData().hasSingle() === false, 'obs.getUiData().hasSingle() === false') count += 1 } testNoSingleSelect() function testWithSingleSelect() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() testState._builder.single_select(_PROBE) const obs = testState._get_obs() testState._check_unit(obs.getUiData().getSingle().getUnit(), _PROBE) count += 1 } testWithSingleSelect() function testNoMultiSelect() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const obs = testState._get_obs() assert(obs.getUiData().hasMulti() === false, 'obs.getUiData().hasMulti() === false') count += 1 } testNoMultiSelect() function testMultiSelect() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const nits = [_MOTHERSHIP, _PROBE, _PROBE, _ZEALOT] testState._builder.multi_select(nits) const obs = testState._get_obs() assert(obs.getUiData().getMulti().getUnitsList().length === 4, 'obs.getUiData().getMulti().getUnitsList().length === 4') const protoUnits = obs.getUiData().getMulti().getUnitsList() for (let i = 0; i < nits.length; i++) { testState._check_unit(protoUnits[i], nits[i]) } count += 1 } testMultiSelect() function testBuildQueue() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const nits = [_MOTHERSHIP, _PROBE] const production = [ { 'ability_id': actions.FUNCTIONS.Train_Mothership_quick.ability_id, 'build_progress': 0.5 }, { 'ability_id': actions.FUNCTIONS.Train_Probe_quick.ability_id, 'build_progress': 0 }, { 'ability_id': actions.FUNCTIONS.Research_ShadowStrike_quick.ability_id, 'build_progress': 0 }, ] testState._builder.build_queue(nits, production) const obs = testState._get_obs() const buildQueue = obs.getUiData().getProduction().getBuildQueueList() assert(buildQueue.length === 2, 'buildQueue.length === 2') for (let i = 0; i < nits.length; i++) { testState._check_unit(buildQueue[i], nits[i]) } const productionQueue = obs.getUiData().getProduction().getProductionQueueList() assert(productionQueue.length === 3, 'productionQueue.length === 3') for (let i = 0; i < nits.length; i++) { testState._check_unit(productionQueue[i], production[i]) assert(productionQueue[i].get) } } testBuildQueue() function testFeatureUnitsAreAdded() { console.log(` running test "${getFuncName()}"`) testState = new TestCase() const pos1 = new common_pb.Point() pos1.setX(10) pos1.setY(10) pos1.setZ(0) const pos2 = new common_pb.Point() pos2.setX(11) pos2.setY(12) pos2.setZ(0) const feature_units = [ new dummy_observation.FeatureUnit({ unit_type: units.Protoss.Probe, alliance: features.PlayerRelative.SELF, owner: 1, pos: pos1, radius: 1.0, health: 10, health_max: 20, is_on_screen: true, shield: 0, shield_max: 20 }), new dummy_observation.FeatureUnit({ unit_type: units.Terran.Marine, alliance: features.PlayerRelative.SELF, owner: 1, pos: pos2, radius: 1.0, health: 35, health_max: 45, is_on_screen: true, shield: 0, shield_max: 0 }), ] testState._builder.feature_units(feature_units) const obs = testState._get_obs() const protoUnits = obs.getRawData().getUnitsList() for (let i = 0; i < feature_units.length; i++) { testState._check_feature_unit(protoUnits[i], feature_units[i]) } count += 1 } testFeatureUnitsAreAdded() console.log(`\n----------------------------------------------------------------------\nRan ${count} test(s) in ${(performance.now() * msToS) - start_timer}s\n\n`) } DummyObservationTest()
36.308889
164
0.657262
946fa929612486836519f7ca8b00e141c171e055
1,950
js
JavaScript
webpack/webpack.common.js
examples-hub/react-starter-ts-webpack4
e7eee94a5a71024b49b10f86bd106c3ec0fa5401
[ "MIT" ]
null
null
null
webpack/webpack.common.js
examples-hub/react-starter-ts-webpack4
e7eee94a5a71024b49b10f86bd106c3ec0fa5401
[ "MIT" ]
null
null
null
webpack/webpack.common.js
examples-hub/react-starter-ts-webpack4
e7eee94a5a71024b49b10f86bd106c3ec0fa5401
[ "MIT" ]
null
null
null
// shared webpack config object for dev, build, prod, demo... const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const isProd = process.env.NODE_ENV === 'production'; // console.log(';;isProd-sass, ', isProd); module.exports = { module: { rules: [ { test: /\.(ts|js)x?$/, use: [ { loader: 'babel-loader', }, ], exclude: /node_modules/, }, { test: /\.(sa|sc|c)ss$/, use: [ isProd ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader', { loader: 'sass-loader', options: { // when node-sass and sass were installed,by default sass-loader prefers sass. implementation: require('sass'), sassOptions: { // fiber: require('fibers'), }, }, }, ], }, // Fonts { test: /\.(ttf|eot|woff|woff2)$/, use: [ { loader: 'file-loader', options: { name: 'fonts/[hash].[ext]', }, }, ], }, // Files { test: /\.(jpg|jpeg|png|gif|svg|ico)$/, use: [ { loader: 'file-loader', options: { name: 'staticI/[hash].[ext]', }, }, ], }, { test: /\.js$/, use: 'source-map-loader', enforce: 'pre', }, ], }, plugins: [new CleanWebpackPlugin()], resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], // alias: {}, }, // experiments: { // topLevelAwait: true, // }, // ignoreWarnings: [/Failed to parse source map/], };
23.780488
92
0.448205
947054702c43872d8c8c875f1d62fef153ad9e9f
7,176
js
JavaScript
thali/install/SSDPReplacer/hook.js
thaliproject/Thali_Codovaplugin
0496da88a125a871d2ebff39359fbbf8ba01fd8f
[ "MIT" ]
255
2015-06-27T20:01:48.000Z
2022-03-06T14:19:00.000Z
thali/install/SSDPReplacer/hook.js
thaliproject/Thali_CordovaPlugin
0496da88a125a871d2ebff39359fbbf8ba01fd8f
[ "MIT" ]
1,929
2015-06-03T00:14:21.000Z
2019-12-12T01:55:40.000Z
thali/install/SSDPReplacer/hook.js
thaliproject/Thali_Codovaplugin
0496da88a125a871d2ebff39359fbbf8ba01fd8f
[ "MIT" ]
59
2015-07-17T07:57:33.000Z
2020-07-30T08:41:28.000Z
'use strict'; var path = require('path'); var util = require('util'); var format = util.format; var findit = require('findit'); var fs = require('fs-extra-promise'); var uuid = require('node-uuid'); var randomString = require('randomstring'); var Promise = require('bluebird'); // ponyfills var endsWith = require('end-with'); require('./process'); var IOS_BUILD_PATH = 'platforms/ios'; var ANDROID_BUILD_PATH = 'platforms/android'; // js files require more specific paths to ignore intermediate/build files from // previous builds var IOS_WWW_PATH = 'platform/ios/www'; var ANDROID_WWW_PATH = 'platforms/android/assets/www'; // We want to find the first path that ends with 'name'. function findFirstFile (name, rootDir) { return new Promise(function (resolve, reject) { var resultPath; function end() { if (resultPath) { resolve(resultPath); } else { reject(new Error( format('file is not found, name: \'%s\'', name) )); } } var finder = findit(rootDir) .on('file', function (path) { // We can receive here 'path': 'a/b/my-file', 'a/b/bad-my-file', // 'my-file', 'bad-my-file'. // Both 'a/b/my-file' and 'my-file' should be valid. if (path === name || endsWith(path, '/' + name)) { resultPath = path; finder.stop(); } }) .on('error', function (error) { reject(new Error(error)); }) .on('stop', end) .on('end', end); }) .catch(function (error) { console.error( 'finder failed, error: \'%s\', stack: \'%s\'', error.toString(), error.stack ); return Promise.reject(error); }); } function replaceContent(path, content, replacements) { // String.prototype.replace in javascript is defected by design. // https://stackoverflow.com/questions/5257000/how-to-know-if-javascript-string-replace-did-anything function replace(string, pattern, replacement) { var isReplaced = false; var result = string.replace(pattern, function () { isReplaced = true; // arguments are $0, $1, ..., offset, string return Array.prototype.slice.call(arguments, 1, -2) .reduce(function (pattern, match, index) { // '$1' from strings like '$11 $12' shouldn't be replaced. return pattern.replace( new RegExp('\\$' + (index + 1) + '(?=[^\\d]|$)', 'g'), match ); }, replacement); }); if (!isReplaced) { throw new Error( format( 'we couldn\'t replace pattern: \'%s\' with value: \'%s\' ' + 'in file: \'%s\'', pattern, replacement, path ) ); } return result; } return replacements.reduce(function (content, replacement) { return replace(content, replacement.pattern, replacement.value); }, content); } // We want to replace multiple 'strings' in file. // 'replacements' will be an array: // [{ pattern: /pattern/, value: 'replacement' }] function replaceStringsInFile(name, rootDir, replacements) { return findFirstFile(name, rootDir) .then(function (path) { return fs.readFileAsync(path, 'utf8') .then(function (content) { return replaceContent(path, content, replacements); }) .then(function (content) { return fs.writeFileAsync(path, content, 'utf8'); }); }) .catch(function (error) { console.error( 'we couldn\'t replace strings in file, error: \'%s\', stack: \'%s\'', error.toString(), error.stack ); return Promise.reject(error); }); } // Our task is to replace 'b' between 'a' and 'c' with other value. // We couldn't use the simpliest solution: // 'abc'.replace(/(?<=a)(b)(?=c)/, 'q') // (?<=...) is not supported in nodejs (we don't want to require 'pcre' here). // So we have to use: // 'abc'.replace(/(a)(b)(c)/, '$1q$3') function replaceThaliConfig (rootDir) { // example: 'SSDP_NT: process.env.SSDP_NT || 'http://www.thaliproject.org/ssdp',' // or: SSDP_NT: 'http://www.thaliproject.org/ssdp', // We want to replace it with random string. var value = randomString.generate({ length: 'http://www.thaliproject.org/ssdp'.length }); var replacement = { pattern: new RegExp( [ '(', 'SSDP_NT', '\\s*', ':', ')', '(', '\\s*', '.*?', ',', ')' ].join('') ), value: '$1 \'' + value + '\',' }; return replaceStringsInFile('thaliConfig.js', rootDir, [replacement]); } function replaceConnectionHelper (rootDir) { var replacements = []; // Example: 'private static final String BLE_SERVICE_UUID_AS_STRING = // "b6a44ad1-d319-4b3a-815d-8b805a47fb51";' // We want to replace 'b6a44ad1-d319-4b3a-815d-8b805a47fb51' with new uuid.v4. replacements.push({ pattern: new RegExp( [ '(', ['static', 'final', 'String', 'BLE_SERVICE_UUID_AS_STRING'] .join('\\s+'), '\\s*', '=', '\\s*', ')', '(', '"', '.*?', '"', ')' ].join('') ), value: '$1"' + uuid.v4() + '"' }); function getRandomNumber (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Example: 'private static final int MANUFACTURER_ID = 7413;' // We want to replace 7413 with random number, 1100 <= number <= 65534. replacements.push({ pattern: new RegExp( [ '(', ['static', 'final', 'int', 'MANUFACTURER_ID'].join('\\s+'), '\\s*', '=', ')', '(', '\\s*', '.*?', ';', ')' ].join('') ), value: '$1 ' + getRandomNumber(1100, 65534) + ';' }); return replaceStringsInFile('ConnectionHelper.java', rootDir, replacements); } function replaceJXcoreExtension(rootDir) { // example: // 'appContext = [[AppContext alloc] initWithServiceType:@"thaliproject"];' // We want to replace 'thaliproject' here with random alphabetic string. var value = randomString.generate({ length: 'thaliproject'.length, charset: 'alphabetic' }); var replacement = { pattern: new RegExp( [ '(', ['initWithServiceType', ':', '@'].join('\\s*'), ')', '(', '"', '.*?', '"', ')' ].join('') ), value: '$1"' + value + '"' }; return replaceStringsInFile('JXcoreExtension.m', rootDir, [replacement]); } module.exports = function (ctx) { var actions = []; var iosPath = path.join(ctx.opts.projectRoot, IOS_BUILD_PATH); var iosWwwPath = path.join(ctx.opts.projectRoot, IOS_WWW_PATH); var androidPath = path.join(ctx.opts.projectRoot, ANDROID_BUILD_PATH); var androidWwwPath = path.join(ctx.opts.projectRoot, ANDROID_WWW_PATH); if (ctx.opts.platforms.indexOf('ios') !== -1) { actions.push( replaceThaliConfig(iosWwwPath), replaceJXcoreExtension(iosPath) ); } if (ctx.opts.platforms.indexOf('android') !== -1) { actions.push( replaceThaliConfig(androidWwwPath), replaceConnectionHelper(androidPath) ); } return Promise.all(actions).then(function () { console.info('We have replaced hardcoded ids with random values.'); }); };
28.141176
102
0.582776
94722f8b07da758b1bfffb47c393cca96c64cadf
1,806
js
JavaScript
src/pages/tips.js
Souravdey777/PandoConnect
4b702d7c60990cae62ba517ff0e26084f4d24b9f
[ "MIT" ]
10
2020-06-25T16:59:10.000Z
2021-11-09T11:24:41.000Z
src/pages/tips.js
Souravdey777/PandoConnect
4b702d7c60990cae62ba517ff0e26084f4d24b9f
[ "MIT" ]
null
null
null
src/pages/tips.js
Souravdey777/PandoConnect
4b702d7c60990cae62ba517ff0e26084f4d24b9f
[ "MIT" ]
null
null
null
import React from "react"; import { IonPage, IonContent, IonSlide, IonSlides } from "@ionic/react"; // import SmallHeader from "../components/Header/SmallHeader"; // import LargeHeader from "../components/Header/LargeHeader"; // import LinkList from "../../components/Link/LinkList"; import image1 from "./tabs/tipimages/1.png"; import image2 from "./tabs/tipimages/2.png"; import image3 from "./tabs/tipimages/3.png"; import image4 from "./tabs/tipimages/4.png"; import image5 from "./tabs/tipimages/5.png"; import image6 from "./tabs/tipimages/6.png"; import image7 from "./tabs/tipimages/7.png"; const Tips = (props) => { return ( <IonPage> <IonContent fullscreen scroll-y="false" > <IonSlides style={{ verticalAlign: "middle", height: "100%" }}> <IonSlide style={{ backgroundColor: "#050a24" }}> <img src={image1} style={{ alignSelf: "flex-end" }} alt="1" /> </IonSlide> <IonSlide> <img src={image2} style={{ alignSelf: "flex-end" }} alt="2" /> </IonSlide> <IonSlide> <img src={image3} style={{ alignSelf: "flex-end" }} alt="3" /> </IonSlide> <IonSlide style={{ backgroundColor: "#050a24" }}> <img src={image4} style={{ alignSelf: "flex-end" }} alt="4" /> </IonSlide> <IonSlide> <img src={image5} style={{ alignSelf: "flex-end" }} alt="5" /> </IonSlide> <IonSlide style={{ backgroundColor: "#050a24" }}> <img src={image6} style={{ alignSelf: "flex-end" }} alt="6" /> </IonSlide> <IonSlide> <img src={image7} style={{ alignSelf: "flex-end" }} alt="7" /> </IonSlide> </IonSlides> </IonContent> </IonPage> ); }; export default Tips;
34.075472
74
0.572536
9473ccf175e19ce80a9f01afa9c2a0faab744c69
5,012
js
JavaScript
utility/aliased/aliased_data.js
typesettin/periodicjs.core.controller
1cd10100ac3bde4196994fba707165d2f57f2ba3
[ "MIT" ]
3
2019-01-19T07:57:12.000Z
2020-07-23T12:48:30.000Z
utility/aliased/aliased_data.js
repetere/periodicjs.core.controller
1cd10100ac3bde4196994fba707165d2f57f2ba3
[ "MIT" ]
9
2015-05-29T18:47:29.000Z
2017-12-02T21:45:04.000Z
utility/aliased/aliased_data.js
repetere/periodicjs.core.controller
1cd10100ac3bde4196994fba707165d2f57f2ba3
[ "MIT" ]
2
2016-05-25T20:56:36.000Z
2017-05-01T13:25:03.000Z
'use strict'; const path = require('path'); const wrapWithDeprecationWarning = require(path.join(__dirname, '../deprecate')); /** * Creates a function that takes configurable options and queries the database for a single document. Alias for CoreController.db.default.load or CoreController.meta.load * @return {Fuction} A function that queries the database for a single document */ var _loadModel = function () { /** * Loads a single document from the database * @param {Object} options Configurable options for load (see periodicjs.core.data for more details) * @param {Function} cb Callback function * @return {Object} Returns a Promise which resolves with document if cb arugment is not passed */ let fn = function loadModel (options = {}, cb) { return this.db.default.load(options, cb); } let message = 'CoreController.loadModel: Use CoreController.db.default.load, CoreController.db[model_name].load, CoreController.meta.load or CoreController.meta.load[model_name] instead'; return wrapWithDeprecationWarning.call(this, fn, message); }; /** * Creates a function that takes configurable options and queries the database for multiple documents. Alias for CoreController.db.default.search or CoreController.meta.search * @return {Fuction} A function that queries the database for multiple documents */ var _searchModel = function () { /** * Queries the database for multiple documents * @param {Object} options Configurable options for search (see periodicjs.core.data for more details) * @param {Function} cb Callback function * @return {Object} Returns a Promise which resolves with documents if cb arugment is not passed */ let fn = function searchModel (options = {}, cb) { return this.db.default.search(options, cb); } let message = 'CoreController.searchModel: Use CoreController.db.default.search, CoreController.db[model_name].search, CoreController.meta.search or CoreController.meta.search[model_name] instead'; return wrapWithDeprecationWarning.call(this, fn, message); }; /** * Creates a function that takes configurable options and creates a document. Alias for CoreController.db.default.create or CoreController.meta.create * @return {Fuction} A function that creates a document */ var _createModel = function () { /** * Creates a document in the database * @param {Object} options Configurable options for create (see periodicjs.core.data for more details) * @param {Function} cb Callback function * @return {Object} Returns a Promise which resolves with created document if cb arugment is not passed */ let fn = function createModel (options = {}, cb) { return this.db.default.create(options, cb); } let message = 'CoreController.createModel: Use CoreController.db.default.create, CoreController.db[model_name].create, CoreController.meta.create or CoreController.meta.create[model_name] instead'; return wrapWithDeprecationWarning.call(this, fn, message); }; /** * Creates a function that takes configurable options and updates a document. Alias for CoreController.db.default.update or CoreController.meta.update * @return {Fuction} A function that updates a document */ var _updateModel = function () { /** * Updates a document in the database * @param {Object} options Configurable options for update (see periodicjs.core.data for more details) * @param {Function} cb Callback function * @return {Object} Returns a Promise which resolves with the update status if cb argument is not passed */ let fn = function updateModel (options = {}, cb) { return this.db.default.update(options, cb); } let message = 'CoreController.updateModel: Use CoreController.db.default.update, CoreController.db[model_name].update, CoreController.meta.update or CoreController.meta.update[model_name] instead'; return wrapWithDeprecationWarning.call(this, fn, message); }; /** * Creates a function that takes configurable options and deletes a document. Alias for CoreController.db.default.delete or CoreController.meta.delete * @return {Fuction} A function that deletes a document */ var _deleteModel = function () { /** * Deletes a document in the database * @param {Object} options Configurable options for delete (see periodicjs.core.data for more details) * @param {Function} cb Callback function * @return {Object} Returns a Promise which resolves with the delete status if cb argument is not passed */ let fn = function deleteModel (options = {}, cb) { return this.db.default.delete(options, cb); } let message = 'CoreController.deleteModel: Use CoreController.db.default.delete, CoreController.db[model_name].delete, CoreController.meta.delete or CoreController.meta.delete[model_name] instead'; return wrapWithDeprecationWarning.call(this, fn, message); }; module.exports = { loadModel: _loadModel, searchModel: _searchModel, createModel: _createModel, updateModel: _updateModel, deleteModel: _deleteModel };
49.623762
198
0.750399
94741a158a1ed092913e5c5d9e8877d497c14acf
1,614
js
JavaScript
decorator/index.js
adamclerk/generator-yeogurt
869441efaa7d1b7946ba9ff1f7810ff717ad5caa
[ "MIT" ]
null
null
null
decorator/index.js
adamclerk/generator-yeogurt
869441efaa7d1b7946ba9ff1f7810ff717ad5caa
[ "MIT" ]
null
null
null
decorator/index.js
adamclerk/generator-yeogurt
869441efaa7d1b7946ba9ff1f7810ff717ad5caa
[ "MIT" ]
null
null
null
'use strict'; var util = require('util'); var yeoman = require('yeoman-generator'); var getRootDir = require('../helpers/get-root-dir'); var path = require('path'); var DecoratorGenerator = module.exports = function DecoratorGenerator() { // By calling `NamedBase` here, we get the argument to the subgenerator call // as `this.name`. yeoman.generators.NamedBase.apply(this, arguments); var fileJSON = this.config.get('config'); // options this.projectName = fileJSON.projectName; this.jsFramework = fileJSON.jsFramework; this.useTesting = fileJSON.useTesting; }; util.inherits(DecoratorGenerator, yeoman.generators.NamedBase); // Prompts DecoratorGenerator.prototype.ask = function ask() { if (this.jsFramework !== 'angular') { this.log('This subgenerator is only used for Angular Applications. It seems as though you are not using Angular'); this.log('Operation aborted'); this.abort = true; return; } var done = this.async(); var prompts = [{ name: 'decoratorFile', message: 'Where would you like to create this decorator?', default: 'client/app' }]; this.prompt(prompts, function(answers) { // Get root directory this.rootDir = getRootDir(answers.decoratorFile); this.decoratorFile = path.join( answers.decoratorFile, this._.slugify(this.name.toLowerCase()), this._.slugify(this.name.toLowerCase()) ); done(); }.bind(this)); }; DecoratorGenerator.prototype.files = function files() { if (this.abort) { return; } this.template('decorator.js', this.decoratorFile + '.decorator.js'); };
26.9
118
0.685874
9474202aca99d5b07afd0f4fa2ac2a8f78b938c6
444
js
JavaScript
lib/admin/admin-sidebar/admin-sidebar.js
Lucas-Geitner/democracyos
3f87ec2411473972b5e8d3199af382b41509b537
[ "CC-BY-3.0" ]
null
null
null
lib/admin/admin-sidebar/admin-sidebar.js
Lucas-Geitner/democracyos
3f87ec2411473972b5e8d3199af382b41509b537
[ "CC-BY-3.0" ]
null
null
null
lib/admin/admin-sidebar/admin-sidebar.js
Lucas-Geitner/democracyos
3f87ec2411473972b5e8d3199af382b41509b537
[ "CC-BY-3.0" ]
null
null
null
import template from './sidebar-template.jade' import View from '../../view/view.js' export default class Sidebar extends View { constructor (forum) { super(template, {forum}) } set (section) { if (!section) return let select = this.find(`a[data-section=${section}]`).parent('li') select.addClass('active') } unset () { let actives = this.find('.active') actives.removeClass('active') return this } }
21.142857
69
0.637387
9474a5997f20f0dcf160dfd38f1ec6af423aaa02
425
js
JavaScript
src/actions/config.js
danbovey/TraktShowTime
237895f7537ae17124edf2c9874bfa5553b8f32e
[ "MIT" ]
7
2017-02-12T14:01:10.000Z
2018-04-26T04:17:18.000Z
src/actions/config.js
danbovey/TraktShowTime
237895f7537ae17124edf2c9874bfa5553b8f32e
[ "MIT" ]
19
2017-02-12T05:04:00.000Z
2017-03-14T18:40:30.000Z
src/actions/config.js
danbovey/TraktShowTime
237895f7537ae17124edf2c9874bfa5553b8f32e
[ "MIT" ]
null
null
null
import qwest from 'qwest'; export const CONFIG_LOADED = 'CONFIG_LOADED'; export const CONFIG_FAILED = 'CONFIG_FAILED'; export function load() { return dispatch => { qwest.get('/config.json') .then((xhr, payload) => dispatch({ type: CONFIG_LOADED, payload })) .catch(err => { console.error(err); dispatch({ type: CONFIG_FAILED }); }); }; }
26.5625
79
0.56
9474b3b89c69d93b3af326b09c51e11bf7ec6180
1,225
js
JavaScript
random-kindness/src/Components/Contacts/Contacts.js
bw-Random-Acts-generator/Front-End
11fff79019943c07a43b96fa49a365356ec509d5
[ "MIT" ]
null
null
null
random-kindness/src/Components/Contacts/Contacts.js
bw-Random-Acts-generator/Front-End
11fff79019943c07a43b96fa49a365356ec509d5
[ "MIT" ]
3
2020-09-07T14:39:14.000Z
2022-02-26T19:02:43.000Z
random-kindness/src/Components/Contacts/Contacts.js
bw-Random-Acts-generator/Front-End
11fff79019943c07a43b96fa49a365356ec509d5
[ "MIT" ]
null
null
null
import React, { useState } from 'react'; import { Collapse, Button, CardBody, Card } from "reactstrap"; import "./Contacts.css" const SoloContact = props => { const [collapse, setCollapse] = useState(false); const toggle = () => setCollapse(!collapse); return ( <div> {props.contactList.map( contact => { return ( <div key={contact.user_id}> <Button className="contacts-name" onClick={toggle} > {contact.name} </Button> <Collapse isOpen={collapse}> <Card> <CardBody className="contacts-card"> <div> <h3>{contact.phone}</h3> <h3>{contact.email}</h3> <h3>{contact.address}</h3> <h3>{contact.group}</h3> <p>{contact.notes}</p> </div> <button className="card-btn" onClick={() => props.delContactFn(contact.user_id)}>X</button> </CardBody> </Card> </Collapse> </div> ); })} </div> ); }; export default SoloContact;
26.630435
80
0.453061