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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29779bfa335787951b5d17b4f785fda1d1823872 | 139 | js | JavaScript | app/routes/loans/index.js | RusPosevkin/ember-101 | 8e201bd6e7a6d8bade2977114a33f26ebaa732c1 | [
"MIT"
] | null | null | null | app/routes/loans/index.js | RusPosevkin/ember-101 | 8e201bd6e7a6d8bade2977114a33f26ebaa732c1 | [
"MIT"
] | null | null | null | app/routes/loans/index.js | RusPosevkin/ember-101 | 8e201bd6e7a6d8bade2977114a33f26ebaa732c1 | [
"MIT"
] | null | null | null | import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.modelFor('friends/show').get('loans');
}
});
| 17.375 | 54 | 0.654676 |
297aaadcd36299c7fd1a838fa5350f75828387f0 | 675 | js | JavaScript | externals/dojo/dijit/tests/helpers.js | ddgc/zf1 | cae3c90c175ddc9b55e7c6eb64cd60c48a249e50 | [
"BSD-3-Clause"
] | 2 | 2020-04-17T14:10:52.000Z | 2021-02-17T21:47:28.000Z | externals/dojo/dijit/tests/helpers.js | mridgway/Zend-Framework-1.x-Mirror | 82d2aa6bf16dbf9eae139a50aba95d89a33d2490 | [
"BSD-3-Clause"
] | 2 | 2021-01-30T03:54:17.000Z | 2021-01-30T23:24:54.000Z | externals/dojo/dijit/tests/helpers.js | mridgway/Zend-Framework-1.x-Mirror | 82d2aa6bf16dbf9eae139a50aba95d89a33d2490 | [
"BSD-3-Clause"
] | 15 | 2020-03-10T01:36:57.000Z | 2022-03-19T07:17:46.000Z | // Helper methods for automated testing
function isVisible(node){
if(node.domNode){ node = node.domNode; }
return (dojo.style(node, "display") != "none") &&
(dojo.style(node, "visibility") != "hidden") &&
(dojo.position(node).y + (dojo._getBorderExtents(node).t || 0) >= 0); // border check is for claro prone to shifting the border offscreen
}
function isHidden(node){
if(node.domNode){ node = node.domNode; }
return (dojo.style(node, "display") == "none") ||
(dojo.style(node, "visibility") == "hidden") ||
(dojo.position(node).y < 0); // + dojo.position(node).h ??
}
function innerText(node){
return node.textContent || node.innerText || "";
}
| 33.75 | 141 | 0.645926 |
297b345c5503ff72d78ee9f15dfc4bb5d235f3d4 | 659 | js | JavaScript | src/io/property.io.js | ArekX/AssignJS | 9d79797dbcfd5be073d78fef731fd81de08590bb | [
"MIT"
] | null | null | null | src/io/property.io.js | ArekX/AssignJS | 9d79797dbcfd5be073d78fef731fd81de08590bb | [
"MIT"
] | null | null | null | src/io/property.io.js | ArekX/AssignJS | 9d79797dbcfd5be073d78fef731fd81de08590bb | [
"MIT"
] | null | null | null | // @import: core
lib(['io', 'inspect'], function(io, inspect) {
io.addHandler('io.property', /\@[^\ ]+\s*/, {
init: init,
read: read,
write: write,
shouldWrite: shouldWrite,
canRead: true
});
function init(element, ioPart) {
var ob = inspect.getElementObject(element);
return {
prop: ioPart.substring(1),
ob: ob
};
}
function read() {
return this.ob.context.props.get(this.prop);
}
function write(value) {
this.ob.context.props.set(this.prop, value);
}
function shouldWrite(value) {
return true;
}
});
| 20.59375 | 52 | 0.522003 |
297b55d72f67de8e7bbfdf2cc157b2fc699dea0f | 2,967 | js | JavaScript | src/cli/commands/login.js | cb1kenobi/appcd-plugin-titanium | 8f39f0756974fe4670eee71e1045dec533352f53 | [
"Apache-2.0"
] | null | null | null | src/cli/commands/login.js | cb1kenobi/appcd-plugin-titanium | 8f39f0756974fe4670eee71e1045dec533352f53 | [
"Apache-2.0"
] | null | null | null | src/cli/commands/login.js | cb1kenobi/appcd-plugin-titanium | 8f39f0756974fe4670eee71e1045dec533352f53 | [
"Apache-2.0"
] | 3 | 2019-08-14T21:23:07.000Z | 2019-11-13T13:25:42.000Z | export default {
desc: 'Log in to the Axway AMPLIFY platform',
options: {
'--base-url [url]': { hidden: true },
'--client-id [id]': { hidden: true },
'--env [name]': 'The environment to use',
'--realm [realm]': { hidden: true },
'--force': 'Re-authenticate even if the account is already authenticated',
'--json': 'Outputs accounts as JSON',
'-c, --client-secret [key]': 'A secret key used to authenticate',
'-s, --secret-file [path]': 'Path to the PEM key used to authenticate',
'-u, --username [user]': 'Username to authenticate with',
'-p, --password [pass]': 'Password to authenticate with'
},
async action({ argv, console, exitCode, terminal }) {
const [
{ snooplogg },
{ prompt }
] = await Promise.all([
import('appcd-logger'),
import('prompts')
]);
const { alert, highlight } = snooplogg.styles;
const data = {
baseUrl: argv.baseUrl,
clientId: argv.clientId,
clientSecret: argv.clientSecret,
env: argv.env,
force: argv.force,
password: argv.password,
secretFile: argv.secretFile,
username: argv.username
};
if (Object.prototype.hasOwnProperty.call(argv, 'username')) {
const questions = [];
if (!argv.username || typeof argv.username !== 'string') {
questions.push({
type: 'text',
name: 'username',
message: 'Username:',
stdin: terminal.stdin,
stdout: terminal.stdout,
validate(s) {
return !!s || 'Please enter your username';
}
});
}
if (!argv.password || typeof argv.password !== 'string') {
questions.push({
type: 'password',
name: 'password',
message: 'Password:',
stdin: terminal.stdin,
stdout: terminal.stdout,
validate(s) {
return !!s || 'Please enter your password';
}
});
}
if (questions.length && argv.json) {
throw new Error('--username and --password are required when --json is set');
}
Object.assign(data, await prompt(questions));
if (!argv.json) {
// add a newline after prompting has completed
console.log();
}
}
try {
const { response: account } = await appcd.call('/amplify/1.x/auth/login', { data });
if (argv.json) {
console.log(JSON.stringify(account, null, 2));
} else {
console.log(`You are logged into ${highlight(account.org.name)} as ${highlight(account.user.email || account.name)}.`);
}
} catch (err) {
if (err.code === 'EAUTHENTICATED') {
const { account } = err;
if (argv.json) {
console.log(JSON.stringify(account, null, 2));
} else {
console.log(`You are already logged into ${highlight(account.org.name)} as ${highlight(account.user.email || account.name)}.`);
}
} else if (err.code === 'ERR_AUTH_FAILED') {
console.error(alert(err.message));
exitCode(1);
} else {
throw err;
}
}
}
};
| 29.376238 | 132 | 0.578699 |
297bcc1766316f808d6cd08981f61b9cfb26a4c9 | 4,488 | js | JavaScript | src/index.js | RicostruzioneTrasparente/albopop-facet-search | 1545c0040fd043d938df4d1be5192ef62282c945 | [
"Apache-2.0"
] | 1 | 2019-07-05T17:23:27.000Z | 2019-07-05T17:23:27.000Z | src/index.js | RicostruzioneTrasparente/albopop-facet-search | 1545c0040fd043d938df4d1be5192ef62282c945 | [
"Apache-2.0"
] | 6 | 2017-06-12T08:22:01.000Z | 2017-06-28T22:48:32.000Z | src/index.js | RicostruzioneTrasparente/albopop-facet-search | 1545c0040fd043d938df4d1be5192ef62282c945 | [
"Apache-2.0"
] | null | null | null | /* Nanoflux + RiotJS + Elasticsearch testing */
var riot = require('riot');
var _ = require('lodash');
var NanoFlux = require('nanoflux-fusion'),
fusionStore = NanoFlux.getFusionStore();
var queries = {
es: require("./query/es/run"),
table: require("./query/table/run")
};
var query = queries[window.ES_CONFIG.backend];
var initialState = {
query: { match: "", fields: [], terms: {}, facet: "", size: 10, from: 0, order: [] },
response: { total: 0, items: [], aggs: {} }
};
require('./tags/es-facet/');
var esFacetTags = _.concat(
riot.mount('es-facet-keywords'),
riot.mount('es-facet-datetimes'),
riot.mount('es-facet-numbers')
);
_.forEach(esFacetTags, function(t) {
initialState.query.terms[t.opts.field] = {
type: t.opts.type,
field: t.opts.field,
interval: t.opts.interval,
size: t.opts.size,
order: t.opts.order,
separator: t.opts.separator,
values: []
};
t.on("submit", function(state) {
var tobj = {};
tobj[t.opts.field] = state;
search({ terms: tobj, facet: !_.isEmpty(state.values) ? t.opts.type+':'+t.opts.field : "" });
});
});
require('./tags/es-search/');
var esSearchTags = riot.mount('es-search');
initialState.query.fields = esSearchTags[0].opts.fields || [];
esSearchTags[0].on("submit", function(state) {
search({ match: state.value });
});
require('./tags/es-list/');
var esListTags = riot.mount('es-list');
initialState.query.size = +esListTags[0].opts.size || 10;
initialState.query.order = esListTags[0].opts.order || [];
esListTags[0].on("submit", function(state) {
search({ from: state.value });
});
require('./tags/es-feed/');
var esFeedTags = riot.mount('es-feed');
NanoFlux.createFusionator({
search: function(previousState, args){
var arg = args[0] || {};
return query(
!_.isUndefined(arg.match) ? arg.match : previousState.query.match,
!_.isUndefined(arg.fields) ? arg.fields : previousState.query.fields,
_.defaults(arg.terms || {}, previousState.query.terms),
!_.isUndefined(arg.facet) ? arg.facet : previousState.query.facet,
!_.isUndefined(arg.size) ? arg.size : previousState.query.size,
!_.isUndefined(arg.from) ? arg.from : previousState.query.from,
!_.isUndefined(arg.order) ? arg.order : previousState.query.order
);
}
}, initialState);
var search = NanoFlux.getFusionActor("search");
function fillFacets(newState, currentState, actionName) {
_.forOwn(currentState.response.aggs, function(v,k,o) {
var newFacets = _.fromPairs(_.map(newState.response.aggs[k], function(el) {
return [
el.key,
{
key: el.key,
doc_count: el.doc_count,
active: _.includes(newState.query.terms[k].values,_.toString(el.key))
}
];
}));
var newAggs = [];
_.each(currentState.response.aggs[k], function(v,i) {
newAggs.push(newFacets[v.key] || { key: v.key, doc_count: 0, active: false });
});
newState.response.aggs[k] = newAggs;
});
return newState;
}
fusionStore.use(fillFacets);
var subscription = fusionStore.subscribe(this, function(currentState) {
_.forEach(esListTags, function(t) {
t.update({
opts: _.defaults({
total: currentState.response.total,
items: currentState.response.items
}, t.opts)
});
});
_.forEach(esFacetTags, function(t) {
if (t.opts.type+':'+t.opts.field !== currentState.query.facet) {
t.update({
opts: _.defaults({
items: _.map(currentState.response.aggs[t.opts.field], function(el) {
return {
value: el.key,
count: el.doc_count,
active: el.active
}
}),
missing: Math.abs(currentState.response.total - _.sumBy(currentState.response.aggs[t.opts.field], function(el) { return el.doc_count; }))
}, t.opts)
});
}
});
_.forEach(esFeedTags, function(t) {
t.update({
opts: _.defaults({
data: currentState.query
}, t.opts)
});
});
});
esSearchTags[0].submit();
| 30.120805 | 157 | 0.558601 |
297c048abdba4b7d768d49c33b552360857cf905 | 3,527 | js | JavaScript | frontend/src/components/_dashboard/forum/AddComment.js | ashish-hacker/KHub | 3d8abab5a194f9770b6bb2e797e70c966a674287 | [
"MIT"
] | 1 | 2021-11-27T17:27:54.000Z | 2021-11-27T17:27:54.000Z | frontend/src/components/_dashboard/forum/AddComment.js | ashish-hacker/KHub | 3d8abab5a194f9770b6bb2e797e70c966a674287 | [
"MIT"
] | 13 | 2021-11-11T04:00:31.000Z | 2021-11-27T17:26:05.000Z | frontend/src/components/_dashboard/forum/AddComment.js | ashish-hacker/KHub | 3d8abab5a194f9770b6bb2e797e70c966a674287 | [
"MIT"
] | null | null | null | // react
import * as React from 'react';
import { useEffect, useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import ListSubheader from '@mui/material/ListSubheader';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import TextField from '@mui/material/TextField';
import Select from '@mui/material/Select';
import { LoadingButton } from '@mui/lab';
import { Stack } from '@mui/material';
import axios from 'axios';
require('dotenv').config();
export default function AddPost({ id }) {
const [open, setOpen] = React.useState(false);
const [textContent, setText] = React.useState('');
const [authorName, setAuthor] = React.useState('');
const [isSubmitting, setIsSubmitting] = React.useState(false);
const handleChange = (e) => {
const val = e.target.value;
const nam = e.target.name;
if (nam === 'author') {
setAuthor(val);
} else if (nam === 'text') {
setText(val);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
const reqBody = {
author: authorName,
comment: textContent
};
await axios
.put(`${process.env.REACT_APP_BACKEND_ENDPOINT}/api/posts/comment/${id}`, reqBody)
.then((res) => console.log(res))
.catch((err) => console.log(err));
setIsSubmitting(false);
setOpen(false);
};
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason !== 'backdropClick') {
setOpen(false);
}
};
return (
<div>
<Button onClick={handleClickOpen}>Add Comment</Button>
<Dialog disableEscapeKeyDown open={open} onClose={handleClose}>
<DialogTitle>Add Comment</DialogTitle>
<DialogContent>
<Box
component="form"
sx={{
display: 'flex',
flexWrap: 'wrap',
'& > :not(style)': { m: 1, width: '25ch' }
}}
spacing={2}
>
<TextField
id="outlined-basic"
label="Name"
value={authorName}
name="author"
variant="outlined"
onChange={handleChange}
/>
</Box>
<Stack direction="column" spacing={2}>
<TextField
id="outlined-multiline-flexible"
label="Content"
multiline
maxRows={10}
value={textContent}
name="text"
onChange={handleChange}
/>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
onClick={handleSubmit}
>
Add Comment
</LoadingButton>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
</DialogActions>
</Dialog>
</div>
);
}
| 30.405172 | 89 | 0.55543 |
297c591e7f5aea0f44e6f4129b2bfb74b321c770 | 1,769 | js | JavaScript | src/main/server/controler/resume/competitions.js | weijiafen/antBlog | d560b17d29cf1654815e7c5d40f64c9db396a5ce | [
"MIT"
] | null | null | null | src/main/server/controler/resume/competitions.js | weijiafen/antBlog | d560b17d29cf1654815e7c5d40f64c9db396a5ce | [
"MIT"
] | null | null | null | src/main/server/controler/resume/competitions.js | weijiafen/antBlog | d560b17d29cf1654815e7c5d40f64c9db396a5ce | [
"MIT"
] | null | null | null | var async = require('asyncawait/async');
var await = require('asyncawait/await');
var competitions = require('../../modules/resume/competitions');
var competitions_item=require('../../modules/resume/competitions_item');
module.exports=(async (function(method,req,response){
var result;
var uid=req.session.uid;
if(method==='get'){
var res=await(competitions.findOne({
where:{
userId:uid
}
}))
var competitionId=res.id;
var items=await(competitions_item.findAll({
where:{
competitionId:competitionId
}
}))
var data=[]
items.forEach(function(item,index){
data.push({
id:item.dataValues.id,
itemImg:item.dataValues.itemImg,
itemDate:item.dataValues.itemDate,
itemTxt:item.dataValues.itemTxt
})
})
result={status:0,data:{
id:res.id,
backgroundImg:res.background_img,
isShow:res.isShow,
title:res.title,
color:res.color,
data:data
}};
}
else if(method==='post'){
//先更新项目经验表
var res=await(competitions.update({
isShow:req.body.isShow,
title:req.body.title,
background_img:req.body.backgroundImg,
color:req.body.color
},{
where:{
userId:uid
}
}))
//更新项目数据表
for(var item of req.body.data){
if(item.id!==0){
//更新一个项目
await(competitions_item.update({
itemImg:item.itemImg,
itemDate:item.itemDate,
itemTxt:item.itemTxt,
},{
where:{
id:item.id
}
}))
}else{
//新增一个项目
var p_item=await(competitions_item.create({
competitionId:req.body.id,
itemImg:item.itemImg,
itemDate:item.itemDate,
itemTxt:item.itemTxt
}))
}
}
result={status:0,msg:'保存成功'};
}
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置respons
response.end(JSON.stringify(result))
})) | 22.392405 | 79 | 0.655738 |
297d8ed527fb51cc1c9a0a4f95f7513b8e03c502 | 90 | js | JavaScript | app/helpers/pattern-alphanum.js | collectiveidea/ember-helpers | 61d6bf0bd82c4c8aacef4ddf2cbd6c286c7aa01b | [
"MIT"
] | 1 | 2022-01-05T19:15:16.000Z | 2022-01-05T19:15:16.000Z | app/helpers/pattern-alphanum.js | collectiveidea/ember-helpers | 61d6bf0bd82c4c8aacef4ddf2cbd6c286c7aa01b | [
"MIT"
] | null | null | null | app/helpers/pattern-alphanum.js | collectiveidea/ember-helpers | 61d6bf0bd82c4c8aacef4ddf2cbd6c286c7aa01b | [
"MIT"
] | 1 | 2020-12-13T11:58:14.000Z | 2020-12-13T11:58:14.000Z | export { default, patternAlphanum } from '@abcum/ember-helpers/helpers/pattern-alphanum';
| 45 | 89 | 0.788889 |
297e786154543a733954df7cdc84998e2d2ebdfb | 262 | js | JavaScript | api/rest/health.rest.js | tejas2706/mcreations_server | c7690d7cf7de8b4239eb7e81a4cbb10a07fc2f30 | [
"MIT"
] | null | null | null | api/rest/health.rest.js | tejas2706/mcreations_server | c7690d7cf7de8b4239eb7e81a4cbb10a07fc2f30 | [
"MIT"
] | null | null | null | api/rest/health.rest.js | tejas2706/mcreations_server | c7690d7cf7de8b4239eb7e81a4cbb10a07fc2f30 | [
"MIT"
] | null | null | null | var serviceHandler = require('../serviceHandler.js').serviceHandler;
module.exports.init = function (app) {
app.get('/health', function(req, res){
let p = Promise.resolve({"success": "ok"});
return serviceHandler(req, res, p)
});
};
| 29.111111 | 72 | 0.618321 |
297eebfb0e299f6ce021df6564eaffb04cebd262 | 1,176 | js | JavaScript | Token/dependencies.js | austintgriffith/Pyth.io | f9c04e3f0e3052210b433cce6ed1bd9e3f4a98a4 | [
"MIT"
] | 5 | 2018-01-27T00:05:46.000Z | 2020-02-18T16:35:18.000Z | Token/dependencies.js | austintgriffith/concurrence.io | f9c04e3f0e3052210b433cce6ed1bd9e3f4a98a4 | [
"MIT"
] | null | null | null | Token/dependencies.js | austintgriffith/concurrence.io | f9c04e3f0e3052210b433cce6ed1bd9e3f4a98a4 | [
"MIT"
] | null | null | null | const fs = require('fs');
module.exports = {
'zeppelin-solidity/contracts/ownership/Ownable.sol': fs.readFileSync('zeppelin-solidity/contracts/ownership/Ownable.sol', 'utf8'),
'zeppelin-solidity/contracts/ownership/HasNoEther.sol': fs.readFileSync('zeppelin-solidity/contracts/ownership/HasNoEther.sol', 'utf8'),
'zeppelin-solidity/contracts/ownership/Contactable.sol': fs.readFileSync('zeppelin-solidity/contracts/ownership/Contactable.sol', 'utf8'),
'zeppelin-solidity/contracts/math/SafeMath.sol': fs.readFileSync('zeppelin-solidity/contracts/math/SafeMath.sol', 'utf8'),
'zeppelin-solidity/contracts/token/ERC20.sol': fs.readFileSync('zeppelin-solidity/contracts/token/ERC20.sol', 'utf8'),
'zeppelin-solidity/contracts/token/ERC20Basic.sol': fs.readFileSync('zeppelin-solidity/contracts/token/ERC20Basic.sol', 'utf8'),
'zeppelin-solidity/contracts/token/BasicToken.sol': fs.readFileSync('zeppelin-solidity/contracts/token/BasicToken.sol', 'utf8'),
'zeppelin-solidity/contracts/token/StandardToken.sol': fs.readFileSync('zeppelin-solidity/contracts/token/StandardToken.sol', 'utf8'),
'Addressed.sol': fs.readFileSync('Addressed/Addressed.sol', 'utf8')
};
| 90.461538 | 140 | 0.784014 |
297efc9c872f031a8bd9a6e5ac236d745f4e4f67 | 884 | js | JavaScript | lib/routes/objects.js | Caellian/node-git-lfs | 884d55814d13f852bc79afebc10dc8801c920392 | [
"Apache-2.0"
] | null | null | null | lib/routes/objects.js | Caellian/node-git-lfs | 884d55814d13f852bc79afebc10dc8801c920392 | [
"Apache-2.0"
] | 3 | 2019-07-16T23:47:06.000Z | 2021-09-10T21:01:18.000Z | lib/routes/objects.js | Caellian/node-git-lfs | 884d55814d13f852bc79afebc10dc8801c920392 | [
"Apache-2.0"
] | 1 | 2019-12-04T11:38:14.000Z | 2019-12-04T11:38:14.000Z | 'use strict';
const Router = require('express-promise-router');
const checkJWT = require('../middleware/checkJWT')
const router = new Router();
const routerConstructor = (store) => {
router.put('/:user/:repo/objects/:oid', checkJWT('upload'), async (req, res, next) => {
await store.put(req.params.user, req.params.repo, req.params.oid, req);
res.sendStatus(200);
});
router.get('/:user/:repo/objects/:oid', checkJWT('download'), async (req, res, next) => {
var size = await store.getSize(req.params.user, req.params.repo, req.params.oid);
if (size < 0) {
return res.sendStatus(404);
}
res.set('Content-Length', size);
var dataStream = await store.get(req.params.user, req.params.repo, req.params.oid);
dataStream.pipe(res);
});
return router;
}
module.exports = routerConstructor;
| 31.571429 | 93 | 0.625566 |
297fa3e0199e6ee4914bde1f4bfd9e5b46e687cf | 7,181 | js | JavaScript | components/authorize/authorize.js | pengshangxian/wujie | 6cdc1aac0f16fb9e858ad794e670e1539407f601 | [
"MIT"
] | null | null | null | components/authorize/authorize.js | pengshangxian/wujie | 6cdc1aac0f16fb9e858ad794e670e1539407f601 | [
"MIT"
] | null | null | null | components/authorize/authorize.js | pengshangxian/wujie | 6cdc1aac0f16fb9e858ad794e670e1539407f601 | [
"MIT"
] | null | null | null | import Util from '../../utils/util.js';
import {
login
} from '../../api/login.js';
let app = getApp();
Component({
properties: {
iShidden: {
type: Boolean,
value: true,
},
//是否自动登录
isAuto: {
type: Boolean,
value: true,
},
isGoIndex: {
type: Boolean,
value: true,
},
goodId: {
type: String,
value: '',
},
invitenum: {
type: String,
value: '',
},
},
data: {
cloneIner: null,
loading: false,
errorSum: 0,
errorNum: 3
},
attached() {
//this.get_logo_url();
this.setAuthStatus();
},
methods: {
close() {
let pages = getCurrentPages();
let currPage = pages[pages.length - 1];
if (this.data.isGoIndex) {
wx.switchTab({
url: '/pages/wujieindex/wujieindex'
});
} else {
this.setData({
iShidden: true
});
if (currPage && currPage.data.iShidden != undefined) {
currPage.setData({
iShidden: true
});
}
}
},
// get_logo_url: function () {
// var that = this;
// if (wx.getStorageSync('logo_url')) return this.setData({ logo_url: wx.getStorageSync('logo_url') });
// getLogo().then(res => {
// wx.setStorageSync('logo_url', res.data.logo_url);
// that.setData({ logo_url: res.data.logo_url });
// });
// },
//检测登录状态并执行自动登录
setAuthStatus() {
var that = this;
Util.chekWxLogin().then((res) => {
let pages = getCurrentPages();
let currPage = pages[pages.length - 1];
if (currPage && currPage.data.iShidden != undefined) {
currPage.setData({
iShidden: true
});
}
console.log(res)
if (res.isLogin) {
if (!Util.checkLogin()) return Promise.reject({
authSetting: true,
msg: '用户token失效',
userInfo: res.userInfo
});
// that.triggerEvent('onLoadFun', app.globalData.userInfo);
} else {
console.log(app.globalData)
// if (wx.getStorageSync("isLog") == true) {
// return
// }
// wx.showLoading({
// title: '正在登录中'
// });
that.setUserInfo(res.userInfo, true);
}
}).catch(res => {
if (res.authSetting === false) {
//没有授权不会自动弹出登录框
if (that.data.isAuto === false) return;
//自动弹出授权
//that.setData({ iShidden: false });
console.log("test" + that.data.goodId);
// wx.navigateTo({
// url: `/pages/login/login?invitenum=${that.data.invitenum}`
// });
// if (that.data.goodId) {
// wx.navigateTo({
// url: '/pages/login/login'
// });
// return;
// } else {
// console.log(111)
// wx.navigateTo({
// url: '/pages/login/login'
// });
// return;
// }
} else if (res.authSetting) {
//授权后登录token失效了
that.setUserInfo(res.userInfo);
}
})
},
//授权
setUserInfo(userInfo, isLogin) {
let that = this;
// wx.showLoading({
// title: '正在登录中'
// });
if (isLogin) {
console.log("正在登录中1");
that.getWxUserInfo(userInfo);
} else {
console.log("正在登录中2");
Util.getCodeLogin((res) => {
Util.wxgetUserInfo().then(userInfo => {
userInfo.code = res.code;
that.getWxUserInfo(userInfo);
}).catch(res => {
wx.hideLoading();
});
});
}
},
getWxUserInfo: function(userInfo) {
let that = this;
// wx.getUserInfo({
// success(res) {
// app.getUserInfo();
// app.globalData.userInfo = e.detail.userInfo
// that.setData({
// userInfo: e.detail.userInfo,
// hasUserInfo: true
// })
// console.log(res)
// // wx.switchTab({
// // url: '../wujieindex/wujieindex',
// // })
// console.log(e.detail.userInfo)
// if (e.detail.userInfo) {
// setTimeout(() => {
// console.log(wx.getStorageSync('hasphone'))
// if (wx.getStorageSync('hasphone') == "true") {
// // //取消登录提示
// wx.hideLoading();
// } else {
// wx.navigateTo({
// url: '../getphonenumber/getphonenumber'
// })
// }
// }, 500)
// }
// },
// fail(res) {
// console.log(111)
// }
// })
console.log(wx.getStorageSync("isLog"))
login({
code: userInfo.code.code
}).then(res => {
console.log(res)
app.globalData.token = res.data.sessionId;
wx.setStorageSync("token", res.data.sessionId)
wx.setStorageSync("sessionId", res.data.sessionId)
wx.setStorageSync('userid', res.data.UserPhone)
wx.setStorageSync('RePecent', res.data.RePecent);
wx.setStorageSync('RatePecent', res.data.RatePecent);
wx.setStorageSync('OrdinaryRePecent', res.data.OrdinaryRePecent);
wx.setStorageSync('sig', res.data.IMSign)
wx.setStorageSync('MemID', res.data.MemID)
wx.setStorageSync('isnew', res.data.IsNewPerson)
// wx.setStorageSync('isnew', true)
app.globalData.isnew = res.data.IsNewPerson
app.globalData.isLog = true;
wx.setStorageSync("isLog", true)
app.globalData.userInfo = res.data;
console.log(app.globalData.userInfo)
// app.globalData.expiresTime = res.data.expires_time;
// wx.setStorageSync(CACHE_TOKEN, res.data.Token);
// wx.setStorageSync(CACHE_EXPIRES_TIME, res.data.expires_time);
// wx.setStorageSync(CACHE_USERINFO, JSON.stringify(res.data.userInfo));
// let promise = app.globalData.tim.login({
// userID: res.data.UserPhone,
// userSig: res.data.IMSign
// });
// promise.then(function(imResponse) {
// console.log(imResponse.data); // 登录成功
// }).catch(function(imError) {
// console.warn('login error:', imError); // 登录失败的相关信息
// });
if (res.data.cache_key) wx.setStorage({
key: 'cache_key',
data: res.data.cache_key
});
//取消登录提示
wx.hideLoading();
//关闭登录弹出窗口
that.setData({
iShidden: true,
errorSum: 0
});
//执行登录完成回调
// that.triggerEvent('onLoadFun', app.globalData.userInfo);
}).catch((err) => {
console.log(err);
wx.hideLoading();
that.data.errorSum++;
that.setData({
errorSum: that.data.errorSum
});
if (that.data.errorSum >= that.data.errorNum) {
// wx.showToast({
// title: err,
// })
Util.toast(err)
} else {
that.setUserInfo(userInfo);
}
});
}
},
}) | 28.724 | 109 | 0.4906 |
297ff4a716b748311581aeb9a3b3b6c00b9c3423 | 4,574 | js | JavaScript | data/split-book-data/1974981649.1654714041543.js | Ninjalord-25/NinjasLibrary | 9ee39e182ec59f091c6696b360bc339e35108a10 | [
"0BSD"
] | null | null | null | data/split-book-data/1974981649.1654714041543.js | Ninjalord-25/NinjasLibrary | 9ee39e182ec59f091c6696b360bc339e35108a10 | [
"0BSD"
] | null | null | null | data/split-book-data/1974981649.1654714041543.js | Ninjalord-25/NinjasLibrary | 9ee39e182ec59f091c6696b360bc339e35108a10 | [
"0BSD"
] | null | null | null | window.peopleAlsoBoughtJSON = [{"asin":"166200768X","authors":"Avery Flynn","cover":"51h3iwJ9EHL","length":"6 hrs and 13 mins","narrators":"Kelsey Navarro, Tim Paige","title":"Loud Mouth"},{"asin":"B09F19SCJL","authors":"Avery Flynn","cover":"51sUopQTSRL","length":"7 hrs and 56 mins","narrators":"Avery Reid, Tim Paige","subHeading":"The Last Man Standing Series, Book 1","title":"Mama’s Boy"},{"asin":"B002UZJXE2","authors":"Rachel Gibson","cover":"415PNUTgujL","length":"8 hrs and 36 mins","narrators":"Nicole Poole","title":"Tangled Up in You"},{"asin":"B09J5CYWVD","authors":"Pippa Grant","cover":"51AXX4l7swL","length":"22 hrs and 15 mins","narrators":"Ava Erickson, Aiden Snow, Erin Mallon, and others","title":"The Copper Valley Thrusters Origin Series"},{"asin":"B09KW3GYWS","authors":"Penny Reid","cover":"51Z4c8dqC0L","length":"11 hrs and 36 mins","narrators":"Chris Brinkley, Cielo Camargo","subHeading":"Good Folk, Book 1","title":"Totally Folked"},{"asin":"1543686680","authors":"Avery Flynn","cover":"41GS3aVapWL","length":"7 hrs and 45 mins","narrators":"Brian Pallino, Savannah Peachwood","subHeading":"The Hartigans, Book 1","title":"Butterface"},{"asin":"B074KHXZ2R","authors":"Avery Flynn","cover":"518ywvV8XxL","length":"7 hrs and 55 mins","narrators":"Stephanie Rose","title":"The Negotiator"},{"asin":"1705266843","authors":"Avery Flynn","cover":"511buGmGQcL","length":"5 hrs and 47 mins","narrators":"Charlotte North","subHeading":"Sweet Salvation Brewery Series, Book 1","title":"Enemies on Tap"},{"asin":"1705266924","authors":"Avery Flynn","cover":"51XG1YP+j2S","length":"6 hrs and 14 mins","narrators":"Amelie Griffin","subHeading":"Killer Style Series, Book 1","title":"Killer Temptation"},{"asin":"1664789235","authors":"Avery Flynn","cover":"511l8e-VrRL","length":"6 hrs and 44 mins","narrators":"John Lane","subHeading":"The Instantly Royal Series, Book 1","title":"Royal Bastard"},{"asin":"1705266800","authors":"Avery Flynn","cover":"51lwY32HNgL","length":"5 hrs and 10 mins","narrators":"Summer Roberts","subHeading":"Tempt Me Series, Book 1","title":"His Undercover Princess"},{"asin":"1664729399","authors":"Avery Flynn","cover":"51YuN5XcQTL","length":"8 hrs and 36 mins","narrators":"Kelsey Navarro","subHeading":"The Double Dilemma Series, Book 1","title":"The Wedding Date Disaster"},{"asin":"B09NRWSSQ9","authors":"Vi Keeland","cover":"51UV83ypEWL","length":"8 hrs and 57 mins","narrators":"Sebastian York, Andi Arndt","title":"The Summer Proposal"},{"asin":"B09J9D3Q39","authors":"Meghan Quinn","cover":"51SDYlRj2kL","length":"11 hrs and 53 mins","narrators":"Ava Erickson, Aaron Shedlock","title":"A Not So Meet Cute"},{"asin":"1094083925","authors":"Monica Murphy","cover":"51UMQtziskL","length":"9 hrs and 10 mins","narrators":"Ava Lucas, Jack DuPont","title":"Save the Date"},{"asin":"B01N7EZPKG","authors":"Mira Lyn Kelly","cover":"51Wl1W2tEVL","length":"10 hrs and 9 mins","narrators":"Seraphine Valentine, Tad Branson","subHeading":"Best Men, Book 1","title":"May the Best Man Win"},{"asin":"B09NWC6QYK","authors":"Meghan Quinn","cover":"51wL9zFaXKL","length":"14 hrs and 4 mins","narrators":"Vanessa Edwin, John Hartley","title":"Put Me in Detention"},{"asin":"B09NMR5V5L","authors":"Jolie Day","cover":"51trAMCen8L","length":"11 hrs and 20 mins","narrators":"Jason Clarke, Samantha Brentmoor","title":"Faking It with the Billionaire Next Door"}];
window.bookSummaryJSON = "<p>One night and my life completely jumped the tracks. Actually, a pack of expired condoms did that - the rest of the night was pretty amazing. Open bar at a friend's wedding. Bad dancing all around. Stupid trivia bets with my fellow Ice Knights hockey teammates. And Tess Gardner. The factoid-blurting, fandom-T-shirt-wearing, no-I-don’t-want-a-relationship-with-you woman makes me forget for one night that I’m a man with a routine and my future all mapped out. Still, it sucked she left our room without giving me her number. </p> <p>Fast-forward to when she tracks me down and tells me I'm going to be a daddy. Jaw, meet floor. Now I've insisted that she and our little peach pit move in with me after her apartment floods. She agrees as long as there’s no funny business, no shotgun weddings, and no more nights spent naked together. Sounds easy enough. I was prepared for the late-night runs for more pickles and peanut butter, but I wasn’t prepared for Tess. She’s like a glitter rainbow sparkling in the middle of my all-neutrals house, messing up my rigid schedule and turning my world upside down. What the hell do we do next?</p>";
| 1,524.666667 | 3,398 | 0.727153 |
29819aa9794e280b48fd72de4689dd73e2d69eb6 | 2,945 | js | JavaScript | lib/es6_global/src/service/state/editor/asset/IndexAssetEditorService.js | phlahut/Wonder-Editor | 4623e8a24f0d1506da5acae0f3dae90acc4c4ad6 | [
"Apache-2.0"
] | 1 | 2019-03-12T05:50:08.000Z | 2019-03-12T05:50:08.000Z | lib/es6_global/src/service/state/editor/asset/IndexAssetEditorService.js | phlahut/Wonder-Editor | 4623e8a24f0d1506da5acae0f3dae90acc4c4ad6 | [
"Apache-2.0"
] | null | null | null | lib/es6_global/src/service/state/editor/asset/IndexAssetEditorService.js | phlahut/Wonder-Editor | 4623e8a24f0d1506da5acae0f3dae90acc4c4ad6 | [
"Apache-2.0"
] | null | null | null |
import * as IndexAssetService$WonderEditor from "../../../record/editor/asset/IndexAssetService.js";
function getNodeIndex(editorState) {
return IndexAssetService$WonderEditor.getNodeIndex(editorState[/* assetRecord */2]);
}
function setNodeIndex(index, editorState) {
return /* record */[
/* settingRecord */editorState[/* settingRecord */0],
/* sceneTreeRecord */editorState[/* sceneTreeRecord */1],
/* assetRecord */IndexAssetService$WonderEditor.setNodeIndex(index, editorState[/* assetRecord */2]),
/* sceneViewRecord */editorState[/* sceneViewRecord */3],
/* gameViewRecord */editorState[/* gameViewRecord */4],
/* eventRecord */editorState[/* eventRecord */5],
/* imguiRecord */editorState[/* imguiRecord */6],
/* inspectorRecord */editorState[/* inspectorRecord */7],
/* consoleRecord */editorState[/* consoleRecord */8],
/* transformRecord */editorState[/* transformRecord */9],
/* pickingRecord */editorState[/* pickingRecord */10],
/* currentDragSource */editorState[/* currentDragSource */11],
/* currentSelectSource */editorState[/* currentSelectSource */12],
/* loopId */editorState[/* loopId */13]
];
}
function getImageDataMapIndex(editorState) {
return IndexAssetService$WonderEditor.getImageDataMapIndex(editorState[/* assetRecord */2]);
}
function setImageDataMapIndex(index, editorState) {
return /* record */[
/* settingRecord */editorState[/* settingRecord */0],
/* sceneTreeRecord */editorState[/* sceneTreeRecord */1],
/* assetRecord */IndexAssetService$WonderEditor.setImageDataMapIndex(index, editorState[/* assetRecord */2]),
/* sceneViewRecord */editorState[/* sceneViewRecord */3],
/* gameViewRecord */editorState[/* gameViewRecord */4],
/* eventRecord */editorState[/* eventRecord */5],
/* imguiRecord */editorState[/* imguiRecord */6],
/* inspectorRecord */editorState[/* inspectorRecord */7],
/* consoleRecord */editorState[/* consoleRecord */8],
/* transformRecord */editorState[/* transformRecord */9],
/* pickingRecord */editorState[/* pickingRecord */10],
/* currentDragSource */editorState[/* currentDragSource */11],
/* currentSelectSource */editorState[/* currentSelectSource */12],
/* loopId */editorState[/* loopId */13]
];
}
function generateImageDataMapIndex(editorState) {
var match = IndexAssetService$WonderEditor.generateImageDataMapIndex(IndexAssetService$WonderEditor.getImageDataMapIndex(editorState[/* assetRecord */2]));
return /* tuple */[
setImageDataMapIndex(match[0], editorState),
match[1]
];
}
export {
getNodeIndex ,
setNodeIndex ,
getImageDataMapIndex ,
setImageDataMapIndex ,
generateImageDataMapIndex ,
}
/* No side effect */
| 43.308824 | 157 | 0.656706 |
2982083e81f01e36d27b4c654fe339d998361ee5 | 96,972 | js | JavaScript | public/assets/js/15.b99e53fa.js | Chivas-Regal/test | 7c4dc437fe86dc0d3b9f150113a28a15cea7a3a8 | [
"MIT"
] | null | null | null | public/assets/js/15.b99e53fa.js | Chivas-Regal/test | 7c4dc437fe86dc0d3b9f150113a28a15cea7a3a8 | [
"MIT"
] | 4 | 2022-01-21T07:11:43.000Z | 2022-01-21T07:36:57.000Z | public/assets/js/15.b99e53fa.js | Chivas-Regal/test | 7c4dc437fe86dc0d3b9f150113a28a15cea7a3a8 | [
"MIT"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[15],{588:function(t,a,s){"use strict";s.r(a);var n=s(5),e=function(t){t.options.__data__block__={mermaid_382ee149:"\ngraph TB;\n1 ==>|4| 2\n1 --\x3e|5| 3\n2 --\x3e|6| 4\n2 ==>|2| 5\n5 ==>|3| 9\n3 ==>|1| 6\n3 --\x3e|6| 7\n3 --\x3e|9| 8\n6 ==>|3| 10\n\n"}},r=Object(n.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h2",{attrs:{id:"定义"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#定义"}},[t._v("#")]),t._v(" 定义")]),t._v(" "),s("p",[t._v("将树剖分成一条条不相交的从祖先到子孙的链")]),t._v(" "),s("p",[t._v("设 "),s("code",[t._v("size[x]")]),t._v(" 表示 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 点的子树大小"),s("br"),t._v(" "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("s")]),s("mi",[t._v("i")]),s("mi",[t._v("z")]),s("mi",[t._v("e")]),s("mo",{attrs:{stretchy:"false"}},[t._v("[")]),s("mi",[t._v("x")]),s("mo",{attrs:{stretchy:"false"}},[t._v("]")]),s("mo",[t._v("=")]),s("mn",[t._v("1")]),s("mo",[t._v("+")]),s("munder",[s("mo",[t._v("∑")]),s("mrow",[s("mi",[t._v("y")]),s("mo",[t._v("∈")]),s("mo",{attrs:{stretchy:"false"}},[t._v("{")]),s("msup",[s("mi",[t._v("x")]),s("mo",{attrs:{mathvariant:"normal",lspace:"0em",rspace:"0em"}},[t._v("′")])],1),s("mi",[t._v("s")]),s("mtext"),s("mi",[t._v("s")]),s("mi",[t._v("o")]),s("mi",[t._v("n")]),s("mo",{attrs:{stretchy:"false"}},[t._v("}")])],1)],1),s("mi",[t._v("s")]),s("mi",[t._v("i")]),s("mi",[t._v("z")]),s("mi",[t._v("e")]),s("mo",{attrs:{stretchy:"false"}},[t._v("[")]),s("mi",[t._v("y")]),s("mo",{attrs:{stretchy:"false"}},[t._v("]")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("size[x] = 1 + \\sum\\limits_{y\\in\\{x's\\;son\\}}size[y]")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("s")]),s("span",{staticClass:"mord mathnormal"},[t._v("i")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")]),s("span",{staticClass:"mord mathnormal"},[t._v("e")]),s("span",{staticClass:"mopen"},[t._v("[")]),s("span",{staticClass:"mord mathnormal"},[t._v("x")]),s("span",{staticClass:"mclose"},[t._v("]")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mrel"},[t._v("=")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}})]),s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.72777em","vertical-align":"-0.08333em"}}),s("span",{staticClass:"mord"},[t._v("1")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2222222222222222em"}}),s("span",{staticClass:"mbin"},[t._v("+")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2222222222222222em"}})]),s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1.9660100000000003em","vertical-align":"-1.216005em"}}),s("span",{staticClass:"mop op-limits"},[s("span",{staticClass:"vlist-t vlist-t2"},[s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"0.7500050000000001em"}},[s("span",{staticStyle:{top:"-2.058995em","margin-left":"0em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",{staticClass:"sizing reset-size6 size3 mtight"},[s("span",{staticClass:"mord mtight"},[s("span",{staticClass:"mord mathnormal mtight",staticStyle:{"margin-right":"0.03588em"}},[t._v("y")]),s("span",{staticClass:"mrel mtight"},[t._v("∈")]),s("span",{staticClass:"mopen mtight"},[t._v("{")]),s("span",{staticClass:"mord mtight"},[s("span",{staticClass:"mord mathnormal mtight"},[t._v("x")]),s("span",{staticClass:"msupsub"},[s("span",{staticClass:"vlist-t"},[s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"0.6828285714285715em"}},[s("span",{staticStyle:{top:"-2.786em","margin-right":"0.07142857142857144em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"2.5em"}}),s("span",{staticClass:"sizing reset-size3 size1 mtight"},[s("span",{staticClass:"mord mtight"},[s("span",{staticClass:"mord mtight"},[t._v("′")])])])])])])])])]),s("span",{staticClass:"mord mathnormal mtight"},[t._v("s")]),s("span",{staticClass:"mspace mtight",staticStyle:{"margin-right":"0.3252777777777778em"}}),s("span",{staticClass:"mord mathnormal mtight"},[t._v("s")]),s("span",{staticClass:"mord mathnormal mtight"},[t._v("o")]),s("span",{staticClass:"mord mathnormal mtight"},[t._v("n")]),s("span",{staticClass:"mclose mtight"},[t._v("}")])])])]),s("span",{staticStyle:{top:"-3.0000050000000003em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",[s("span",{staticClass:"mop op-symbol small-op"},[t._v("∑")])])])]),s("span",{staticClass:"vlist-s"},[t._v("")])]),s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"1.216005em"}},[s("span")])])])]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.16666666666666666em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("s")]),s("span",{staticClass:"mord mathnormal"},[t._v("i")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")]),s("span",{staticClass:"mord mathnormal"},[t._v("e")]),s("span",{staticClass:"mopen"},[t._v("[")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("y")]),s("span",{staticClass:"mclose"},[t._v("]")])])])])]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"title"}),s("p",[t._v("重儿子:一个点的子节点中 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("s")]),s("mi",[t._v("i")]),s("mi",[t._v("z")]),s("mi",[t._v("e")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("size")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.65952em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("s")]),s("span",{staticClass:"mord mathnormal"},[t._v("i")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")]),s("span",{staticClass:"mord mathnormal"},[t._v("e")])])])]),t._v(" 最大的儿子"),s("br"),t._v("\n轻儿子:一个点的子节点中 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("s")]),s("mi",[t._v("i")]),s("mi",[t._v("z")]),s("mi",[t._v("e")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("size")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.65952em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("s")]),s("span",{staticClass:"mord mathnormal"},[t._v("i")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")]),s("span",{staticClass:"mord mathnormal"},[t._v("e")])])])]),t._v(" 不是最大的儿子"),s("br"),t._v("\n重边:连接 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 和 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 重儿子的边"),s("br"),t._v("\n轻边:连接 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 和 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 轻儿子的边"),s("br"),t._v("\n重链:重边连起来形成的链。每个点恰好属于一条重边")])]),s("Mermaid",{attrs:{id:"mermaid_382ee149",graph:t.$dataBlock.mermaid_382ee149}}),s("p",[t._v("图中有五条重链:"),s("br"),t._v(" "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mtable",{attrs:{rowspacing:"0.24999999999999992em",columnalign:"right left",columnspacing:"0em"}},[s("mtr",[s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow")],1)],1),s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow",[s("mrow"),s("mn",[t._v("1")]),s("mo",[t._v("→")]),s("mn",[t._v("3")]),s("mo",[t._v("→")]),s("mn",[t._v("6")]),s("mo",[t._v("→")]),s("mn",[t._v("10")])],1)],1)],1)],1),s("mtr",[s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow")],1)],1),s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow",[s("mrow"),s("mn",[t._v("2")]),s("mo",[t._v("→")]),s("mn",[t._v("5")]),s("mo",[t._v("→")]),s("mn",[t._v("9")])],1)],1)],1)],1),s("mtr",[s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow")],1)],1),s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow",[s("mrow"),s("mn",[t._v("4")])],1)],1)],1)],1),s("mtr",[s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow")],1)],1),s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow",[s("mrow"),s("mn",[t._v("7")])],1)],1)],1)],1),s("mtr",[s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow")],1)],1),s("mtd",[s("mstyle",{attrs:{scriptlevel:"0",displaystyle:"true"}},[s("mrow",[s("mrow"),s("mn",[t._v("8")])],1)],1)],1)],1)],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("\\begin{aligned}\n&1\\rightarrow3\\rightarrow6\\rightarrow10\\\\\n&2\\rightarrow5\\rightarrow9\\\\\n&4\\\\\n&7\\\\\n&8\\\\ \n\\end{aligned}")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"7.500000000000002em","vertical-align":"-3.5000000000000018em"}}),s("span",{staticClass:"mord"},[s("span",{staticClass:"mtable"},[s("span",{staticClass:"col-align-r"},[s("span",{staticClass:"vlist-t vlist-t2"},[s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"4em"}},[s("span",{staticStyle:{top:"-6em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"2.84em"}}),s("span",{staticClass:"mord"})]),s("span",{staticStyle:{top:"-4.499999999999999em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"2.84em"}}),s("span",{staticClass:"mord"})]),s("span",{staticStyle:{top:"-2.9999999999999982em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"2.84em"}}),s("span",{staticClass:"mord"})]),s("span",{staticStyle:{top:"-1.4999999999999982em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"2.84em"}}),s("span",{staticClass:"mord"})]),s("span",{staticStyle:{top:"1.7763568394002505e-15em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"2.84em"}}),s("span",{staticClass:"mord"})])]),s("span",{staticClass:"vlist-s"},[t._v("")])]),s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"3.5000000000000018em"}},[s("span")])])])]),s("span",{staticClass:"col-align-l"},[s("span",{staticClass:"vlist-t vlist-t2"},[s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"4em"}},[s("span",{staticStyle:{top:"-6.16em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",{staticClass:"mord"},[s("span",{staticClass:"mord"}),s("span",{staticClass:"mord"},[t._v("1")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mrel"},[t._v("→")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mord"},[t._v("3")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mrel"},[t._v("→")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mord"},[t._v("6")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mrel"},[t._v("→")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mord"},[t._v("1")]),s("span",{staticClass:"mord"},[t._v("0")])])]),s("span",{staticStyle:{top:"-4.659999999999999em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",{staticClass:"mord"},[s("span",{staticClass:"mord"}),s("span",{staticClass:"mord"},[t._v("2")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mrel"},[t._v("→")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mord"},[t._v("5")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mrel"},[t._v("→")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2777777777777778em"}}),s("span",{staticClass:"mord"},[t._v("9")])])]),s("span",{staticStyle:{top:"-3.1599999999999984em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",{staticClass:"mord"},[s("span",{staticClass:"mord"}),s("span",{staticClass:"mord"},[t._v("4")])])]),s("span",{staticStyle:{top:"-1.6599999999999984em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",{staticClass:"mord"},[s("span",{staticClass:"mord"}),s("span",{staticClass:"mord"},[t._v("7")])])]),s("span",{staticStyle:{top:"-0.15999999999999837em"}},[s("span",{staticClass:"pstrut",staticStyle:{height:"3em"}}),s("span",{staticClass:"mord"},[s("span",{staticClass:"mord"}),s("span",{staticClass:"mord"},[t._v("8")])])])]),s("span",{staticClass:"vlist-s"},[t._v("")])]),s("span",{staticClass:"vlist-r"},[s("span",{staticClass:"vlist",staticStyle:{height:"3.5000000000000018em"}},[s("span")])])])])])])])])])]),t._v(" "),s("p",[t._v("可以发现,每个轻边指向的一个点,都是一条新的重链的开始")]),t._v(" "),s("h2",{attrs:{id:"过程"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#过程"}},[t._v("#")]),t._v(" 过程")]),t._v(" "),s("p",[t._v("预处理出 "),s("code",[t._v("d[x]")]),t._v(" 表示 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 的深度"),s("br"),t._v("\n预处理出 "),s("code",[t._v("f[x]")]),t._v(" 表示 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 的父亲"),s("br"),t._v("\n预处理出 "),s("code",[t._v("size[x]")]),t._v(" 表示以 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 点为跟的子树大小"),s("br"),t._v("\n预处理出 "),s("code",[t._v("son[x]")]),t._v(" 表示 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 的重儿子"),s("br"),t._v("\n预处理出 "),s("code",[t._v("top[x]")]),t._v(" 表示 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 所在的重链顶端"),s("br"),t._v("\n成对记忆:大小{大小、深度},亲情{父亲、重儿子},"),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("t")]),s("mi",[t._v("o")]),s("mi",[t._v("p")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("top")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.80952em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("t")]),s("span",{staticClass:"mord mathnormal"},[t._v("o")]),s("span",{staticClass:"mord mathnormal"},[t._v("p")])])])])]),t._v(" "),s("p",[t._v("预处理出可以通过两边 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 在 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("O")]),s("mo",{attrs:{stretchy:"false"}},[t._v("(")]),s("mi",[t._v("n")]),s("mo",{attrs:{stretchy:"false"}},[t._v(")")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("O(n)")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("O")]),s("span",{staticClass:"mopen"},[t._v("(")]),s("span",{staticClass:"mord mathnormal"},[t._v("n")]),s("span",{staticClass:"mclose"},[t._v(")")])])])]),t._v(" 时间内完成"),s("br"),t._v("\n第一遍 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 算出 "),s("code",[t._v("size[x],d[x],f[x]")]),t._v(" ,并找到重儿子 "),s("code",[t._v("son[x]")]),s("br"),t._v("\n第二遍算出 "),s("code",[t._v("top[x]")]),t._v(" ,"),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 和 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 的重儿子的 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("t")]),s("mi",[t._v("o")]),s("mi",[t._v("p")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("top")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.80952em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("t")]),s("span",{staticClass:"mord mathnormal"},[t._v("o")]),s("span",{staticClass:"mord mathnormal"},[t._v("p")])])])]),t._v(" 相同")]),t._v(" "),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//f和d正序就能推出,而size和son都是跟孩子有关,要后序回溯出来")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//所以f、d正序用父亲,size、son回溯用儿子")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("void")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" fath"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n size"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("fath"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//d[0] = 0, 根节点深度+1")]),t._v("\n son"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" f"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" fath"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//根节点编号为1,0表示不存在")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("for")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" i "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" head"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("~")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" i "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("nxt"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" to "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("to "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("==")]),t._v(" fath"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("continue")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//如果往上走了(链式前向星的问题,无法准确寻找的到底是父亲还是儿子)就不计")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n size"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+=")]),t._v(" size"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("size"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("son"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" size"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" son"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br"),s("span",{staticClass:"line-number"},[t._v("7")]),s("br"),s("span",{staticClass:"line-number"},[t._v("8")]),s("br"),s("span",{staticClass:"line-number"},[t._v("9")]),s("br"),s("span",{staticClass:"line-number"},[t._v("10")]),s("br"),s("span",{staticClass:"line-number"},[t._v("11")]),s("br"),s("span",{staticClass:"line-number"},[t._v("12")]),s("br"),s("span",{staticClass:"line-number"},[t._v("13")]),s("br")])]),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("void")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" topx"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" topx"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("son"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("son"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" topx"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//最开始的时候访问的序列是以x为top的这条重链")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("for")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" i "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" head"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("~")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" i "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("nxt"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("to "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!=")]),t._v(" f"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("to "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!=")]),t._v(" son"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//只处理x的轻儿子")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" edge"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("i"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("to"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//开启一个新重链")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("main")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br"),s("span",{staticClass:"line-number"},[t._v("7")]),s("br"),s("span",{staticClass:"line-number"},[t._v("8")]),s("br")])]),s("h2",{attrs:{id:"最近公共祖先"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#最近公共祖先"}},[t._v("#")]),t._v(" 最近公共祖先")]),t._v(" "),s("h3",{attrs:{id:"定义-2"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#定义-2"}},[t._v("#")]),t._v(" 定义")]),t._v(" "),s("ul",[s("li",[t._v("深度:有根树上x到根的距离")]),t._v(" "),s("li",[s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")])])])]),t._v(":"),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("u")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("u")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("u")])])])]),t._v(" 和 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("b")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("b")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.69444em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("b")])])])]),t._v(" 的最近公共祖先 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")]),s("mo",{attrs:{stretchy:"false"}},[t._v("(")]),s("mi",[t._v("u")]),s("mo",{attrs:{separator:"true"}},[t._v(",")]),s("mi",[t._v("v")]),s("mo",{attrs:{stretchy:"false"}},[t._v(")")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA(u, v)")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")]),s("span",{staticClass:"mopen"},[t._v("(")]),s("span",{staticClass:"mord mathnormal"},[t._v("u")]),s("span",{staticClass:"mpunct"},[t._v(",")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.16666666666666666em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("v")]),s("span",{staticClass:"mclose"},[t._v(")")])])])]),t._v(" 定义为 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("u")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("u")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("u")])])])]),t._v(" 到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("v")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("v")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("v")])])])]),t._v(" 路径上深度最小的点")])]),t._v(" "),s("p",[t._v("任何一条路径都能表示成 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("u")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("u")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("u")])])])]),t._v(" 到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")]),s("mo",{attrs:{stretchy:"false"}},[t._v("(")]),s("mi",[t._v("u")]),s("mo",{attrs:{separator:"true"}},[t._v(",")]),s("mi",[t._v("v")]),s("mo",{attrs:{stretchy:"false"}},[t._v(")")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA(u, v)")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")]),s("span",{staticClass:"mopen"},[t._v("(")]),s("span",{staticClass:"mord mathnormal"},[t._v("u")]),s("span",{staticClass:"mpunct"},[t._v(",")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.16666666666666666em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("v")]),s("span",{staticClass:"mclose"},[t._v(")")])])])]),t._v(" 以及 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("v")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("v")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("v")])])])]),t._v(" 到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")]),s("mo",{attrs:{stretchy:"false"}},[t._v("(")]),s("mi",[t._v("u")]),s("mo",{attrs:{separator:"true"}},[t._v(",")]),s("mi",[t._v("v")]),s("mo",{attrs:{stretchy:"false"}},[t._v(")")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA(u, v)")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")]),s("span",{staticClass:"mopen"},[t._v("(")]),s("span",{staticClass:"mord mathnormal"},[t._v("u")]),s("span",{staticClass:"mpunct"},[t._v(",")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.16666666666666666em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("v")]),s("span",{staticClass:"mclose"},[t._v(")")])])])]),t._v(" 这两段深度严格递减的链")]),t._v(" "),s("h3",{attrs:{id:"思路"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#思路"}},[t._v("#")]),t._v(" 思路")]),t._v(" "),s("ul",[s("li",[t._v("若 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 和 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("y")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("y")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.625em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("y")])])])]),t._v(" 在同一条重链,那么 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")])])])]),t._v(" 就是深度较小的那个点")]),t._v(" "),s("li",[t._v("否则将 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("t")]),s("mi",[t._v("o")]),s("mi",[t._v("p")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("top")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.80952em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("t")]),s("span",{staticClass:"mord mathnormal"},[t._v("o")]),s("span",{staticClass:"mord mathnormal"},[t._v("p")])])])]),t._v(" 的深度较大的那个点往上跳到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("t")]),s("mi",[t._v("o")]),s("mi",[t._v("p")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("top")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.80952em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("t")]),s("span",{staticClass:"mord mathnormal"},[t._v("o")]),s("span",{staticClass:"mord mathnormal"},[t._v("p")])])])]),t._v(" 的父亲,这一步跳过了一条轻边")]),t._v(" "),s("li",[t._v("不断重复第二步直到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 和 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("y")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("y")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.625em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("y")])])])]),t._v(" 在同一条重链中")]),t._v(" "),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("LCA")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("while")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!=")]),t._v(" top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//不在同一条重链")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("SWAP")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//总是让top[x]深度更大(也可也if、else if)")]),t._v("\n x "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" f"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//x往上跳过一条轻边")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//位于同一条重链的情况")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" x "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br"),s("span",{staticClass:"line-number"},[t._v("7")]),s("br"),s("span",{staticClass:"line-number"},[t._v("8")]),s("br")])])]),t._v(" "),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("LCA")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("while")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!=")]),t._v(" top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//不在同一条重链")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("SWAP")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//总是让top[x]深度更大(也可也if、else if)")]),t._v("\n x "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" f"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//x往上跳过一条轻边")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//位于同一条重链的情况")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" x "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br"),s("span",{staticClass:"line-number"},[t._v("7")]),s("br"),s("span",{staticClass:"line-number"},[t._v("8")]),s("br")])]),s("p",[t._v("所以过程就是:"),s("br"),t._v("\n提前预处理,并将树剖分成几个链("),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")]),s("mn",[t._v("1")]),s("mo",{attrs:{separator:"true"}},[t._v(",")]),s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")]),s("mn",[t._v("2")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS1, DFS2")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.8777699999999999em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")]),s("span",{staticClass:"mord"},[t._v("1")]),s("span",{staticClass:"mpunct"},[t._v(",")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.16666666666666666em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")]),s("span",{staticClass:"mord"},[t._v("2")])])])]),t._v(")"),s("br"),t._v("\n然后获取 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")])])])]),t._v(" 时可以更快,因为每次跳的是一个链("),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("L")]),s("mi",[t._v("C")]),s("mi",[t._v("A")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("LCA")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("L")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.07153em"}},[t._v("C")]),s("span",{staticClass:"mord mathnormal"},[t._v("A")])])])]),t._v(")")]),t._v(" "),s("h2",{attrs:{id:"树上操作"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#树上操作"}},[t._v("#")]),t._v(" 树上操作")]),t._v(" "),s("p",[t._v("操作有以下四种")]),t._v(" "),s("ul",[s("li",[s("code",[t._v("1 x y z")]),t._v(" 将 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("y")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("y")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.625em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("y")])])])]),t._v(" 路径上每个点点权都加上 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("z")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("z")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")])])])])]),t._v(" "),s("li",[s("code",[t._v("2 x z")]),t._v(" 将子树内每个点点权都加上 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("z")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("z")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")])])])])]),t._v(" "),s("li",[s("code",[t._v("3 x y")]),t._v(" 查询 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 到 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("y")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("y")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.625em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("y")])])])]),t._v(" 路径上每个点的点权之和")]),t._v(" "),s("li",[s("code",[t._v("4 x")]),t._v(" 查询 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("x")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("x")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.43056em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("x")])])])]),t._v(" 子树内每个点的点权之和")])]),t._v(" "),s("h3",{attrs:{id:"思路-2"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#思路-2"}},[t._v("#")]),t._v(" 思路")]),t._v(" "),s("p",[t._v("树链剖分,在第二次 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 中先 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 重儿子再 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 轻儿子"),s("br"),t._v("\n将依次 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 到的点记录下来,则每条重链是一个连续区间,每个点的子树也是一个连续区间"),s("br"),t._v("\n对于子树操作,至此转化为了区间操作,可以线段树维护"),s("br"),t._v("\n对于任意路径操作,要么在同一条重链,要么可以分解为最多 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("l")]),s("mi",[t._v("o")]),s("mi",[t._v("g")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("log")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.8888799999999999em","vertical-align":"-0.19444em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.01968em"}},[t._v("l")]),s("span",{staticClass:"mord mathnormal"},[t._v("o")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("g")])])])]),t._v(" 条重链+轻边,同样可以转化为区间操作"),s("br"),t._v("\n子树操作:"),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("O")]),s("mo",{attrs:{stretchy:"false"}},[t._v("(")]),s("mi",[t._v("l")]),s("mi",[t._v("o")]),s("mi",[t._v("g")]),s("mi",[t._v("n")]),s("mo",{attrs:{stretchy:"false"}},[t._v(")")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("O(logn)")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("O")]),s("span",{staticClass:"mopen"},[t._v("(")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.01968em"}},[t._v("l")]),s("span",{staticClass:"mord mathnormal"},[t._v("o")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.03588em"}},[t._v("g")]),s("span",{staticClass:"mord mathnormal"},[t._v("n")]),s("span",{staticClass:"mclose"},[t._v(")")])])])])]),t._v(" "),s("p",[t._v("添加成员变量 "),s("code",[t._v("dfn[], id[]")])]),t._v(" "),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("void")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("DFS2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" topx"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" topx"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n dfn"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("++")]),t._v("dfsid"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//原始x对应的DFS序新编号是Nid[x];")]),t._v("\n id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" dfsid"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//新编号Nid[x]对应的老编号是x,即Oid[Nid[x]] = x")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br"),s("span",{staticClass:"line-number"},[t._v("7")]),s("br"),s("span",{staticClass:"line-number"},[t._v("8")]),s("br")])]),s("h3",{attrs:{id:"路径操作"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#路径操作"}},[t._v("#")]),t._v(" 路径操作")]),t._v(" "),s("p",[t._v("切割为一个个重链与轻边从而保证每片 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 序连续"),s("br"),t._v("\n然后对切割后对路径进行操作")]),t._v(" "),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" ll "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("ope_Path")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" ll c"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("bool")]),t._v(" op "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// op 0:修改 1:查询")]),t._v("\n ll res "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("while")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!=")]),t._v(" top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("swap")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),t._v("op "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("Update")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" c "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("else")]),t._v(" res "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("Query")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n x "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" f"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(">")]),t._v(" d"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("swap")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),t._v("op "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("Update")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" c "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("else")]),t._v(" res "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("Query")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("y"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" res"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br"),s("span",{staticClass:"line-number"},[t._v("7")]),s("br"),s("span",{staticClass:"line-number"},[t._v("8")]),s("br"),s("span",{staticClass:"line-number"},[t._v("9")]),s("br"),s("span",{staticClass:"line-number"},[t._v("10")]),s("br"),s("span",{staticClass:"line-number"},[t._v("11")]),s("br"),s("span",{staticClass:"line-number"},[t._v("12")]),s("br"),s("span",{staticClass:"line-number"},[t._v("13")]),s("br")])]),s("h3",{attrs:{id:"子树操作"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#子树操作"}},[t._v("#")]),t._v(" 子树操作")]),t._v(" "),s("p",[t._v("因为子树内一定是连续的 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("D")]),s("mi",[t._v("F")]),s("mi",[t._v("S")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("DFS")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.68333em","vertical-align":"0em"}}),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.02778em"}},[t._v("D")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.13889em"}},[t._v("F")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.05764em"}},[t._v("S")])])])]),t._v(" 序,所以起始为 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("i")]),s("mi",[t._v("d")]),s("mo",{attrs:{stretchy:"false"}},[t._v("[")]),s("mi",[t._v("x")]),s("mo",{attrs:{stretchy:"false"}},[t._v("]")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("id[x]")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("i")]),s("span",{staticClass:"mord mathnormal"},[t._v("d")]),s("span",{staticClass:"mopen"},[t._v("[")]),s("span",{staticClass:"mord mathnormal"},[t._v("x")]),s("span",{staticClass:"mclose"},[t._v("]")])])])]),t._v(" ,结束于起始序加上子树大小的值 "),s("span",{staticClass:"katex"},[s("span",{staticClass:"katex-mathml"},[s("math",{attrs:{xmlns:"http://www.w3.org/1998/Math/MathML"}},[s("semantics",[s("mrow",[s("mi",[t._v("i")]),s("mi",[t._v("d")]),s("mo",{attrs:{stretchy:"false"}},[t._v("[")]),s("mi",[t._v("x")]),s("mo",{attrs:{stretchy:"false"}},[t._v("]")]),s("mo",[t._v("+")]),s("mi",[t._v("s")]),s("mi",[t._v("z")]),s("mo",{attrs:{stretchy:"false"}},[t._v("[")]),s("mi",[t._v("x")]),s("mo",{attrs:{stretchy:"false"}},[t._v("]")]),s("mo",[t._v("−")]),s("mn",[t._v("1")])],1),s("annotation",{attrs:{encoding:"application/x-tex"}},[t._v("id[x]+sz[x]-1")])],1)],1)],1),s("span",{staticClass:"katex-html",attrs:{"aria-hidden":"true"}},[s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("i")]),s("span",{staticClass:"mord mathnormal"},[t._v("d")]),s("span",{staticClass:"mopen"},[t._v("[")]),s("span",{staticClass:"mord mathnormal"},[t._v("x")]),s("span",{staticClass:"mclose"},[t._v("]")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2222222222222222em"}}),s("span",{staticClass:"mbin"},[t._v("+")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2222222222222222em"}})]),s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"1em","vertical-align":"-0.25em"}}),s("span",{staticClass:"mord mathnormal"},[t._v("s")]),s("span",{staticClass:"mord mathnormal",staticStyle:{"margin-right":"0.04398em"}},[t._v("z")]),s("span",{staticClass:"mopen"},[t._v("[")]),s("span",{staticClass:"mord mathnormal"},[t._v("x")]),s("span",{staticClass:"mclose"},[t._v("]")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2222222222222222em"}}),s("span",{staticClass:"mbin"},[t._v("−")]),s("span",{staticClass:"mspace",staticStyle:{"margin-right":"0.2222222222222222em"}})]),s("span",{staticClass:"base"},[s("span",{staticClass:"strut",staticStyle:{height:"0.64444em","vertical-align":"0em"}}),s("span",{staticClass:"mord"},[t._v("1")])])])])]),t._v(" "),s("div",{staticClass:"language-cpp line-numbers-mode"},[s("pre",{pre:!0,attrs:{class:"language-cpp"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("inline")]),t._v(" ll "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("ope_Son")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("int")]),t._v(" x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" ll c"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("bool")]),t._v(" op "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// op 0:修改 1:查询")]),t._v("\n ll res "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),t._v("op "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("Update")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" sz"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("-")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" c "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("else")]),t._v(" res "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("Query")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" id"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" sz"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("x"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("-")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" res"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),t._v(" "),s("div",{staticClass:"line-numbers-wrapper"},[s("span",{staticClass:"line-number"},[t._v("1")]),s("br"),s("span",{staticClass:"line-number"},[t._v("2")]),s("br"),s("span",{staticClass:"line-number"},[t._v("3")]),s("br"),s("span",{staticClass:"line-number"},[t._v("4")]),s("br"),s("span",{staticClass:"line-number"},[t._v("5")]),s("br"),s("span",{staticClass:"line-number"},[t._v("6")]),s("br")])])],1)}),[],!1,null,null,null);"function"==typeof e&&e(r);a.default=r.exports}}]); | 96,972 | 96,972 | 0.58784 |
29827f50dce8196087ae33bbe92935651371b298 | 855 | js | JavaScript | js/card.js | kggold4/memory-cards-js-game | f062daf90d7e6027083acf78ffcc27acea31e8aa | [
"MIT"
] | null | null | null | js/card.js | kggold4/memory-cards-js-game | f062daf90d7e6027083acf78ffcc27acea31e8aa | [
"MIT"
] | null | null | null | js/card.js | kggold4/memory-cards-js-game | f062daf90d7e6027083acf78ffcc27acea31e8aa | [
"MIT"
] | null | null | null | // cards
let cards = [];
let randomalCards;
// cards counter by limit range
let idCount = 0;
// string variables
let path = "cards/"
let format = ".png";
// card object class
class Card {
// card constructor
constructor() {
if(idCount == limit / 2) idCount = 0;
this.id = idCount;
var i = idCount + 1;
this.img = path + i + format;
idCount++;
add(this);
}
}
// generate cards function
function generate() {
var n = limit;
while(n != 0) {
let card = new Card();
n--;
}
randomalCards = cards.sort(randomal);
}
// ordering cards in random
function randomal() {
return 0.5 - Math.random();
}
// add card to cards
function add(card) {
cards.push(card);
}
// clear all cards
function clear() {
cards = [];
randomalCards = [];
idCount = 0;
}
| 16.442308 | 45 | 0.561404 |
29835c32712b42e1eb48dba5b360b9c429b2a318 | 76 | js | JavaScript | app/views/logs/log.js | SweetPixel/balanced-dashboard | 2d85a6f7f94664939ec0e92f776aafc848087415 | [
"MIT"
] | 1 | 2020-03-18T10:19:55.000Z | 2020-03-18T10:19:55.000Z | app/views/logs/log.js | SweetPixel/balanced-dashboard | 2d85a6f7f94664939ec0e92f776aafc848087415 | [
"MIT"
] | null | null | null | app/views/logs/log.js | SweetPixel/balanced-dashboard | 2d85a6f7f94664939ec0e92f776aafc848087415 | [
"MIT"
] | null | null | null | Balanced.LogsLogView = Balanced.View.extend({
templateName: 'logs/log'
});
| 19 | 45 | 0.736842 |
2983bc1b6b630191f3c13cb9bc532c24a78729c6 | 214 | js | JavaScript | tests/baselines/reference/nonexistentPropertyUnavailableOnPromisedType.js | nilamjadhav/TypeScript | b059135c51ee93f8fb44dd70a2ca67674ff7a877 | [
"Apache-2.0"
] | 49,134 | 2015-01-01T02:37:27.000Z | 2019-05-06T20:38:53.000Z | tests/baselines/reference/nonexistentPropertyUnavailableOnPromisedType.js | nilamjadhav/TypeScript | b059135c51ee93f8fb44dd70a2ca67674ff7a877 | [
"Apache-2.0"
] | 26,488 | 2015-01-01T13:57:03.000Z | 2019-05-06T20:40:00.000Z | tests/baselines/reference/nonexistentPropertyUnavailableOnPromisedType.js | nilamjadhav/TypeScript | b059135c51ee93f8fb44dd70a2ca67674ff7a877 | [
"Apache-2.0"
] | 8,518 | 2015-01-05T03:29:29.000Z | 2019-05-06T14:37:49.000Z | //// [nonexistentPropertyUnavailableOnPromisedType.ts]
function f(x: Promise<number>) {
x.toLowerCase();
}
//// [nonexistentPropertyUnavailableOnPromisedType.js]
function f(x) {
x.toLowerCase();
}
| 19.454545 | 55 | 0.696262 |
2984ccc0ede78474850ee57a5a79571fbe56b03c | 1,544 | js | JavaScript | devUtils/getItemsImages.js | EtsTest-ReactNativeApps/mobile | 1503359bbae9796ca745cf54c09e3245710f88f8 | [
"MIT"
] | 150 | 2016-09-30T12:37:51.000Z | 2022-01-29T16:55:48.000Z | devUtils/getItemsImages.js | EtsTest-ReactNativeApps/mobile | 1503359bbae9796ca745cf54c09e3245710f88f8 | [
"MIT"
] | 77 | 2016-09-30T12:39:12.000Z | 2020-12-24T19:29:20.000Z | devUtils/getItemsImages.js | EtsTest-ReactNativeApps/mobile | 1503359bbae9796ca745cf54c09e3245710f88f8 | [
"MIT"
] | 71 | 2016-10-19T09:57:21.000Z | 2022-01-24T21:37:40.000Z | var items = require('../node_modules/dotaconstants/build/items.json');
var fs = require('fs');
var request = require('request');
var buildItemsArray = function() {
var importedItems = items;
//console.log(importedAbilities);
var itemsArray = [];
for(var key in importedItems) {
if(importedItems.hasOwnProperty(key)) {
itemsArray.push(key);
}
}
return itemsArray;
}
var itemsArray = buildItemsArray();
var download = function(uri, filename, callback) {
request.head(uri, function(err, res, body){
// console.log('content-type:', res.headers['content-type']);
// console.log('content-length:', res.headers['content-length']);
var r = request(uri);
r.pause();
r.on('response', function (resp) {
if(resp.statusCode === 200) {
r.pipe(fs.createWriteStream(filename)).on('close', callback);
r.resume();
console.log("Done");
} else {
console.log("404");
}
})
});
};
console.log('Downloading images for ' + itemsArray.length + ' items');
for(i = 0; i < itemsArray.length; i++) {
console.log('Downloading image for ' + itemsArray[i]);
var constructedFileName = itemsArray[i] + '_lg.png';
var url = 'http://cdn.dota2.com/apps/dota2/images/items/' + constructedFileName;
var path = '../app/assets/items/' + constructedFileName;
download(url, path, function() {
});
}
| 32.851064 | 84 | 0.568005 |
298556b31a258c033e556ccea0c1519d337896fe | 587 | js | JavaScript | packages/ext-web-components-tests/test/AllTests/rel/releditor.js | a4-data/a4-UI-EXT | ec16d056f5e768dd1d4ef0ada84aedb50629a6bb | [
"Apache-2.0",
"MIT"
] | 23 | 2019-05-02T19:30:52.000Z | 2022-03-09T02:27:26.000Z | packages/ext-web-components-tests/test/AllTests/rel/releditor.js | a4-data/a4-UI-EXT | ec16d056f5e768dd1d4ef0ada84aedb50629a6bb | [
"Apache-2.0",
"MIT"
] | 13 | 2019-08-16T04:04:06.000Z | 2019-08-23T21:35:03.000Z | packages/ext-web-components-tests/test/AllTests/rel/releditor.js | a4-data/a4-UI-EXT | ec16d056f5e768dd1d4ef0ada84aedb50629a6bb | [
"Apache-2.0",
"MIT"
] | 19 | 2019-05-07T12:21:07.000Z | 2021-08-05T16:00:05.000Z | describe('main rel columns inside grid', () => {
it("should auto-assign column, nested column, cell, and widget from children", () => {
ST.navigate('#RelEditor').and(function() {
ST.component('#gridComponentEditor').visible().and(grid => {
const columns = grid.getColumns();
expect(columns.length).toBe(1);
});
ST.component('@ext-gridcell-1').visible();
ST.play([
{ type: "tap", target: "#ext-gridcell-1"},
{ type: "tap", target: -1, delay:0 }
]);
ST.element('>> .editor').visible();
});
});
});
| 29.35 | 88 | 0.545145 |
298619dd2b9b87c5d71b7a8def0144ec7ae02a5b | 133 | js | JavaScript | XilinxProcessorIPLib/drivers/gpio/doc/html/api/xgpio__low__level__example_8c.js | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 595 | 2015-02-03T15:07:36.000Z | 2022-03-31T18:21:23.000Z | XilinxProcessorIPLib/drivers/gpio/doc/html/api/xgpio__low__level__example_8c.js | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 144 | 2016-01-08T17:56:37.000Z | 2022-03-31T13:23:52.000Z | XilinxProcessorIPLib/drivers/gpio/doc/html/api/xgpio__low__level__example_8c.js | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 955 | 2015-03-30T00:54:27.000Z | 2022-03-31T11:32:23.000Z | var xgpio__low__level__example_8c =
[
[ "main", "xgpio__low__level__example_8c.html#a840291bc02cba5474a4cb46a9b9566fe", null ]
]; | 33.25 | 92 | 0.796992 |
29863a659a5fa40f49bffb4483872c1868cff338 | 786 | js | JavaScript | exstack/src/endpoints/page/index.js | cocm1324/socialmakers | 82d47906fbb98d70e5cd5b9aad09bef9cb8965c8 | [
"MIT"
] | null | null | null | exstack/src/endpoints/page/index.js | cocm1324/socialmakers | 82d47906fbb98d70e5cd5b9aad09bef9cb8965c8 | [
"MIT"
] | 3 | 2021-08-31T19:54:32.000Z | 2022-03-02T08:15:20.000Z | exstack/src/endpoints/page/index.js | cocm1324/socialmakers | 82d47906fbb98d70e5cd5b9aad09bef9cb8965c8 | [
"MIT"
] | null | null | null | const page = require('express').Router();
const pageController = require('./page.controller');
const aboutUs = require('./aboutUs');
const course = require('./course');
const notice = require('./notice');
const courseCategory = require('./course-category');
page.use('/aboutUs', aboutUs);
page.use('/course', course);
page.use('/courseCategory', courseCategory);
page.use('/notice', notice);
page.get('/', pageController.get);
page.post('/:pageId', pageController.postByPageId);
page.put('/:pageId/:contentId', pageController.putByPageIdContentId);
page.delete('/:pageId/:contentId', pageController.deleteByPageIdContentId);
page.put('/:pageId/:contentId/downSeq', pageController.putDownSeq);
page.put('/:pageId/:contentId/upSeq', pageController.putUpSeq);
module.exports = page; | 34.173913 | 75 | 0.735369 |
2986c1419b6922dec470414a481f169d2cfb71ca | 1,416 | js | JavaScript | app/middleware/auth.js | liuyib/koa-template | 2ba73dc339663cdbb4ae4a86062b25e8b4b48b14 | [
"MIT"
] | 1 | 2021-03-23T09:10:37.000Z | 2021-03-23T09:10:37.000Z | app/middleware/auth.js | liuyib/koa-template | 2ba73dc339663cdbb4ae4a86062b25e8b4b48b14 | [
"MIT"
] | null | null | null | app/middleware/auth.js | liuyib/koa-template | 2ba73dc339663cdbb4ae4a86062b25e8b4b48b14 | [
"MIT"
] | null | null | null | const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')
class Auth {
/**
* @param {number} level - 权限等级
*/
constructor(level) {
this.level = level || 1
}
/**
* 1. 通过 HTTP Basic Authorization 方式验证 JWT
* 2. 第 1 步通过后,验证接口权限
* 3. 第 2 步通过后,将 JWT 中携带的信息返回给客户端
* @returns {Function} KOA 中间件函数
*/
get verify() {
return async (ctx, next) => {
// { name: '账号', pass: '密码' }
const auth = basicAuth(ctx.req)
let errMsg = 'jwt 不合法'
if (!auth || !auth.name) {
throw new __ERROR__.Forbbiden(errMsg)
}
let userAuth = null
try {
const { secretKey } = __CONFIG__.jwt
userAuth = jwt.verify(auth.name, secretKey)
} catch (error) {
if (error.name === 'TokenExpiredError') {
errMsg = 'jwt 已过期'
}
throw new __ERROR__.Forbbiden(errMsg)
}
// 用户权限 < 接口权限
if (userAuth.permission < this.level) {
errMsg = '权限不足'
throw new __ERROR__.Forbbiden(errMsg)
}
ctx.auth = userAuth
await next()
}
}
/**
* 验证 JWT 是否合法
* @param {string} token - JWT
* @returns {boolean}
*/
static verifyToken(token) {
try {
const { secretKey } = __CONFIG__.jwt
jwt.verify(token, secretKey)
} catch (error) {
throw new __ERROR__.ParamException('token 不合法')
}
}
}
module.exports = {
Auth,
}
| 20.228571 | 53 | 0.550141 |
2988c7cab434887165775e4387227a34b5b07108 | 1,904 | js | JavaScript | src/focus-on.directive.js | diosmosis/ng-fast-focus | ae9cf4f036ffa3db7f53c16a46dde14615b02abf | [
"MIT"
] | null | null | null | src/focus-on.directive.js | diosmosis/ng-fast-focus | ae9cf4f036ffa3db7f53c16a46dde14615b02abf | [
"MIT"
] | null | null | null | src/focus-on.directive.js | diosmosis/ng-fast-focus | ae9cf4f036ffa3db7f53c16a46dde14615b02abf | [
"MIT"
] | null | null | null | (function () {
'use strict';
angular
.module('ngFastFocus')
.directive('focusOn', focusOn);
focusOn.$inject = ['fastFocusFocuser'];
/**
* This directive should be used on child elements of an element that uses the
* focus-model directive.
*
* It marks elements so they will be focused when the focus model variable changes
* to a certain value.
*
* The value is determined by the expression supplied to the focus-on=""
* attribute.
*/
function focusOn(fastFocusFocuser) {
return {
restrict: 'A',
link: function ($scope, $element, $attr) {
var focusOnExpr = $attr.focusOn;
if (!focusOnExpr) {
throw new Error("focus-on directive requires namesake attribute to be set to expression");
}
var currentFocusGroupId = findCurrentFocusGroup();
if (!currentFocusGroupId) {
throw new Error("cannot find focus group in current or parent scopes");
}
var focusOnValue = $scope.$eval(focusOnExpr);
if (focusOnValue === undefined || focusOnValue === null) {
throw new Error("invalid focus-on expression or value '" + focusOnExpr + "'");
}
fastFocusFocuser.setFocusOn(currentFocusGroupId, focusOnValue, $element);
function findCurrentFocusGroup() {
var currentScope = $scope;
do {
if (currentScope._focusGroupId) {
return currentScope._focusGroupId;
}
currentScope = currentScope.$parent;
} while (currentScope);
return null;
}
}
};
}
})();
| 32.827586 | 110 | 0.516282 |
2988d727cc88347256ba7e302408b3f0c452d23a | 9,127 | js | JavaScript | spec/codefreezeSpec.js | SeanCannon/codefreeze | 05f45a66ff0be40c7d4f0519b29f9fe40e87f265 | [
"MIT"
] | null | null | null | spec/codefreezeSpec.js | SeanCannon/codefreeze | 05f45a66ff0be40c7d4f0519b29f9fe40e87f265 | [
"MIT"
] | null | null | null | spec/codefreezeSpec.js | SeanCannon/codefreeze | 05f45a66ff0be40c7d4f0519b29f9fe40e87f265 | [
"MIT"
] | null | null | null | 'use strict';
const codefreeze = require('../codefreeze');
describe('codefreeze', () => {
beforeEach(() => {
process.env.CODE_FREEZE_DAY_BEGIN = 'Thursday';
process.env.CODE_FREEZE_DAY_END = 'Saturday';
process.env.CODE_FREEZE_HOUR_BEGIN = '6';
process.env.CODE_FREEZE_HOUR_END = '11';
});
describe('environment variable validation', () => {
it('throws when CODE_FREEZE_DAY_BEGIN is missing', () => {
delete process.env.CODE_FREEZE_DAY_BEGIN;
expect(() => {
codefreeze();
}).toThrow(new Error('ERROR: Missing environment variable CODE_FREEZE_DAY_BEGIN. It should be a string representing the day of the week the code freeze begins. Example: "Wednesday"'));
});
it('throws when CODE_FREEZE_HOUR_BEGIN is missing', () => {
delete process.env.CODE_FREEZE_HOUR_BEGIN;
expect(() => {
codefreeze();
}).toThrow(new Error('ERROR: Missing environment variable CODE_FREEZE_HOUR_BEGIN. It should be a number from 0 to 23, representing the hour the code freeze begins on the CODE_FREEZE_DAY_BEGIN. Example: "14" would be 2PM'));
});
it('throws when CODE_FREEZE_HOUR_BEGIN is not a parsable integer', () => {
process.env.CODE_FREEZE_HOUR_BEGIN = 'foo';
expect(() => {
codefreeze();
}).toThrow(new Error('ERROR: CODE_FREEZE_HOUR_BEGIN value "foo" could not be converted to an integer. It should be a number from 0 to 23, representing the hour the code freeze begins on the CODE_FREEZE_DAY_BEGIN. Example: "14" would be 2PM'));
});
it('throws when CODE_FREEZE_DAY_END is missing', () => {
delete process.env.CODE_FREEZE_DAY_END;
expect(() => {
codefreeze();
}).toThrow(new Error('ERROR: Missing environment variable CODE_FREEZE_DAY_END. It should be a string representing the day of the week the code freeze ends. Example: "Wednesday"'));
});
it('throws when CODE_FREEZE_HOUR_END is missing', () => {
delete process.env.CODE_FREEZE_HOUR_END;
expect(() => {
codefreeze();
}).toThrow(new Error('ERROR: Missing environment variable CODE_FREEZE_HOUR_END. It should be a number from 0 to 23, representing the hour the code freeze ends on the CODE_FREEZE_DAY_END. Example: "14" would be 2PM'));
});
it('throws when CODE_FREEZE_HOUR_END is not a parsable integer', () => {
process.env.CODE_FREEZE_HOUR_END = 'foo';
expect(() => {
codefreeze();
}).toThrow(new Error('ERROR: CODE_FREEZE_HOUR_END value "foo" could not be converted to an integer. It should be a number from 0 to 23, representing the hour the code freeze ends on the CODE_FREEZE_DAY_END. Example: "14" would be 2PM'));
});
});
describe('with overrides', () => {
afterEach(() => {
delete process.env.CODE_FREEZE_OVERRIDE;
});
it('throws when frozen override is in effect', () => {
process.env.CODE_FREEZE_OVERRIDE = 'frozen';
expect(() => {
codefreeze('2020-12-14 17:45', 'America/Los_Angeles'); // Monday
}).toThrow(new Error('Code freeze full override in effect. All merges frozen.'));
});
it('does not throw when unfrozen override is in effect', () => {
process.env.CODE_FREEZE_OVERRIDE = 'unfrozen';
expect(() => {
codefreeze('2020-12-18 17:45', 'America/Los_Angeles'); // Friday
}).not.toThrow(new Error('Code freeze in effect: Today (12/18 05:45 PM) is between 12/17 06:00 AM and 12/19 11:00 AM'));
});
});
describe('biweekly', () => {
beforeEach(() => {
process.env.CODE_FREEZE_BI_WEEKLY = 'true';
process.env.CODE_FREEZE_BI_WEEKLY_WEEK = 'odd';
});
describe('which crosses weekend', () => {
beforeEach(() => {
process.env.CODE_FREEZE_DAY_END = 'Monday';
});
it('exits without throwing when maybeNowOverride does not land in an active code freeze during freeze week', () => {
expect(() => {
// Freeze-week Monday before Thursday 6AM freeze start
codefreeze('2020-12-14 17:45', 'America/Los_Angeles');
}).not.toThrow();
});
it('exits without throwing when maybeNowOverride does not land in an active code freeze during non-freeze week', () => {
expect(() => {
// Next Tuesday after the Monday 11AM freeze end
codefreeze('2020-12-22 17:45', 'America/Los_Angeles');
}).not.toThrow();
});
it('throws when maybeNowOverride is in the code freeze at the end of the freeze week', () => {
expect(() => {
// Thursday after 6AM freeze start
codefreeze('2020-12-17 17:45', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/17 05:45 PM) is between 12/17 06:00 AM and 12/21 11:00 AM'));
});
it('throws when maybeNowOverride is in the code freeze at the beginning of the non-freeze week', () => {
expect(() => {
// Next Monday before 11AM freeze end
codefreeze('2020-12-21 05:00', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/21 05:00 AM) is between 12/17 06:00 AM and 12/21 11:00 AM'));
});
it('throws when maybeNowOverride is in the code freeze at the beginning of the non-freeze week when the even/odd calculation is inverted', () => {
expect(() => {
// Next Monday before 11AM freeze end
process.env.CODE_FREEZE_BI_WEEKLY_WEEK = 'even';
codefreeze('2020-12-28 05:00', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/28 05:00 AM) is between 12/24 06:00 AM and 12/28 11:00 AM'));
});
});
describe('which does not cross the weekend', () => {
beforeEach(() => {
process.env.CODE_FREEZE_DAY_END = 'Saturday';
});
it('exits without throwing when maybeNowOverride does not land in an active code freeze during freeze week', () => {
expect(() => {
// Freeze-week Monday before Thursday 6AM freeze start
codefreeze('2020-12-14 17:45', 'America/Los_Angeles');
}).not.toThrow();
});
it('throws when maybeNowOverride is in the code freeze during freeze week', () => {
expect(() => {
// Thursday after 6AM freeze start
codefreeze('2020-12-17 17:45', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/17 05:45 PM) is between 12/17 06:00 AM and 12/19 11:00 AM'));
});
it('exits without throwing when maybeNowOverride does not land anywhere in freeze week', () => {
expect(() => {
// Next Monday after last Saturday 11AM freeze end
codefreeze('2020-12-21 05:00', 'America/Los_Angeles');
}).not.toThrow();
});
});
afterAll(() => {
delete process.env.CODE_FREEZE_BI_WEEKLY;
delete process.env.CODE_FREEZE_BI_WEEKLY_WEEK;
});
});
describe('weekly', () => {
describe('which crosses weekend', () => {
beforeEach(() => {
process.env.CODE_FREEZE_DAY_END = 'Monday';
});
it('exits without throwing when maybeNowOverride does not land in an active code freeze', () => {
expect(() => {
// Monday after 11AM freeze end, before Thursday 6AM freeze start
codefreeze('2020-12-14 17:45', 'America/Los_Angeles');
}).not.toThrow();
});
it('throws when maybeNowOverride is in the code freeze at the beginning of the week, while code was frozen last week over the weekend', () => {
expect(() => {
// Monday after last Thursday 6AM freeze start, but before same-day 11AM freeze end
codefreeze('2020-12-14 05:00', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/14 05:00 AM) is between 12/10 06:00 AM and 12/14 11:00 AM'));
});
it('throws when maybeNowOverride is in the code freeze at the end of the week, during code freeze which ends next week', () => {
expect(() => {
// Friday after the Thursday 6AM freeze start, but before next monday 11AM freeze end
codefreeze('2020-12-18 05:00', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/18 05:00 AM) is between 12/17 06:00 AM and 12/21 11:00 AM'));
});
});
describe('which does not cross the weekend', () => {
beforeEach(() => {
process.env.CODE_FREEZE_DAY_END = 'Saturday';
});
it('exits without throwing when maybeNowOverride does not land in an active code freeze during freeze week', () => {
expect(() => {
// Freeze-week Monday before Thursday 6AM freeze start
codefreeze('2020-12-14 17:45', 'America/Los_Angeles');
}).not.toThrow();
});
it('throws when maybeNowOverride is in the code freeze', () => {
expect(() => {
// Thursday after 6AM freeze start
codefreeze('2020-12-17 17:45', 'America/Los_Angeles');
}).toThrow(new Error('Code freeze in effect: Today (12/17 05:45 PM) is between 12/17 06:00 AM and 12/19 11:00 AM'));
});
});
});
});
| 44.521951 | 249 | 0.62222 |
2989451b80dda33ad95bafe132640b004fd094a1 | 1,105 | js | JavaScript | gulpfile.js | soniabrami/soniabrahmi.com | 283d938be664daf9dd2e094dbbd02e71a81d4839 | [
"MIT"
] | null | null | null | gulpfile.js | soniabrami/soniabrahmi.com | 283d938be664daf9dd2e094dbbd02e71a81d4839 | [
"MIT"
] | null | null | null | gulpfile.js | soniabrami/soniabrahmi.com | 283d938be664daf9dd2e094dbbd02e71a81d4839 | [
"MIT"
] | null | null | null | var gulp = require('gulp'),
browserify = require('browserify'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
reactify = require('reactify'),
sass = require('gulp-sass'),
package = require('./package.json'),
nodemon = require('nodemon'),
render = require('./render.js');
gulp.task('bundle', function() {
return browserify(package.paths.app)
.transform('reactify', {stripTypes: true, es6: true})
.bundle()
.pipe(source(package.dest.app))
.pipe(gulp.dest(package.dest.dist));
});
gulp.task('sass', function() {
gulp.src('public/css/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('public/css'));
});
gulp.task('watch', function () {
gulp.watch(['src/**/*.js', 'src/**/*.jsx'],['bundle']);
gulp.watch('public/css/*.scss', ['sass']);
gulp.watch('public/static/*.md', ['render']);
});
gulp.task('render', function() {
render();
});
gulp.task('nodemon', function () {
nodemon({
script: 'bin/www', ext: 'js jsx jade',ignore:['public/scripts/react/*']
});
}); | 27.625 | 79 | 0.590045 |
298aaadffbd71ff60ad5c245048afacd7ab0b6c4 | 704 | js | JavaScript | test/services/analyzer/mongo-collections-analyzer.test.js | ridem/lumber | d38673a079ac313cb0541784616ddb29943a32c8 | [
"MIT"
] | 2,291 | 2016-11-07T04:58:56.000Z | 2022-03-14T09:45:43.000Z | test/services/analyzer/mongo-collections-analyzer.test.js | em3ndez/lumber | d17bbcd2cc6e460c998a68a302cdb9f538ddc977 | [
"MIT"
] | 458 | 2016-11-14T12:28:06.000Z | 2022-03-21T13:49:21.000Z | test/services/analyzer/mongo-collections-analyzer.test.js | em3ndez/lumber | d17bbcd2cc6e460c998a68a302cdb9f538ddc977 | [
"MIT"
] | 137 | 2016-11-14T11:56:24.000Z | 2021-09-27T15:38:35.000Z | const analyzeMongoCollections = require('../../../services/analyzer/mongo-collections-analyzer');
const EmptyDatabaseError = require('../../../utils/errors/database/empty-database-error');
describe('services > mongoCollectionsAnalyzer', () => {
describe('analyzeMongoCollections', () => {
it('should return an EmptyDatabase error if connection doesn\'t have collections', async () => {
expect.assertions(1);
const databaseConnectionMock = {
collections: jest.fn().mockResolvedValue([]),
};
const error = new EmptyDatabaseError('no collections found');
await expect(analyzeMongoCollections(databaseConnectionMock)).rejects.toThrow(error);
});
});
});
| 37.052632 | 100 | 0.691761 |
298bafd1bf4300d63a522e6f66a41261ee0180d4 | 1,421 | js | JavaScript | src/App.js | thomas-demagny/dragons | 03e0216390c84df6bb91a4ab0cef74f539250de7 | [
"MIT"
] | null | null | null | src/App.js | thomas-demagny/dragons | 03e0216390c84df6bb91a4ab0cef74f539250de7 | [
"MIT"
] | null | null | null | src/App.js | thomas-demagny/dragons | 03e0216390c84df6bb91a4ab0cef74f539250de7 | [
"MIT"
] | null | null | null | import React from 'react';
import './App.css';
import FormDragon from "./components/FormDragon";
import DragonList from "./components/DragonList";
import KnightList from "./components/KnightList";
import FormKnight from "./components/FormKnight";
import {useSelector} from "react-redux";
import LogList from "./components/LogList";
function App() {
const {count} = useSelector(state => state.dragonReducer);
const {countKnight} = useSelector(state => state.knightReducer)
return (
<>
<header className="bg-secondary">
<h1 className="text-center p-4">Dragon's and Knight's List, number of dragon(s): {count} ,
number of Knight(s): {countKnight} </h1>
</header>
<div className="d-flex ">
<div className="col pt-5">
<h2 className="bg-primary p-2"> Enter a dragon</h2>
<FormDragon />
<h2 className="bg-primary p-2"> Enter a knight</h2>
<FormKnight />
</div>
<div className="col pt-5">
<DragonList />
</div>
<div className="col pt-5">
<KnightList />
</div>
</div>
<div >
<LogList />
</div>
</>
);
}
export default App;
| 19.465753 | 106 | 0.503871 |
298bb516e62dabb2563eba4f0af92e3b5e5850dd | 8,706 | js | JavaScript | client/src/utils/utils.js | carl-eis/CryptoCape | 8a681a6afb2aae85ed81809e7f565312fa9e5a6a | [
"MIT"
] | 2 | 2021-04-25T01:15:34.000Z | 2021-05-18T17:22:19.000Z | client/src/utils/utils.js | carl-eis/CryptoCape | 8a681a6afb2aae85ed81809e7f565312fa9e5a6a | [
"MIT"
] | 13 | 2020-11-07T19:16:55.000Z | 2022-03-03T22:06:02.000Z | client/src/utils/utils.js | carl-eis/CryptoCape | 8a681a6afb2aae85ed81809e7f565312fa9e5a6a | [
"MIT"
] | 2 | 2021-03-30T10:50:18.000Z | 2021-05-22T19:30:51.000Z | import numeral from 'numeral';
import { createBrowserHistory, createHashHistory } from 'history';
import BigNumber from 'bignumber.js';
import moment from 'moment';
BigNumber.config({ EXPONENTIAL_AT: 100 });
const getDynamicFormat = (currentFormat = '0,0.00', number) => {
let requestedDecimals;
let preDecimalFormat;
let postDecimalFormat;
if(currentFormat.split(".").length > 0) {
requestedDecimals = currentFormat.split(".")[1].length;
postDecimalFormat = currentFormat.split(".")[1];
preDecimalFormat = currentFormat.split(".")[0];
}
let currentFormattedNumber = numeral(number).format(currentFormat).toString();
let currentFormattedDecimals = '';
if(currentFormattedNumber.split('.') && currentFormattedNumber.split('.')[1]) {
currentFormattedDecimals = currentFormattedNumber.split('.')[1];
}
let currentUnformattedDecimals = '';
if(number.toString().split(".").length > 0 && number.toString().split(".")[1]) {
currentUnformattedDecimals = number.toString().split(".")[1];
}
let dynamicFormat = currentFormat;
if((currentFormattedDecimals.replace(/[^1-9]/g,"").length < requestedDecimals) && (currentUnformattedDecimals.replace(/[^1-9]/g,"").length >= requestedDecimals)) {
let indexOfSignificantFigureAchievement;
let significantFiguresEncountered = 0;
let numberString = number.toString();
let numberStringPostDecimal = "";
if(numberString.split(".").length > 0) {
numberStringPostDecimal = numberString.split(".")[1]
}
for(let i = 0; i < numberStringPostDecimal.length; i++) {
if((numberStringPostDecimal[i] * 1) > 0) {
significantFiguresEncountered++;
if(significantFiguresEncountered === requestedDecimals) {
indexOfSignificantFigureAchievement = i + 1;
}
}
}
if(indexOfSignificantFigureAchievement > requestedDecimals) {
let requestedDecimalsToSignificantFiguresDelta = indexOfSignificantFigureAchievement - requestedDecimals;
dynamicFormat = preDecimalFormat + ".";
if(postDecimalFormat) {
dynamicFormat = preDecimalFormat + "." + postDecimalFormat;
}
for(let i = 0; i < requestedDecimalsToSignificantFiguresDelta; i++) {
dynamicFormat = dynamicFormat + "0";
}
}
}
return dynamicFormat;
}
export const priceFormat = (number, decimals = 2, currency = "$", prefix = true) => {
let decimalString = "";
for(let i = 0; i < decimals; i++){
decimalString += "0";
}
if (currency.length > 1) {
prefix = false;
}
let format = '0,0.' + decimalString;
if(number < 10) {
format = getDynamicFormat(format, number);
}
if (prefix) {
return `${currency}${'\u00A0'}`+ numeral(number).format(format);
} else {
return numeral(number).format(format) + `${'\u00A0'}${currency}`
}
}
export const weiToEther = (wei) => {
if(typeof wei === "string"){
return BigNumber(wei).dividedBy('1e18').toString();
}else{
return BigNumber(wei.toString()).dividedBy('1e18').toString();
}
}
export const tokenBalanceFromDecimals = (value, decimals = 18) => {
if(typeof value === "string"){
return BigNumber(value).dividedBy(`1e${decimals}`).toString();
}else{
return BigNumber(value.toString()).dividedBy(`1e${decimals}`).toString();
}
}
export const tokenInflatedBalanceFromDecimals = (value, decimals = 18) => {
if(typeof value === "string"){
return BigNumber(value).multipliedBy(`1e${decimals}`).toString();
}else{
return BigNumber(value.toString()).multipliedBy(`1e${decimals}`).toString();
}
}
export const subtractNumbers = (value1, value2) => BigNumber(value1).minus(BigNumber(value2)).toString();
export const addNumbers = (value1, value2) => BigNumber(value1).plus(BigNumber(value2)).toString();
export const multiplyNumbers = (value1, value2) => BigNumber(value1).multipliedBy(BigNumber(value2)).toString();
export const divideNumbers = (value1, value2) => BigNumber(value1).dividedBy(BigNumber(value2)).toString();
// Credit for percToColour: https://gist.github.com/mlocati/7210513
export const percToColor = (perc) => {
if(perc > 100){
perc = 100;
}
let r, g, b = 0;
if(perc < 50) {
r = 255;
g = Math.round(5.1 * perc);
}
else {
g = 255;
r = Math.round(510 - 5.10 * perc);
}
let h = r * 0x10000 + g * 0x100 + b * 0x1;
return '#' + ('000000' + h.toString(16)).slice(-6);
}
export const tokenValueFormat = (value, decimals = 2) => {
//Rounds down - I think it is better to under represent this value than to over represent it
return BigNumber(value).toFixed(decimals, 1).toString();
}
export const tokenValueFormatDisplay = (value, decimals = 2, currency = false, prepend = false, adaptiveDecimals = false) => {
if(adaptiveDecimals) {
let detectAdaptiveValue = value < 0 ? value * -1 : value * 1;
if((detectAdaptiveValue < 0.1) && (decimals >= 2)) {
decimals = 3;
}
}
if(currency) {
if(prepend){
return `${currency}${'\u00A0'}` + new BigNumber(tokenValueFormat(value, decimals)).toFormat(decimals);
}
return new BigNumber(tokenValueFormat(value, decimals)).toFormat(decimals) + `${'\u00A0'}${currency}`;
}
return new BigNumber(tokenValueFormat(value, decimals)).toFormat(decimals);
}
export const isPrefixWWW = () => {
if(window.location.href.indexOf("www.") > -1) {
return true
}else{
return false;
}
}
export function rangeToTimebox(range, earliestDate){
let fromDate;
switch(range){
case '24HR': {
fromDate = moment().startOf('day').subtract(1, 'day').format('YYYY-MM-DD');
break;
}
case '1W': {
fromDate = moment().startOf('day').subtract(1, 'week').format('YYYY-MM-DD');
break;
}
case '1M': {
fromDate = moment().startOf('day').subtract(1, 'month').format('YYYY-MM-DD');
break;
}
case '3M': {
fromDate = moment().startOf('day').subtract(3, 'month').format('YYYY-MM-DD');
break;
}
case '6M': {
fromDate = moment().startOf('day').subtract(6, 'month').format('YYYY-MM-DD');
break;
}
case '1Y': {
fromDate = moment().startOf('day').subtract(1, 'year').format('YYYY-MM-DD');
break;
}
default: {
fromDate = moment(earliestDate).startOf('day').format('YYYY-MM-DD');
break;
}
}
return JSON.stringify({
fromDate,
toDate: moment().format('YYYY-MM-DD')
})
}
export function configureHistory() {
return window.matchMedia('(display-mode: standalone)').matches
? createHashHistory()
: createBrowserHistory()
}
export const numberFormat = (number) => {
let format = '0,0.00';
return numeral(number).format(format);
}
export const debounce = (func, wait, immediate) => {
// 'private' variable for instance
// The returned function will be able to reference this due to closure.
// Each call to the returned function will share this common timer.
let timeout;
// Calling debounce returns a new anonymous function
return function() {
// reference the context and args for the setTimeout function
let context = this,
args = arguments;
// Should the function be called now? If immediate is true
// and not already in a timeout then the answer is: Yes
let callNow = immediate && !timeout;
// This is the basic debounce behaviour where you can call this
// function several times, but it will only execute once
// [before or after imposing a delay].
// Each time the returned function is called, the timer starts over.
clearTimeout(timeout);
// Set the new timeout
timeout = setTimeout(function() {
// Inside the timeout function, clear the timeout variable
// which will let the next execution run when in 'immediate' mode
timeout = null;
// Check if the function already ran with the immediate flag
if (!immediate) {
// Call the original function with apply
// apply lets you define the 'this' object as well as the arguments
// (both captured before setTimeout)
func.apply(context, args);
}
}, wait);
// Immediate mode and no wait timer? Execute the function..
if (callNow) func.apply(context, args);
}
} | 35.534694 | 167 | 0.616816 |
298d9d77e574e9e7854b40f1f0b67c365b80e852 | 1,792 | js | JavaScript | www/tablet/lib/jquery.unveil.js | skydns/fhem-tablet-ui | ab6e80a2de1505e6c15c5e256e0b93548cbd5616 | [
"MIT"
] | 182 | 2015-03-21T22:03:28.000Z | 2022-02-23T18:41:33.000Z | www/tablet/lib/jquery.unveil.js | skydns/fhem-tablet-ui | ab6e80a2de1505e6c15c5e256e0b93548cbd5616 | [
"MIT"
] | 122 | 2015-03-08T19:59:19.000Z | 2021-01-25T11:21:33.000Z | www/tablet/lib/jquery.unveil.js | skydns/fhem-tablet-ui | ab6e80a2de1505e6c15c5e256e0b93548cbd5616 | [
"MIT"
] | 119 | 2015-03-04T12:25:25.000Z | 2022-03-24T21:15:02.000Z | /**
* jQuery Unveil
* A very lightweight jQuery plugin to lazy load images
* inspired from http://luis-almeida.github.com/unveil (2013 Luís Almeida)
*
* Copyright (c) 2017 Mario Stephan <mstephan@shared-files.de>
* Under MIT License (http://www.opensource.org/licenses/mit-license.php)
* https://github.com/knowthelist/fhem-tablet-ui
*/
;(function($) {
$.fn.unveil = function (options) {
var opts = $.extend({}, $.fn.unveil.defaults, options);
var loaded,
images = this;
this.one("unveil", function () {
//console.log('unveil');
var elem = $(this).find('[' + opts.attrib + ']');
var source = elem.attr(opts.attrib);
if (source) {
elem.attr("src", source);
if (typeof opts.afterUnveil === "function") opts.afterUnveil.call(this);
}
});
function unveil() {
var inview = images.filter(function () {
var elem = $(this);
if (elem.is(":hidden")) return;
var viewTop = opts.container.scrollTop(),
viewBottom = viewTop + opts.container.height(),
elemTop = elem.position().top,
elemBottom = elemTop + elem.height();
//console.log(elemTop,elemBottom ,viewTop - opts.threshold, viewBottom + opts.threshold);
return elemBottom >= viewTop - opts.threshold && elemTop <= viewBottom + opts.threshold;
});
loaded = inview.trigger("unveil");
images = images.not(loaded);
}
opts.container.on("scroll.unveil resize.unveil", unveil);
$(document).on(opts.customEvent, unveil);
unveil();
return this;
};
// Plugin defaults
$.fn.unveil.defaults = {
container: $(window),
threshold: 0,
attrib: "data-src",
};
})(window.jQuery); | 27.151515 | 101 | 0.587054 |
298dbf3f587285c1b16e51951f724ef6a173ad13 | 2,956 | js | JavaScript | build/precache-manifest.a17113244059c67e5d283f99e6fb2df3.js | Lucifier129/learn-webgl | bba54f5454ba9e26927b7ea97aa6832708a6afc9 | [
"MIT"
] | 16 | 2019-04-24T01:17:12.000Z | 2021-10-21T07:29:23.000Z | build/precache-manifest.a17113244059c67e5d283f99e6fb2df3.js | Lucifier129/learn-webgl | bba54f5454ba9e26927b7ea97aa6832708a6afc9 | [
"MIT"
] | null | null | null | build/precache-manifest.a17113244059c67e5d283f99e6fb2df3.js | Lucifier129/learn-webgl | bba54f5454ba9e26927b7ea97aa6832708a6afc9 | [
"MIT"
] | null | null | null | self.__precacheManifest = [
{
"revision": "3bbc7faac50e594ac044",
"url": "/learn-webgl/build/static/js/0.31ca90db.chunk.js"
},
{
"revision": "fe4dc16884c151af1fb3",
"url": "/learn-webgl/build/static/js/1.8addac5e.chunk.js"
},
{
"revision": "488effb36770cd4ae0fe",
"url": "/learn-webgl/build/static/js/2.5c4a54f4.chunk.js"
},
{
"revision": "3c2e3d423e72270b9684",
"url": "/learn-webgl/build/static/js/3.9999e71c.chunk.js"
},
{
"revision": "cde171e9fdc05c96f99f",
"url": "/learn-webgl/build/static/js/main.c3aaeede.chunk.js"
},
{
"revision": "f044778635f98a8cf691",
"url": "/learn-webgl/build/static/js/runtime~main.91c2e5da.js"
},
{
"revision": "097c506a0a80167a6b44",
"url": "/learn-webgl/build/static/js/6.6c2aa0b5.chunk.js"
},
{
"revision": "b354ad4ee54d8a28bc1f",
"url": "/learn-webgl/build/static/js/7.9e637108.chunk.js"
},
{
"revision": "b7b22d52e9ec8f351e6f",
"url": "/learn-webgl/build/static/js/8.8cbbc2c1.chunk.js"
},
{
"revision": "77b3b6c18feeef179288",
"url": "/learn-webgl/build/static/js/9.faf08f60.chunk.js"
},
{
"revision": "d694e995fcf421bc6d7c",
"url": "/learn-webgl/build/static/js/10.4aa8808f.chunk.js"
},
{
"revision": "f4b1189c678daca124cd",
"url": "/learn-webgl/build/static/js/11.b099ef1b.chunk.js"
},
{
"revision": "4aff4ccff04dcf329cfb",
"url": "/learn-webgl/build/static/js/12.a1e494ed.chunk.js"
},
{
"revision": "1dfd882cd844cfb8f1c0",
"url": "/learn-webgl/build/static/js/13.e1c921c6.chunk.js"
},
{
"revision": "711433ac963cde22c8e8",
"url": "/learn-webgl/build/static/js/14.66a7b292.chunk.js"
},
{
"revision": "5005669c10b7b2f81331",
"url": "/learn-webgl/build/static/js/15.f2c1d553.chunk.js"
},
{
"revision": "9ef83a357bd1f22bec67",
"url": "/learn-webgl/build/static/js/16.5504a9ec.chunk.js"
},
{
"revision": "35b9551903d1999e6865",
"url": "/learn-webgl/build/static/js/17.c36a2fa9.chunk.js"
},
{
"revision": "4077953f89efd9a99bcb",
"url": "/learn-webgl/build/static/js/18.aa9a1e03.chunk.js"
},
{
"revision": "7656245453e80f66b8be",
"url": "/learn-webgl/build/static/js/19.b6f1fb55.chunk.js"
},
{
"revision": "54a5e3a73c3e81ffa3f1",
"url": "/learn-webgl/build/static/js/20.fb1edd26.chunk.js"
},
{
"revision": "a5884583cfb65043c478",
"url": "/learn-webgl/build/static/js/21.39aaeda4.chunk.js"
},
{
"revision": "64d5ce5720b174514771",
"url": "/learn-webgl/build/static/js/22.2c060b0e.chunk.js"
},
{
"revision": "2b11efd69a0706609e35dd0f1f46eaba",
"url": "/learn-webgl/build/static/media/sky.2b11efd6.jpg"
},
{
"revision": "def06678ed2158414e1ba6fccd09ffe8",
"url": "/learn-webgl/build/static/media/circle.def06678.gif"
},
{
"revision": "ef7c0392e9e359aa5aa1f7128a4be83a",
"url": "/learn-webgl/build/index.html"
}
]; | 27.886792 | 66 | 0.639039 |
298e386c31e11ad0eba16dfe64285ebb69f64803 | 11,516 | js | JavaScript | react/features/login-signup/components/register.component.js | devsupport2/meet2 | 49fae4dfab2694dd137d5a191357da390a5a6b32 | [
"Apache-2.0"
] | null | null | null | react/features/login-signup/components/register.component.js | devsupport2/meet2 | 49fae4dfab2694dd137d5a191357da390a5a6b32 | [
"Apache-2.0"
] | null | null | null | react/features/login-signup/components/register.component.js | devsupport2/meet2 | 49fae4dfab2694dd137d5a191357da390a5a6b32 | [
"Apache-2.0"
] | 1 | 2020-11-04T06:03:27.000Z | 2020-11-04T06:03:27.000Z | import React from 'react';
import { Component } from 'react';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import { makeStyles } from "@material-ui/core/styles";
import Link from '@material-ui/core/Link';
import InputAdornment from "@material-ui/core/InputAdornment";
// @material-ui/icons
import Email from "@material-ui/icons/Email";
import People from "@material-ui/icons/People";
import Phone from "@material-ui/icons/Phone";
import Check from "@material-ui/icons/Check";
import Warning from "@material-ui/icons/Warning";
import AuthService from "../auth.service";
// core components
import GridContainer from "../../Vatchit/Components/Grid/GridContainer.js";
import GridItem from "../../Vatchit/Components/Grid/GridItem.js";
import Button from "../../Vatchit/Components/CustomButtons/Button.js";
import Card from "../../Vatchit/Components/Card/Card.js";
import CardBody from "../../Vatchit/Components/Card/CardBody.js";
import CardHeader from "../../Vatchit/Components/Card/CardHeader.js";
import CardFooter from "../../Vatchit/Components/Card/CardFooter.js";
import CustomInput from "../../Vatchit/Components/CustomInput/CustomInput.js";
import CustomSelect from "../../Vatchit/Components/CustomSelect/CustomSelect.js";
import Snackbar from "../../Vatchit/Components/Snackbar/SnackbarContent.js";
import styles from "../../Vatchit/Assets/jss/vatchit/views/loginPage.js";
const logo = "/images/img/Logo-VatChit.png";
const image2 = "/images/img/image-2.png";
const image1 = "/images/img/image-1.png";
const useStyles = makeStyles(styles);
//const bg = "/images/img/background2.png";
function RegisterPage(props) {
var ct = props.ctr;
if (localStorage.getItem("token") != null)
{
window.location.href="/";
}
const [cardAnimaton, setCardAnimation] = React.useState("cardHidden");
setTimeout(function() {
setCardAnimation("");
}, 700);
const classes = useStyles();
const { ...rest } = props;
document.title = "Vatchit | Register";
document.body.style.backgroundColor = "#f5f5f5";
document.body.style.overflow = "auto";
return (
<div>
<div className={classes.container}>
<GridContainer justify="center">
<GridItem xs={12} sm={12} md={4}>
<Card className={classes[cardAnimaton]}>
<img src={image2} className={classes.image2}/>
<img src={image1} className={classes.image1}/>
<form className={classes.form} onSubmit={ct.handleRegister}>
<CardHeader color="primary" className={classes.cardHeader}>
<img src={logo}/>
</CardHeader>
<CardBody>
<h3 className={classes.title}>Register</h3>
<GridContainer justify="center">
<GridItem xs={6} sm={6} md={6}>
<CustomInput
labelText="First Name"
id="first"
formControlProps={{
fullWidth: true
}}
inputProps={{
type: "text",
onChange: ct.onChangeFirstName,
// endAdornment: (
// <InputAdornment position="end">
// <People className={classes.inputIconsColor} />
// </InputAdornment>
// )
}}
/>
</GridItem>
<GridItem xs={6} sm={6} md={6}>
<CustomInput
labelText="Last Name"
id="last"
formControlProps={{
fullWidth: true
}}
inputProps={{
type: "text",
onChange: ct.onChangeLastName,
endAdornment: (
<InputAdornment position="end">
<People className={classes.inputIconsColor} />
</InputAdornment>
)
}}
/>
</GridItem>
</GridContainer>
<CustomInput
labelText="Email..."
id="email"
formControlProps={{
fullWidth: true
}}
inputProps={{
onChange: ct.onChangeEmail,
type: "email",
endAdornment: (
<InputAdornment position="end">
<Email className={classes.inputIconsColor} />
</InputAdornment>
)
}}
/>
<GridContainer justify="center">
<GridItem xs={4} sm={4} md={4}>
<CustomSelect list={ct.countries} id="country" value={ct.state.country}
inputProps={{
onChange: ct.onChangeCountry,
}}
/>
</GridItem>
<GridItem xs={8} sm={8} md={8}>
<CustomInput
labelText="Phone..."
id="phone"
formControlProps={{
fullWidth: true
}}
inputProps={{
onChange: ct.onChangePhone,
type: "text",
endAdornment: (
<InputAdornment position="end">
<Phone className={classes.inputIconsColor} />
</InputAdornment>
)
}}
/>
</GridItem>
</GridContainer>
<CustomInput
labelText="Password"
id="pass"
formControlProps={{
fullWidth: true
}}
inputProps={{
onChange: ct.onChangePassword,
type: "password",
endAdornment: (
<InputAdornment position="end">
<LockOutlinedIcon/>
</InputAdornment>
),
autoComplete: "off"
}}
/>
</CardBody>
<CardFooter className={classes.cardFooter}>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign Up
</Button>
</CardFooter>
<div className={classes.footerHelper}>
<Link href="/Login" className={classes.title}>
{"Already have an account? Login"}
</Link>
</div>
</form>
</Card>
</GridItem>
</GridContainer>
</div>
{ct.state.message && (
<Snackbar
open={ct.state.open}
message={
<span>
{ct.state.message}
</span>
}
color={
ct.state.successful
? "success"
: "danger"
}
icon={
ct.state.successful
? Check
: Warning
}
/>
)}
</div>
);
}
export default class Register extends Component {
constructor(props) {
super(props);
this.handleRegister = this.handleRegister.bind(this);
this.onChangeFirstName = this.onChangeFirstName.bind(this);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onChangePhone = this.onChangePhone.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onChangeCountry = this.onChangeCountry.bind(this);
this.getCountry();
this.countries = [];
this.state = {
userName: "",
phone: "",
email: "",
password: "",
country: "IN",
successful: false,
message: "",
lastName: ""
};
}
componentDidMount() {
this.getCountry();
}
getCountry(){
console.log("getCountrycalled");
AuthService.getCountries().then(
response => {
if(response.data.success){
console.log("responseSuccess");
this.countries = response.data.countries;
}
},
error => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
this.setState({
successful: false,
message: resMessage
});
}
);
}
onChangeCountry(e){
console.log("country changed");
this.setState({
country: e.target.value
});
}
onChangePhone(e) {
console.log("phone changed");
this.setState({
phone: e.target.value
});
}
onChangeFirstName(e) {
console.log("username changed");
this.setState({
userName: e.target.value
});
}
onChangeLastName(e) {
console.log("username changed");
this.setState({
lastName: e.target.value
});
}
onChangeEmail(e) {
console.log("email changed");
this.setState({
email: e.target.value
});
}
onChangePassword(e) {
console.log("password changed");
this.setState({
password: e.target.value
});
}
handleRegister(e) {
e.preventDefault();
console.log("handle register called");
this.setState({
message: "",
successful: false,
userName: this.state.userName+" "+this.state.lastName
});
//this.form.validateAll();
console.log(JSON.stringify(this.state));
AuthService.register(
this.state.userName,
this.state.phone,
this.state.email,
this.state.password,
this.state.country
).then(
response => {
this.setState({
message: response.data.message,
successful: response.data.success
});
setTimeout(function(){ window.location.href="/Login"; }, 3000);
},
error => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
this.setState({
successful: false,
message: resMessage
});
}
);
}
render() {
return (
<RegisterPage ctr={this}/>
);
}
} | 32.348315 | 95 | 0.462053 |
298fc00fa6b34170225b13be3248be4d98e37609 | 2,144 | js | JavaScript | src/router/index.js | ZhangJianChengZzz/netease-cloud-music | 55889e1a7afd33048cbd0416f84912179312edc5 | [
"MIT"
] | 3 | 2020-08-23T17:13:16.000Z | 2021-06-10T06:38:28.000Z | src/router/index.js | ZhangJianChengZzz/netease-cloud-music | 55889e1a7afd33048cbd0416f84912179312edc5 | [
"MIT"
] | null | null | null | src/router/index.js | ZhangJianChengZzz/netease-cloud-music | 55889e1a7afd33048cbd0416f84912179312edc5 | [
"MIT"
] | null | null | null | import Vue from "vue";
import VueRouter from "vue-router";
import Discover from "../pages/discover-page/Discover";
import Myself from "@/pages/myself-page/Myself";
Vue.use(VueRouter);
const routes = [
{
path: "/",
component: Discover,
redirect: "/discover",
children: [
{
path: "/",
name: "发现",
component: () => import("@/pages/discover-page/child/index/Index"),
meta: {
showBackBar: false
}
},
{
path: "play-list/:id",
name: "歌单",
component: () =>
import("@/pages/discover-page/child/detail/PlayListDetail")
},
{
path: "singer/:id",
name: "",
component: () =>
import("@/pages/discover-page/child/singer-detail/SingerDetail")
},
{
path: "playlist-comments/:id",
name: "歌单评论",
component: () =>
import("@/pages/discover-page/child/comments/PlayListComments")
},
{
path: "song-comments/:id",
name: "歌曲评论",
component: () =>
import("@/pages/discover-page/child/comments/SongComments")
},
{
path: "playlist-place",
name: "歌单广场",
component: () =>
import("@/pages/discover-page/child/playlist-place/PlayListPlace")
},
{
path: "top-list",
name: "排行榜",
component: () => import("@/pages/discover-page/child/top-list/TopList")
}
]
},
{
path: "/myself",
component: Myself,
children: [
{
path: "/myself",
name: "我的",
component: () => import("@/pages/myself-page/child/index/Index"),
meta: {
showBackBar: false
}
}
]
},
{
path: "/search",
name: "",
component: () => import("@/pages/search-page/SearchHot")
},
{
path: "/search/result/:keyword",
name: "",
component: () => import("@/pages/search-page/SearchResult")
},
{
path: "/video/:id",
name: "",
component: () => import("@/pages/video-page/Video")
}
];
const router = new VueRouter({
routes
});
export default router;
| 22.568421 | 79 | 0.508396 |
298fdc7e5f0b89a013b74257afb329eb17fb9d31 | 4,791 | js | JavaScript | client/src/pages/About/About.js | manuelsanchez2/doicheliving-app | 0cb9c6cdadd7fb3ea5fe1275d8136137eae95243 | [
"MIT"
] | 12 | 2020-09-09T07:52:38.000Z | 2021-03-11T08:14:44.000Z | client/src/pages/About/About.js | manuelsanchez2/doicheliving-app | 0cb9c6cdadd7fb3ea5fe1275d8136137eae95243 | [
"MIT"
] | 22 | 2020-09-07T08:59:16.000Z | 2020-09-29T11:54:05.000Z | client/src/pages/About/About.js | manuelsanchez2/doicheliving-app | 0cb9c6cdadd7fb3ea5fe1275d8136137eae95243 | [
"MIT"
] | null | null | null | import React from "react";
import Header from "../../components/Header";
import Footer from "../../components/Footer";
import Main from "../../components/Main";
import GridContainer from "../../components/GridContainer";
import styled from "@emotion/styled";
import AboutPersonContainer from "../../components/AboutPersonContainer";
import manuelSrc from "../../assets/admins/manuel.png";
import miriamSrc from "../../assets/admins/miriam.png";
import lauraSrc from "../../assets/admins/laura.png";
import nuriaSrc from "../../assets/admins/nuria.png";
import mariaSrc from "../../assets/admins/maria.png";
const VideoContainer = styled.div`
position: relative;
width: 100%;
padding-bottom: 50%;
height: 0;
border-radius: 5px;
iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 10px;
}
`;
const About = () => {
return (
<GridContainer>
<Header />
<Main>
<h2>¿Qué es Doiche Living?</h2>
<p>
Doiche Living es un blog de viajes por Alemania fundado a mediados de
2019 en el que la máxima es que el protagonista seas tú: Nosotros
estaremos ahí para echarte una mano y asesorarte, pero serás tú desde
el minuto 1 el que se organice un viaje a Alemania que jamás olvidará.
</p>
<VideoContainer>
<iframe
title="Doicheliving"
width="560"
height="315"
src="https://www.youtube.com/embed/UlXPz9k9_tQ"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
></iframe>
</VideoContainer>
<h3>La plantilla de Doiche Living</h3>
<nav>
<AboutPersonContainer
src={manuelSrc}
alt="manuel"
name="Manuel Sánchez - Fundador & CEO"
description="Desde hace unos años alterno España y Alemania porque siempre encuentro una razón que me hace volver al país germano. Asentado en Hamburgo desde hace casi dos años, mi objetivo con este blog es contarte todo lo que tienes que ver en este país tan increíble mientras aprendes lo fácil que es organizarte un viaje por tu cuenta a Alemania."
/>
<AboutPersonContainer
src={miriamSrc}
alt="miriam"
name="Miriam Amat - Diseño & Community Management"
description="Ahora vivo en Hamburgo al igual que el jefe, pero antes he vivido en Kiel, en Berlín y en Regensburg. Gracias a haber pasado casi 4 años en Alemania, ¡ he podido recorrer tanto grandes metrópolis como pueblos recónditos! ¡Espero que tras leer sobre este país te entre el gusanillo de visitarlo!"
/>
<AboutPersonContainer
src={lauraSrc}
alt="laura"
name="Laura Gómez - Redactora & Community Management"
description="Actualmente vivo en España, pero he pasado algunas temporadas en Alemania, concretamente en Leipzig y Lippstadt. Durante ese tiempo viajé por el país teutón y descubrí lo increíble que es su cultura, su geografía y su gente. Soy una enamorada de Alemania y ¡pretendo que tú también acabes siéndolo con todo lo que publique!"
/>
<AboutPersonContainer
src={nuriaSrc}
alt="nuria"
name="Nuria Cabezas - Redactora & Community Management"
description="Después de vivir dos años en Múnich, Baviera se convirtió en mi segundo hogar. ¿El motivo? No solo sus ciudades y paisajes de cuento, sino la calidad de vida y su gente consiguieron que esta región se convirtiera en mi lugar favorito para vivir. En mis posts te contaré todo lo que debes saber sobre la capital bávara y alrededores."
/>
<AboutPersonContainer
src={mariaSrc}
alt="maria"
name="María de Torres - Experta en Berlín"
description="Nací en Almería pero vivo en Berlín desde hace un par de años. Aunque comencé mis aventuras alemanas en Friburgo de Brisgovia y Münster, Berlín tiene ese no sé qué que ha hecho que me quede. Es por eso que quiero ser una de las responsables de que te enamores de la capital germana."
/>
</nav>
<h3>¿Quieres colaborar con Doiche Living?</h3>
<p>
Si crees que encajarías en un proyecto como este puedes contactarnos a
través de{" "}
<a href="mailto: info@doicheliving.com">info@doicheliving.com</a>{" "}
contándonos algo sobre ti y dándonos algunos detalles sobre lo que
crees que puedes aportar a la plantilla. ¡Te esperamos!
</p>
</Main>
<Footer />
</GridContainer>
);
};
export default About;
| 45.628571 | 363 | 0.652891 |
2990a30c5efdf6c278dab777788204e72597db58 | 1,177 | js | JavaScript | clockCode/countdown.js | Alessfg/eBuy | 92e2da4ad3dd4d16aed9d1db557e7387d37c05bb | [
"MIT"
] | 4 | 2018-01-13T16:48:06.000Z | 2020-06-18T15:56:21.000Z | clockCode/countdown.js | Alessfg/eBuy | 92e2da4ad3dd4d16aed9d1db557e7387d37c05bb | [
"MIT"
] | null | null | null | clockCode/countdown.js | Alessfg/eBuy | 92e2da4ad3dd4d16aed9d1db557e7387d37c05bb | [
"MIT"
] | 5 | 2018-03-16T12:45:13.000Z | 2021-11-01T06:19:53.000Z | function getTimeRemaining(endtime){
var t = Date.parse(endtime)-Date.parse(new Date());
var seconds = Math.floor((t/1000)%60);
var minutes = Math.floor((t/1000/60)%60);
var hours = Math.floor((t/(1000*60*60))%24);
var days = Math.floor(t/(1000*60*60*24));
return {
'total':t,
'days': days,
'hours': hours,
'minutes' : minutes,
'seconds' : seconds
};
}
function setClock(endtime,destination,id){
var clock = document.getElementById(id);
var timeLeft = getTimeRemaining(endtime);
clock.innerHTML = 'Time Remaining: days: ' + timeLeft.days +
' hours: '+ timeLeft.hours +
' minutes: ' + timeLeft.minutes +
' seconds: ' + timeLeft.seconds;
var inter = setInterval(function(){
var timeLeft = getTimeRemaining(endtime);
clock.innerHTML = 'Time Remaining: days: ' + timeLeft.days +
' hours: '+ timeLeft.hours +
' minutes: ' + timeLeft.minutes +
' seconds: ' + timeLeft.seconds;
if(timeLeft.total<= 900000){
clock.style.color = '#7f0000';
}
if(timeLeft.total<=0){
clearInterval(inter);
window.location = destination;
}
},1000);
}
| 29.425 | 68 | 0.604928 |
2990c7dfeb9f4c1b92a1642ef1d911f898827946 | 7,278 | js | JavaScript | test/users/users-thirdparty-test.js | flatiron/http-users | bcca73bdfb88375794b7aaa66dfbc882024f7de4 | [
"MIT"
] | 4 | 2015-01-11T10:17:08.000Z | 2021-08-23T14:38:40.000Z | test/users/users-thirdparty-test.js | flatiron/http-users | bcca73bdfb88375794b7aaa66dfbc882024f7de4 | [
"MIT"
] | 2 | 2016-01-26T12:37:37.000Z | 2016-01-26T12:38:02.000Z | test/users/users-thirdparty-test.js | flatiron/http-users | bcca73bdfb88375794b7aaa66dfbc882024f7de4 | [
"MIT"
] | 2 | 2019-10-05T05:25:00.000Z | 2021-01-02T16:12:58.000Z | /*
* users-thirdparty-api-test.js: Tests for the RESTful users 3rdparty tokens.
*
* (C) 2012, Nodejitsu Inc.
*
*/
var assert = require('assert'),
apiEasy = require('api-easy'),
app = require('../fixtures/app/couchdb'),
macros = require('../macros'),
base64 = require('flatiron').common.base64;
var port = 8080;
apiEasy.describe('http-users/user/api/thirdparty')
.addBatch(macros.requireStart(app))
.addBatch(macros.seedDb(app))
.use('localhost', port)
.setHeader('Content-Type', 'application/json')
//
// Charlie is an admin user
//
.setHeader('Authorization', 'Basic ' + base64.encode('charlie:1234'))
//
// Add a named token
//
.post('/users/charlie/thirdparty', { token: {
provider: "twitter",
token: "12345",
app: "*",
info: {somestuff: "from testing 1"}
},
id: "testing"
})
.expect(201)
.expect("should return the token that was created", function (err, r, b){
var result = JSON.parse(b);
assert.isObject(result);
//
// Has Id `testing`
//
assert.equal(result.id, "testing");
//
// Has app "*"
//
assert.equal(result.app, "*");
//
// Kept the token
//
assert.equal(result.info.somestuff, "from testing 1");
})
.next()
//
// Update named token
//
.post('/users/charlie/thirdparty', { token: {
id: "testing",
provider: "twitter",
token: "12345",
app: "dinosaur",
info: {somestuff: "from testing 2"}
}
})
.expect(201)
.expect("should return the token that was updated", function (err, r, b){
var result = JSON.parse(b);
assert.isObject(result);
//
// Has Id `testing`
//
assert.equal(result.id, "testing");
//
// Has app "dinosaur"
//
assert.equal(result.app, "dinosaur");
})
.next()
//
// Create an unnamed token with id
//
.post('/users/charlie/thirdparty', { token: {
provider: "github",
token: "12345",
info: {somestuff: "from github"}
}
})
.expect(201)
.expect("should return the token that was created", function (err, r, b) {
var result = JSON.parse(b);
assert.isObject(result);
//
// Has auto generated id
//
assert.isString(result.id);
//
// Has app "*"
//
assert.equal(result.app, "*");
//
// Kept the token
//
assert.equal(result.provider, "github");
assert.equal(result.token, "12345");
assert.equal(result.info.somestuff, "from github");
})
.next()
//
// Create some more tokens for testing purposes (delete's/etc)
//
.post('/users/charlie/thirdparty', { token: {
provider: "travis",
token: "12345",
info: {somestuff: "from travis"}
}
})
.expect(201)
.next()
//
// Create some more tokens for testing purposes (delete's/etc)
//
.post('/users/charlie/thirdparty', { token: {
id: "watwat",
provider: "bitbucket",
token: "12345",
info: {somestuff: "from bitbucket"}
}
})
.expect(201)
.next()
.del('/users/charlie/thirdparty/watwat')
.expect(201)
.expect("should return the token that was created", function (err, r, b) {
var result = JSON.parse(b);
//
// Id is watwat
//
assert.equal(result.id, "watwat");
//
// The deleted object was returned
//
assert.isObject(result.deleted);
})
.next()
//
// Try to create a token without a token should fail
//
.post('/users/charlie/thirdparty', {})
.expect(500)
.next()
//
// Try to create a token without a token without a provider
// should also fail
//
.post('/users/charlie/thirdparty', {token: {token: "123"}})
.expect(500)
.next()
//
// Try to create a token without a token without a token
// should also fail
//
.post('/users/charlie/thirdparty', {token: {provider: "123"}})
.expect(500)
.next()
.get('/users/charlie/thirdparty')
.expect(200)
.expect("should return all non app spec tokens", function (err, r, b) {
var result = JSON.parse(b);
//
// Travis and github
// Both wildcarded and non deleted
//
assert.equal(result.length, 2);
//
// Providers should be travis and github
//
var githubOrTravis = result.filter(function (t) {
return t.provider === "github" || t.provider === "travis";
});
assert.equal(githubOrTravis.length, 2);
//
// Make sure all tokens are wildcarded since we did not request a
// particular app
//
var wildcardedTokens = result.filter(function (t) {
return t.app === "*";
});
assert.equal(wildcardedTokens.length, result.length);
})
.next()
.get('/users/charlie/thirdparty/app/dinosaur')
.expect(200)
.expect("should return all dinosaur and * tokens", function (err, r, b) {
var result = JSON.parse(b);
//
// Travis and github
// Both wildcarded and non deleted
//
// Also the dinosaur twitter one that was subject to update
//
assert.equal(result.length, 3);
//
// Providers should be travis, github and twitter
//
var rightProviders = result.filter(function (t) {
return t.provider === "github" || t.provider === "travis" ||
t.provider === "twitter";
});
assert.equal(rightProviders.length, result.length);
//
// Wildcarded tokens should be returned for all apps
// In our database we have two
//
var wildcardedTokens = result.filter(function (t) {
return t.app === "*";
});
assert.equal(wildcardedTokens.length, 2);
//
// One app specific token exists
//
var dinoTokens = result.filter(function (t) {
return t.app === "dinosaur";
});
assert.equal(dinoTokens.length, 1);
})
.next()
.get('/users/charlie/thirdparty/app/dinosaur?provider=twitter')
.expect(200)
.expect("should return all dinosaur and * tokens", function (err, r, b) {
var result = JSON.parse(b);
//
// Only one has the provider `twitter`
//
assert.equal(result.length, 1);
//
// Providers should be twitter
//
var rightProviders = result.filter(function (t) {
return t.provider === "twitter";
});
assert.equal(rightProviders.length, result.length);
//
// Wildcarded tokens should be out, cause we asked for a specific
// provider
//
var wildcardedTokens = result.filter(function (t) {
return t.app === "*";
});
assert.equal(wildcardedTokens.length, 0);
//
// One app specific token exists, cause it was twitter
//
var dinoTokens = result.filter(function (t) {
return t.app === "dinosaur";
});
assert.equal(dinoTokens.length, 1);
})
.next()
//
// Charlie is an admin user
// Using token for auth
//
.setHeader('Authorization', 'Basic ' + base64.encode('charlie:token123'))
.get('/users/charlie/thirdparty')
.expect(200)
["export"](module); | 25.900356 | 78 | 0.561281 |
29924904b132231c8715066f62a00d74b54f9536 | 664 | js | JavaScript | components/form/toggle/Toggle.es6.js | ekratskih/metronome | d5934fc2e9cae4a3bd958d6b187f8fbbe6d3ddac | [
"Apache-2.0"
] | null | null | null | components/form/toggle/Toggle.es6.js | ekratskih/metronome | d5934fc2e9cae4a3bd958d6b187f8fbbe6d3ddac | [
"Apache-2.0"
] | 10 | 2020-07-19T23:40:46.000Z | 2022-03-28T16:11:21.000Z | components/form/toggle/Toggle.es6.js | ekratskih/metronome | d5934fc2e9cae4a3bd958d6b187f8fbbe6d3ddac | [
"Apache-2.0"
] | 1 | 2021-02-19T06:00:26.000Z | 2021-02-19T06:00:26.000Z | /* @flow */
import React from 'react'
import type { Node } from 'react'
type Props = {|
children: (isOpen: boolean, onToggle: () => void, onBlur: () => void) => Node,
isOpen: boolean
|}
type State = {|
isOpen: boolean
|}
class Toggle extends React.Component<Props, State> {
state = { isOpen: this.props.isOpen }
static defaultProps = {
isOpen: false
}
handleBlur = () => {
this.setState({ isOpen: false })
}
handleToggle = () => {
this.setState(({ isOpen }) => ({
isOpen: !isOpen
}))
}
render () {
return this.props.children(this.state.isOpen, this.handleToggle, this.handleBlur)
}
}
export default Toggle
| 17.945946 | 85 | 0.606928 |
29932248aa07dffa4b43478373d1e8c89b87f92d | 2,280 | js | JavaScript | src/api/components/Chat/controller.js | juansacok/intercom-api | 1bea2f1e10f4987ae790df11a889cee3bf79dd7f | [
"MIT"
] | null | null | null | src/api/components/Chat/controller.js | juansacok/intercom-api | 1bea2f1e10f4987ae790df11a889cee3bf79dd7f | [
"MIT"
] | null | null | null | src/api/components/Chat/controller.js | juansacok/intercom-api | 1bea2f1e10f4987ae790df11a889cee3bf79dd7f | [
"MIT"
] | null | null | null | const response = require("../../lib/response");
const {
getAllChats,
getOneChatById,
createOneChat,
deleteOneChatById,
} = require('./store')
const getChats = async (req, res) => {
try {
const data = await getAllChats();
return response.success({
res,
data,
status: 200,
});
} catch (error) {
return response.error({
res,
msg: "Internal error",
status: 500,
error,
});
}
}
const getChatById = async (req, res) => {
const { chatId } = req.params
try {
const data = await getOneChatById(chatId);
if (!data) {
return response.error({
res,
msg: "El chat no existe",
status: 404,
error: `Se intento obtener un chat que no existe`,
});
}
return response.success({
res,
data,
status: 200,
});
} catch (error) {
return response.error({
res,
msg: "Internal error",
status: 500,
error,
});
}
}
const createChat = async (req, res) => {
const { userid } = req.headers
const { toUserId } = req.params
if (!userid) {
return response.error({
res,
msg: "Por favor inserte cabecera userId",
status: 400,
error: "El usuario no ingreso la cabecera userId",
});
}
if (!toUserId) {
return response.error({
res,
msg: "Por favor inserte información en los campos",
status: 400,
error: "El usuario no ingreso los campos requeridos",
});
}
const chatData = {
toUserId,
userid,
};
try {
const data = await createOneChat(chatData);
return response.success({
res,
data,
msg: 'Chat creado con exito!',
status: 201,
});
} catch (error) {
return response.error({
res,
msg: "Internal Error",
status: 500,
error,
});
}
}
const deleteChatById = async (req, res) => {
const { chatId } = req.params
try {
const data = await deleteOneChatById(chatId)
if (!data) {
return response.error({
res,
msg: "El chat no existe",
status: 404,
error: `Se intento eliminar un chat que no existe`,
});
}
return response.success({
res,
data,
msg:'Chat Eliminado con exito!',
status: 200,
});
} catch (error) {
return response.error({
res,
msg: "Internal Error",
status: 500,
error,
});
}
}
module.exports = {
getChats,
createChat,
getChatById,
deleteChatById,
} | 16.642336 | 56 | 0.604386 |
29935d5ca6361d8aae8bc5f8782d90735d22f11f | 1,495 | js | JavaScript | startUp/db.js | raghunayudurayapudi/super-heroes-api | 84ff9c586efe26ac22aa447f39d43c909fe7126c | [
"MIT"
] | null | null | null | startUp/db.js | raghunayudurayapudi/super-heroes-api | 84ff9c586efe26ac22aa447f39d43c909fe7126c | [
"MIT"
] | null | null | null | startUp/db.js | raghunayudurayapudi/super-heroes-api | 84ff9c586efe26ac22aa447f39d43c909fe7126c | [
"MIT"
] | 1 | 2020-04-29T14:50:36.000Z | 2020-04-29T14:50:36.000Z | const { MongoMemoryServer } = require("mongodb-memory-server");
const mongoose = require('mongoose');
const {Heroes} = require('../models/Heroes');
const {Teams} = require('../models/Teams');
module.exports = () => {
const mongoServer = new MongoMemoryServer();
mongoose.Promise = Promise;
mongoServer.getUri().then((mongoUri) => {
const mongooseOpts = {
useNewUrlParser: true,
useUnifiedTopology: true
};
mongoose.connect(mongoUri, mongooseOpts);
mongoose.connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') {
console.log(e);
mongoose.connect(mongoUri, mongooseOpts);
}
console.log(e);
});
mongoose.connection.once('open', () => {
Heroes.collection.insertMany([{
name: 'Arrow',
alignment: 'GOOD',
teams: [
]
},
{
name: 'Super Man',
alignment: 'GOOD',
teams: [
]
},
{
name: 'Dark Side',
alignment: 'Bad',
teams: [
]
}], function (err, doc) {
if (err){
return console.error(err);
} else {
console.log("Multiple documents inserted to Collection");
}
});
Teams.collection.insertMany([{
name: 'JusticeLeage',
meanAlignment: 'NEUTRAL',
heroes: [
]
}], function (err, doc) {
if (err){
return console.error(err);
} else {
console.log("Multiple documents inserted to Collection");
}
});
console.log(`MongoDB successfully connected to ${mongoUri}`);
});
});
} | 23.359375 | 65 | 0.580602 |
29936677b39d6c1cf8fe56c44892fef23aaeba06 | 3,282 | js | JavaScript | public/certificates-viewer/dist/collection/crypto/attribute.js | PrimeEuler/PWA | 703ede25c66f65baadf3ed61b20689048f54dd93 | [
"MIT"
] | null | null | null | public/certificates-viewer/dist/collection/crypto/attribute.js | PrimeEuler/PWA | 703ede25c66f65baadf3ed61b20689048f54dd93 | [
"MIT"
] | null | null | null | public/certificates-viewer/dist/collection/crypto/attribute.js | PrimeEuler/PWA | 703ede25c66f65baadf3ed61b20689048f54dd93 | [
"MIT"
] | null | null | null | /**
* @license
* Copyright (c) Peculiar Ventures, LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Convert } from 'pvtsutils';
import { AsnParser, AsnConvert } from '@peculiar/asn1-schema';
import { Attribute as AsnAttribute } from '@peculiar/asn1-x509';
import { id_DomainNameBeneficiary, DomainNameBeneficiary, id_DomainNameLegalRepresentative, DomainNameLegalRepresentative, id_DomainNameOwner, DomainNameOwner, id_DomainNameTechnicalOperator, DomainNameTechnicalOperator, id_TypeRelationship, TypeRelationship, id_ActivityDescription, ActivityDescription, id_WebGDPR, WebGDPR, id_InsuranceValue, InsuranceValue, id_ValuationRanking, ValuationRanking, } from '@peculiar/asn1-ntqwac';
import { id_pkcs9_at_extensionRequest, ExtensionRequest, id_pkcs9_at_challengePassword, ChallengePassword, id_pkcs9_at_unstructuredName, UnstructuredName, } from '@peculiar/asn1-pkcs9';
import { Extension } from './extension';
import { AsnData } from './asn_data';
export class Attribute extends AsnData {
constructor(raw) {
super(raw, AsnAttribute);
const asnExtnValue = this.getAsnExtnValue();
switch (this.asn.type) {
case id_DomainNameBeneficiary:
this.value = AsnParser.parse(asnExtnValue, DomainNameBeneficiary);
break;
case id_DomainNameLegalRepresentative:
this.value = AsnParser.parse(asnExtnValue, DomainNameLegalRepresentative);
break;
case id_DomainNameOwner:
this.value = AsnParser.parse(asnExtnValue, DomainNameOwner);
break;
case id_DomainNameTechnicalOperator:
this.value = AsnParser.parse(asnExtnValue, DomainNameTechnicalOperator);
break;
case id_TypeRelationship:
this.value = AsnParser.parse(asnExtnValue, TypeRelationship);
break;
case id_ActivityDescription:
this.value = AsnParser.parse(asnExtnValue, ActivityDescription);
break;
case id_WebGDPR:
this.value = AsnParser.parse(asnExtnValue, WebGDPR);
break;
case id_InsuranceValue:
this.value = AsnParser.parse(asnExtnValue, InsuranceValue);
break;
case id_ValuationRanking:
this.value = AsnParser.parse(asnExtnValue, ValuationRanking);
break;
case id_pkcs9_at_challengePassword:
this.value = AsnParser.parse(asnExtnValue, ChallengePassword);
break;
case id_pkcs9_at_unstructuredName:
this.value = AsnParser.parse(asnExtnValue, UnstructuredName);
break;
case id_pkcs9_at_extensionRequest: {
const extensionRequest = AsnParser.parse(asnExtnValue, ExtensionRequest);
this.value = extensionRequest
.map((e) => new Extension(AsnConvert.serialize(e)));
break;
}
default:
this.value = Convert.ToHex(asnExtnValue);
}
}
getAsnExtnValue() {
return this.asn.values[0];
}
}
| 48.985075 | 431 | 0.651432 |
299495a9ecdf7b74a3fe130243aa53368037b152 | 372 | js | JavaScript | validation/newcomment.js | AverageDemo/Pesticide-Legacy | 25566640c8b4626bf290174a263aa16432d024a9 | [
"MIT"
] | null | null | null | validation/newcomment.js | AverageDemo/Pesticide-Legacy | 25566640c8b4626bf290174a263aa16432d024a9 | [
"MIT"
] | null | null | null | validation/newcomment.js | AverageDemo/Pesticide-Legacy | 25566640c8b4626bf290174a263aa16432d024a9 | [
"MIT"
] | null | null | null | const Validator = require("validator");
const isEmpty = require("./is-empty");
module.exports = validateNewCommentInput = data => {
let errors = {};
data.comment = !isEmpty(data.comment) ? data.comment : "";
if (Validator.isEmpty(data.comment)) {
errors.comment = "Text field is required";
}
return { errors, isValid: isEmpty(errors) };
};
| 24.8 | 62 | 0.639785 |
29949fcaf59e35c512ceff1885d8c368490cdf13 | 6,233 | js | JavaScript | src/publicmethods.js | bZez/elbajs | dc788134a1c6bbe52d8fd1a794c157955c201928 | [
"MIT"
] | 37 | 2015-01-23T12:58:46.000Z | 2021-08-22T22:01:07.000Z | src/publicmethods.js | bZez/elbajs | dc788134a1c6bbe52d8fd1a794c157955c201928 | [
"MIT"
] | 2 | 2017-02-01T20:49:55.000Z | 2017-09-07T21:00:53.000Z | src/publicmethods.js | bZez/elbajs | dc788134a1c6bbe52d8fd1a794c157955c201928 | [
"MIT"
] | 5 | 2015-12-21T18:20:24.000Z | 2019-10-28T18:30:29.000Z | /*
====================================
PUBLIC METHODS
====================================*/
Elba.prototype.loadImages = function(){
var self = this;
//Set images' src
ImageHandler.setSource(self.base, self.options);
//Set the width of each slide
ImageHandler.setSlidesWidth(self.base);
//Starting lazy load
ImageHandler.lazyLoadImages(self.base, self.options);
};
Elba.prototype.bindEvents = function(){
var self = this,
position,
startingOffset,
cachedPosition,
startingPointer,
currentSlideWidth,
dragged = false,
tick = 0,
delta;
if(self.base.count > 1){
//Bind touch events
setListener(self.base.el, Toucher.touchEvents.start, function(e){
if(self.base.animated) return false;
dragged = true;
self.clearSlideshow();
startingOffset = parseInt(Animator.offset(self.base.el));
cachedPosition = Toucher.onTouchStart(e);
currentSlideWidth = parseInt(self.base.containerWidth);
startingPointer = self.base.pointer;
});
setListener(self.base.el, Toucher.touchEvents.move, function(e){
position = Toucher.onTouchMove(e);
if(position && dragged){
delta = position.currX - cachedPosition.cachedX;
//Let's drag the slides around
Animator.drag(self.base.el, (delta + startingOffset));
cachedPosition = position;
}
});
setListener(self.base.el, Toucher.touchEvents.end, function(){
if(!dragged) return false;
Toucher.onTouchEnd();
var offset = Math.abs(Math.abs((currentSlideWidth * self.base.pointer)) - Math.abs(Animator.offset(self.base.el)));
var duration = Math.floor(((currentSlideWidth - offset) * self.options.duration) / currentSlideWidth );
Animator.stopDragging();
if(Math.abs(delta) > self.options.swipeThreshold){
if(delta > 0){
slideTo(self.base, self.options, 'left', (self.base.pointer - 1), - (currentSlideWidth - offset), duration);
}else{
slideTo(self.base, self.options, 'right', (self.base.pointer + 1), currentSlideWidth - offset, duration);
}
}else{
//Fix the gallery offset because it didn't reach the threshold.
Animator.offset(self.base.el, getLeftOffset(self.base.container, self.base.pointer));
}
delta = 0;
startingOffset = 0;
dragged = false;
self.startSlideshow();
});
}
if(self.options.navigation && self.base.navigation.left && self.base.navigation.right){
//Attach events to the navigation arrows
self.base.navigation.left.addEventListener('click', function(ev) {
ev.preventDefault();
self.goTo('left');
self.startSlideshow();
}, false);
self.base.navigation.right.addEventListener('click', function(ev) {
ev.preventDefault();
self.goTo('right');
self.startSlideshow();
}, false);
}
//Setting up dots events
if(self.options.dots && self.base.navigation.dots){
var dotHandler = function(i){
return function(){
var index = parseInt(self.base.navigation.dots[i].getAttribute('data-target'));
if(parseInt(index) === self.base.pointer){
return false;
}else{
self.goTo(index);
}
self.startSlideshow();
return false;
};
};
for(var i = 1; i < self.base.slides.length - 1; i++){
self.base.navigation.dots[i].setAttribute('data-target', i);
self.base.navigation.dots[i].addEventListener('click', dotHandler(i), false);
}
}
if(self.options.slideshow){
if (typeof document[hidden] !== 'undefined') {
// If the page is hidden, pause the slideshow;
// if the page is shown, play the slideshow
var handleVisibilityChange = function() {
if (document[hidden]) {
self.clearSlideshow();
} else {
self.startSlideshow();
}
};
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
}
//We start the slideshow
self.startSlideshow();
}
//Bind resize event
window.addEventListener('resize', function(){
EventHandler.resizeHandler(self.base, self.options);
}, false);
};
/**
* Manages which direction and which picture to slide to
* @param {String} || {Number} accepts 'right','left'
* or the numerical index of the slide
*/
Elba.prototype.goTo = function(direction){
var self = this;
if(!self.base.animated){
if(typeof direction === 'string' && isNaN(direction)){
var count = self.base.slides.length;
if(direction === 'right'){
if(self.base.pointer + 1 >= count){
return false;
}
slideTo(self.base, self.options, 'right', (self.base.pointer + 1), self.base.containerWidth);
}else{
if(self.base.pointer - 1 < 0 ){
return false;
}
slideTo(self.base, self.options, 'left', (self.base.pointer - 1), -self.base.containerWidth);
}
}else if(typeof direction === 'number'){
var oldPointer = self.base.pointer;
if(self.base.pointer > oldPointer){
slideTo(self.base, self.options, 'right', direction, parseInt(self.base.containerWidth * (direction - oldPointer)));
}else{
slideTo(self.base, self.options, 'left', direction, -parseInt(self.base.containerWidth * (oldPointer - direction)));
}
}
}
};
/**
* A pretty self-explainatory method.
*/
Elba.prototype.startSlideshow = function(){
var self = this;
if(self.options.slideshow){
if(self.base.slides.length > 1){
if(!!self.slideshow){
clearInterval(self.slideshow);
}
self.slideshow = setInterval(function(){
if(!isElementInViewport(self.base.container)){
return false;
}
var nextSlide = self.base.slides[self.base.pointer + 1];
if(!!nextSlide){
self.goTo('right');
}
},self.options.slideshow);
}
}
};
/**
* This method temporarly stops the slideshow,
* which is restarted after a click on a navigation button.
*/
Elba.prototype.clearSlideshow = function(){
var self = this;
if(self.slideshow){
clearInterval(self.slideshow);
}
};
/**
* This method permanently stops the slideshow.
*/
Elba.prototype.stopSlideshow = function(){
var self = this;
if(self.slideshow){
clearInterval(self.slideshow);
}
self.options.slideshow = 0;
};
/**
* This function returns the current index of the slideshow
* @return {Number}
*/
Elba.prototype.getCurrent = function(){
return this.base.pointer;
};
| 23.881226 | 120 | 0.662602 |
29958f12928d2f70568d572fa031e51bdd0519c2 | 155 | js | JavaScript | config.js | AkhileshThite/polytickets-marketplace | 77136e18fa47778fa90c0cdf1647a9e43292833c | [
"MIT"
] | 5 | 2021-12-22T14:53:46.000Z | 2022-03-14T17:31:44.000Z | config.js | AkhileshThite/polytickets-marketplace | 77136e18fa47778fa90c0cdf1647a9e43292833c | [
"MIT"
] | null | null | null | config.js | AkhileshThite/polytickets-marketplace | 77136e18fa47778fa90c0cdf1647a9e43292833c | [
"MIT"
] | 1 | 2021-12-14T05:40:39.000Z | 2021-12-14T05:40:39.000Z |
export const nftmarketaddress = "0x857D328aDf0e4AB10ac794930a72f8F034b6a277"
export const nftaddress = "0x47DcD05009DEcB836B588fd6969045CfF646454A"
| 38.75 | 78 | 0.851613 |
2995f441151ccbcbc0a2112d844238439d39c0b7 | 2,379 | js | JavaScript | doc/html/dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.js | lfmc/VItA | f7f6c80a09f49cd0d1cca7e6657f18889d95b719 | [
"Apache-2.0"
] | 4 | 2021-05-10T12:38:16.000Z | 2022-02-12T23:31:53.000Z | doc/html/dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.js | lfmc/VItA | f7f6c80a09f49cd0d1cca7e6657f18889d95b719 | [
"Apache-2.0"
] | 3 | 2021-01-14T21:37:08.000Z | 2021-03-04T23:02:20.000Z | doc/html/dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.js | lfmc/VItA | f7f6c80a09f49cd0d1cca7e6657f18889d95b719 | [
"Apache-2.0"
] | 4 | 2020-09-11T14:47:26.000Z | 2021-11-08T22:45:32.000Z | var class_fixed_radius_root_c_c_o_tree_legacy =
[
[ "FixedRadiusRootCCOTreeLegacy", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a423950865b90803617be124a13e8b660", null ],
[ "~FixedRadiusRootCCOTreeLegacy", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a4cf9e8bf1edd2cb4c7f22a3deb9b52ff", null ],
[ "addVessel", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a8322a2cf314cae0c93db3e0d53f4942b", null ],
[ "areValidAngles", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a1f99abd9b40ce0986e2fc1cb483b6af7", null ],
[ "clone", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a7ee8da3159245b4000e631c199762f61", null ],
[ "cloneTree", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#aa431d3484d8d4914ed6717bffe65de19", null ],
[ "evaluate", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a53a21d00d523d17ad2845954d625aab1", null ],
[ "getCloseSegments", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#affd26c5ca4319ea7f207e4eb1bfea6b1", null ],
[ "getClosestTreePoint", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a43a7c1b6584b258580538764f0a17c18", null ],
[ "getRootRadius", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a4101d7bb1970dda44e58b788ccc58e5e", null ],
[ "getTreeName", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#af66ee29f27519813afaa18842d132520", null ],
[ "isIntersectingVessels", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a2ffef1e8b11af99c71d4f4335c81a625", null ],
[ "isOverlapped", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#ab5a4e37cc1fd3633b7a05fc07ed088a9", null ],
[ "isSymmetricallyValid", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#af66e950340138e0650f52fc2a6b90ea4", null ],
[ "print", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a0de200e3f10bdd9c2fc4e3c1f37334e1", null ],
[ "saveTree", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#ae37ce4b6bd66712303927b7d67df3eb0", null ],
[ "testVessel", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a1b36d4046bc3d3ac897eec5d1cec0308", null ],
[ "updateTree", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a52b3973fad2b0905b6848fd3f7c55221", null ],
[ "rootRadius", "dc/ddc/class_fixed_radius_root_c_c_o_tree_legacy.html#a21b54a45c92fe9c86a3a566966127048", null ]
]; | 108.136364 | 137 | 0.820933 |
29968be0bd8f0321cadf02eb213ae2c1ca1447b6 | 6,354 | js | JavaScript | client/src/context/MainProvider.js | decentralMind/sign-the-doc | 88a512454600f1494a8c3e7c684d6f2ff48b3cd7 | [
"MIT"
] | 1 | 2021-06-30T12:56:26.000Z | 2021-06-30T12:56:26.000Z | client/src/context/MainProvider.js | decentralMind/sign-the-doc | 88a512454600f1494a8c3e7c684d6f2ff48b3cd7 | [
"MIT"
] | 1 | 2019-04-29T12:38:18.000Z | 2019-05-18T09:34:14.000Z | client/src/context/MainProvider.js | decentralMind/sign-the-doc | 88a512454600f1494a8c3e7c684d6f2ff48b3cd7 | [
"MIT"
] | 1 | 2019-05-14T15:15:29.000Z | 2019-05-14T15:15:29.000Z | import React from 'react';
import { initState, MainContext } from './MainContext';
class MainProvider extends React.Component {
constructor(props) {
super(props);
this.updateHashOutput = (hashOutput, fileName) => {
let newState = {
...initState(),
...this.updaterFunction
};
newState.loadWeb3 = this.state.loadWeb3;
newState.hashFile.hashOutput = hashOutput;
newState.hashFile.fileName = fileName;
this.setState(newState);
};
this.updateSignerListCheckBox = (checkboxValues) => {
//signerListForm(slf)
let slf = this.state.signerListForm;
//Todo:
//Use getCheckBox
const signerInfo = slf.signerInfo;
const slFirstLabel = slf.checkbox.name.firstLabel;
const slSecondLabel = slf.checkbox.name.secondLabel;
const slFirstValue = checkboxValues[slFirstLabel];
const slSecondValue = checkboxValues[slSecondLabel];
if (slFirstValue && signerInfo.length === 0) {
// slf.checkbox.values = checkboxValues;
this.intializeForm(checkboxValues);
} else if (slSecondValue && signerInfo.length && !signerInfo[0].error) {
if (window.confirm('Warning: All entered address will be reset')) {
this.resetSignerListCheckBox(checkboxValues);
}
} else {
this.resetSignerListCheckBox(checkboxValues);
}
};
this.resetSignerListCheckBox = (checkboxValues) => {
let newState = {
...initState(),
...this.updaterFunction
};
//Load web3 state
newState.loadWeb3 = this.state.loadWeb3;
newState.hashFile = this.state.hashFile;
newState.signHash = this.state.signHash;
newState.signerListForm.checkbox.values = checkboxValues;
this.setState(newState);
};
this.intializeForm = (checkboxValues) => {
let newState = {
...initState(),
...this.updaterFunction
};
//Load web3 state
newState.loadWeb3 = this.state.loadWeb3;
newState.hashFile = this.state.hashFile;
newState.signHash = this.state.signHash;
newState.signerListForm.checkbox.values = checkboxValues;
/*
It is the initialization process of address input field.
During initialization process Add New Signer button is enabled and shown.
The state doesn't have any entry of signer address yet.
*/
//Error key is set to true because empty address is consider invalid.
const newField = { address: '', error: true };
//Display first input field.
newState.signerListForm.signerInfo = [...newState.signerListForm.signerInfo, newField];
//Show Add New Signer button.
newState.signerListForm.displayAddBtn = true;
newState.signerListForm.openSig = false;
this.setState(newState)
}
this.resetExpiryDate = (checkboxValues) => {
let newState = {
...initState(),
...this.updaterFunction
};
//Load web3 state
newState.loadWeb3 = this.state.loadWeb3;
newState.hashFile = this.state.hashFile;
newState.signHash = this.state.signHash;
newState.signerListForm = this.state.signerListForm;
newState.expiryDate.checkbox.values = checkboxValues;
this.setState(newState);
};
this.updateExpiryDate = (expiryDate) => {
this.setState({
expiryDate: expiryDate
});
};
this.updateSignerListForm = (signerListForm) => {
const signerInfo = this.state.signerListForm.signerInfo;
// When last remaining entered address is removed.
// SignerListForm checkbox value is restored to it's original state.
if (signerInfo.length === 0) {
const checkboxValues = {};
this.resetSignerListCheckBox(checkboxValues);
}
this.setState({
signerListForm: signerListForm
});
};
this.updateLoadWeb3 = (web3Data) => {
this.setState({ loadWeb3: web3Data });
};
this.updateSignHash = (signData, account) => {
const signHash = { ...this.state.signHash };
signHash.signData = signData;
signHash.account = account;
this.setState({ signHash });
}
this.updateNextButton = (toUpdate, reset = false) => {
let stateValue = this.state[toUpdate];
if (!stateValue) {
throw new Error(`${toUpdate} key doesn't exit in state`);
} else if (!reset) {
stateValue.nextBtn.value = true;
stateValue.nextBtn.disable = true;
this.setState({
[toUpdate]: stateValue
});
} else if (reset) {
stateValue.nextBtn.value = false;
stateValue.nextBtn.disable = false;
}
}
this.updateVerifyAndDeploy = (txHash) => {
//VerifyAndDeploy
let vd = { ...this.state.verifyAndDeploy };
vd.txHash = txHash;
// Reset state and only update VerifyAndDeploy state.
this.setState({
verifyAndDeploy: vd,
}, () => this.redirectToStatus());
}
this.resetState = () => {
const loadWeb3 = { ...this.state };
this.setState({
...initState(),
loadWeb3: loadWeb3
});
}
this.updaterFunction = {
updateLoadWeb3: this.updateLoadWeb3,
updateHashOutput: this.updateHashOutput,
updateSignerListCheckBox: this.updateSignerListCheckBox,
resetExpiryDate: this.resetExpiryDate,
updateSignerListForm: this.updateSignerListForm,
updateExpiryDate: this.updateExpiryDate,
updateSignHash: this.updateSignHash,
updateNextButton: this.updateNextButton,
updateVerifyAndDeploy: this.updateVerifyAndDeploy,
resetState: this.resetState
}
this.state = {
...initState(),
...this.updaterFunction
};
this.redirectToStatus = () => {
const state = this.state;
const txHash = state.verifyAndDeploy.txHash;
const web3 = state.loadWeb3.web3;
this.props.history.push({
pathname: '/status',
txHash: txHash,
web3: web3
});
}
}
render() {
// console.log("+++++++Main State++++++++", this.state);
return (
<div>
<MainContext.Provider value={this.state}>
{this.props.children}
</MainContext.Provider>
</div >
);
}
}
const MainConsumer = MainContext.Consumer;
export { MainProvider, MainConsumer }
| 29.146789 | 93 | 0.628423 |
299735d5913d9b8f938b26defb4a943485fcfe06 | 782 | js | JavaScript | .eslintrc.js | jpikl/repl-0 | c05f57c0712626fc7cc282e27f2282a5a64ff5f4 | [
"MIT"
] | null | null | null | .eslintrc.js | jpikl/repl-0 | c05f57c0712626fc7cc282e27f2282a5a64ff5f4 | [
"MIT"
] | null | null | null | .eslintrc.js | jpikl/repl-0 | c05f57c0712626fc7cc282e27f2282a5a64ff5f4 | [
"MIT"
] | null | null | null | module.exports = {
'env': {
'browser': true,
'es6': true,
},
'extends': [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings'
],
'plugins': [
'import',
],
'parserOptions': {
'sourceType': 'module',
},
'globals': {
'__dirname': true,
},
'rules': {
'comma-dangle': ['warn', 'always-multiline'],
'eqeqeq': ['error', 'smart'],
'indent': ['warn', 2],
'linebreak-style': ['warn', 'unix'],
'quotes': ['warn', 'single'],
'semi': ['warn', 'always'],
},
'overrides': [
{
'files': 'src/intro.js',
'globals': {
'println': true,
},
}
],
};
| 21.135135 | 53 | 0.401535 |
299766b375471a1a1d6788308f77ba256a864cc9 | 1,381 | js | JavaScript | src/game.js | ChristianJHughes/DiggyHoleWorld | 3c7a92e857fb8ecad2ef6acf983654595e890630 | [
"MIT"
] | 1 | 2015-09-26T02:12:31.000Z | 2015-09-26T02:12:31.000Z | src/game.js | ChristianJHughes/DiggyHoleWorld | 3c7a92e857fb8ecad2ef6acf983654595e890630 | [
"MIT"
] | null | null | null | src/game.js | ChristianJHughes/DiggyHoleWorld | 3c7a92e857fb8ecad2ef6acf983654595e890630 | [
"MIT"
] | null | null | null | // game.js
//
// Contains game object declerations, as well as the main game loop.
// Imports the tileMap and player files via Browserify, which ensure that all files are loaded correctly.
//
// Author: Chrisian Hughes
var tileMap = require('./tileMap.js');
var playerSprite = require('./player.js');
window.onload = function() {
// Store the canvas and define its size. This is the bottom layer containing the game world.
var canvas = document.getElementById("DiggyHoleCanvas");
canvas.width = 850;
canvas.height = 850;
//Get the canvas context, and assign to a variable.
var context = canvas.getContext("2d");
tileMap.initialize(
"images/underground_tiles_scaled.png",
85,
85,
10,
10,
context
);
playerSprite.initialize("images/dwarf_sprite_sheet_scaled.png", context, 320, 63, 4, 4, tileMap, canvas.width, canvas.height);
// Updates all game objects.
function update()
{
playerSprite.update();
}
// Renders all game objects. Clears the entire canvas on each redraw.
function render()
{
context.clearRect(0, 0, canvas.width, canvas.height);
tileMap.render();
playerSprite.render();
}
function gameLoop() {
update();
render();
window.requestAnimationFrame(gameLoop);
}
// Begin the gameLoop(), and the game.
gameLoop();
}
| 25.109091 | 129 | 0.658219 |
29983b6520f37e4fcc69c5ffae4d3eafd8ef739c | 11,596 | js | JavaScript | Resources/ui/login/loginView.js | caiochaim/Cesunotas | ab7d2b7312090a3bf68aa53e5ba89e93996ea403 | [
"Apache-2.0"
] | 1 | 2020-07-25T12:36:07.000Z | 2020-07-25T12:36:07.000Z | Resources/ui/login/loginView.js | caiochaim/Cesunotas | ab7d2b7312090a3bf68aa53e5ba89e93996ea403 | [
"Apache-2.0"
] | null | null | null | Resources/ui/login/loginView.js | caiochaim/Cesunotas | ab7d2b7312090a3bf68aa53e5ba89e93996ea403 | [
"Apache-2.0"
] | 2 | 2019-10-01T11:52:31.000Z | 2019-10-01T13:39:24.000Z | /**
* @author jmilanes
*/
var width = Ti.Platform.displayCaps.platformWidth;
var userExists = false;
function LoginView()
{
// create the login window to hold our login form
var loginWindow = Ti.UI.createWindow({
//title:'SquidTech login',
tabBarHidden:true,
navBarHidden:true,
exitOnClose: true,
backgroundColor: '#fff'
});
var scrollView = Ti.UI.createScrollView({
contentWidth: 'auto',
contentHeight: 'auto',
showVerticalScrollIndicator: true,
showHorizontalScrollIndicator: true,
height: '100%',
width: '100%',
top: 0,
left: 0,
bottom: 50
});
scrollView.addEventListener('postlayout', function(){
scrollView.height = Ti.Platform.displayCaps.platformHeight - 50;
});
scrollView.add( getLoginWindowLabel() );
scrollView.add( getLoginForm() );
scrollView.add( getLoginDescriptionLabel() );
loginWindow.add(scrollView);
loginWindow.add( getFooterTemplate() );
loginWindow.add( activityIndicator );
var activity = loginWindow.activity;
activity.onCreateOptionsMenu = function(e){
var menu = e.menu;
var menuItem = menu.add({
title: "remover credênciais",
icon: "/icons/light/light_x.png",
showAsAction: Ti.Android.SHOW_AS_ACTION_IF_ROOM
});
var alert = Ti.UI.createAlertDialog({ title: 'Limpar', message: 'Remover credênciais do sistema ?', buttonNames: ['Yes', 'No'], cancel: 1 });
menuItem.addEventListener("click", function(e) {
alert.show();
});
alert.addEventListener("click", function(e){
//Clicked cancel, first check is for iphone, second for android
if (e.cancel === e.index || e.cancel === true) { return false; }
//now you can use parameter e to switch/case
switch (e.index) {
case 0: deleteUserCredentials();
break;
//This will never be reached, if you specified cancel for index 1
case 1: return false;
break;
default:
return false
break;
}
});
}
loginWindow.open();
return loginWindow;
}
function getLoginWindowLabel()
{
var labelContainer = Ti.UI.createView({
top: 0,
left: 0,
width: Titanium.UI.SIZE, height: Titanium.UI.SIZE
});
var logo = Ti.UI.createImageView({
image: '/images/logo.png',
height: '50dp',
left: 15,
top: 20
});
labelContainer.add(logo);
return labelContainer;
}
function getLoginDescriptionLabel()
{
var labelDescriptionContainer = Ti.UI.createView({
top: '60dp',
left: 0,
backgroundColor: '#fff',
width: Titanium.UI.SIZE, height: '60dp'
});
if( userExists ){
var image = '/icons/dark_2x/dark_check@2x.png';
} else {
var image = '/icons/dark_2x/dark_key@2x.png';
}
var loginDescriptionIcon = Ti.UI.createImageView({
image: image,
left: 20,
top: 20,
width: 45, height: 45
});
labelDescriptionContainer.add(loginDescriptionIcon);
if( userExists ){
var description = 'Clique no botão abaixo para ver suas notas.';
} else {
var description = 'Informe seu Ra e senha para visualizar sua notas.';
}
var loginDescriptionLabel = Ti.UI.createLabel({
color: '#333',
shadow:{
shadowRadius:3,
shadowOpacity:1,
shadowOffset:{x:5, y:5},
shadowColor:"#000000"
},
text: description,
textAlign: Ti.UI.TEXT_ALIGNMENT_LEFT,
top: 20,
left: 80,
width: Titanium.UI.SIZE, height: '50dp',
font: { fontSize:'14dp' },
});
labelDescriptionContainer.add(loginDescriptionLabel);
return labelDescriptionContainer;
}
function getLoginForm(){
var formContainerView = Ti.UI.createView({
top: '110dp',
left: 0,
width: Titanium.UI.SIZE, height: '100%'
});
var username = getRaInput();
var password = getPasswordInput();
var checkbox = getCheckboxInput();
var user = getStoredUserCredentioals( username.value );
userExists = ( user.rowCount > 0 )? true : false;
if( userExists ){
username.value = user.fieldByName('ra');
password.value = user.fieldByName('password');
}
var loginBtn = getLoginBtn();
loginBtn.addEventListener('touchend', function(){
activityIndicator.show();
loginAction({username: username.value, password: password.value, keep: checkbox.value });
});
if( !userExists ){
formContainerView.add( username );
formContainerView.add( password );
formContainerView.add( checkbox );
} else {
loginBtn.top = '50dp';
if( debug ){
formContainerView.add( getDeleteBtn() );
}
}
formContainerView.add( loginBtn );
return formContainerView;
}
function getLoginWindowActionLabel()
{
var actionLabel = Ti.UI.createLabel({
color: '#fff',
shadowColor: '#aaa',
shadowOffset: {x:5, y:5},
text: 'Entre com suas credenciais da àrea do aluno para ver suas notas.',
textAlign: Ti.UI.TEXT_ALIGNMENT_LEFT,
top: 0,
width: width, height: 80,
font: { fontSize:'20dp',fontWeight:'bold' },
});
return actionLabel;
}
function getRaInput()
{
var username = Ti.UI.createTextField({
color:'#fff',
top:'30dp',
left:'5%',
width: '90%',
height:'50dp',
hintText:'RA',
value: '11036102',
backgroundColor: "#025F8B",
keyboardType: Ti.UI.KEYBOARD_DEFAULT,
returnKeyType: Ti.UI.RETURNKEY_DEFAULT,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
borderColor: '#025F8B',
borderWidth: 3,
font: { fontSize: '20dp' }
});
username.addEventListener('focus', function(){
username.backgroundColor = '#fff';
username.color = '#333';
username.borderColor = '#025F8B'
});
username.addEventListener('blur', function(){
username.backgroundColor = '#025F8B';
username.color = '#fff';
username.borderColor = '#025F8B'
});
return username;
}
function getPasswordInput()
{
var password = Ti.UI.createTextField({
color:'#fff',
top: '90dp',
left:'5%',
width: '90%',
height:'50dp',
hintText:'Senha',
value: 'senha1',
passwordMask:true,
backgroundColor: "#025F8B",
keyboardType: Ti.UI.KEYBOARD_DEFAULT,
returnKeyType: Ti.UI.RETURNKEY_DEFAULT,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
borderColor: '#025F8B',
borderWidth: 3,
font: { fontSize: '20dp' }
});
password.addEventListener('focus', function(){
password.backgroundColor = '#fff';
password.color = '#333';
password.borderColor = '#025F8B'
});
password.addEventListener('blur', function(){
password.backgroundColor = '#025F8B';
password.color = '#fff';
password.borderColor = '#025F8B'
});
return password;
}
function getCheckboxInput()
{
var checkbox = Ti.UI.createSwitch({
style : Ti.UI.Android.SWITCH_STYLE_CHECKBOX,
title : 'Salvar credenciais ?',
value : false,
top : '140dp',
height : '50dp',
left:'5%',
width: '90%',
color: '#333'
});
return checkbox;
}
function getLoginBtn()
{
if( userExists ){
var text = 'Ver notas';
} else {
var text = 'Enviar';
}
var loginBtn = Ti.UI.createButton({
title: text,
top:'200dp',
left:'5%',
width: '90%',
height:'50dp',
borderRadius:1,
backgroundColor: '#2292CE',
color: '#fff',
font: {fontFamily:'Tahoma',fontWeight:'bold',fontSize:'20dp'},
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
borderColor: '#2292CE',
//borderWidth: 3
});
loginBtn.addEventListener('touchstart', function(){
var matrix = Ti.UI.create2DMatrix()
//matrix = matrix.rotate(180);
matrix = matrix.scale(.9, .9);
var animation = Ti.UI.createAnimation({
transform : matrix,
duration : 200,
autoreverse : true,
repeat : 1,
backgroundColor: '#025F8B'
});
//loginBtn.backgroundColor = '#025F8B';
//loginBtn.color = '#fff';
//loginBtn.borderColor = '#2292CE';
loginBtn.animate(animation);
});
return loginBtn;
}
function getDeleteBtn()
{
var deleteBtn = Ti.UI.createButton({
title:'remover credenciais',
top:250,
left:'5%',
width: '90%',
height:80,
borderRadius:1,
backgroundColor: '#8F1111',
color: '#fff',
font: {fontFamily:'Tahoma',fontWeight:'bold',fontSize:'20dp'},
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
borderColor: '#8F1111',
borderWidth: 3
});
deleteBtn.addEventListener('click', function(){
deleteUserCredentials();
});
return deleteBtn;
}
function getExistingCredentialsView(){
}
function loginAction(loginInfo){
var data = getDataFromDb(loginInfo.username);
Ti.API.debug(data);
Ti.API.debug(data);
//return false;
var isOlder = true;
if( false !== data ){
var lasttime = new Date(lasttime).getTime();
var oneHour = 1000 * 60 * 60;
var isOlder = ((new Date().getTime() - oneHour) < lasttime) ? true: false;
}
if( !isOlder ){
return getNotesWindow(data.json);
}
else {
var url = 'http://squidtech.layoutz.com.br/cesunotas_wbs/webservice.php';
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.debug(loginInfo.keep);
if( loginInfo.keep ){
updateUserCredentilas(loginInfo);
}
updateDataInDb({
user: loginInfo.username,
responseText: this.responseText
});
return getNotesWindow(this.responseText);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
//Ti.API.debug(e.error);
return false;
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("POST", url);
// Send the request.
client.send(loginInfo);
}
}
function getNotesWindow(notes)
{
//Ti.API.info(notes);
var NotesList = require('/ui/common/NotesList');
/*var currentWin = Ti.UI.currentWindow;
if( currentWin !== null ){
currentWin.close();
}*/
return new NotesList( notes );
//return true;
}
function updateUserCredentilas(loginInfo){
var db = Ti.Database.open('squidtech.sqlite');
Ti.API.debug(db);
var results = db.execute('REPLACE INTO credentials ( ra, password ) VALUES("'+loginInfo.username+'","'+loginInfo.password+'")');
db.close();
return results;
}
function getStoredUserCredentioals(ra){
var db = Ti.Database.open('squidtech.sqlite');
var results = db.execute('SELECT * FROM credentials WHERE ra = "'+ra+'"');
db.close();
if( results.isValidRow() ){
return results;
}
return false;
}
function getDataFromDb(ra){
var db = Ti.Database.open('squidtech.sqlite');
var results = db.execute('SELECT * FROM data WHERE id = "'+ra+'"');
db.close();
if( results.isValidRow() ){
return {json: results.fieldByName('json'), lasttime: results.fieldByName('lasttime'),};
}
return false;
}
function updateDataInDb(data){
var db = Ti.Database.open('squidtech.sqlite');
var lasttime = new Date();
value = data.responseText;
var results = db.execute("REPLACE INTO data ( id, json, lasttime ) VALUES('"+data.user+"','"+value.toString()+"', '"+lasttime.toString("yyyy/mm/dd HH:MM:ss")+"')");
db.close();
return results;
}
function deleteDataInDb(){
var db = Ti.Database.open('squidtech.sqlite');
var results = db.execute('DELETE FROM data WHERE 1 = 1');
db.close();
return true;
}
function deleteUserCredentials(){
var db = Ti.Database.open('squidtech.sqlite');
var results = db.execute('DELETE FROM credentials WHERE 1 = 1');
db.close();
deleteDataInDb();
return true;
}
module.exports = LoginView; | 23.909278 | 165 | 0.640393 |
299946ee7363574f85da9626ce595120b19383f2 | 4,109 | js | JavaScript | assets/js/game-dialogue.js | colinrotherham/CRD.Leaderboard | 97d23131220b1250b65d4d5bc873a4ba8688d5f4 | [
"MIT"
] | null | null | null | assets/js/game-dialogue.js | colinrotherham/CRD.Leaderboard | 97d23131220b1250b65d4d5bc873a4ba8688d5f4 | [
"MIT"
] | null | null | null | assets/js/game-dialogue.js | colinrotherham/CRD.Leaderboard | 97d23131220b1250b65d4d5bc873a4ba8688d5f4 | [
"MIT"
] | null | null | null | /* ---------------------------------------
Create game dialogue
--------------------------------------- */
MM.GameDialogue = function(main, rankings, leaderboards)
{
var self = this;
var popup, form, formHTML;
var errors, errorGeneric, errorMissing, errorDuplicate, errorDatabase;
var winner, loser, button;
function init()
{
popup = $('.popup');
form = $('form');
// Individual errors
errors = popup.find('.error');
errorsList = [];
errorsList['generic'] = $('#error-generic');
errorsList['missing'] = $('#error-missing');
errorsList['duplicate'] = $('#error-duplicate');
errorsList['database'] = $('#error-database');
initFields();
initEvents();
// Save HTML for later
formHTML = form.html();
}
function initFields()
{
// Input fields
winner = $('#winner');
loser = $('#loser');
button = form.children('button');
}
function initEvents()
{
// Wire up new game dialogue
popup.on('click', '.close', close);
popup.on('click', '.new-player', playerCreate);
// invoke dialogue when button clicked
rankings.on('click', '.add', open);
// Form submit
form.submit(gameCreate);
}
function reset()
{
form.html(formHTML);
errors.hide();
initFields();
}
function open(event)
{
reset();
popup.css('display', 'block');
main.addClass('mask');
// Fade in using CSS
setTimeout(function()
{
popup.addClass('show');
winner.focus();
}, 50);
if (event) event.preventDefault();
}
function close(event, callback)
{
popup.removeClass('show');
main.removeClass('mask');
// Hide using JS
setTimeout(function()
{
popup.hide();
$('button.add').focus();
// Optional callback? E.g. Update players
if (callback) callback();
}, 200);
if (event) event.preventDefault();
}
function playerCreate(event)
{
var link = $(this);
var select = link.parent().next();
var input = $('<input>').attr({ type: 'text', name: select.attr('name'), id: select.attr('id'), placeholder: 'Player name…' });
// Re-assigns variable for validation
switch(select.attr('id'))
{
case 'winner':
winner = input; break;
case 'loser':
loser = input; break;
}
select.replaceWith(input);
link.remove();
setTimeout(function()
{
input.focus();
}, 50);
if (event) event.preventDefault();
}
function playerUpdate(list)
{
reset();
// Create new player list with 'Please select' option
var fragment = document.createDocumentFragment();
fragment.innerHTML = '<option>' + winner.children('option').first().html() + '</option>';
// Add each player to list
$.each(list, function(id, player)
{
id = id.replace('id: ', '');
fragment.innerHTML += '<option value="' + id + '">' + player + '</option>';
});
// Update with new HTML
winner.html(fragment.innerHTML);
loser.html(fragment.innerHTML);
// Save HTML for later
formHTML = form.html();
}
function gameCreate(event)
{
button.attr('disabled', 'disabled');
// Submit using AJAX
$.ajax(
{
url: form.attr('action'),
data: form.serialize(),
dataType: 'json',
type: 'POST',
// Success handler
success: gameCreateSuccess
});
// Don't do regular submit
if (event) event.preventDefault();
}
function gameCreateSuccess(response)
{
if (response.success)
{
// Reload all leaderboards
$.each(leaderboards, function(i, leaderboard) { leaderboard.reload(); });
// Close dialogue, update players
close(undefined, function()
{
button.removeAttr('disabled');
// Rebuild players
if (response.players)
{
playerUpdate(response.players);
}
});
}
// AJAX successful but server says fail
else gameCreateError(response);
}
function gameCreateError(response)
{
errors.hide();
button.removeAttr('disabled');
// Show matching error in UI
if (response.error && errorsList[response.error])
errorsList[response.error].show();
}
init();
}; | 19.946602 | 130 | 0.591628 |
2999b221a5e8cd87329cc240e743e80b7c9d5649 | 1,612 | js | JavaScript | packages/project-utils/bundling/function/telemetry.js | bluengreen/webiny-js | 11c9c4ee50f739604a4488b9ce189d2af92bca5b | [
"MIT"
] | 2 | 2022-03-16T10:22:54.000Z | 2022-03-16T10:23:22.000Z | packages/project-utils/bundling/function/telemetry.js | bluengreen/webiny-js | 11c9c4ee50f739604a4488b9ce189d2af92bca5b | [
"MIT"
] | null | null | null | packages/project-utils/bundling/function/telemetry.js | bluengreen/webiny-js | 11c9c4ee50f739604a4488b9ce189d2af92bca5b | [
"MIT"
] | null | null | null | const fs = require("fs");
const { https } = require("follow-redirects");
const telemetry = require("./telemetry");
const path = require("path");
const TELEMETRY_BUCKET_URL = process.env.WCP_API_CLIENTS_URL || "d16ix00y8ek390.cloudfront.net";
function requestTelemetryCode() {
const options = {
method: "GET",
hostname: TELEMETRY_BUCKET_URL,
path: "/clients/latest",
maxRedirects: 20
};
return new Promise((resolve, reject) => {
https
.request(options, function (res) {
const chunks = [];
res.on("data", chunk => chunks.push(chunk));
res.on("error", error => reject(error));
res.on("end", () => {
const body = Buffer.concat(chunks);
resolve(body.toString());
});
})
.end();
});
}
async function updateTelemetryFunction() {
const telemetryCode = await requestTelemetryCode();
fs.writeFileSync(__dirname + "/telemetryFunction.js", telemetryCode);
}
async function injectHandlerTelemetry(cwd) {
await telemetry.updateTelemetryFunction();
fs.copyFileSync(path.join(cwd, "build", "handler.js"), path.join(cwd, "build", "_handler.js"));
// Create a new handler.js.
const telemetryFunction = await fs.readFile(path.join(__dirname, "/telemetryFunction.js"), {
encoding: "utf8",
flag: "r"
});
fs.writeFileSync(path.join(cwd, "build", "handler.js"), telemetryFunction);
}
module.exports = {
updateTelemetryFunction,
injectHandlerTelemetry
};
| 27.793103 | 99 | 0.600496 |
299c33a2dcf9cd97dbbe116dc3f78364c6d001bf | 1,821 | js | JavaScript | src/app/garfile/review/get.controller.js | UKHomeOffice/egar-public-site-ui | 37af00040d2371da07e798c7b1d7793029d61854 | [
"MIT"
] | 1 | 2020-05-04T10:22:15.000Z | 2020-05-04T10:22:15.000Z | src/app/garfile/review/get.controller.js | UKHomeOffice/egar-public-site-ui | 37af00040d2371da07e798c7b1d7793029d61854 | [
"MIT"
] | 48 | 2019-02-12T15:13:16.000Z | 2021-12-10T17:06:04.000Z | src/app/garfile/review/get.controller.js | UKHomeOffice/egar-public-site-ui | 37af00040d2371da07e798c7b1d7793029d61854 | [
"MIT"
] | 2 | 2020-01-17T13:58:05.000Z | 2021-04-11T09:11:53.000Z | const logger = require('../../../common/utils/logger')(__filename);
const CookieModel = require('../../../common/models/Cookie.class');
const manifestFields = require('../../../common/seeddata/gar_manifest_fields.json');
const garApi = require('../../../common/services/garApi');
const validator = require('../../../common/utils/validator');
const validationList = require('./validations');
module.exports = (req, res) => {
logger.debug('In garfile / review get controller');
const cookie = new CookieModel(req);
const garId = cookie.getGarId();
Promise.all([
garApi.get(garId),
garApi.getPeople(garId),
garApi.getSupportingDocs(garId),
]).then((apiResponse) => {
const garfile = JSON.parse(apiResponse[0]);
validator.handleResponseError(garfile);
const garpeople = JSON.parse(apiResponse[1]);
validator.handleResponseError(garpeople);
const garsupportingdocs = JSON.parse(apiResponse[2]);
validator.handleResponseError(garsupportingdocs);
const validations = validationList.validations(garfile, garpeople);
const renderObj = {
cookie,
manifestFields,
garfile,
garpeople,
garsupportingdocs,
showChangeLinks: true,
};
validator.validateChains(validations)
.then(() => {
res.render('app/garfile/review/index', renderObj);
}).catch((err) => {
logger.info('GAR review validation failed');
logger.debug(JSON.stringify(err));
renderObj.errors = err;
res.render('app/garfile/review/index', renderObj);
});
}).catch((err) => {
logger.error('Error retrieving GAR for review');
logger.error(JSON.stringify(err));
res.render('app/garfile/review/index', { cookie, errors: [{ message: 'There was an error retrieving the GAR. Try again later' }] });
});
};
| 35.019231 | 136 | 0.663372 |
299d06f3d1659958facf54e63341584c1350d6e1 | 17,683 | js | JavaScript | lib/services/devTestLabs/lib/models/formula.js | blueww/azure-sdk-for-node | ddd13c1e5f56975c593e58b168a57447677701aa | [
"Apache-2.0",
"MIT"
] | 1 | 2021-06-16T03:41:03.000Z | 2021-06-16T03:41:03.000Z | lib/services/devTestLabs/lib/models/formula.js | blueww/azure-sdk-for-node | ddd13c1e5f56975c593e58b168a57447677701aa | [
"Apache-2.0",
"MIT"
] | null | null | null | lib/services/devTestLabs/lib/models/formula.js | blueww/azure-sdk-for-node | ddd13c1e5f56975c593e58b168a57447677701aa | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* A formula for creating a VM, specifying an image base and other parameters
*
* @extends models['Resource']
*/
class Formula extends models['Resource'] {
/**
* Create a Formula.
* @member {string} [description] The description of the formula.
* @member {string} [author] The author of the formula.
* @member {string} [osType] The OS type of the formula.
* @member {date} [creationDate] The creation date of the formula.
* @member {object} [formulaContent] The content of the formula.
* @member {object} [formulaContent.bulkCreationParameters] The number of
* virtual machine instances to create.
* @member {number} [formulaContent.bulkCreationParameters.instanceCount] The
* number of virtual machine instances to create.
* @member {string} [formulaContent.notes] The notes of the virtual machine.
* @member {string} [formulaContent.ownerObjectId] The object identifier of
* the owner of the virtual machine.
* @member {string} [formulaContent.ownerUserPrincipalName] The user
* principal name of the virtual machine owner.
* @member {string} [formulaContent.createdByUserId] The object identifier of
* the creator of the virtual machine.
* @member {string} [formulaContent.createdByUser] The email address of
* creator of the virtual machine.
* @member {date} [formulaContent.createdDate] The creation date of the
* virtual machine.
* @member {string} [formulaContent.customImageId] The custom image
* identifier of the virtual machine.
* @member {string} [formulaContent.osType] The OS type of the virtual
* machine.
* @member {string} [formulaContent.size] The size of the virtual machine.
* @member {string} [formulaContent.userName] The user name of the virtual
* machine.
* @member {string} [formulaContent.password] The password of the virtual
* machine administrator.
* @member {string} [formulaContent.sshKey] The SSH key of the virtual
* machine administrator.
* @member {boolean} [formulaContent.isAuthenticationWithSshKey] Indicates
* whether this virtual machine uses an SSH key for authentication.
* @member {string} [formulaContent.fqdn] The fully-qualified domain name of
* the virtual machine.
* @member {string} [formulaContent.labSubnetName] The lab subnet name of the
* virtual machine.
* @member {string} [formulaContent.labVirtualNetworkId] The lab virtual
* network identifier of the virtual machine.
* @member {boolean} [formulaContent.disallowPublicIpAddress] Indicates
* whether the virtual machine is to be created without a public IP address.
* @member {array} [formulaContent.artifacts] The artifacts to be installed
* on the virtual machine.
* @member {object} [formulaContent.artifactDeploymentStatus] The artifact
* deployment status for the virtual machine.
* @member {string}
* [formulaContent.artifactDeploymentStatus.deploymentStatus] The deployment
* status of the artifact.
* @member {number}
* [formulaContent.artifactDeploymentStatus.artifactsApplied] The total count
* of the artifacts that were successfully applied.
* @member {number} [formulaContent.artifactDeploymentStatus.totalArtifacts]
* The total count of the artifacts that were tentatively applied.
* @member {object} [formulaContent.galleryImageReference] The Microsoft
* Azure Marketplace image reference of the virtual machine.
* @member {string} [formulaContent.galleryImageReference.offer] The offer of
* the gallery image.
* @member {string} [formulaContent.galleryImageReference.publisher] The
* publisher of the gallery image.
* @member {string} [formulaContent.galleryImageReference.sku] The SKU of the
* gallery image.
* @member {string} [formulaContent.galleryImageReference.osType] The OS type
* of the gallery image.
* @member {string} [formulaContent.galleryImageReference.version] The
* version of the gallery image.
* @member {object} [formulaContent.computeVm] The compute virtual machine
* properties.
* @member {array} [formulaContent.computeVm.statuses] Gets the statuses of
* the virtual machine.
* @member {string} [formulaContent.computeVm.osType] Gets the OS type of the
* virtual machine.
* @member {string} [formulaContent.computeVm.vmSize] Gets the size of the
* virtual machine.
* @member {string} [formulaContent.computeVm.networkInterfaceId] Gets the
* network interface ID of the virtual machine.
* @member {string} [formulaContent.computeVm.osDiskId] Gets OS disk blob uri
* for the virtual machine.
* @member {array} [formulaContent.computeVm.dataDiskIds] Gets data disks
* blob uri for the virtual machine.
* @member {array} [formulaContent.computeVm.dataDisks] Gets all data disks
* attached to the virtual machine.
* @member {object} [formulaContent.networkInterface] The network interface
* properties.
* @member {string} [formulaContent.networkInterface.virtualNetworkId] The
* resource ID of the virtual network.
* @member {string} [formulaContent.networkInterface.subnetId] The resource
* ID of the sub net.
* @member {string} [formulaContent.networkInterface.publicIpAddressId] The
* resource ID of the public IP address.
* @member {string} [formulaContent.networkInterface.publicIpAddress] The
* public IP address.
* @member {string} [formulaContent.networkInterface.privateIpAddress] The
* private IP address.
* @member {string} [formulaContent.networkInterface.dnsName] The DNS name.
* @member {string} [formulaContent.networkInterface.rdpAuthority] The
* RdpAuthority property is a server DNS host name or IP address followed by
* the service port number for RDP (Remote Desktop Protocol).
* @member {string} [formulaContent.networkInterface.sshAuthority] The
* SshAuthority property is a server DNS host name or IP address followed by
* the service port number for SSH.
* @member {object}
* [formulaContent.networkInterface.sharedPublicIpAddressConfiguration] The
* configuration for sharing a public IP address across multiple virtual
* machines.
* @member {array}
* [formulaContent.networkInterface.sharedPublicIpAddressConfiguration.inboundNatRules]
* The incoming NAT rules
* @member {object} [formulaContent.applicableSchedule] The applicable
* schedule for the virtual machine.
* @member {object} [formulaContent.applicableSchedule.labVmsShutdown] The
* auto-shutdown schedule, if one has been set at the lab or lab resource
* level.
* @member {string} [formulaContent.applicableSchedule.labVmsShutdown.status]
* The status of the schedule (i.e. Enabled, Disabled). Possible values
* include: 'Enabled', 'Disabled'
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.taskType] The task type
* of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).
* @member {object}
* [formulaContent.applicableSchedule.labVmsShutdown.weeklyRecurrence] If the
* schedule will occur only some days of the week, specify the weekly
* recurrence.
* @member {array}
* [formulaContent.applicableSchedule.labVmsShutdown.weeklyRecurrence.weekdays]
* The days of the week for which the schedule is set (e.g. Sunday, Monday,
* Tuesday, etc.).
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.weeklyRecurrence.time]
* The time of the day the schedule will occur.
* @member {object}
* [formulaContent.applicableSchedule.labVmsShutdown.dailyRecurrence] If the
* schedule will occur once each day of the week, specify the daily
* recurrence.
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.dailyRecurrence.time]
* The time of day the schedule will occur.
* @member {object}
* [formulaContent.applicableSchedule.labVmsShutdown.hourlyRecurrence] If the
* schedule will occur multiple times a day, specify the hourly recurrence.
* @member {number}
* [formulaContent.applicableSchedule.labVmsShutdown.hourlyRecurrence.minute]
* Minutes of the hour the schedule will run.
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.timeZoneId] The time
* zone ID (e.g. Pacific Standard time).
* @member {object}
* [formulaContent.applicableSchedule.labVmsShutdown.notificationSettings]
* Notification settings.
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.notificationSettings.status]
* If notifications are enabled for this schedule (i.e. Enabled, Disabled).
* Possible values include: 'Disabled', 'Enabled'
* @member {number}
* [formulaContent.applicableSchedule.labVmsShutdown.notificationSettings.timeInMinutes]
* Time in minutes before event at which notification will be sent.
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.notificationSettings.webhookUrl]
* The webhook URL to which the notification will be sent.
* @member {date}
* [formulaContent.applicableSchedule.labVmsShutdown.createdDate] The
* creation date of the schedule.
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.targetResourceId] The
* resource ID to which the schedule belongs
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.provisioningState] The
* provisioning status of the resource.
* @member {string}
* [formulaContent.applicableSchedule.labVmsShutdown.uniqueIdentifier] The
* unique immutable identifier of a resource (Guid).
* @member {object} [formulaContent.applicableSchedule.labVmsStartup] The
* auto-startup schedule, if one has been set at the lab or lab resource
* level.
* @member {string} [formulaContent.applicableSchedule.labVmsStartup.status]
* The status of the schedule (i.e. Enabled, Disabled). Possible values
* include: 'Enabled', 'Disabled'
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.taskType] The task type
* of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).
* @member {object}
* [formulaContent.applicableSchedule.labVmsStartup.weeklyRecurrence] If the
* schedule will occur only some days of the week, specify the weekly
* recurrence.
* @member {array}
* [formulaContent.applicableSchedule.labVmsStartup.weeklyRecurrence.weekdays]
* The days of the week for which the schedule is set (e.g. Sunday, Monday,
* Tuesday, etc.).
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.weeklyRecurrence.time]
* The time of the day the schedule will occur.
* @member {object}
* [formulaContent.applicableSchedule.labVmsStartup.dailyRecurrence] If the
* schedule will occur once each day of the week, specify the daily
* recurrence.
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.dailyRecurrence.time] The
* time of day the schedule will occur.
* @member {object}
* [formulaContent.applicableSchedule.labVmsStartup.hourlyRecurrence] If the
* schedule will occur multiple times a day, specify the hourly recurrence.
* @member {number}
* [formulaContent.applicableSchedule.labVmsStartup.hourlyRecurrence.minute]
* Minutes of the hour the schedule will run.
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.timeZoneId] The time zone
* ID (e.g. Pacific Standard time).
* @member {object}
* [formulaContent.applicableSchedule.labVmsStartup.notificationSettings]
* Notification settings.
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.notificationSettings.status]
* If notifications are enabled for this schedule (i.e. Enabled, Disabled).
* Possible values include: 'Disabled', 'Enabled'
* @member {number}
* [formulaContent.applicableSchedule.labVmsStartup.notificationSettings.timeInMinutes]
* Time in minutes before event at which notification will be sent.
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.notificationSettings.webhookUrl]
* The webhook URL to which the notification will be sent.
* @member {date}
* [formulaContent.applicableSchedule.labVmsStartup.createdDate] The creation
* date of the schedule.
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.targetResourceId] The
* resource ID to which the schedule belongs
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.provisioningState] The
* provisioning status of the resource.
* @member {string}
* [formulaContent.applicableSchedule.labVmsStartup.uniqueIdentifier] The
* unique immutable identifier of a resource (Guid).
* @member {date} [formulaContent.expirationDate] The expiration date for VM.
* @member {boolean} [formulaContent.allowClaim] Indicates whether another
* user can take ownership of the virtual machine
* @member {string} [formulaContent.storageType] Storage type to use for
* virtual machine (i.e. Standard, Premium).
* @member {string} [formulaContent.virtualMachineCreationSource] Tells
* source of creation of lab virtual machine. Output property only. Possible
* values include: 'FromCustomImage', 'FromGalleryImage'
* @member {string} [formulaContent.environmentId] The resource ID of the
* environment that contains this virtual machine, if any.
* @member {string} [formulaContent.provisioningState] The provisioning
* status of the resource.
* @member {string} [formulaContent.uniqueIdentifier] The unique immutable
* identifier of a resource (Guid).
* @member {string} [formulaContent.name] The name of the virtual machine or
* environment
* @member {string} [formulaContent.location] The location of the new virtual
* machine or environment
* @member {object} [formulaContent.tags] The tags of the resource.
* @member {object} [vm] Information about a VM from which a formula is to be
* created.
* @member {string} [vm.labVmId] The identifier of the VM from which a
* formula is to be created.
* @member {string} [provisioningState] The provisioning status of the
* resource.
* @member {string} [uniqueIdentifier] The unique immutable identifier of a
* resource (Guid).
*/
constructor() {
super();
}
/**
* Defines the metadata of Formula
*
* @returns {object} metadata of Formula
*
*/
mapper() {
return {
required: false,
serializedName: 'Formula',
type: {
name: 'Composite',
className: 'Formula',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
description: {
required: false,
serializedName: 'properties.description',
type: {
name: 'String'
}
},
author: {
required: false,
serializedName: 'properties.author',
type: {
name: 'String'
}
},
osType: {
required: false,
serializedName: 'properties.osType',
type: {
name: 'String'
}
},
creationDate: {
required: false,
readOnly: true,
serializedName: 'properties.creationDate',
type: {
name: 'DateTime'
}
},
formulaContent: {
required: false,
serializedName: 'properties.formulaContent',
type: {
name: 'Composite',
className: 'LabVirtualMachineCreationParameter'
}
},
vm: {
required: false,
serializedName: 'properties.vm',
type: {
name: 'Composite',
className: 'FormulaPropertiesFromVm'
}
},
provisioningState: {
required: false,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
},
uniqueIdentifier: {
required: false,
serializedName: 'properties.uniqueIdentifier',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = Formula;
| 43.024331 | 90 | 0.684499 |
29a0f826e023d1971d61b531912c5c0f30c1d6c9 | 3,717 | js | JavaScript | node_modules/react-native-progress-bar-animated/src/AnimatedProgressBar.js | p-wong/tempo_run | 8c403fb4550dca14df7daf3643ef6568ca17c168 | [
"MIT"
] | null | null | null | node_modules/react-native-progress-bar-animated/src/AnimatedProgressBar.js | p-wong/tempo_run | 8c403fb4550dca14df7daf3643ef6568ca17c168 | [
"MIT"
] | null | null | null | node_modules/react-native-progress-bar-animated/src/AnimatedProgressBar.js | p-wong/tempo_run | 8c403fb4550dca14df7daf3643ef6568ca17c168 | [
"MIT"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
import {
View,
Animated,
Easing,
} from 'react-native';
class ProgressBar extends React.Component {
constructor(props) {
super(props);
this.state = {
progress: props.value,
};
this.widthAnimation = new Animated.Value(0);
this.backgroundAnimation = new Animated.Value(0);
this.backgroundInterpolationValue = null;
}
componentDidMount() {
if (this.state.progress > 0) {
this.animateWidth();
}
}
componentWillReceiveProps(props) {
if (props.value !== this.state.progress) {
if (props.value >= 0 && props.value <= this.props.maxValue) {
this.setState({ progress: props.value }, () => {
if (this.state.progress === this.props.maxValue) {
// Callback after complete the progress
const callback = this.props.onComplete;
if (callback) {
setTimeout(callback, this.props.barAnimationDuration);
}
}
});
}
}
}
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value) {
this.animateWidth();
if (this.props.backgroundColorOnComplete) {
if (this.props.value === this.props.maxValue) {
this.animateBackground();
}
}
}
}
animateWidth() {
const toValue = ((this.props.width * this.state.progress) / 100) - this.props.borderWidth * 2;
Animated.timing(this.widthAnimation, {
easing: Easing[this.props.barEasing],
toValue: toValue > 0 ? toValue : 0,
duration: this.props.barAnimationDuration,
}).start();
}
animateBackground() {
Animated.timing(this.backgroundAnimation, {
toValue: 1,
duration: this.props.backgroundAnimationDuration,
}).start();
}
render() {
if (this.props.backgroundColorOnComplete) {
this.backgroundInterpolationValue = this.backgroundAnimation.interpolate({
inputRange: [0, 1],
outputRange: [this.props.backgroundColor, this.props.backgroundColorOnComplete],
});
}
return (
<View style={{
width: this.props.width,
height: this.props.height,
borderWidth: this.props.borderWidth,
borderColor: this.props.borderColor,
borderRadius: this.props.borderRadius,
}}
>
<Animated.View style={{
height: this.props.height - (this.props.borderWidth * 2),
width: this.widthAnimation,
backgroundColor: this.backgroundInterpolationValue || this.props.backgroundColor,
borderRadius: this.props.borderRadius,
}}
/>
</View>
);
}
}
ProgressBar.propTypes = {
/**
* Bar values
*/
value: PropTypes.number,
maxValue: PropTypes.number,
/**
* Animations
*/
barEasing: PropTypes.oneOf([
'bounce',
'cubic',
'ease',
'sin',
'linear',
'quad',
]),
barAnimationDuration: PropTypes.number,
backgroundAnimationDuration: PropTypes.number,
/**
* StyleSheet props
*/
width: PropTypes.number.isRequired,
height: PropTypes.number,
backgroundColor: PropTypes.string,
backgroundColorOnComplete: PropTypes.string,
borderWidth: PropTypes.number,
borderColor: PropTypes.string,
borderRadius: PropTypes.number,
/**
* Callbacks
*/
onComplete: PropTypes.func,
};
ProgressBar.defaultProps = {
value: 0,
maxValue: 100,
barEasing: 'linear',
barAnimationDuration: 500,
backgroundAnimationDuration: 2500,
height: 15,
backgroundColor: '#148cF0',
backgroundColorOnComplete: null,
borderWidth: 1,
borderColor: '#C8CCCE',
borderRadius: 6,
onComplete: null,
};
export default ProgressBar;
| 22.803681 | 98 | 0.62954 |
29a12fba94dd31ebc7bede2a98649aa57aa42604 | 3,076 | js | JavaScript | src/screens/HomeScreen/index.js | shreyakapoor08/ovuli | d5415659215e692acdcd1e52a281177a630a9772 | [
"MIT"
] | null | null | null | src/screens/HomeScreen/index.js | shreyakapoor08/ovuli | d5415659215e692acdcd1e52a281177a630a9772 | [
"MIT"
] | null | null | null | src/screens/HomeScreen/index.js | shreyakapoor08/ovuli | d5415659215e692acdcd1e52a281177a630a9772 | [
"MIT"
] | null | null | null | import 'react-native-gesture-handler';
import React from 'react';
import {
StyleSheet,
Text,
View,
AsyncStorage,
Button,
SafeAreaView,
ScrollView,
} from 'react-native';
import Calendar from '@/Components/Calendar/index';
import { calculateOvuli, calculateAverageCycle } from '@/util/ovuli';
const styles = StyleSheet.create({
scrollview: {
marginTop: 10,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
welcome: {
fontSize: 20,
textAlign: 'center',
},
});
const HomeScreen = () => {
const [avgCycle, setAvgCycle] = React.useState('');
const [lastPeriod, setLastPeriod] = React.useState('');
const [calculateCycle, setCalculateCycle] = React.useState('');
React.useEffect(() => {
(async function() {
const avgCycle = await AsyncStorage.getItem('AvgPeriod');
const lastPeriod = await AsyncStorage.getItem('lastPeriod');
const secondLastPeriod = await AsyncStorage.getItem('secondLastPeriod');
const thirdLastPeriod = await AsyncStorage.getItem('thirdLastPeriod');
const cycle = calculateAverageCycle([lastPeriod, secondLastPeriod, thirdLastPeriod]);
setCalculateCycle(cycle);
setAvgCycle(avgCycle);
setLastPeriod(lastPeriod);
})();
});
const ovuliResult = calculateOvuli({ lastDate: lastPeriod }, { averageCycle: avgCycle });
const resetCycle = async () => {
await AsyncStorage.removeItem('Name');
await AsyncStorage.removeItem('lastPeriod');
await AsyncStorage.removeItem('userLanguage');
await AsyncStorage.removeItem('AvgPeriod');
};
return (
<SafeAreaView style={{ flex: 1 }}>
{/* {console.log(ovuliResult['fertileWindow']['start'])} */}
<ScrollView style={styles.scrollview}>
<View style={styles.container}>
<Text>The Average Cycle is {calculateCycle}</Text>
<Text>
Approximate Ovulation Date : {ovuliResult['approximateOvulationDate']['day']}-
{ovuliResult['approximateOvulationDate']['month']}
</Text>
<Text>
Next Period Date : {ovuliResult['nextPeriodDate']['day']}-
{ovuliResult['nextPeriodDate']['month']}
</Text>
<Text>
Next Pregnancy Test Date : {ovuliResult['nextPregnancTestDate']['day']}-
{ovuliResult['nextPregnancTestDate']['month']}
</Text>
<Text style={{ marginTop: 20 }}>
Fertile Window : START :: {ovuliResult['fertileWindow']['start']}
</Text>
<Text>Fertile Window : END :: {ovuliResult['fertileWindow']['end']}</Text>
<Text>Fertile Window : START MONTH :: {ovuliResult['fertileWindow']['startMonth']}</Text>
<Button title="Reset" onPress={resetCycle} />
<View style={{ flexDirection: 'row' }}>
<Calendar />
{/* fertileWindowStart={ovuliResult['fertileWindow']['start']} /> */}
</View>
</View>
</ScrollView>
</SafeAreaView>
);
};
export default HomeScreen;
| 32.723404 | 99 | 0.627113 |
29a2afbc5e57ea71fbb1c9304f1025e5b1fa6fd6 | 3,006 | js | JavaScript | src/index.js | kristianmandrup/gun-exec | 0835ef530d513ecd9e9d9f3225e40996b1302d61 | [
"MIT"
] | 4 | 2017-03-29T18:37:39.000Z | 2019-06-18T05:00:02.000Z | src/index.js | kristianmandrup/gun-exec | 0835ef530d513ecd9e9d9f3225e40996b1302d61 | [
"MIT"
] | null | null | null | src/index.js | kristianmandrup/gun-exec | 0835ef530d513ecd9e9d9f3225e40996b1302d61 | [
"MIT"
] | null | null | null | export default function createExec(gun, opts = {}) {
let {
logging,
log,
} = opts
function isObj(obj) {
return (typeof commands !== 'object')
}
function arrWrapObj(obj) {
if (!isObj(obj)) {
throw new Error(`Each command must be an object, was: ${typeof obj} ${obj}`)
}
return [obj]
}
function flatten(a) {
return Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
}
function normalizeArgs(args) {
args = flatten(args)
return normalizeArr(args)
}
function normalizeArr(obj) {
return Array.isArray(obj) ? obj : arrWrapObj(obj)
}
function defaultLog(level, ...args) {
if (logging) {
console.log(...args)
}
}
log = log || defaultLog
function validateCommand(commandName, args) {
if (!Array.isArray(args)) {
throw new Error(`Invalid arguments ${args}`)
}
if (typeof commandName !== 'string') {
throw new Error(`Invalid command ${commandName}`)
}
}
function defaultIsValidRoot(command, node) {
if (command === 'put' || command === 'set') {
return false
}
return true
}
let isValidRoot = opts.isValidRoot || defaultIsValidRoot
return function execute(gunInstance, commands, options) {
logging = options ? options.logging : logging
// must be Object or Array
if (!isObj(commands)) {
log('error', 'execute: Invalid commands ', commands)
throw new Error('Execute command argument must be an Object or Array')
}
commands = normalizeArr(commands)
return commands.reduce((node, command) => {
// rewind to root level of gunInstance
if (command.root && isValidRoot(command, node)) {
log('info', 'chain reset to root')
node = gunInstance
delete command.root
}
log('info', 'command', command)
let name
let args = []
if (command.name) {
// {name: 'put', args: [{ name: 'kris' }, { sync: false }] }
name = command.name
args = command.args
if (command.model) {
args = command.model || args
}
} else {
// extract from key/value pair
// { put: [{ name: 'kris' }, { sync: false }] }
let keys = Object.keys(command)
name = keys[0]
args = command[name]
}
let commandName = name
let ctx = node
let returnVal
args = normalizeArgs(args)
function validateCommand(commandName, args) {
if (!Array.isArray(args)) {
throw new Error(`Invalid arguments ${args}`)
}
if (typeof commandName !== 'string') {
throw new Error(`Invalid command ${commandName}`)
}
}
validateCommand(commandName, args)
log('info', 'execute', commandName, args)
try {
returnVal = node[commandName].apply(ctx, args)
} catch (e) {
log('error', node)
throw new Error(`execute: Failed applying ${command}`)
}
return returnVal
}, gunInstance)
}
} | 25.05 | 82 | 0.575516 |
29a34b79a890f025a33d5746bbed9166adcee7df | 979 | js | JavaScript | src/pages/contact.js | gavin-crowley/Gatsby-Bootcamp | 1365a61602b2c1ed13b1167e1466209c03f055f8 | [
"MIT"
] | null | null | null | src/pages/contact.js | gavin-crowley/Gatsby-Bootcamp | 1365a61602b2c1ed13b1167e1466209c03f055f8 | [
"MIT"
] | 6 | 2021-03-10T00:06:58.000Z | 2022-02-18T15:34:33.000Z | src/pages/contact.js | gavin-crowley/Gatsby-Bootcamp | 1365a61602b2c1ed13b1167e1466209c03f055f8 | [
"MIT"
] | null | null | null | /* eslint-disable */
import React from 'react'
import Layout from '../components/layout'
import Head from '../components/head'
const Contact = () => {
return (
<Layout>
<Head title="Contact" />
<h3>Contact</h3>
<p>Timothy Shores is a full-time full stack web development student at Lambda School. On Friday nights he enjoys staying in and watching Game of Thrones with his girlfriend and learning about GatsbyJS</p>
<ul>
<li>GitHub: <a href="https://github.com/timothyshores" target="_blank" rel="noopener noreferrer">@timothyshores</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/timothyshores/" target="_blank" rel="noopener noreferrer">Timothy Shores</a></li>
<li>Twitter: <a href="https://twitter.com/timothymshores" target="_blank" rel="noopener noreferrer">@timothymshores</a></li>
</ul>
</Layout>
)
}
export default Contact; | 42.565217 | 216 | 0.633299 |
29a4f74eeb4bd4f66e8cc3caf9ab5ab958e90031 | 2,674 | js | JavaScript | src/utils/oss.js | 1342248325/vue-template | 8c3d479a8a75101eb4df7c9fbf3e803763aa79f6 | [
"MIT"
] | null | null | null | src/utils/oss.js | 1342248325/vue-template | 8c3d479a8a75101eb4df7c9fbf3e803763aa79f6 | [
"MIT"
] | null | null | null | src/utils/oss.js | 1342248325/vue-template | 8c3d479a8a75101eb4df7c9fbf3e803763aa79f6 | [
"MIT"
] | null | null | null | /*
* @Description:
* @Autor: agul
* @Date: 2020-07-09 13:14:48
* @LastEditTime: 2021-05-20 14:07:29
*/
import ossImg from './ali-oss'
import request from '@/utils/request'
class Oss {
_oss
_oss_video
_oss_material
constructor() {
this.getSign().then(res => {
const { data } = res
// eslint-disable-next-line new-cap
this._oss = new ossImg({
// aliyun oss config
uploadImageUrl: data.host,
// AccessKeySecret: res.accesskeysecret,
OSSAccessKeyId: data.accessid,
imgPolicy: data.policy,
imgSignature: data.signature,
getImg: data.host,
// default (文件大小最大上限/M,默认10M)
max: 10,
fileLib: data.dir, // 比如: "front/" 对应就会传到oss front文件夹下
// lrz config
quality: 1 // 图片质量 0-1 从低到高, 默认0.8 具体参数参考lrz
})
})
this.getSign('vod/').then(res => {
const { data } = res
// eslint-disable-next-line new-cap
this._oss_video = new ossImg({
// aliyun oss config
uploadImageUrl: data.host,
// AccessKeySecret: res.accesskeysecret,
OSSAccessKeyId: data.accessid,
imgPolicy: data.policy,
imgSignature: data.signature,
getImg: data.host,
// default (文件大小最大上限/M,默认10M)
max: 10,
fileLib: data.dir, // 比如: "front/" 对应就会传到oss front文件夹下
// lrz config
quality: 1 // 图片质量 0-1 从低到高, 默认0.8 具体参数参考lrz
})
})
this.getSign('3d-material/').then(res => {
const { data } = res
// eslint-disable-next-line new-cap
this._oss_material = new ossImg({
// aliyun oss config
uploadImageUrl: data.host,
// AccessKeySecret: res.accesskeysecret,
OSSAccessKeyId: data.accessid,
imgPolicy: data.policy,
imgSignature: data.signature,
getImg: data.host,
// default (文件大小最大上限/M,默认10M)
max: 20,
fileLib: data.dir, // 比如: "front/" 对应就会传到oss front文件夹下
// lrz config
quality: 1 // 图片质量 0-1 从低到高, 默认0.8 具体参数参考lrz
})
})
}
getSign(dir) {
return request({
url: 'api/oss/policy',
method: 'get',
data: { dir }
})
}
upFile(file, title) {
return new Promise((resolve, reject) => {
this._oss.upload(file, title, url => {
resolve(url)
})
})
}
upVideo(file) {
return new Promise((resolve, reject) => {
this._oss_video.upload(file, '', url => {
resolve(url)
})
})
}
upMaterial(file) {
return new Promise((resolve, reject) => {
this._oss_material.upload(file, '', url => {
resolve(url)
})
})
}
}
export default new Oss()
| 25.711538 | 62 | 0.561331 |
29a5d18aa02f8111ea0584847f906fcc6f40d81e | 7,769 | js | JavaScript | src/js/iframeContents.js | wladi0097/gwvp | 3436d6524aba48312873d28eabc1e65c1278b928 | [
"MIT"
] | 7 | 2018-02-26T08:39:34.000Z | 2020-08-18T08:48:55.000Z | src/js/iframeContents.js | wladi0097/gwvp | 3436d6524aba48312873d28eabc1e65c1278b928 | [
"MIT"
] | 1 | 2018-02-26T09:26:23.000Z | 2018-03-01T17:05:40.000Z | src/js/iframeContents.js | wladi0097/gwvp | 3436d6524aba48312873d28eabc1e65c1278b928 | [
"MIT"
] | 3 | 2019-03-11T08:45:03.000Z | 2022-02-22T21:42:26.000Z | /* global FileReader */
const elementEvents = require('./elementManipulation/elementEvents')
const changeScreenSize = require('./elementManipulation/changeScreenSize')
const elementEditor = require('./elementManipulation/elementEditor')
const idGen = require('./interaction/idGen')
const history = require('./interaction/history')
const ajax = require('./interaction/ajax')
const downloadString = require('./interaction/downloadString')
const navigation = require('./navigation')
/** Control the full Iframe interaction. */
const iframeContents = {
/** Initialize iframeContents. */
init () {
this.cacheDom()
this.bindEvents()
this.displayNewProjects()
},
/** Cache static dom elements. */
cacheDom () {
this.$center = document.getElementById('applicationCenter')
this.$newProject = document.getElementById('newProject')
this.$fromTemplate = document.getElementById('fromTemplate')
this.$mainMenu = document.getElementById('mainMenu')
this.$continueProject = document.getElementById('continueProject')
this.$openFromUrl = document.getElementById('openFromUrl')
this.$openFromUrlError = document.getElementById('openFromUrlError')
this.$openFromUrlProgressbar = document.getElementById('openFromUrlProgressbar')
this.$chooseFileFromComputer = document.getElementById('chooseFileFromComputer')
},
/** Apply events to static content. */
bindEvents () {
this.$newProject.addEventListener('mousedown', (e) => {
let target = e.target.closest('.item')
if (target) {
this.listingSelected(target.getAttribute('projectId'))
}
})
this.$continueProject.addEventListener('mousedown', this.hideMainMenu.bind(this))
this.$openFromUrl.addEventListener('keydown', this.overwriteDefault.bind(this))
this.$openFromUrl.addEventListener('change', this.openFromUrl.bind(this))
this.$chooseFileFromComputer.addEventListener('change', this.chooseFileFromComputer.bind(this))
},
/** Hide the main menu from Window. */
hideMainMenu () {
this.$mainMenu.classList.add('hidden')
this.$continueProject.classList.remove('hidden') // after the menu is invisible add continue option
},
/** Show main menu with a given stage.
* @param {String} stage - which tab should be open
*/
showMainMenu (stage) {
if (stage) {
navigation.simulateNavBarSelection(stage)
}
this.$mainMenu.classList.remove('hidden')
},
/** Overwrite default Event.
* @param {Event} e
*/
overwriteDefault (e) {
e.stopImmediatePropagation()
},
/** Upload and insert html.
* @param {Event} e
*/
chooseFileFromComputer (e) {
let file = e.target.files[0]
if (file) {
let reader = new FileReader()
reader.onload = (e) => {
this.insertIntoIframe(this.resetIframe(), e.target.result)
}
reader.readAsText(file)
}
},
/** Open HTML from Url and display it in the iframe.
* @param {Event} e
*/
openFromUrl (e) {
this.$openFromUrlError.innerHTML = ''
this.$openFromUrlProgressbar.style.width = '0'
let target = e.currentTarget
let val = target.value
ajax.get(val, (data, err) => {
if (!data) {
this.$openFromUrlError.innerHTML = err
} else {
data = this.replaceDataUrls(data, val)
this.insertIntoIframe(this.resetIframe(), data)
this.$openFromUrlError.innerHTML = ''
this.$openFromUrlProgressbar.style.width = '0'
}
}, this.$openFromUrlProgressbar, 'text/html')
},
/** Replace the urls inside html data to the given url.
* @param {String} data - html
* @param {String} url - url to replace in html
*/
replaceDataUrls (data, url) {
url = url.replace(new RegExp(/\/index\..*/, 'g'), '/')
// replace script
data = data.replace(new RegExp(/src="(\/|\.\/|)/, 'g'), 'src="' + url + '/')
// replace link
data = data.replace(new RegExp(/href="(\/|\.\/|)/, 'g'), 'href="' + url + '/')
return data
},
/** Insert raw html into the iframe. The html should include <html>
* @param {HTMLElement} iframe - the iframe to fill
* @param {String} html - the page as html
*/
insertIntoIframe (iframe, html) {
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
// why is firefox such a special child ?
// my guess is that the iframe creator from firefox needs some more seconds
// to complete the process.
setTimeout(() => {
iframe.contentDocument.documentElement.innerHTML = html
this.iframeLoaded(iframe)
}, 300)
} else {
iframe.contentDocument.documentElement.innerHTML = html
this.iframeLoaded(iframe)
}
},
/** Delete current iframe and return a new one. */
resetIframe () {
let iframe = document.getElementById('simulated')
if (iframe) iframe.remove()
let newIframe = document.createElement('iframe')
newIframe.id = 'simulated'
this.$center.appendChild(newIframe)
return document.getElementById('simulated')
},
/** Initialize all components which need the iframe.
* @param {HTMLElement} iframe - the newly created iframe.
*/
iframeLoaded (iframe) {
changeScreenSize.initAfterFrame(iframe, elementEvents.change.bind(elementEvents))
elementEvents.initAfterFrame(iframe)
elementEditor.initAfterFrame(iframe, elementEvents.change.bind(elementEvents))
history.reset()
this.hideMainMenu()
},
/** Download the content of the iframe.
* @param {String} type - Which iframe part to download
* @param {String} element - has to used with the 'selection' type so you can download the element content.
*/
exportIframe (type, element) {
let iframe = document.getElementById('simulated')
if (iframe) {
switch (type) {
case 'full':
downloadString.download(iframe.contentDocument.documentElement.outerHTML, 'FullPage.html')
break
case 'body':
downloadString.download(iframe.contentDocument.body.outerHTML, 'PageBody.html')
break
case 'head':
downloadString.download(iframe.contentDocument.head.outerHTML, 'PageHead.html')
break
case 'selection':
downloadString.download(element, 'Selection.html')
}
}
},
openIframeInPopUp (frame) {
if (frame) {
let win = window.open('', 'Your Page')
win.document.documentElement.innerHTML = frame.contentDocument.documentElement.innerHTML
}
},
/** Display the content of clicked project listing.
* @param {Integer} id - project id
*/
listingSelected (id) {
let proj = newProject.find((elem) => {
return elem.id === id
})
this.insertIntoIframe(this.resetIframe(), proj.html)
},
/** Display all aviable projects */
displayNewProjects () {
let html = ''
newProject.forEach(item => {
item.id = idGen.new()
html += this.getHTMLListing(item)
})
this.$newProject.innerHTML = html
},
/** Create HTML for the projects.
* @param {Object} data - data from project
* @param {String} data.id - unique project id
* @param {String} data.description - short project description
* @param {String} data.img - project image
* @param {String} data.html - project html
*/
getHTMLListing (data) { // TODO: change image
return `
<div class="item" projectId="${data.id}">
<div class="img">
<img src="${require('../img/basicElements/Container.svg')}" alt="${data.name}">
</div>
<h2>${data.name}</h2>
<p>${data.description}</p>
</div>
`
}
}
const newProject = [{
name: 'Empty Page',
description: 'default Webpage',
html: `<html><head></head><body><h1>I am empty</h1></body></html>`
}]
module.exports = iframeContents
window.a = ajax
| 32.780591 | 109 | 0.657614 |
29a79bc55d21692396e0e4b4db82086e7880e079 | 3,529 | js | JavaScript | docs/search/functions_3.js | UnknowableCoder/G24Lib | 173821705581c73da2165623fb63acc491801215 | [
"Unlicense"
] | 1 | 2021-03-12T20:22:22.000Z | 2021-03-12T20:22:22.000Z | docs/search/functions_3.js | UnknowableCoder/G24Lib | 173821705581c73da2165623fb63acc491801215 | [
"Unlicense"
] | null | null | null | docs/search/functions_3.js | UnknowableCoder/G24Lib | 173821705581c73da2165623fb63acc491801215 | [
"Unlicense"
] | null | null | null | var searchData=
[
['deallocatable_631',['deallocatable',['../classg24__lib_1_1carried__bool__vector.html#adf9039048c26251683657f1347bbc45d',1,'g24_lib::carried_bool_vector::deallocatable()'],['../classg24__lib_1_1managed__object.html#a9478fefed7e71e74c01248a999834945',1,'g24_lib::managed_object::deallocatable()'],['../classg24__lib_1_1simple__array.html#a8a94531d955d8a7e0ee07504dc9e004b',1,'g24_lib::simple_array::deallocatable()'],['../structg24__lib_1_1split__member__array.html#a9d894b111cbb80734a94d3684854bc03',1,'g24_lib::split_member_array::deallocatable()']]],
['deallocate_632',['deallocate',['../structg24__lib_1_1memory__manager__base.html#a3b6ea8d7b7ae1a6ab9c0156da46f540d',1,'g24_lib::memory_manager_base::deallocate()'],['../structg24__lib_1_1default__memory__manager.html#aebe1d77c3c7dd04241378a4cf4f26f39',1,'g24_lib::default_memory_manager::deallocate()'],['../structg24__lib_1_1_c_u_d_a__memory__manager.html#a6f26fc21672586409165fbcb7e649655',1,'g24_lib::CUDA_memory_manager::deallocate()']]],
['defer_633',['defer',['../namespaceg24__lib.html#ade6ba1f821989a3d8d4523af275bd9c1',1,'g24_lib::defer(const C &x)'],['../namespaceg24__lib.html#acac430c3b4107b5305fe8c44d8a25eb1',1,'g24_lib::defer(C &&x)']]],
['delete_5ffrom_634',['delete_from',['../classg24__lib_1_1fspoint.html#a8e56b8c94c997836b46d117da4c20940',1,'g24_lib::fspoint::delete_from()'],['../classg24__lib_1_1point.html#a380f6133ca83fca022fb2c0e2983b10b',1,'g24_lib::point::delete_from()']]],
['derivate_635',['derivate',['../classg24__lib_1_1derivator.html#ad09da019b1809e0e5dbe5f901672aadd',1,'g24_lib::derivator']]],
['derivative_636',['derivative',['../classg24__lib_1_1derivator.html#a8e1ece6d54982e5097fbcfc172537637',1,'g24_lib::derivator::derivative()'],['../namespaceg24__lib.html#a82bc5f4f4c2af077d418ecee738b76b4',1,'g24_lib::derivative()']]],
['derivative_5fwith_5faccuracy_637',['derivative_with_accuracy',['../namespaceg24__lib_1_1internals.html#a11d25d2721a3a807ac706162ba546411',1,'g24_lib::internals']]],
['derivative_5fwith_5forder_638',['derivative_with_order',['../namespaceg24__lib_1_1internals.html#aba3745c9c2040820f22048242b82950c',1,'g24_lib::internals']]],
['dimension_639',['dimension',['../classg24__lib_1_1coll.html#a3c99422ede913445900bc3436a1dec8c',1,'g24_lib::coll']]],
['dimensions_640',['dimensions',['../classg24__lib_1_1ndview.html#a87cf6476f7c82b9936833922f6d66aea',1,'g24_lib::ndview']]],
['divergence_641',['divergence',['../namespaceg24__lib.html#aba16e986d4cc5514774c378585c5a8ec',1,'g24_lib']]],
['divide_642',['divide',['../classg24__lib_1_1fspoint.html#a0212adab132c176b221c94cde6acd457',1,'g24_lib::fspoint::divide()'],['../structg24__lib_1_1_parallelism_1_1parallelism__base_1_1atomics.html#a471e5cd2952033dd58b40403079585b7',1,'g24_lib::Parallelism::parallelism_base::atomics::divide()'],['../structg24__lib_1_1_parallelism_1_1_none_1_1atomics.html#a6f186b485b72d9f8a21f5b112a97f1a3',1,'g24_lib::Parallelism::None::atomics::divide()'],['../structg24__lib_1_1_parallelism_1_1_open_m_p_1_1atomics.html#afea6e6a27945436826b15b5547cb89d3',1,'g24_lib::Parallelism::OpenMP::atomics::divide()'],['../structg24__lib_1_1_parallelism_1_1_c_u_d_a_1_1atomics.html#a3054d335dc5d90a49239ef307589f72e',1,'g24_lib::Parallelism::CUDA::atomics::divide()']]],
['dotp_643',['dotp',['../classg24__lib_1_1fspoint.html#a00aaa5d528394ac89a4ef820693b858c',1,'g24_lib::fspoint::dotp()'],['../classg24__lib_1_1point.html#ad79392a73bb5ce6324682010e8b96476',1,'g24_lib::point::dotp()']]]
];
| 207.588235 | 751 | 0.804761 |
29a84fa2bb07494a9bb4f41447458c394b12102d | 222 | js | JavaScript | src/core/logger.js | hiteshsomani/dashboard | 3191dda8977a08c70b615f53923e3e616776c0e1 | [
"MIT"
] | null | null | null | src/core/logger.js | hiteshsomani/dashboard | 3191dda8977a08c70b615f53923e3e616776c0e1 | [
"MIT"
] | null | null | null | src/core/logger.js | hiteshsomani/dashboard | 3191dda8977a08c70b615f53923e3e616776c0e1 | [
"MIT"
] | null | null | null | import { getLogger } from 'botworx-utils/lib/logger';
import { log as logConfig } from '../config';
export const logger = getLogger(logConfig.app);
export const dblogger = getLogger(logConfig.db);
export default logger;
| 27.75 | 53 | 0.747748 |
29a9108943466912dff6f02d682dd70545445499 | 3,560 | js | JavaScript | components/corespring/drag-and-drop/test/server/index-test.js | corespring/corespring-components | 3e2003840e3d9acd6da65a7efd366d5fee0a18f4 | [
"0BSD"
] | 1 | 2020-07-27T00:55:55.000Z | 2020-07-27T00:55:55.000Z | components/corespring/drag-and-drop/test/server/index-test.js | corespring/corespring-components | 3e2003840e3d9acd6da65a7efd366d5fee0a18f4 | [
"0BSD"
] | null | null | null | components/corespring/drag-and-drop/test/server/index-test.js | corespring/corespring-components | 3e2003840e3d9acd6da65a7efd366d5fee0a18f4 | [
"0BSD"
] | null | null | null | var assert, component, server, settings, should, _, helper;
var fbu = require('../../../server-shared/src/server/feedback-utils');
var proxyquire = require('proxyquire').noCallThru();
server = proxyquire('../../src/server', {
'corespring.server-shared.server.feedback-utils' : fbu
});
helper = require('../../../../../test-lib/test-helper');
assert = require('assert');
should = require('should');
_ = require('lodash');
component = {
"componentType": "corespring-drag-and-drop",
"title": "Butterfly D&D",
"correctResponse": {
"1": ["egg", "pupa"],
"2": [],
"3": ["larva", "adult"],
"4": []
},
"feedback": [
{
"feedback": [
{
"larva": "Great"
},
{
"other": "Not great"
}
],
"landingPlace": "1"
}
],
"model": {
"answerArea": "<div>A butterfly is first a <span landing-place id='1' class='inline' cardinality='ordered'></landing-place> then a <span landing-place id='2' class='inline'></landing-place> and then a <span landing-place id='3' class='inline'></landing-place> and then a <span landing-place id='4' class='inline'></landing-place> </div>",
"choices": [
{
"content": "Pupa",
"fixed": true,
"id": "pupa"
},
{
"content": "Egg",
"id": "egg"
},
{
"content": "Larva",
"id": "larva"
},
{
"content": "Adult",
"id": "adult"
}
],
"config": {
"shuffle": true
}
},
"weight": 1
};
settings = function(feedback, userResponse, correctResponse) {
feedback = feedback === undefined ? true : feedback;
userResponse = userResponse === undefined ? true : userResponse;
correctResponse = correctResponse === undefined ? true : correctResponse;
return {
highlightUserResponse: userResponse,
highlightCorrectResponse: correctResponse,
showFeedback: feedback
};
};
describe('drag and drop server logic', function() {
helper.assertNullOrUndefinedAnswersReturnsIncorrect(server);
it('responds incorrect', function() {
var response = server.createOutcome(_.cloneDeep(component), {
1: ['larva']
}, settings(false, true, true));
response.correctness.should.equal('incorrect');
response.score.should.equal(0);
});
it('respond correct', function() {
var answer = {
"1": ["egg", "pupa"],
"2": [],
"3": ["larva", "adult"],
"4": []
};
var response = server.createOutcome(_.cloneDeep(component), answer, settings(false, true, true));
response.correctness.should.equal('correct');
response.score.should.equal(1);
});
it('cardinality is considered', function() {
var answer = {
"1": ["egg", "pupa"],
"2": [],
"3": ["larva", "adult"],
"4": []
};
var response = server.createOutcome(_.cloneDeep(component), answer, settings(false, true, true));
response.correctness.should.equal('correct');
answer = {
"1": ["pupa", "egg"], // ordered, so incorrect
"2": [],
"3": ["larva", "adult"],
"4": []
};
response = server.createOutcome(_.cloneDeep(component), answer, settings(false, true, true));
response.correctness.should.equal('incorrect');
answer = {
"1": ["egg", "pupa"],
"2": [],
"3": ["adult", "larva"], // not ordered, so correct
"4": []
};
response = server.createOutcome(_.cloneDeep(component), answer, settings(false, true, true));
response.correctness.should.equal('correct');
});
});
| 26.567164 | 342 | 0.567697 |
29a9f93eb3340acc69258290d22fe5ea63d8efb5 | 12,587 | js | JavaScript | js/app.js | pa4373/parsestore_js | 5a9c8905e49d879751cd0aa254e6a399ce5b3c44 | [
"BSD-3-Clause"
] | 1 | 2019-07-20T23:43:09.000Z | 2019-07-20T23:43:09.000Z | js/app.js | pa4373/parsestore_js | 5a9c8905e49d879751cd0aa254e6a399ce5b3c44 | [
"BSD-3-Clause"
] | null | null | null | js/app.js | pa4373/parsestore_js | 5a9c8905e49d879751cd0aa254e6a399ce5b3c44 | [
"BSD-3-Clause"
] | null | null | null | /*
* The code below didn't fully leverage the power of Parse SDK, which is the fork of Backbone.js.
* While the code emphasises on the usage of Parse SDK on the premise of not confusing readers
* who are not familiar with MVC and override in object-oriented programming, the use of router,
* event listener and handler functions guarantees the basic architecture on a certain level.
*
* If you're determined to become an front-end developer of web application, I encourage you to
* learn how to use frameworks such as Backbone.js or Ember.js. See what goods they're offering
* you for free, and what the design principle saves you from wrting lousy, messy JavaScript codes.
* Certianly, you won't feel free for the first time, since it FORCES you to think in its own
* way. It's kind of like the deal Faust made with the devil, you give up your way of thinking
* for something good. (such as View object, Data binding) However, once you're used to it, and
* start to think outside of the box, you broke the deal and gained knowledge, pretty much like
* the ending of Goethe's Faust.
*
* So, shall we begin?
*
* */
var cart = null;
(function(){
Parse.initialize('4sm6oolNwqCWoKLqHQLfAA0oPabqt8CLRVWpcZKg',
'1bKw1v2vRiLuF9wtRzMZNiyZFg0GxiEmyNoy4VAo');
// Precompile each template and collects them all in an object.
var templates = {};
['loginTemplate', 'catalogTemplate', 'catalogPaginationTemplate', 'dress_detialTemplate', 'mycartTemplate'].forEach(function(e){
var tpl = document.getElementById(e).text;
templates[e] = doT.template(tpl);
});
myCart = {
setAmountTo: function(user, dress, amount, callback){
var Order = Parse.Object.extend("Order");
// Make new created object available only to the creater.
var orderACL = new Parse.ACL();
orderACL.setPublicReadAccess(false);
orderACL.setPublicWriteAccess(false);
orderACL.setReadAccess(user, true);
orderACL.setWriteAccess(user, true);
// Ask if the order already exists, if so, update the amount, or create new order object.
var query = new Parse.Query(Order);
query.equalTo('user', user);
query.equalTo('dress', dress);
// We only need the first item (and the only item) of the query result.
query.first({
success: function(order){
// Set amount to zero indicates that the order is discarded.
if( amount === 0 && order ){
order.destroy({
success: function(order){
callback();
}
});
} else {
// the order object is not created, yet. (Notice order.setACL, and relational data.)
if( order === undefined ){
order = new Order();
order.set('user', user);
order.set('dress', dress);
order.setACL(orderACL);
}
// Update and save the object to server.
order.set('amount', amount);
order.save(null, {
success: function(order){
callback();
}
});
}
}, error: function(object, err){
}
});
},
};
/* Handler Functions */
var handlers = {
navbar: function(){
var currentUser = Parse.User.current();
if (currentUser){
// Determine what authenticated user can see......
document.getElementById('login_button').style.display = 'none';
document.getElementById('cart_button').style.display = 'block';
document.getElementById('logout_button').style.display = 'block';
document.getElementById('user_id').innerHTML = currentUser.get('username');
} else {
// Or anonymous user can see.
document.getElementById('login_button').style.display = 'block';
document.getElementById('cart_button').style.display = 'none';
document.getElementById('logout_button').style.display = 'none';
}
document.getElementById('logout_button').addEventListener('click', function(){
Parse.User.logOut();
handlers.navbar();
window.location.hash = '';
});
},
catalog: function(page){
window.scrollTo(0,0);
// To support pagination.
var limit = 16;
var skip = (page-1) * limit;
var Dress = Parse.Object.extend("Dress");
var query = new Parse.Query(Dress);
query.limit(limit);
query.skip(skip);
query.descending("createdAt");
query.find({
success: function(results) {
var objList = results.map(function(e){ return e.toJSON() });
document.getElementById('content').innerHTML = templates.catalogTemplate(objList);
query.limit(0);
query.skip(0);
var option = {};
// To support pagination.
query.count({
success: function(count){
var totalPage = Math.ceil(count / limit);
var currentPage = parseInt(page);
option = {
// Watch out the limit.
'previous': (currentPage === 1) ? 1 : currentPage-1,
'next': (currentPage === totalPage) ? currentPage : currentPage+1,
'current': currentPage,
'last': totalPage,
};
document.getElementById('pagination').innerHTML =
templates.catalogPaginationTemplate(option);
}, error: function(err){
}
});
}
});
},
dress_detail: function(dress_id){
if(dress_id){
var Dress = Parse.Object.extend("Dress");
var query = new Parse.Query(Dress);
query.get(dress_id, {
success: function(dress){
document.getElementById('content').innerHTML =
templates.dress_detialTemplate(dress.toJSON());
// Binding for add to the cart function.
document.getElementById('addToCart').addEventListener('click', function(){
var currentUser = Parse.User.current();
if(currentUser){
var e = document.getElementById('amount');
var amount = parseInt(e.options[e.selectedIndex].value);
// Remember we declare myCart.setAmountTo function prior to this object?
myCart.setAmountTo(currentUser, dress, amount, function(){
alert("此商品已加入到您的購物車。");
});
} else {
// If the user isn't logged in, redirect to login page with successful callback to this product.
window.location.hash = 'login/'+ window.location.hash;
}
});
}, error: function(object, error){
}
});
} else {
window.location.hash = '';
}
},
mycart: function(){
var currentUser = Parse.User.current();
if (currentUser) {
var Order = Parse.Object.extend("Order");
var query = new Parse.Query(Order);
query.equalTo('user', currentUser);
// Let the query return results along with relational data.
query.include('dress');
query.find({
success: function(results){
var objList = results.map(function(e){
return {
'dressId': e.get('dress').id,
'amount': e.get('amount'),
'name': e.get('dress').get('name'),
'previewUrl': e.get('dress').get('previewUrl'),
}
});
document.getElementById('content').innerHTML = templates.mycartTemplate(objList);
results.forEach(function(e){
var changeAmount = document.getElementById('change_amount_'+e.get('dress').id);
changeAmount.addEventListener('change', function(){
var amount = parseInt(this.options[this.selectedIndex].value);
myCart.setAmountTo(currentUser, e.get('dress'), amount, function(){});
});
var cancelOrderBtn = document.getElementById('cancel_order_'+e.get('dress').id);
cancelOrderBtn.addEventListener('click', function(){
myCart.setAmountTo(currentUser, e.get('dress'), 0, function(){
if (cancelOrderBtn.parentNode.parentNode.childElementCount === 1){
handlers.mycart();
} else {
cancelOrderBtn.parentNode.remove();
}
});
});
});
// Easter Egg!!!
document.getElementById('payButton').parentNode.addEventListener('click', function(){
// Toogle Effect
if( this.childElementCount === 1){
var YTcode = '<iframe width="960" height="517" ' +
'src="https://www.youtube-nocookie.com/embed/NkQc4FXCvtA?autoplay=1&rel=0&iv_load_policy=3"' +
' frameborder="0" allowfullscreen></iframe>';
this.innerHTML += YTcode;
} else {
this.children[1].remove();
}
return false
});
},
error: function(error){
},
});
} else {
window.location.hash = 'login/'+ window.location.hash;
}
},
login: function(redirect){
var currentUser = Parse.User.current();
// What to do after signin / signup is successfully performed.
var postAction = function(){
handlers.navbar();
window.location.hash = (redirect) ? redirect : '';
}
if (currentUser) {
window.location.hash = '';
} else {
// Signin Function binding, provided by Parse SDK.
document.getElementById('content').innerHTML = templates.loginTemplate();
document.getElementById('loginForm').addEventListener('submit', function(){
Parse.User.logIn(document.getElementById('loginForm_username').value,
document.getElementById('loginForm_password').value, {
success: function(user) {
postAction();
},
error: function(user, error) {
}
});
});
// Signup Form Password Match Check Binding.
document.getElementById('singupForm_password1').addEventListener('keyup', function(){
var singupForm_password = document.getElementById('singupForm_password');
var message = (this.value !== singupForm_password.value) ? '密碼不一致,請再確認一次。' : '';
document.getElementById('signupForm_message').innerHTML = message;
});
// Signup Function binding, provided by Parse SDK.
document.getElementById('singupForm').addEventListener('submit', function(){
var singupForm_password = document.getElementById('singupForm_password');
var singupForm_password1 = document.getElementById('singupForm_password1');
if(singupForm_password.value !== singupForm_password1.value){
document.getElementById('signupForm_message').innerHTML = '密碼不一致,請再確認一次。';
return false;
}
var user = new Parse.User();
user.set("username", document.getElementById('singupForm_username').value);
user.set("password", document.getElementById('singupForm_password').value);
user.set("email", document.getElementById('singupForm_emailAddress').value);
user.signUp(null, {
success: function(user) {
postAction();
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
document.getElementById('signupForm_message').innerHTML = error.message + '['+error.code+']';
}
});
}, false);
}
}
}
/* Router */
var App = Parse.Router.extend({
routes: {
'': 'index',
'page/:page/': 'catalog',
'dress/:dress_id/': 'dress_detail',
'mycart/': 'mycart',
'login/*redirect': 'login',
},
// If frontpage is requested, show the first page of catalog.
index: function(){
return handlers.catalog(1);
},
catalog: handlers.catalog,
dress_detail: handlers.dress_detail,
mycart: handlers.mycart,
login: handlers.login,
});
// Initialize the App
this.Router = new App();
Parse.history.start();
handlers.navbar();
})();
| 40.214058 | 130 | 0.575435 |
29aae1f978d35b40573279012551a514cc6f195a | 1,340 | js | JavaScript | App/src/pages/HomePage/HomePage.test.js | Kurczak1233/AllegroSearchEngine | 3a38c68fcb340aa951b8d231eb5c0962356fc777 | [
"MIT"
] | 5 | 2022-02-23T10:16:16.000Z | 2022-02-23T10:25:45.000Z | App/src/pages/HomePage/HomePage.test.js | Kurczak1233/AllegroSearchEngine | 3a38c68fcb340aa951b8d231eb5c0962356fc777 | [
"MIT"
] | 8 | 2022-02-23T10:23:46.000Z | 2022-02-23T10:41:30.000Z | App/src/pages/HomePage/HomePage.test.js | Kurczak1233/AllegroSearchEngine | 3a38c68fcb340aa951b8d231eb5c0962356fc777 | [
"MIT"
] | null | null | null | import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import HomePage from "./HomePage";
test("input should be initially empty", () => {
render(<HomePage />);
const searchInputElement = screen.getByRole("textbox");
expect(searchInputElement.value).toBe("");
});
test("input should contain inputted value", () => {
render(<HomePage />);
const searchInputElement = screen.getByRole("textbox");
userEvent.type(searchInputElement, "Laptop");
expect(searchInputElement.value).toBe("Laptop");
});
test("should call onClick prop when search button clicked", () => {
const onClick = jest.fn();
render(<HomePage handleSearchClick={onClick()} />);
const searchButtonElement = screen.getByText(/Search/);
userEvent.click(searchButtonElement);
expect(onClick).toHaveBeenCalledTimes(1);
});
test("should display 'Loading...' when loading data", () => {
const onClick = jest.fn();
render(<HomePage handleSearchClick={onClick()} />);
const searchInputElement = screen.getByRole("textbox");
const searchButtonElement = screen.getByText(/Search/);
userEvent.type(searchInputElement, "Laptop");
userEvent.click(searchButtonElement);
const mainContentElement = screen.getByRole("main-content");
expect(mainContentElement).toHaveTextContent(/Loading.../);
});
| 37.222222 | 67 | 0.724627 |
29abc2099ff96d9e24e1bd7738f451c4ac90d265 | 978 | js | JavaScript | js/src/forum/components/PrivateDiscussionsUserPage.js | mrothauer/byobu | 68ae9b9b4271445887c824798941cbf4915d8f40 | [
"MIT"
] | null | null | null | js/src/forum/components/PrivateDiscussionsUserPage.js | mrothauer/byobu | 68ae9b9b4271445887c824798941cbf4915d8f40 | [
"MIT"
] | null | null | null | js/src/forum/components/PrivateDiscussionsUserPage.js | mrothauer/byobu | 68ae9b9b4271445887c824798941cbf4915d8f40 | [
"MIT"
] | null | null | null | import UserPage from 'flarum/components/UserPage';
import PrivateDiscussionList from './PrivateDiscussionList';
export default class PrivateDiscussionsUserPage extends UserPage {
init() {
super.init();
this.loadUser(m.route.param('username'));
}
show(user) {
// We can not create the list in init because the user will not be available if it has to be loaded asynchronously
this.list = new PrivateDiscussionList({
params: {
q: `byobu:${user.username()} is:private`,
sort: 'newest'
}
});
this.list.refresh();
// We call the parent method after creating the list, this way the this.list property
// is set before content() is called for the first time
super.show(user);
}
content() {
return (
<div className="DiscussionsUserPage">
{this.list.render()}
</div>
);
}
}
| 27.942857 | 122 | 0.579755 |
29aca9beb973789c5a03a7a250b3edd71dc7509d | 2,617 | js | JavaScript | src/components/TablaFac.js | Gdaimon/Cooperativa_MinTic_Ciclo3 | 0443d364d1fd007e487a4c3a433a1d3f6f524460 | [
"MIT"
] | null | null | null | src/components/TablaFac.js | Gdaimon/Cooperativa_MinTic_Ciclo3 | 0443d364d1fd007e487a4c3a433a1d3f6f524460 | [
"MIT"
] | null | null | null | src/components/TablaFac.js | Gdaimon/Cooperativa_MinTic_Ciclo3 | 0443d364d1fd007e487a4c3a433a1d3f6f524460 | [
"MIT"
] | 1 | 2021-10-07T22:29:02.000Z | 2021-10-07T22:29:02.000Z | import React from "react"
/* import { BrowserRouter as Router, Switch, Route } from "react-router-dom" */
/* import Index from "pages/index" */
import {FormControl,Image,Table,InputGroup} from "react-bootstrap"
import "styles/style.css"
import Modificar from 'media/modificar.png';
import Eliminar from 'media/eliminar.png';
function TablaNs() {
return (
<Table striped bordered hover>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Codigo</th>
<th scope="col">Servicio</th>
<th scope="col">Precio</th>
<th scope="col">Cantidad</th>
<th scope="col">Subtotal</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>4001</td>
<td>Tarjeta Credito</td>
<td>
1000
</td>
<td>
<InputGroup.Text id="basic-addon1" style={{display:'none'}}>1</InputGroup.Text>
<span class="">1</span>
</td>
<td>
1000
<Image src={Modificar} rounded width="15" height="15"/>
<Image src= {Eliminar} rounded width="15" height="15"/>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td>4007</td>
<td>Tarjeta Debito</td>
<td>
2000
</td>
<td>
<InputGroup.Text id="basic-addon1" style={{display:'none'}}>2</InputGroup.Text>
<span class="">2</span>
</td>
<td>
4000
<Image src={Modificar} rounded width="15" height="15"/>
<Image src= {Eliminar} rounded width="15" height="15"/>
</td>
</tr>
<tr>
<th></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</Table>
);
}
export default TablaNs;
| 29.738636 | 99 | 0.365304 |
29adea8f28dcee7638bdbe8bf950ea27f6a45eb3 | 1,888 | js | JavaScript | public/javascripts/notification.js | honcho-man/OHE-Pro_finders | 7ef5c607be62e3da13b787325c7a598e8e538f5a | [
"MIT"
] | null | null | null | public/javascripts/notification.js | honcho-man/OHE-Pro_finders | 7ef5c607be62e3da13b787325c7a598e8e538f5a | [
"MIT"
] | null | null | null | public/javascripts/notification.js | honcho-man/OHE-Pro_finders | 7ef5c607be62e3da13b787325c7a598e8e538f5a | [
"MIT"
] | null | null | null | /*
var notice = ['hello there oladokun','welcome to ohe','you have a new message'],
notification = $('.notifications'),
noticeDate = '1 day ago',
ringer = $('.ringer'),
noticeChildren = $('.msgs');
var noticeMsgs = $.map(notice,function (value) {
//value.toUpperCase
return('<div class="notice msgs unread container-fluid"><div class="row"><div class="col-12 text-left pl-2 pr-2 pt-0 pb-0">'+value+'</div><div class="col-12 pl-2 pr-2 pt-0 pb-0 text-muted notice-date text-left">'+noticeDate+'<a class="mark-read" title="mark read"><i class="lni lni-checkmark marker"></i></a></div></div></div>');
})
function noticeState(){
$('.notifications .notice').on("click", function(event) {
//console.log(event)
console.log(event.target.nextSibling.lastChild.insertBefore)
//event.target.classList.remove('unread')
//event.target.classList.add('read')
if(event.target.classList.contains('notice-date')){
// console.log('yes')
event.currentTarget.classList.remove('unread')
event.currentTarget.classList.add('read')
} else{
event.currentTarget.classList.remove('unread')
event.currentTarget.classList.add('read')
}
event.target.nextSibling.lastChild.classList.add('read');
event.target.nextSibling.lastChild.childNodes.classList.remove('lni-checkmark')
event.target.nextSibling.lastChild.childNodes.classList.add('lni-checkmark-circle')
//mark.addClass('read')
}
)}
function bellState(){
if (notification.children) {
console.log('yass')
}
}
//notification.html(jobshtml.join(''))
if (notice == '' || undefined) {
let notice = 'No new notifications'
notification.html('<div class="notice">'+notice+'</div>')
} else {
ringer.addClass('bell')
notification.html(noticeMsgs.join(''))
noticeState()
// bellState()
}
*/ | 41.043478 | 333 | 0.650953 |
29ae8783c03fba6b339c03e87ab7f593233d7864 | 2,509 | js | JavaScript | Final CSIS279 - JeanPaul Chami/Final/app/src/index.js | jeanpaul11/finals | c787437ecff32c325d193f2fdf1adad235f15b54 | [
"Apache-2.0"
] | null | null | null | Final CSIS279 - JeanPaul Chami/Final/app/src/index.js | jeanpaul11/finals | c787437ecff32c325d193f2fdf1adad235f15b54 | [
"Apache-2.0"
] | null | null | null | Final CSIS279 - JeanPaul Chami/Final/app/src/index.js | jeanpaul11/finals | c787437ecff32c325d193f2fdf1adad235f15b54 | [
"Apache-2.0"
] | null | null | null | import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-bootstrap-table/dist/react-bootstrap-table-all.min.css';
import 'react-calendar/dist/Calendar.css';
import LoginForm from './components/LoginForm';
import SignUp from './components/SignUp';
import HomePage from './components/HomePage';
import DeleteAccount from './components/DeleteAccount';
import NavbarComponent from './components/Navbar';
import Orders from './components/Orders';
import PriceTable from './components/PriceTable';
import DeleteRecords from './components/DeleteRecords';
import item from "./components/item";
import itemsTable from "./components/itemsTable";
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './configure-store';
import { Container } from './counter/container';
import { connect } from 'react-redux'
import { increment, decrement, reset } from './actionCreators'
class RouterNavigationSample extends React.Component {
const
render() {
return (
<Router>
<div className="container">
<>
<Route
exact
path="/"
render={props => <LoginForm {...props} />} />
<Route path="/Signup" render={props => <SignUp {...props} />} />
<Route path="/Navbar" render={props => <NavigationBar {...props} />} />
<Route path="/DeleteAccount" render={props => <DeleteAccount {...props} />} />
<Route path="/Home" render={props => <HomePage {...props} />} />
<Route path="/items" render={props => <itemsTable {...props} />} />
<Route path="/item" render={props => <item {...props} />} />
<Route path="/PriceTable" render={props => <PriceTable {...props} />} />
<Route path="/Order" render={props => <Orders {...props} />} />
<Route path="/Delete" render={props => <DeleteRecords {...props} />} />
</>
</div>
</Router>
);
}
}
const App = () => (
<Provider store={store}>
<Container />
</Provider>
);
const mapStateToProps = (state /*, ownProps*/) => {
return {
counter: state.counter
}
}
const mapDispatchToProps = { increment, decrement, reset }
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
ReactDOM.render(<App />, document.getElementById('root'));
| 31.759494 | 90 | 0.626544 |
29af7df17cc6e9e5c28b81e58380ca702db52891 | 1,691 | js | JavaScript | HttpTrigger1/node_modules/@pnp/office365-cli/dist/o365/spo/commands/tenant/tenant-appcatalogurl-get.js | VelinGeorgiev/azure-function-office365-cli-powershell | 30e74e5aacd43461d97c6c2951690fb1bd16fc11 | [
"Apache-2.0"
] | null | null | null | HttpTrigger1/node_modules/@pnp/office365-cli/dist/o365/spo/commands/tenant/tenant-appcatalogurl-get.js | VelinGeorgiev/azure-function-office365-cli-powershell | 30e74e5aacd43461d97c6c2951690fb1bd16fc11 | [
"Apache-2.0"
] | null | null | null | HttpTrigger1/node_modules/@pnp/office365-cli/dist/o365/spo/commands/tenant/tenant-appcatalogurl-get.js | VelinGeorgiev/azure-function-office365-cli-powershell | 30e74e5aacd43461d97c6c2951690fb1bd16fc11 | [
"Apache-2.0"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const request_1 = require("../../../../request");
const commands_1 = require("../../commands");
const SpoCommand_1 = require("../../../base/SpoCommand");
const vorpal = require('../../../../vorpal-init');
class SpoTenantAppCatalogUrlGetCommand extends SpoCommand_1.default {
get name() {
return commands_1.default.TENANT_APPCATALOGURL_GET;
}
get description() {
return 'Gets the URL of the tenant app catalog';
}
commandAction(cmd, args, cb) {
this
.getSpoUrl(cmd, this.debug)
.then((spoUrl) => {
const requestOptions = {
url: `${spoUrl}/_api/SP_TenantSettings_Current`,
headers: {
accept: 'application/json;odata=nometadata'
}
};
return request_1.default.get(requestOptions);
})
.then((res) => {
const json = JSON.parse(res);
if (json.CorporateCatalogUrl) {
cmd.log(json.CorporateCatalogUrl);
}
else {
if (this.verbose) {
cmd.log("Tenant app catalog is not configured.");
}
}
cb();
}, (err) => this.handleRejectedPromise(err, cmd, cb));
}
commandHelp(args, log) {
log(vorpal.find(this.name).helpInformation());
log(` Examples:
Get the URL of the tenant app catalog
${commands_1.default.TENANT_APPCATALOGURL_GET}
`);
}
}
module.exports = new SpoTenantAppCatalogUrlGetCommand();
//# sourceMappingURL=tenant-appcatalogurl-get.js.map | 34.510204 | 69 | 0.55825 |
29b15bc3518c9b9a3c2a35867e7c2dd5b3e445c5 | 836 | js | JavaScript | src/style/restaurantStyles.js | khuynh92/chewsit-client | 067399bc1a427c62d9a5fbea91deb5a677961b89 | [
"MIT"
] | 1 | 2018-10-25T04:18:09.000Z | 2018-10-25T04:18:09.000Z | src/style/restaurantStyles.js | khuynh92/chewsit-client | 067399bc1a427c62d9a5fbea91deb5a677961b89 | [
"MIT"
] | null | null | null | src/style/restaurantStyles.js | khuynh92/chewsit-client | 067399bc1a427c62d9a5fbea91deb5a677961b89 | [
"MIT"
] | null | null | null | export const styles = theme => {
theme.breakpoints.values.sm = 480;
theme.breakpoints.values.md = 769;
theme.breakpoints.values.lg = 1024;
theme.breakpoints.values.xl = 3000;
return ({
card: {
minHeight: 250,
[theme.breakpoints.between('xs', 'md')]: {
minWidth: 300,
marginBottom: '2%',
marginLeft: 'auto',
marginRight: 'auto',
width: '50%',
height: '40vh',
},
[theme.breakpoints.between('md', 'xl')]: {
minWidth: 300,
marginBottom: '2%',
display: 'inline-block',
width: '50%',
height: '40vh',
},
},
media: {
cursor: 'pointer',
height: '100%',
},
cardActionArea: {
width: '100%',
},
cardContent: {
paddingBottom: 0,
marginBottom: 0,
},
});
}; | 21.435897 | 48 | 0.507177 |
29b174bdb0c1356de5b5b15b374cfc6a35556901 | 7,379 | js | JavaScript | src/carousel.js | XavierMod/react-native-anchor-carousel | ef9f2ae3bd8735bec19af0f243f253fe29627511 | [
"MIT"
] | 98 | 2019-05-29T06:03:14.000Z | 2022-03-17T13:00:53.000Z | src/carousel.js | XavierMod/react-native-anchor-carousel | ef9f2ae3bd8735bec19af0f243f253fe29627511 | [
"MIT"
] | 18 | 2019-06-23T18:11:43.000Z | 2022-03-09T22:41:05.000Z | src/carousel.js | XavierMod/react-native-anchor-carousel | ef9f2ae3bd8735bec19af0f243f253fe29627511 | [
"MIT"
] | 30 | 2019-06-17T11:08:20.000Z | 2022-02-25T15:09:38.000Z | import React, {
Component,
useEffect,
useImperativeHandle,
useRef,
useState,
forwardRef
} from 'react';
import { Animated, StyleSheet, Dimensions, FlatList } from 'react-native';
const { width: windowWidth } = Dimensions.get('window');
const styles = StyleSheet.create({
container: {},
itemContainer: { justifyContent: 'center' }
});
const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
function useConstructor(callBack = () => {}) {
const [hasBeenCalled, setHasBeenCalled] = useState(false);
if (hasBeenCalled) {
return;
}
callBack();
setHasBeenCalled(true);
}
function Carousel(props, ref) {
const {
data = [],
style = {},
containerWidth = windowWidth,
itemWidth = 0.9 * windowWidth,
itemContainerStyle = {},
separatorWidth = 10,
minScrollDistance = 5,
inActiveScale = 0.8,
inActiveOpacity = 0.8,
inverted = false,
initialIndex = 0,
bounces = true,
showsHorizontalScrollIndicator = false,
keyExtractor = (item, index) => index.toString(),
renderItem = () => {},
onScrollEnd = () => {},
onScrollBeginDrag = () => {},
onScrollEndDrag = () => {},
...otherProps
} = props;
const scrollViewRef = useRef(null);
const currentIndexRef = useRef(initialIndex);
const scrollXRef = useRef(0);
const scrollXBeginRef = useRef(0);
const xOffsetRef = useRef(new Animated.Value(0));
const handleOnScrollRef = useRef(() => {});
const halfContainerWidth = containerWidth / 2;
const halfItemWidth = itemWidth / 2;
const itemTotalMarginBothSide = getItemTotalMarginBothSide();
const containerStyle = [styles.container, { width: containerWidth }, style];
const dataLength = data ? data.length : 0;
useConstructor(() => {
setScrollHandler();
});
useImperativeHandle(ref, () => ({
scrollToIndex: scrollToIndex
}));
function isLastItem(index) {
return index === dataLength - 1;
}
function isFirstItem(index) {
return index === 0;
}
function getItemLayout(data, index) {
return {
offset: getItemOffset(index),
length: itemWidth,
index
};
}
function setScrollHandler() {
handleOnScrollRef.current = Animated.event(
[{ nativeEvent: { contentOffset: { x: xOffsetRef.current } } }],
{
useNativeDriver: true,
listener: event => {
scrollXRef.current = event.nativeEvent.contentOffset.x;
}
}
);
}
function scrollToIndex(index) {
if (index < 0 || index >= dataLength) {
return;
}
onScrollEnd && onScrollEnd(data[index], index);
currentIndexRef.current = index;
setTimeout(() => {
scrollViewRef.current &&
scrollViewRef.current.scrollToOffset({
offset: getItemOffset(index),
animated: true
});
});
}
function handleOnScrollBeginDrag() {
onScrollBeginDrag && onScrollBeginDrag();
scrollXBeginRef.current = scrollXRef.current;
}
function handleOnScrollEndDrag() {
onScrollEndDrag && onScrollEndDrag();
if (scrollXRef.current < 0) {
return;
}
const scrollDistance = scrollXRef.current - scrollXBeginRef.current;
scrollXBeginRef.current = 0;
if (Math.abs(scrollDistance) < minScrollDistance) {
scrollToIndex(currentIndexRef.current);
return;
}
if (scrollDistance < 0) {
scrollToIndex(currentIndexRef.current - 1);
} else {
scrollToIndex(currentIndexRef.current + 1);
}
}
function getItemTotalMarginBothSide() {
const compensatorOfSeparatorByScaleEffect = (1 - inActiveScale) * itemWidth;
return separatorWidth - compensatorOfSeparatorByScaleEffect / 2;
}
function getItemOffset(index) {
return (
index * (itemWidth + itemTotalMarginBothSide) -
(halfContainerWidth - halfItemWidth)
);
}
function getAnimatedOffset(index) {
if (isFirstItem(index)) {
return halfItemWidth;
}
if (isLastItem(index)) {
return containerWidth - halfItemWidth;
}
return halfContainerWidth;
}
function getMidPontInterpolate(index, animatedOffset) {
return (
index * (itemWidth + itemTotalMarginBothSide) +
halfItemWidth -
animatedOffset
);
}
function getStartPontInterpolate(index, midPoint) {
if (index === 1) {
return 0;
}
if (isLastItem(index)) {
return (
(dataLength - 2) * (itemWidth + itemTotalMarginBothSide) +
halfItemWidth -
halfContainerWidth
);
}
return midPoint - itemWidth - itemTotalMarginBothSide;
}
function getEndPointInterpolate(index, midPoint) {
if (isFirstItem(index)) {
return (
itemWidth + itemTotalMarginBothSide + halfItemWidth - halfContainerWidth
);
}
if (index === dataLength - 2) {
return (
(dataLength - 1) * (itemWidth + itemTotalMarginBothSide) +
itemWidth -
containerWidth
);
}
return midPoint + itemWidth + itemTotalMarginBothSide;
}
function getItemAnimatedStyle(index) {
const animatedOffset = getAnimatedOffset(index);
const midPoint = getMidPontInterpolate(index, animatedOffset);
const startPoint = getStartPontInterpolate(index, midPoint);
const endPoint = getEndPointInterpolate(index, midPoint);
const animatedOpacity = {
opacity: xOffsetRef.current.interpolate({
inputRange: [startPoint, midPoint, endPoint],
outputRange: [inActiveOpacity, 1, inActiveOpacity]
})
};
const animatedScale = {
transform: [
{
scale: xOffsetRef.current.interpolate({
inputRange: [startPoint, midPoint, endPoint],
outputRange: [inActiveScale, 1, inActiveScale]
})
}
]
};
return { ...animatedOpacity, ...animatedScale };
}
function getItemMarginStyle(index) {
const marginSingleItemSide = itemTotalMarginBothSide / 2;
if (isFirstItem(index)) {
return !!inverted
? { marginLeft: marginSingleItemSide }
: { marginRight: marginSingleItemSide };
}
if (isLastItem(index)) {
return !!inverted
? { marginRight: marginSingleItemSide }
: { marginLeft: marginSingleItemSide };
}
return { marginHorizontal: marginSingleItemSide };
}
function renderItemContainer({ item, index }) {
return (
<Animated.View
pointerEvents={'box-none'}
style={[
styles.itemContainer,
itemContainerStyle,
{ width: itemWidth },
getItemMarginStyle(index),
getItemAnimatedStyle(index)
]}
>
{renderItem({ item, index })}
</Animated.View>
);
}
return (
<AnimatedFlatList
{...otherProps}
ref={scrollViewRef}
data={data}
style={containerStyle}
horizontal={true}
inverted={inverted}
bounces={bounces}
decelerationRate={0}
initialScrollIndex={initialIndex}
automaticallyAdjustContentInsets={false}
showsHorizontalScrollIndicator={showsHorizontalScrollIndicator}
onScroll={handleOnScrollRef.current}
keyExtractor={keyExtractor}
getItemLayout={getItemLayout}
renderItem={renderItemContainer}
onScrollBeginDrag={handleOnScrollBeginDrag}
onScrollEndDrag={handleOnScrollEndDrag}
/>
);
}
export default forwardRef(Carousel);
| 26.735507 | 80 | 0.64399 |
29b225a24e0cb8a68165020ef26eb5f8d643fb23 | 3,167 | js | JavaScript | templates/wp-content/plugins/types/vendor/toolset/types/embedded/resources/js/wp-views.js | Steenify/steengen-wp | 82f902502333abea7d1efdd19ccad0ee0f001494 | [
"MIT"
] | 1 | 2018-01-25T08:00:58.000Z | 2018-01-25T08:00:58.000Z | templates/wp-content/plugins/types/vendor/toolset/types/embedded/resources/js/wp-views.js | Steenify/steengen-wp | 82f902502333abea7d1efdd19ccad0ee0f001494 | [
"MIT"
] | null | null | null | templates/wp-content/plugins/types/vendor/toolset/types/embedded/resources/js/wp-views.js | Steenify/steengen-wp | 82f902502333abea7d1efdd19ccad0ee0f001494 | [
"MIT"
] | null | null | null | /*
* Toolset Views plugin.
*
* Loaded on Views or Views Template edit screens.
*/
var typesWPViews = (function(window, $){
function openFrameForWizard( fieldID, metaType, postID, shortcode ) {
var colorboxWidth = 750 + 'px';
if ( !( jQuery.browser.msie && parseInt(jQuery.browser.version) < 9 ) ) {
var documentWidth = jQuery(document).width();
if ( documentWidth < 750 ) {
colorboxWidth = 600 + 'px';
}
}
var url = ajaxurl+'?action=wpcf_ajax&wpcf_action=editor_callback'
+ '&_typesnonce=' + types.wpnonce
+ '&callback=views_wizard'
+ '&field_id=' + fieldID
+ '&field_type=' + metaType
+ '&post_id=' + postID
+ '&shortcode=' + shortcode;
jQuery.colorbox({
href: url,
iframe: true,
inline : false,
width: colorboxWidth,
opacity: 0.7,
closeButton: false
});
}
/**
* Open the Types colorbox instance to insert a field, with a specific callback name.
*
* @param string fieldID
* @param string metaType
* @param int postID
* @param string callback
*
* @since 2.2.9
*/
function openFrameForCloseAndTrigger( fieldID, metaType, postID, callback ) {
var colorboxWidth = 750 + 'px';
if ( !( jQuery.browser.msie && parseInt(jQuery.browser.version) < 9 ) ) {
var documentWidth = jQuery(document).width();
if ( documentWidth < 750 ) {
colorboxWidth = 600 + 'px';
}
}
var url = ajaxurl+'?action=wpcf_ajax&wpcf_action=editor_callback'
+ '&_typesnonce=' + types.wpnonce
+ '&callback=' + callback
+ '&field_id=' + fieldID
+ '&field_type=' + metaType
+ '&post_id=' + postID;
jQuery.colorbox({
href: url,
iframe: true,
inline : false,
width: colorboxWidth,
opacity: 0.7,
closeButton: false
});
}
/**
* Close the colorbox dialog to insert a Types field shortcode, and trigger a custom event.
*
* This is used by Views on the admin bar shortcodes generator, and also on the generic inputs shortcodes appender.
*
* @param string shortcode
*
* @since 2.2.9
*/
function closeFrameAndTrigger( shortcode ) {
window.parent.jQuery.colorbox.close();
$( document ).trigger( 'js_types_shortcode_created', shortcode );
}
return {
wizardEditShortcode: function( fieldID, metaType, postID, shortcode ) {
openFrameForWizard( fieldID, metaType, postID, shortcode );
},
wizardSendShortcode: function( shortcode ) {
window.wpv_restore_wizard_popup(shortcode);
},
interceptEditShortcode: function( fieldID, metaType, postID, callback ) {
openFrameForCloseAndTrigger( fieldID, metaType, postID, callback );
},
interceptCreateShortcode: function( shortcode ) {
closeFrameAndTrigger( shortcode );
},
wizardCancel: function() {
window.wpv_cancel_wizard_popup();
}
};
})(window, jQuery, undefined); | 29.877358 | 116 | 0.584781 |
29b351c113079df1fca5e719431675d28a233818 | 916 | js | JavaScript | api/createDL.js | Jozty/website | ac8ec327c263505118426c66c43e6739d01bb096 | [
"MIT"
] | 1 | 2021-01-31T16:25:53.000Z | 2021-01-31T16:25:53.000Z | api/createDL.js | Jozty/website | ac8ec327c263505118426c66c43e6739d01bb096 | [
"MIT"
] | null | null | null | api/createDL.js | Jozty/website | ac8ec327c263505118426c66c43e6739d01bb096 | [
"MIT"
] | null | null | null | const fetch = require('node-fetch')
const { writeResponse, parseBody } = require('./utilities')
async function createLink(reqBody, req, res) {
try {
const body = {
dynamicLinkInfo: {
domainUriPrefix: 'https://dyl.jozty.io',
link: reqBody.shareUrl,
},
suffix: {
option: 'UNGUESSABLE',
},
}
const key = process.env.FIREBASE_API_KEY
const response = await fetch(
`https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=${key}`,
{
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
}
)
const data = await response.json()
writeResponse(200, res, data.shortLink)
} catch (error) {
console.error(error)
writeResponse(400, res, error.message || error, true)
}
}
export default function (req, res, next) {
parseBody(req, res, createLink)
}
| 26.171429 | 77 | 0.613537 |
29b3767fc8046adeb59b3a8aa3d34aa43e3abcab | 6,285 | js | JavaScript | node_modules/es_client/plugins/maps/views/map_dialog.js | luigser/Ethersheet2 | 634219d1c80f6fe3e53df452f4065a3c9b7ce3f3 | [
"BSD-2-Clause"
] | 1 | 2018-10-29T11:41:39.000Z | 2018-10-29T11:41:39.000Z | node_modules/es_client/plugins/maps/views/map_dialog.js | luigser/Ethersheet2 | 634219d1c80f6fe3e53df452f4065a3c9b7ce3f3 | [
"BSD-2-Clause"
] | null | null | null | node_modules/es_client/plugins/maps/views/map_dialog.js | luigser/Ethersheet2 | 634219d1c80f6fe3e53df452f4065a3c9b7ce3f3 | [
"BSD-2-Clause"
] | null | null | null | if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define( function(require,exports,module)
{
/*const ol = require('ol');
const Geocoder = require('ol').Geocoder*/
const MapView = require('./map_view').View;
class MapDialog extends MapView
{
constructor(params)
{
super(params);
this.config = JSON.parse(JSON.stringify(this.config));
this.config.VIEW = "map_dialog";
this.config.ELEMENT = "#es-modal-box";
this.events = {
'change #interaction_type' : 'changeInteraction',
'click #sat_map_button' : 'makeVisibleSatLayer',
'click #add_map_button' : 'addToMap',
'click #es-modal-close' : 'close'
};
this.selected_interaction = "Marker";
this.template_view = "map_dialog";
}
initializeElements()
{
super.initializeElements();
this.modal_overlay = $('#es-modal-overlay');
this.overlay = $(".es-overlay");
this.modal_overlay.show();
}
loadStyle()
{
super.loadStyle();
super.loadSupportStyles(['ol3-geocoder.min']);
}
loadView()
{
super.loadView();
}
postRendering()
{
super.postRendering();
//this.modal_overlay.show();
//Instantiate with some options and add the Control
this.overlay = new ol.Overlay({
element: document.getElementById('popup'),
offset: [0, -40]
});
this.geocoder = new Geocoder('nominatim', {
provider: 'photon',
lang: 'en',
placeholder: 'Search for ...',
limit: 5,
keepOpen: true,
preventDefault : true
});
this.map.addControl(this.geocoder);
//Listen when an address is chosen
this.geocoder.on('addresschosen', function(evt){
this.olview.setCenter(evt.coordinate);
this.olview.setZoom(16);
if(this.selected_interaction == "Marker") {
this.setMarker(evt.coordinate);
}
}.bind(this));
this.map.on('click', function(evt) {
if(this.selected_interaction == "Marker") {
this.setMarker(evt.coordinate);
}
}.bind(this));
}
changeInteraction(e){
this.selected_interaction = $(e.currentTarget).find(":selected").html();
this.addInteraction();
}
addInteraction() {
if(this.draw != null) this.map.removeInteraction(this.draw);
let geometryFunction, maxPoints, interaction_type = this.selected_interaction;
switch(this.selected_interaction){
case "Square":
interaction_type = "Circle";
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
break;
case "Box":
interaction_type = "LineString";
maxPoints = 2;
geometryFunction = function(coordinates, geometry) {
if (!geometry) {
geometry = new ol.geom.Polygon(null);
}
var start = coordinates[0];
var end = coordinates[1];
geometry.setCoordinates([
[start, [start[0], end[1]], end, [end[0], start[1]], start]
]);
return geometry;
};
break;
}
if(this.selected_interaction != "Marker") {
this.draw = new ol.interaction.Draw({
source: this.source,
type: interaction_type,
geometryFunction: geometryFunction,
maxPoints: maxPoints,
style : this.getTextStyle(-12)
});
this.map.addInteraction(this.draw);
this.draw.on('drawend', function(e) {
e.feature.setStyle(this.getTextStyle(-12));
}.bind(this));
}
}
getTextStyle(offsetX) {
return new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)'
}),
stroke: new ol.style.Stroke({
color: '#ffff00',
width: 4
}),
text : new ol.style.Text({
fill : new ol.style.Fill({
color : '#000'
}),
stroke : new ol.style.Stroke({
color : '#fff',
width : 4
}),
text : this.label,
font : '20px Verdana',
offsetX : offsetX ? offsetX : 0,
offsetY : 12
})
});
}
getGeoJSON(){
let allFeatures = this.draw_layer.getSource().getFeatures();
let format = new ol.format.GeoJSON();
return format.writeFeatures(allFeatures);
}
makeVisibleSatLayer(e){
this.satLayer.setVisible(!this.satLayer.getVisible());
}
addToMap(e){
let data;
if(this.selected_interaction == "Marker") {
data = (!_.isUndefined(this.coords)) ? _.clone(this.coords).reverse().join(",") : "";
}else{
data = this.getGeoJSON();
}
this.es_controller.table.getSheet().updateCell($(this.cell).attr('data-row_id'), $(this.cell).attr('data-col_id'),data);
$(this.$el).empty();
this.modal_overlay.hide();
//this.overlay.remove();
}
close(){
$(this.$el).empty();
}
};
module.exports.View = MapDialog;
});
| 33.078947 | 132 | 0.453779 |
29b3a636c42e6d9b6d7192812bf0b163d6294e4e | 586 | js | JavaScript | frontend/web/js/script.js | hamo1991/project | 0d43d8f42737de2b73f3e1bc387079e6d55c1e83 | [
"BSD-3-Clause"
] | 1 | 2019-01-21T22:14:34.000Z | 2019-01-21T22:14:34.000Z | frontend/web/js/script.js | hamo1991/project | 0d43d8f42737de2b73f3e1bc387079e6d55c1e83 | [
"BSD-3-Clause"
] | null | null | null | frontend/web/js/script.js | hamo1991/project | 0d43d8f42737de2b73f3e1bc387079e6d55c1e83 | [
"BSD-3-Clause"
] | null | null | null | $(document).ready(function () {
var owl = $('.brand-slide');
owl.owlCarousel({
items:5,
loop:true,
margin:10,
autoplay:true,
autoplayTimeout:1000,
dots: false
});
$('form.search-wrap').submit(function (ev) {
if($('#products-search').length){
ev.preventDefault();
var href= $(this).attr('action') + '?search=' + $(this).find('.search').val();
$('#products-search').append('<a id="search-link" href="'+href+'"></a>');
$('#search-link').click();
}
});
}); | 27.904762 | 90 | 0.481229 |
29b3d3c3d2406b423206476987fbd49395bb2c34 | 1,672 | js | JavaScript | dev/register.js | bradennapier/ts-type | 9bec1ceac5bdf9315f8544cbe0aa7073e2523306 | [
"MIT"
] | null | null | null | dev/register.js | bradennapier/ts-type | 9bec1ceac5bdf9315f8544cbe0aa7073e2523306 | [
"MIT"
] | 2 | 2021-09-02T14:35:52.000Z | 2022-01-22T13:26:52.000Z | dev/register.js | bradennapier/ts-type | 9bec1ceac5bdf9315f8544cbe0aa7073e2523306 | [
"MIT"
] | null | null | null | /* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable @typescript-eslint/no-var-requires */
/*
This allows for fast development compilation by utilizing the faster compile mode
of `transpileOnly`. Since this doesn't support transformers, we utilize `tsconfig-paths`
to handle our path resolutions.
When using `ts-node` or `ts-node-dev` we simply register the tsconfig-paths hooks on require
but if we are using `node` or `mocha` or similar we need to also require the `ts-node` hooks
and simulate `--script-mode` (-s) so we get the appropriate `compilerOptions`.
## ts-node-dev
> ts-node-dev allows for fast compilations and respawns on file modifications:
```
ts-node-dev -s -H -T -r ./register --respawn -- src/tests/quick.ts
```
## ts-node
```
ts-node -s -H -T -r ./register -- src/tests/quick.ts
```
## Node
```
node -r ./register -- src/tests/quick.ts
```
## Mocha
```
mocha --timeout 10000 -r ./register -- src/tests/acceptance/api-deposits.ts
```
*/
const path = require('path');
const { loadConfig, register } = require('tsconfig-paths');
const scriptPath = path.resolve(
process.cwd(),
process.argv[process.argv.length - 1],
);
const dirName = path.dirname(require.resolve(scriptPath));
const config = loadConfig(dirName);
if (!process.argv[1].includes('ts-node')) {
// eslint-disable-next-line global-require
require('ts-node').register({
dir: dirName,
transpileOnly: true,
compilerHost: true,
});
}
// dev support for absolute path resolution while allowing transpileOnly to work
register({
baseUrl: config.absoluteBaseUrl,
paths: config.paths,
});
| 25.723077 | 95 | 0.686005 |
29b4787aa2b76bcf79957cc60fc039707eb88d78 | 787 | js | JavaScript | src/redux/formData/reducer.js | few-bits/cv-application | 9b09a6de93f18c8646f17ca46e9e0fbf3fbb009c | [
"MIT"
] | null | null | null | src/redux/formData/reducer.js | few-bits/cv-application | 9b09a6de93f18c8646f17ca46e9e0fbf3fbb009c | [
"MIT"
] | 7 | 2019-12-29T07:15:57.000Z | 2022-02-26T13:51:48.000Z | src/redux/formData/reducer.js | few-bits/cv-application | 9b09a6de93f18c8646f17ca46e9e0fbf3fbb009c | [
"MIT"
] | null | null | null | import * as constants from '../../constants/formData';
import * as types from './types';
const initialState = {
[constants.FIELD_POSITION_ID]: null,
[constants.FIELD_NAME]: '',
[constants.FIELD_LAST_NAME]: '',
[constants.FIELD_MOBILE]: '',
[constants.FIELD_COMMENTS]: '',
[constants.FIELD_LINK]: '',
[constants.FIELD_CV_FILE]: null,
};
export default (state = {
...initialState,
}, action) => {
switch (action.type) {
case types.CHANGE_FIELD: {
const { fieldId, value } = action.payload;
return {
...state,
[fieldId]: value,
};
}
case types.SEND_SUCCESS: {
return { ...initialState };
}
default:
return state
}
}
| 24.59375 | 54 | 0.536213 |
29b5e66f45c8ef691180be6043e73fb93a05a5cb | 393 | js | JavaScript | src/utils/auth.js | AtLastDopamine/vue3-admin-plus | ac815775ab1974126e655933d370764a8da00b8d | [
"MIT"
] | 114 | 2021-09-05T15:09:38.000Z | 2022-03-30T04:39:40.000Z | src/utils/auth.js | Shouhua/vue3-admin-plus | b313f281f84541fe61134fe696578e0cb17703f2 | [
"MIT"
] | 11 | 2021-09-05T16:59:40.000Z | 2022-03-22T03:32:38.000Z | src/utils/auth.js | Shouhua/vue3-admin-plus | b313f281f84541fe61134fe696578e0cb17703f2 | [
"MIT"
] | 35 | 2021-09-05T10:00:50.000Z | 2022-03-27T12:02:23.000Z | //to fix js-token issue for electron so replace js-cookie to localStorage
//detail to look https://bbs.csdn.net/topics/397963088
const TokenKey = 'Admin-Token'
export function getToken() {
return localStorage.getItem(TokenKey)
}
export function setToken(token) {
return localStorage.setItem(TokenKey, token)
}
export function removeToken() {
return localStorage.removeItem(TokenKey)
}
| 26.2 | 73 | 0.776081 |
29b81b3b23682297e669b8ad1eeaa6b0cc7f4b38 | 244 | js | JavaScript | babel/es6/let.js | vikkastaneja/advjs | 5687ca84264b118795db59635cf9e33910e2947d | [
"BSD-2-Clause"
] | 8 | 2015-06-23T21:12:29.000Z | 2017-12-19T21:20:38.000Z | babel/es6/let.js | vikkastaneja/advjs | 5687ca84264b118795db59635cf9e33910e2947d | [
"BSD-2-Clause"
] | null | null | null | babel/es6/let.js | vikkastaneja/advjs | 5687ca84264b118795db59635cf9e33910e2947d | [
"BSD-2-Clause"
] | 5 | 2015-07-22T16:47:53.000Z | 2019-05-25T18:15:01.000Z | (function() {
/****************************************************************************/
// <<: Does this look familiar?
for (let i=0; i<3; ++i) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
// :>>
})();
| 18.769231 | 80 | 0.29918 |
29b8286129808c061fe43ec401a545ea5cca896b | 380 | js | JavaScript | config.js | ESTOS/meet | b8098856dbf04382140f914ee1b6065193739d0e | [
"MIT"
] | 16 | 2015-02-18T13:17:07.000Z | 2021-08-08T22:18:37.000Z | config.js | ESTOS/meet | b8098856dbf04382140f914ee1b6065193739d0e | [
"MIT"
] | 4 | 2015-04-01T21:36:37.000Z | 2016-05-19T19:51:10.000Z | config.js | ESTOS/meet | b8098856dbf04382140f914ee1b6065193739d0e | [
"MIT"
] | 4 | 2015-02-18T13:17:10.000Z | 2016-04-23T08:17:13.000Z | var config = {
hosts: {
domain: 'your.domain.example',
muc: 'conference.your.domain.example', // FIXME: use XEP-0030
bridge: 'jitsi-videobridge.your.domain.example' // FIXME: use XEP-0030
},
// getroomnode: function (path) { return 'someprefixpossiblybasedonpath'; },
useNicks: false,
bosh: '/http-bind' // FIXME: use xep-0156 for that
};
| 34.545455 | 78 | 0.634211 |
29baa2cc05a93b2c31a23011874e46f9ba2a4504 | 130 | js | JavaScript | web/src/server/middlewares/requestHandlers/handleError/index.js | max181199/memas | 1f817a9f331a19aba5f3718c2a56dc6952f628e2 | [
"Apache-2.0"
] | null | null | null | web/src/server/middlewares/requestHandlers/handleError/index.js | max181199/memas | 1f817a9f331a19aba5f3718c2a56dc6952f628e2 | [
"Apache-2.0"
] | null | null | null | web/src/server/middlewares/requestHandlers/handleError/index.js | max181199/memas | 1f817a9f331a19aba5f3718c2a56dc6952f628e2 | [
"Apache-2.0"
] | 1 | 2020-06-10T09:41:23.000Z | 2020-06-10T09:41:23.000Z | function handleError(error, res) {
console.log(error.stack);
res.send({error: error.stack});
}
module.exports = handleError;
| 18.571429 | 34 | 0.715385 |
29bb8b8f54edff3fef29da5412797e680cbaba42 | 538 | js | JavaScript | packages/cip2/test/jest.setup.js | Davinci-Leonardo/cardano-js-sdk | 2fd03c3ba930ddbc4fd8f3af0158db2a2d5a015c | [
"Apache-2.0"
] | null | null | null | packages/cip2/test/jest.setup.js | Davinci-Leonardo/cardano-js-sdk | 2fd03c3ba930ddbc4fd8f3af0158db2a2d5a015c | [
"Apache-2.0"
] | null | null | null | packages/cip2/test/jest.setup.js | Davinci-Leonardo/cardano-js-sdk | 2fd03c3ba930ddbc4fd8f3af0158db2a2d5a015c | [
"Apache-2.0"
] | null | null | null | /* eslint-disable unicorn/prefer-module */
/* eslint-disable @typescript-eslint/no-var-requires */
// TODO: jest environment is not happy with 'lodash-es' exports.
// I think using non-es-module 'lodash' in 'dependencies' is too heavy.
// eslint-disable-next-line unicorn/prefer-module
jest.mock('lodash-es', () => require('lodash'));
const { testTimeout } = require('../jest.config');
require('fast-check').configureGlobal({
interruptAfterTimeLimit: testTimeout * 0.7,
numRuns: testTimeout / 50,
markInterruptAsFailure: true
});
| 35.866667 | 71 | 0.723048 |
29bbc1d74bfd57b943d21db15e0f01a97a01c648 | 9,707 | js | JavaScript | src/routes/JobSummary/components/RecordsTable.test.js | folio-org/ui-cataload | ed88ceb4542bbca216fb9148e746a0f33638701b | [
"Apache-2.0"
] | null | null | null | src/routes/JobSummary/components/RecordsTable.test.js | folio-org/ui-cataload | ed88ceb4542bbca216fb9148e746a0f33638701b | [
"Apache-2.0"
] | null | null | null | src/routes/JobSummary/components/RecordsTable.test.js | folio-org/ui-cataload | ed88ceb4542bbca216fb9148e746a0f33638701b | [
"Apache-2.0"
] | null | null | null | import React from 'react';
import { fireEvent } from '@testing-library/react';
import faker from 'faker';
import { noop } from 'lodash';
import { BrowserRouter } from 'react-router-dom';
import {
buildMutator,
buildResources
} from '@folio/stripes-data-transfer-components/test/helpers';
import { renderWithIntl } from '@folio/stripes-data-transfer-components/test/jest/helpers';
import '../../../../test/jest/__mock__';
import { translationsProperties } from '../../../../test/jest/helpers';
import { RecordsTable } from './RecordsTable';
window.open = jest.fn();
window.open.mockReturnValue({ focus: jest.fn() });
const firstRecordJobExecutionId = faker.random.uuid();
const sourceRecordsIds = [
faker.random.uuid(),
faker.random.uuid(),
faker.random.uuid(),
faker.random.uuid(),
faker.random.uuid(),
faker.random.uuid(),
];
const instanceId = faker.random.uuid();
const authorityId = faker.random.uuid();
const jobLogEntriesResources = buildResources({
resourceName: 'jobLogEntries',
records: [{
sourceRecordActionStatus: 'CREATED',
sourceRecordType: 'MARC_BIBLIOGRAPHIC',
instanceActionStatus: 'CREATED',
authorityActionStatus: 'CREATED',
jobExecutionId: firstRecordJobExecutionId,
sourceRecordId: sourceRecordsIds[0],
sourceRecordOrder: '0',
sourceRecordTitle: 'Test item 1',
}, {
instanceActionStatus: 'UPDATED',
authorityActionStatus: 'UPDATED',
sourceRecordType: 'MARC_BIBLIOGRAPHIC',
jobExecutionId: faker.random.uuid(),
sourceRecordId: sourceRecordsIds[1],
sourceRecordOrder: '1',
sourceRecordTitle: 'Test item 2',
}, {
holdingsActionStatus: 'MULTIPLE',
sourceRecordType: 'MARC_BIBLIOGRAPHIC',
jobExecutionId: faker.random.uuid(),
sourceRecordId: sourceRecordsIds[2],
sourceRecordOrder: '2',
sourceRecordTitle: 'Test item 3',
}, {
itemActionStatus: 'DISCARDED',
sourceRecordType: 'MARC_BIBLIOGRAPHIC',
jobExecutionId: faker.random.uuid(),
sourceRecordId: sourceRecordsIds[3],
sourceRecordOrder: '3',
sourceRecordTitle: 'Test item 4',
error: 'Error message',
}, {
sourceRecordActionStatus: 'CREATED',
holdingsActionStatus: 'CREATED',
holdingsRecordHridList: ['holdingsHrid1'],
sourceRecordType: 'MARC_HOLDINGS',
jobExecutionId: faker.random.uuid(),
sourceRecordId: sourceRecordsIds[4],
sourceRecordOrder: '4',
sourceRecordTitle: 'Test item 5',
}, {
sourceRecordActionStatus: 'DISCARDED',
holdingsActionStatus: 'DISCARDED',
holdingsRecordHridList: ['holdingsHrid2'],
sourceRecordType: 'MARC_HOLDINGS',
jobExecutionId: faker.random.uuid(),
sourceRecordId: sourceRecordsIds[5],
sourceRecordOrder: '5',
sourceRecordTitle: 'Test item 6',
}],
});
const jobLogResources = buildResources({
resourceName: 'jobLog',
records: [{
sourceRecordId: sourceRecordsIds[0],
sourceRecordOrder: '0',
sourceRecordTitle: 'Test item 1',
relatedInstanceInfo: {
actionStatus: 'CREATED',
idList: [instanceId],
},
relatedHoldingsInfo: {
actionStatus: 'CREATED',
idList: [faker.random.uuid()],
},
relatedItemInfo: {
actionStatus: 'CREATED',
idList: [faker.random.uuid()],
},
relatedAuthorityInfo: {
actionStatus: 'CREATED',
idList: [authorityId],
},
}, {
sourceRecordId: sourceRecordsIds[1],
sourceRecordOrder: '1',
sourceRecordTitle: 'Test item 2',
relatedInstanceInfo: {
actionStatus: 'UPDATED',
idList: [instanceId],
},
relatedHoldingsInfo: {
actionStatus: 'UPDATED',
idList: [faker.random.uuid()],
},
relatedItemInfo: {
actionStatus: 'UPDATED',
idList: [faker.random.uuid()],
},
relatedAuthorityInfo: {
actionStatus: 'UPDATED',
idList: [authorityId],
},
}, {
sourceRecordId: sourceRecordsIds[2],
sourceRecordOrder: '2',
sourceRecordTitle: 'Test item 1',
relatedInstanceInfo: {
actionStatus: 'MULTIPLE',
idList: [faker.random.uuid()],
},
relatedHoldingsInfo: {
actionStatus: 'MULTIPLE',
idList: [faker.random.uuid()],
},
relatedItemInfo: {
actionStatus: 'MULTIPLE',
idList: [faker.random.uuid()],
},
relatedAuthorityInfo: {
actionStatus: 'MULTIPLE',
idList: [faker.random.uuid()],
},
}, {
sourceRecordId: sourceRecordsIds[3],
sourceRecordOrder: '3',
sourceRecordTitle: 'Test item 4',
relatedInstanceInfo: {
actionStatus: 'DISCARDED',
idList: [faker.random.uuid()],
},
relatedHoldingsInfo: {
actionStatus: 'DISCARDED',
idList: [faker.random.uuid()],
},
relatedItemInfo: {
actionStatus: 'DISCARDED',
idList: [faker.random.uuid()],
},
relatedAuthorityInfo: {
actionStatus: 'DISCARDED',
idList: [faker.random.uuid()],
},
}],
});
const resources = {
...jobLogEntriesResources,
...jobLogResources,
};
const mutator = buildMutator();
const source = {
records: () => resources.jobLogEntries.records,
pending: () => false,
totalCount: () => resources.jobLogEntries.other.totalRecords,
fetchMore: noop,
fetchOffset: noop,
};
const renderRecordsTable = ({ isEdifactType = false }) => {
const component = (
<BrowserRouter>
<RecordsTable
isEdifactType={isEdifactType}
resources={resources}
mutator={mutator}
source={source}
resultCountIncrement={5}
pageAmount={5}
/>
</BrowserRouter>
);
return renderWithIntl(component, translationsProperties);
};
describe('RecordsTable component', () => {
it('should have proper columns', () => {
const { getByText } = renderRecordsTable({});
/*
* Get "Holdings" and "Error" labels by query selector instead of by "getByText" because there are
* "Holdings" / "Error" column labels and "Holdings" / "Error" messages in cells on the page
*/
const holdingsColumn = document.querySelector('#list-column-holdingsstatus div[class^="mclHeaderInner"] > div');
const errorColumn = document.querySelector('#list-column-error div[class^="mclHeaderInner"] > div');
expect(getByText('Record')).toBeDefined();
expect(getByText('Title')).toBeDefined();
expect(getByText('SRS MARC')).toBeDefined();
expect(getByText('Instance')).toBeDefined();
expect(holdingsColumn.innerHTML).toEqual('Holdings');
expect(getByText('Item')).toBeDefined();
expect(getByText('Authority')).toBeDefined();
expect(getByText('Order')).toBeDefined();
expect(getByText('Invoice')).toBeDefined();
expect(errorColumn.innerHTML).toEqual('Error');
});
describe('record order field', () => {
describe('for EDIFACT data type', () => {
it('should display order as it is', () => {
const { container } = renderRecordsTable({ isEdifactType: true });
const cells = container.querySelectorAll('[role="gridcell"]');
const firstRowRecordOrder = cells[0].innerHTML;
expect(firstRowRecordOrder).toEqual('0');
});
});
describe('for MARC data type', () => {
it('should display incremented order', () => {
const { container } = renderRecordsTable({});
const cells = container.querySelectorAll('[role="gridcell"]');
const firstRowRecordOrder = cells[0].innerHTML;
expect(firstRowRecordOrder).toEqual('1');
});
});
});
describe('when clicking on a record title', () => {
it('should navigate to the log details screen', () => {
const { getByText } = renderRecordsTable({});
expect(getByText('Test item 1').href).toContain(`/data-import/log/${firstRecordJobExecutionId}/${sourceRecordsIds[0]}`);
});
});
describe('when action status is CREATED', () => {
it('the instance value should be a hotlink', () => {
const { container } = renderRecordsTable({});
fireEvent.click(container.querySelector('[data-row-index="row-0"] [data-test-entity-name="instance"]'));
expect(window.location.href).toContain(`/inventory/view/${instanceId}`);
});
it('the authority value should be a hotlink', () => {
const { container } = renderRecordsTable({});
fireEvent.click(container.querySelector('[data-row-index="row-0"] [data-test-entity-name="authority"]'));
expect(window.location.href).toContain(`/marc-authorities/authorities/${authorityId}`);
});
});
describe('when action status is UPDATED', () => {
it('the instance value should be a hotlink', () => {
const { container } = renderRecordsTable({});
fireEvent.click(container.querySelector('[data-row-index="row-1"] [data-test-entity-name="instance"]'));
expect(window.location.href).toContain(`/inventory/view/${instanceId}`);
});
it('the authority value should be a hotlink', () => {
const { container } = renderRecordsTable({});
fireEvent.click(container.querySelector('[data-row-index="row-1"] [data-test-entity-name="authority"]'));
expect(window.location.href).toContain(`/marc-authorities/authorities/${authorityId}`);
});
});
describe('when action status is MULTIPLE', () => {
it('the value should be a text', () => {
const { getByText } = renderRecordsTable({});
expect(getByText('Multiple')).not.toHaveAttribute('href');
});
});
describe('when action status is DISCARDED', () => {
it('the value should be a text', () => {
const { getAllByText } = renderRecordsTable({});
const discardedStatuses = getAllByText('Discarded');
discardedStatuses.forEach(status => {
expect(status).not.toHaveAttribute('href');
});
});
});
});
| 31.212219 | 126 | 0.650458 |
29bbc78769eca030e9eff84fd99e20abd3ca3728 | 5,376 | js | JavaScript | tests/unit/abilities/doi-test.js | front-matter/bracco | e80b25a1814672a026aa597e67ab19fe79f016fe | [
"MIT"
] | 8 | 2017-12-10T18:51:52.000Z | 2022-02-12T17:50:00.000Z | tests/unit/abilities/doi-test.js | front-matter/bracco | e80b25a1814672a026aa597e67ab19fe79f016fe | [
"MIT"
] | 533 | 2017-08-28T09:30:25.000Z | 2022-03-09T17:26:30.000Z | tests/unit/abilities/doi-test.js | front-matter/bracco | e80b25a1814672a026aa597e67ab19fe79f016fe | [
"MIT"
] | 6 | 2018-03-22T17:07:00.000Z | 2022-02-12T17:50:08.000Z | import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import Service from '@ember/service';
import { setupFactoryGuy, make } from 'ember-data-factory-guy';
module('Unit | Ability | doi', function(hooks) {
setupTest(hooks);
setupFactoryGuy(hooks);
test('it exists', function(assert) {
const ability = this.owner.lookup('ability:doi');
assert.ok(ability);
});
test('role staff_admin', function(assert) {
const ability = this.owner.lookup('ability:doi');
const currentUser = Service.extend({
uid: 'admin',
name: 'Admin',
role_id: 'staff_admin',
});
this.owner.register('service:current-user', currentUser);
assert.equal(ability.canViewHealth, true);
assert.equal(ability.canViewState, true);
assert.equal(ability.canSource, true);
assert.equal(ability.canTransfer, true);
assert.equal(ability.canMove, true);
assert.equal(ability.canUpdate, true);
assert.equal(ability.canUpload, true);
assert.equal(ability.canCreate, true);
assert.equal(ability.canDelete, true);
assert.equal(ability.canModify, true);
assert.equal(ability.canEdit, true);
assert.equal(ability.canForm, true);
assert.equal(ability.canDetail, true);
assert.equal(ability.canRead, true);
});
test('role provider_admin', function(assert) {
const ability = this.owner.lookup('ability:doi');
const currentUser = Service.extend({
uid: 'datacite',
name: 'DataCite',
role_id: 'provider_admin',
provider_id: 'ands',
});
this.owner.register('service:current-user', currentUser);
this.set('provider', make('ands'));
this.set('repository', make('repository', { id: 'ands.centre9', provider: this.provider }));
this.set('model', make('doi', { repository: this.repository }));
ability.model = this.model;
assert.equal(ability.canViewHealth, true);
assert.equal(ability.canViewState, true);
assert.equal(ability.canSource, false);
assert.equal(ability.canTransfer, true);
assert.equal(ability.canMove, true);
assert.equal(ability.canUpdate, true);
assert.equal(ability.canUpload, false);
assert.equal(ability.canCreate, false);
assert.equal(ability.canDelete, false);
assert.equal(ability.canModify, false);
assert.equal(ability.canEdit, false);
assert.equal(ability.canForm, false);
assert.equal(ability.canDetail, true);
assert.equal(ability.canRead, true);
});
test('role client_admin', function(assert) {
const ability = this.owner.lookup('ability:doi');
const currentUser = Service.extend({
uid: 'ands.centre9',
name: 'Australian Data Archive',
role_id: 'client_admin',
client_id: 'ands.centre9',
});
this.owner.register('service:current-user', currentUser);
this.set('provider', make('ands'));
this.set('repository', make('repository', { id: 'ands.centre9', provider: this.provider }));
this.set('model', make('doi', { repository: this.repository }));
ability.model = this.model;
assert.equal(ability.canViewHealth, false);
assert.equal(ability.canViewState, true);
assert.equal(ability.canSource, false);
assert.equal(ability.canTransfer, false);
assert.equal(ability.canMove, false);
assert.equal(ability.canUpdate, true);
assert.equal(ability.canUpload, true);
assert.equal(ability.canCreate, true);
assert.equal(ability.canDelete, true);
assert.equal(ability.canModify, true);
assert.equal(ability.canEdit, true);
assert.equal(ability.canForm, false);
assert.equal(ability.canDetail, true);
assert.equal(ability.canRead, true);
});
test('role consortium_admin', function(assert) {
const ability = this.owner.lookup('ability:doi');
const currentUser = Service.extend({
uid: 'carl',
name: 'Admin',
role_id: 'consortium_admin',
consortium_id: 'carl.frdr',
});
this.owner.register('service:current-user', currentUser);
this.set('provider', make('carl'));
this.set('repository', make('repository', { id: 'carl.frdr', provider: this.provider }));
this.set('model', make('doi', { repository: this.repository }));
ability.model = this.model;
assert.equal(ability.canViewHealth, true);
assert.equal(ability.canViewState, true);
assert.equal(ability.canSource, false);
assert.equal(ability.canTransfer, true);
assert.equal(ability.canMove, true);
assert.equal(ability.canUpdate, true);
assert.equal(ability.canUpload, false);
assert.equal(ability.canCreate, false);
assert.equal(ability.canDelete, false);
assert.equal(ability.canModify, false);
assert.equal(ability.canEdit, false);
assert.equal(ability.canForm, false);
assert.equal(ability.canDetail, true);
assert.equal(ability.canRead, true);
});
// test('it canViewHealth', function(assert) {
// let ability = this.owner.lookup('ability:doi');
// const currentUser = Service.extend({
// uid: 'tib.awi',
// name: 'Alfred Wegener Institute',
// role_id: 'client_admin',
// provider_id: 'tib',
// client_id: 'tib.awi',
// });
// this.owner.register('service: ', currentUser);
// console.log(ability.currentUser);
// assert.equal(ability.canViewHealth, true);
// assert.equal(ability.canViewState, true);
// });
});
| 36.571429 | 96 | 0.672991 |
29bca797e0de6330495c97148c13e38192fb00ec | 2,128 | js | JavaScript | src/components/map/Map.js | ialixandroae/day-and-night | c098022db0d56a382edb2b629efcc2f62655c05c | [
"MIT"
] | null | null | null | src/components/map/Map.js | ialixandroae/day-and-night | c098022db0d56a382edb2b629efcc2f62655c05c | [
"MIT"
] | null | null | null | src/components/map/Map.js | ialixandroae/day-and-night | c098022db0d56a382edb2b629efcc2f62655c05c | [
"MIT"
] | null | null | null | import React, { useEffect, useRef, useContext, useState } from 'react';
import ReactDOM from 'react-dom';
import { loadModules } from 'esri-loader';
import { generateCones } from '../../helpers/helpers';
import { store } from '../../store/store';
import Controller from '../controller/Controller';
export const MapView = () => {
const globalState = useContext(store);
const { dispatch } = globalState;
const mapRef = useRef();
const [mapView, setView] = useState(null);
let [graphicsLayer, setGraphicsLayer] = useState(null);
const now = globalState.state.date;
useEffect(() => {
// lazy load the required ArcGIS API for JavaScript modules and CSS
async function loadWebScene() {
const [Map, MapView, GraphicsLayer, Expand] = await loadModules(
[
'esri/Map',
'esri/views/MapView',
'esri/layers/GraphicsLayer',
'esri/widgets/Expand',
],
{
css: true,
}
);
graphicsLayer = new GraphicsLayer();
await generateCones(now, graphicsLayer, 0.3);
const map = new Map({
basemap: 'topo-vector',
});
map.add(graphicsLayer);
const view = new MapView({
container: mapRef.current,
map: map,
zoom: 2,
});
var node = document.createElement('div');
ReactDOM.render(
<Controller dispatch={dispatch} view={view} now={now} />,
node
);
let expand = new Expand({
view: view,
content: node,
});
view.ui.add(expand, 'top-right');
setView(view);
setGraphicsLayer(graphicsLayer);
return () => {
if (view) {
// destroy the map view
view.container = null;
}
};
}
loadWebScene();
}, []);
useEffect(() => {
if (mapView) {
graphicsLayer.removeAll();
async function recreateCones() {
await generateCones(globalState.state.date, graphicsLayer, 0.3);
}
recreateCones();
}
}, [globalState.state.date]);
return <div style={{ height: '100%', width: '100%' }} ref={mapRef} />;
};
| 25.035294 | 72 | 0.572838 |
29bd5b43929376fb627196a069ac60ce8f78da2e | 2,139 | js | JavaScript | dist/chain.js | scrat-lol/loop | 3ff183da93f0bed6a195ba0bd9495ba53efd3c5c | [
"0BSD"
] | 6 | 2019-08-12T19:07:43.000Z | 2021-11-09T15:17:30.000Z | dist/chain.js | scrat-lol/loop | 3ff183da93f0bed6a195ba0bd9495ba53efd3c5c | [
"0BSD"
] | 5 | 2019-07-09T14:02:18.000Z | 2021-06-28T05:52:56.000Z | dist/chain.js | scrat-lol/loop | 3ff183da93f0bed6a195ba0bd9495ba53efd3c5c | [
"0BSD"
] | 2 | 2019-06-20T15:38:43.000Z | 2019-08-12T19:12:40.000Z | "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Chain = void 0;
class Chain {
constructor(tasks = [], alive = true) {
this.tasks = tasks;
this.alive = alive;
}
// old alias for "add" remains here for backwards compatibility
do(...callable) {
return this.add(...callable);
}
add(...callable) {
this.tasks = this.tasks.concat(callable);
return this;
}
once(async = false) {
this.alive = false;
(async && ((self) => __awaiter(this, void 0, void 0, function* () { return self.async(); }))(this)) || this.sync();
return this;
}
every(milliseconds) {
this.add(() => new Promise((resolve) => setTimeout(resolve, milliseconds)));
return this.forever(true);
}
forever(async = false) {
this.alive = true;
(async && ((self) => __awaiter(this, void 0, void 0, function* () { return self.async(); }))(this)) || this.sync();
return this;
}
cancel() {
this.alive = false;
return this;
}
async() {
return __awaiter(this, void 0, void 0, function* () {
for (let task of this.tasks) {
yield task();
}
this.alive && this.async();
});
}
sync() {
for (let task of this.tasks) {
task();
}
this.alive && this.sync();
}
}
exports.Chain = Chain;
| 35.65 | 123 | 0.553997 |
29bea1f814a6d49fdba2f96ccb45fa7a520a5781 | 769 | js | JavaScript | ui.js | nikosandronikos/svg_battle | eafdb00008b55c39c8f2c83cc372a2f3663a8876 | [
"MIT"
] | null | null | null | ui.js | nikosandronikos/svg_battle | eafdb00008b55c39c8f2c83cc372a2f3663a8876 | [
"MIT"
] | null | null | null | ui.js | nikosandronikos/svg_battle | eafdb00008b55c39c8f2c83cc372a2f3663a8876 | [
"MIT"
] | null | null | null | function Window(parent, x, y, w, h, fill)
{
this.g = create_group(parent);
this.rect = create_rect(this.g, x, y, w, h, fill);
}
function Message(parent, msg)
{
Message.baseConstructor.call(this, parent, 10, 10, 200, 100, "rgb(200,200,220)");
create_text(this.g, msg, 40, 40, "black");
this.b = new Button(this.g, 40, 50, "Ok", "reset_game()", event_handlers);
console.log(msg);
}
KevLinDev.extend(Message, Window);
function Button(parent, x, y, msg, handler, event_handlers)
{
Button.baseConstructor.call(this, parent, x, y, 120, 40, "red");
create_text(this.g, msg, x+20, y+20, "black");
event_handlers.addHandler("temp_ui", this.rect, handler);
}
KevLinDev.extend(Button, Window); | 27.464286 | 86 | 0.620286 |
29bfe412a9d17b19c7c34d3fce16eeb91af02e76 | 541 | js | JavaScript | index.js | OstlerDev/wpd2txt-electron | 7ed32c42d8eb0a6e14bad5308af182d30fe9849a | [
"MIT"
] | 1 | 2018-04-01T06:24:14.000Z | 2018-04-01T06:24:14.000Z | index.js | OstlerDev/wpd2txt-electron | 7ed32c42d8eb0a6e14bad5308af182d30fe9849a | [
"MIT"
] | null | null | null | index.js | OstlerDev/wpd2txt-electron | 7ed32c42d8eb0a6e14bad5308af182d30fe9849a | [
"MIT"
] | null | null | null | const electron = require('electron');
const {app} = electron
let window
const createWindow = () => {
// window = new electron.BrowserWindow(electron.screen.getPrimaryDisplay().workAreaSize)
window = new electron.BrowserWindow({ width: 600, height: 300 })
// window.openDevTools();
window.loadURL(`file://${__dirname}/index.html`)
// window.webContents.openDevTools()
window.on('closed', () => { window = null })
}
app.on('ready', createWindow)
app.on('window-all-closed', app.quit)
app.on('activate', () => {
createWindow()
}) | 22.541667 | 89 | 0.683919 |
29c01793cd5c111652e24d9dee8cfe57d1fea667 | 882 | js | JavaScript | app/components/common/OverlaySpinner/overlay-spinner.js | builtwithluv/ZenFocus | 16896b56d336f001de2c09d2ec147a0fcddffc9a | [
"MIT"
] | 101 | 2017-05-25T19:28:49.000Z | 2022-01-05T14:17:48.000Z | app/components/common/OverlaySpinner/overlay-spinner.js | builtwithluv/ZenFocus | 16896b56d336f001de2c09d2ec147a0fcddffc9a | [
"MIT"
] | 141 | 2017-05-26T06:53:40.000Z | 2022-02-22T13:32:33.000Z | app/components/common/OverlaySpinner/overlay-spinner.js | builtwithluv/ZenFocus | 16896b56d336f001de2c09d2ec147a0fcddffc9a | [
"MIT"
] | 27 | 2017-05-25T00:40:16.000Z | 2022-01-03T19:33:09.000Z | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Intent, Overlay, Spinner } from '@blueprintjs/core';
const OverlaySpinner = ({ isOpen, children }) => {
const containerStyles = classNames(
'd-flex',
'flex-column',
'align-items-center',
'justify-content-center',
'w-100',
'h-100',
'z-21',
);
return (
<Overlay
canEscapeKeyClose={false}
canOutsideClickClose={false}
isOpen={isOpen}
backdropClassName="bg-black"
>
<div className={containerStyles}>
<Spinner intent={Intent.SUCCESS} className="w-50" />
<div className="mt-2 text-white">
{children}
</div>
</div>
</Overlay>
);
};
OverlaySpinner.propTypes = {
isOpen: PropTypes.bool.isRequired,
children: PropTypes.node
};
export default OverlaySpinner;
| 22.615385 | 61 | 0.628118 |
29c0405839371f64b0d31d4abee573702fe95e53 | 4,098 | js | JavaScript | utils/insertDatabaseContent.js | MTC-ETH/labelling-tool-aesthetics | 0e37aee6fd7cd7bbecd11f042d8523c436cb9287 | [
"Apache-2.0"
] | null | null | null | utils/insertDatabaseContent.js | MTC-ETH/labelling-tool-aesthetics | 0e37aee6fd7cd7bbecd11f042d8523c436cb9287 | [
"Apache-2.0"
] | null | null | null | utils/insertDatabaseContent.js | MTC-ETH/labelling-tool-aesthetics | 0e37aee6fd7cd7bbecd11f042d8523c436cb9287 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 ETH Zurich, Media Technology Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const fs = require('fs');
let path = '.env';
try {
if (!fs.existsSync(path)) {
path = "../.env"
}
} catch(err) {
console.error(err);
}
require('dotenv').config({path: path});
const mongoose = require('mongoose');
const uri = process.env.MONGODB_URI || "mongodb://localhost/labelling_tool";
mongoose.connect(uri, {useNewUrlParser:true, useCreateIndex: true, useUnifiedTopology:true});
const connection = mongoose.connection;
let articlesJson = require(`../json/articles_examples`);
//insert consecutive ids for paragraphs
articlesJson = articlesJson
.map(article => {
article.paragraphs = article.paragraphs.map((par, index) => {
return {consecutiveID: index, text: par};
});
if(!article.stanceQuestions) {
article.stanceQuestions = [{"ID": -1, text: "Is the article in favour or against the topic it is talking about?"}]
}
return article;
});
connection.once("open", () => {
console.log("MongoDB database connection established successfully");
const articles = require(`../models/articles`);
console.log("Creating database");
connection.db.listCollections({name: 'articles'})
.next(function(err, collinfo) {
console.log("Collection articles");
if (collinfo) {
console.log("already exists, updating instead");
// articles.find({}).exec((err, res) => console.log(JSON.stringify(res)));
const allPromises = [];
articlesJson.forEach(art => {
allPromises.push(articles.findOneAndUpdate({articleID: art.articleID}, art).exec());
});
Promise.all(allPromises)
.then(() => console.log("Updated succesfully"))
.catch(err => console.log(err));
} else {
console.log("doesn't exist, creating it");
articles.insertMany(articlesJson, function(err, result) {
if (err) {
console.log(err);
} else {
console.log("SUCCESS, inserted " + articlesJson.length + " articles");
}
});
}
});
const addAlsoLabellers = false;
if(addAlsoLabellers) {
const {getCorrectLabellersSchema} = require("../routes/utils");
const labellers = getCorrectLabellersSchema();
connection.db.listCollections({name: 'labellers'})
.next(function(err, collinfo) {
console.log("Collection articles");
if (collinfo) {
console.log("labellers already exists");
} else {
console.log("labellers doesn't exist, attempting to create it");
try {
const labellersJson = require(`../json/labellers`);
labellers.insertMany(labellersJson, function(err, result) {
if (err) {
console.log(err);
} else {
console.log("SUCCESS, inserted " + labellersJson.length + " labellers");
}
});
} catch (ex) {
console.log("Cannot find file ./json/labellers.json, no labellers were added");
}
}
});
}
}); | 37.59633 | 126 | 0.554417 |
29c0deeb2558a817c74da419af80c5e003169a49 | 725 | js | JavaScript | web/src/components/Form/TradeFormFields/Slider.js | JEstradaTbot/tbotx | 6c0a19dc0242a31a083593b5b9b379d02f7e1743 | [
"MIT"
] | 1 | 2022-02-24T17:16:19.000Z | 2022-02-24T17:16:19.000Z | web/src/components/Form/TradeFormFields/Slider.js | JEstradaTbot/tbotx | 6c0a19dc0242a31a083593b5b9b379d02f7e1743 | [
"MIT"
] | null | null | null | web/src/components/Form/TradeFormFields/Slider.js | JEstradaTbot/tbotx | 6c0a19dc0242a31a083593b5b9b379d02f7e1743 | [
"MIT"
] | null | null | null | import React from 'react';
import { Slider } from 'antd';
// todo: connect antd slider to redux form
const marks = {
0: {},
25: {
label: '25%',
style: {
transform: 'translateX(-66%)',
},
},
50: {
label: '50%',
style: {
transform: 'translateX(-66%)',
},
},
75: {
label: '75%',
style: {
transform: 'translateX(-66%)',
},
},
100: {
label: '100%',
style: {
transform: 'translateX(-66%)',
},
},
};
const SizeSlider = (props) => {
const { onClick } = props;
return (
<div className="size-slider px-1 pb-2">
<Slider
marks={marks}
step={null}
defaultValue={0}
tooltipVisible={false}
onAfterChange={onClick}
/>
</div>
);
};
export default SizeSlider;
| 14.215686 | 42 | 0.548966 |
29c1c923198cf0906f6b2a2b895f1a6c2ea8f788 | 110 | js | JavaScript | next_version/src/utils/log.js | mikestaub/serverless-offline | 7e46f8cbd3c50ff3c34586b711ef540ceb52d112 | [
"MIT"
] | null | null | null | next_version/src/utils/log.js | mikestaub/serverless-offline | 7e46f8cbd3c50ff3c34586b711ef540ceb52d112 | [
"MIT"
] | 1 | 2016-08-21T01:39:15.000Z | 2016-08-21T01:39:15.000Z | next_version/src/utils/log.js | mikestaub/serverless-offline | 7e46f8cbd3c50ff3c34586b711ef540ceb52d112 | [
"MIT"
] | 4 | 2016-08-11T15:27:37.000Z | 2017-04-11T12:51:51.000Z | 'use strict';
const chalk = require('chalk');
module.exports = console.log.bind(null, chalk.gray('slso:'));
| 18.333333 | 61 | 0.681818 |
29c2942ce421ed81a35c5042419ee9f298fe5436 | 907 | js | JavaScript | src/Layer.js | Dash-OS/react-page-layers | 2fd09be59b4ae669924fa341ce8d2d16423c164f | [
"MIT"
] | null | null | null | src/Layer.js | Dash-OS/react-page-layers | 2fd09be59b4ae669924fa341ce8d2d16423c164f | [
"MIT"
] | null | null | null | src/Layer.js | Dash-OS/react-page-layers | 2fd09be59b4ae669924fa341ce8d2d16423c164f | [
"MIT"
] | null | null | null | import React, { Component, PropTypes } from 'react'
export default class Layer extends Component {
componentWillUnmount = () =>
this.context.pageLayers.registry('layer', 'unmount', this)
componentDidMount = () =>
this.context.pageLayers.registry('layer', 'mount', this)
componentWillReceiveProps = np => np.show !== this.props.show
&& this.context.pageLayers.registry('layer', np.show === true ? 'mount' : 'unmount', this)
shouldComponentUpdate = np => np.show !== this.props.show
render = () => this.props.show === true
? this.context.pageLayers.getLayerContent(this)
: null
}
Layer.defaultProps = { show: true }
Layer.propTypes = {
layerID: PropTypes.string.isRequired,
show: PropTypes.bool
}
Layer.contextTypes = {
pageLayers: PropTypes.shape({
registry: PropTypes.func.isRequired,
getLayerContent: PropTypes.func.isRequired
}).isRequired
} | 28.34375 | 96 | 0.689085 |
29c37d3e0b3095d50ad765c46ff96e934f112fd5 | 1,390 | js | JavaScript | static/src/javascripts/projects/commercial/modules/third-party-tags/remarketing.spec.js | Omrisnyk/frontend | 98f6234c99ac87cc653664aeb6fd5953646cace4 | [
"Apache-2.0"
] | null | null | null | static/src/javascripts/projects/commercial/modules/third-party-tags/remarketing.spec.js | Omrisnyk/frontend | 98f6234c99ac87cc653664aeb6fd5953646cace4 | [
"Apache-2.0"
] | null | null | null | static/src/javascripts/projects/commercial/modules/third-party-tags/remarketing.spec.js | Omrisnyk/frontend | 98f6234c99ac87cc653664aeb6fd5953646cace4 | [
"Apache-2.0"
] | null | null | null | // @flow
import { remarketing } from 'commercial/modules/third-party-tags/remarketing';
const { shouldRun, url } = remarketing;
const onLoad: any = remarketing.onLoad;
/**
* we have to mock config like this because
* loading remarketing has side affects
* that are dependent on config.
* */
jest.mock('lib/config', () => {
const defaultConfig = {
switches: {
remarketing: true,
},
};
return Object.assign({}, defaultConfig, {
get: (path: string = '', defaultValue: any) =>
path
.replace(/\[(.+?)\]/g, '.$1')
.split('.')
.reduce((o, key) => o[key], defaultConfig) || defaultValue,
});
});
describe('Remarketing', () => {
it('should exist', () => {
expect(shouldRun).toEqual(true);
expect(url).toEqual(
expect.stringContaining('www.googleadservices.com')
);
expect(onLoad).toBeDefined();
});
it('should call google_trackConversion', () => {
window.google_trackConversion = jest.fn();
window.google_tag_params = 'google_tag_params__test';
onLoad();
expect(window.google_trackConversion).toHaveBeenCalledWith({
google_conversion_id: 971225648,
google_custom_params: 'google_tag_params__test',
google_remarketing_only: true,
});
});
});
| 28.367347 | 78 | 0.577698 |
29c4b6500e63d8cd80a4f93522ef63761938beaa | 408 | js | JavaScript | objeto/oo.js | RamonDiego00/exercicios-js | 6089735a709e4c45cebe661b9a2b4a8e6c6f16ff | [
"MIT"
] | null | null | null | objeto/oo.js | RamonDiego00/exercicios-js | 6089735a709e4c45cebe661b9a2b4a8e6c6f16ff | [
"MIT"
] | null | null | null | objeto/oo.js | RamonDiego00/exercicios-js | 6089735a709e4c45cebe661b9a2b4a8e6c6f16ff | [
"MIT"
] | null | null | null | // CONTIGO NÃO EXECUTÁVEL!!!
// Procedural(esses valores são processados e não redirecionados)
processamento(valor1, valor2, valor3)
// O
objeto= {
valor1,
valor2,
valor3,
processamento() {
// ...
}
}
objeto.processamento() // Foco passou a ser o objeto e não a função
//Principais importantes:
// 1. abstração
// 2. encapsulamento
// 3. herança(prototype)
// 4. polimorfismo | 17.73913 | 67 | 0.661765 |
29c4bebda4fd2b08df7a3475b73994a981fbcaf3 | 1,411 | js | JavaScript | p5js/forest-01/app.js | brianhonohan/sketchbook | b43df1a8106e1073500ddf37885a8537c702be7b | [
"MIT"
] | 10 | 2021-12-16T18:47:37.000Z | 2022-03-12T00:28:01.000Z | p5js/forest-01/app.js | brianhonohan/sketchbook | b43df1a8106e1073500ddf37885a8537c702be7b | [
"MIT"
] | 4 | 2018-09-08T04:00:26.000Z | 2021-12-25T18:19:34.000Z | p5js/forest-02/app.js | brianhonohan/sketchbook | b43df1a8106e1073500ddf37885a8537c702be7b | [
"MIT"
] | null | null | null | var system;
var gui;
var systemParams = {
foraging_rate: 0.6,
seeds_per_tree: 2,
seed_drop_dist: 70,
initial_trees: 10,
paused: false,
tree: {
max_age: 200,
years_as_sapling: 4,
years_as_mature: 140,
age_to_make_seeds: 40,
}
};
function setup() {
createCanvas(windowWidth, windowHeight-35);
P5JsSettings.init();
gui = P5JsSettings.addDatGui({autoPlace: false});
gui.add(systemParams, 'foraging_rate').min(0.1).max(0.9).step(0.05);
gui.add(systemParams, 'seeds_per_tree').min(1).max(20).step(1);
gui.add(systemParams, 'seed_drop_dist').min(1).max(150).step(10);
gui.add(systemParams, 'initial_trees').min(1).max(50).step(1);
gui.add(systemParams, "paused");
let treeCfg = gui.addFolder('Tree Attributes');
treeCfg.add(systemParams.tree, 'max_age').min(20).max(500).step(5);
treeCfg.add(systemParams.tree, 'years_as_sapling').min(3).max(30).step(1);
treeCfg.add(systemParams.tree, 'years_as_mature').min(15).max(300).step(5);
treeCfg.add(systemParams.tree, 'age_to_make_seeds').min(3).max(60).step(3);
let rect = new Rect(0, 0, width, height);
system = new System(rect, systemParams);
system.init();
}
function keyPressed() {
if (key === 'c'){
P5JsSettings.init();
system.init();
} else if (key === 't'){
system.forest.sproutTree(mouseX, mouseY);
}
}
function draw(){
background(50);
system.tick();
system.render();
}
| 26.12963 | 77 | 0.671864 |
29c50e27757399be7668cd6532408648c0d98fac | 1,047 | js | JavaScript | pyraminx/heuristic.js | unixpickle/puzzle.js | d75e1737e98230f7424285746092644d9bba7b7d | [
"BSD-2-Clause"
] | 4 | 2016-06-30T01:29:41.000Z | 2020-04-07T08:37:44.000Z | pyraminx/heuristic.js | unixpickle/puzzle.js | d75e1737e98230f7424285746092644d9bba7b7d | [
"BSD-2-Clause"
] | null | null | null | pyraminx/heuristic.js | unixpickle/puzzle.js | d75e1737e98230f7424285746092644d9bba7b7d | [
"BSD-2-Clause"
] | 1 | 2020-04-07T08:37:46.000Z | 2020-04-07T08:37:46.000Z | // EdgesHeuristic determines a lower-bound for the number of moves to solve a set of Edges.
function EdgesHeuristic(maxDepth) {
this._table = new Uint8Array(11520);
for (var i = 0, len = this._table.length; i < len; ++i) {
this._table[i] = maxDepth + 1;
}
var moves = allMoves();
var queue = [{state: new Edges(), depth: 0}];
while (queue.length > 0) {
var node = queue.shift();
var state = node.state;
var depth = node.depth;
var hash = state.hash();
if (this._table[hash] <= maxDepth) {
continue;
}
this._table[hash] = depth;
if (depth !== maxDepth) {
for (var moveIndex = 0; moveIndex < 8; ++moveIndex) {
var newState = state.copy();
newState.move(moves[moveIndex]);
queue.push({state: newState, depth: depth+1});
}
}
}
}
// lowerBound returns a lower bound for the number of moves to solve a set of edges.
EdgesHeuristic.prototype.lowerBound = function(edges) {
return this._table[edges.hash()];
};
exports.EdgesHeuristic = EdgesHeuristic;
| 28.297297 | 91 | 0.630372 |
29c50efc46246c65626865339e9e82d87a195a76 | 6,115 | js | JavaScript | frontend/build.config.js | suomenriistakeskus/oma-riista-web | 4b641df6b80384ed36bc3e284f104b98f8a84afd | [
"MIT"
] | 14 | 2017-01-11T23:22:36.000Z | 2022-02-09T06:49:46.000Z | frontend/build.config.js | suomenriistakeskus/oma-riista-web | 4b641df6b80384ed36bc3e284f104b98f8a84afd | [
"MIT"
] | 4 | 2018-04-16T13:00:49.000Z | 2021-02-15T11:56:06.000Z | frontend/build.config.js | suomenriistakeskus/oma-riista-web | 4b641df6b80384ed36bc3e284f104b98f8a84afd | [
"MIT"
] | 4 | 2017-01-20T10:34:24.000Z | 2021-02-09T14:41:46.000Z | 'use strict';
var path = require('path');
var targetBase = './_public/frontend/';
module.exports = {
target: {
js: path.join(targetBase, 'js'),
lib: path.join(targetBase, 'js', 'lib'),
css: path.join(targetBase, 'css'),
fonts: path.join(targetBase, 'fonts'),
partials: path.join(targetBase, 'partials'),
assets: targetBase
},
buildProfile: process.env.BUILD_PROFILE || 'dev',
e2e: {
profile: process.env.E2E_PROFILE || 'local',
testFiles: ['./e2e/**/*.spec.js'],
config: {
local: './protractor.conf.js',
ci: './protractor.ci.conf.js'
},
hub: {
local: 'http://localhost:4444/wd/hub',
ci: 'http://hub.selenium.vincit.intranet/wd/hub'
},
baseUrl: {
local: 'http://localhost:9494/',
ci: 'http://ci.vincit.intranet:9494/'
}
},
vendorFiles: {
fonts: [
'../node_modules/bootstrap/dist/fonts/*',
'../node_modules/font-awesome/fonts/*'
],
other: [
'../node_modules/lodash/lodash.min.js',
'../node_modules/moment/min/moment.min.js',
'../node_modules/leaflet/dist/leaflet.js',
'../node_modules/leaflet.markercluster/dist/leaflet.markercluster.js',
'../node_modules/drmonty-leaflet-awesome-markers/js/leaflet.awesome-markers.min.js',
'../node_modules/leaflet.vectorgrid/dist/Leaflet.VectorGrid.bundled.js',
'../node_modules/leaflet-fullscreen/dist/Leaflet.fullscreen.min.js',
'../node_modules/leaflet-draw/dist/leaflet.draw.js',
'../node_modules/leaflet-geometryutil/src/leaflet.geometryutil.js',
'../node_modules/leaflet-snap/leaflet.snap.js',
'../node_modules/leaflet-measure-path/leaflet-measure-path.js',
'../node_modules/leaflet-easybutton/src/easy-button.js',
'../node_modules/proj4/dist/proj4.js',
'../node_modules/proj4leaflet/src/proj4leaflet.js',
'./app/leaflet/leaflet-projection.js',
'./app/leaflet/leaflet-lasso.js',
'./app/leaflet/leaflet-marquee.js',
'./app/leaflet/leaflet-polyline.js',
'./app/leaflet/leaflet-geojson-layers.js',
'./app/leaflet/leaflet-coordinates.js',
'./app/leaflet/leaflet-simple-legend.js',
'../node_modules/greiner-hormann/dist/greiner-hormann.min.js',
'../node_modules/qrcodejs/qrcode.min.js'
],
angular: [
'../node_modules/es6-promise-polyfill/promise.min.js',
// Must load jQuery here for angular auto-detection
'../node_modules/jquery/dist/jquery.min.js',
'../node_modules/dropzone/dist/min/dropzone.min.js',
'../node_modules/angular/angular.min.js',
'../node_modules/angular-i18n/angular-locale_fi-fi.js',
'../node_modules/angular-cookies/angular-cookies.min.js',
'../node_modules/angular-resource/angular-resource.min.js',
'../node_modules/angular-sanitize/angular-sanitize.min.js',
'../node_modules/angular-messages/angular-messages.min.js',
'../node_modules/angular-cache/dist/angular-cache.min.js',
'../node_modules/angular-loading-bar/build/loading-bar.min.js',
'../node_modules/angular-translate/dist/angular-translate.min.js',
'../node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
'../node_modules/angular-translate-storage-cookie/angular-translate-storage-cookie.min.js',
'../node_modules/angular-translate-storage-local/angular-translate-storage-local.min.js',
'../node_modules/angular-translate-handler-log/angular-translate-handler-log.min.js',
'../node_modules/angular-ui-router/release/angular-ui-router.min.js',
'./vendor/ui-router-history.js',
'../node_modules/angular-ui-mask/dist/mask.min.js',
'../node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js',
'../node_modules/angular-ui-select2/src/select2.js',
'../node_modules/ui-select/dist/select.js',
//'../node_modules/ui-leaflet/dist/ui-leaflet.js',
'./vendor/ui-leaflet.min.js',
'../node_modules/angular-bootstrap-show-errors/src/showErrors.min.js',
'../node_modules/angular-growl-v2/build/angular-growl.min.js',
'../node_modules/angular-dialog-service/dist/dialogs.min.js',
'../node_modules/angular-simple-logger/dist/angular-simple-logger.light.min.js',
'../node_modules/angular-vs-repeat/src/angular-vs-repeat.min.js',
'../node_modules/angular-block-ui/dist/angular-block-ui.min.js',
'../node_modules/angular-upload/angular-upload.min.js',
'../node_modules/angular-http-auth/src/http-auth-interceptor.js',
'../node_modules/angular-dropzone/lib/angular-dropzone.js',
'../node_modules/ng-idle/angular-idle.min.js',
'../node_modules/diff/dist/diff.min.js',
'../node_modules/angular-file-saver/dist/angular-file-saver.bundle.min.js',
// This must be the last dependency due to packaging issues
'../node_modules/select2/select2.js'
]
},
appFiles: {
code: [
'./app/**/*.js',
'!./app/leaflet/**',
'!./app/**/*.spec.js'
],
style: './app/app.less',
styleBase: './app/',
styleWatch: './app/**/*.less',
partials: [
"./app/module/**/*.html"
],
assetsBase: './app/assets/',
assets: [
'./app/assets/**'
],
shim: [
'../node_modules/angular-loader/angular-loader.min.js',
// Old async loader is still required by cached scripts
'../node_modules/scriptjs/dist/script.min.js',
'../node_modules/loadjs/dist/loadjs.min.js'
]
}
};
| 45.977444 | 113 | 0.585446 |
29c64aaa40d2b88e95abc888c5b53d2062e4ea22 | 7,443 | js | JavaScript | src/pages/dashboard/routes/Settings/Settings.js | LABS-EU3/flashcards_frontend | 7a70d4d37dfb9ddcb0d7bcd7eb0ae5a087d45a11 | [
"MIT"
] | null | null | null | src/pages/dashboard/routes/Settings/Settings.js | LABS-EU3/flashcards_frontend | 7a70d4d37dfb9ddcb0d7bcd7eb0ae5a087d45a11 | [
"MIT"
] | 41 | 2019-12-13T14:01:02.000Z | 2020-02-08T21:47:02.000Z | src/pages/dashboard/routes/Settings/Settings.js | LABS-EU3/flashcards_frontend | 7a70d4d37dfb9ddcb0d7bcd7eb0ae5a087d45a11 | [
"MIT"
] | 1 | 2020-02-17T16:19:20.000Z | 2020-02-17T16:19:20.000Z | /* eslint-disable import/no-cycle */
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';
import RoundedImage from 'react-rounded-image';
import { MdKeyboardArrowDown, MdCloudUpload } from 'react-icons/md';
import useAction from '../../../../utils/useAction';
import * as action from '../../../../modules/user/userActions';
import { H1, H2, H3, P } from '../../../../styles/typography';
import { LogoutButton } from '../../../../styles/buttons';
import ProfileManagementForm from './SettingsForms/ProfileManagement';
import PasswordManagementForm from './SettingsForms/PasswordManagement';
import AccountManagementForm from './SettingsForms/AccountManagement';
import HelpCenterForm from './SettingsForms/HelpCenter';
import { ProfileImageDiv } from '../../styles/DashboardStyles';
import profileDefault from '../../../../assets/user_profile_default.jpg';
import { openUploadWidget } from '../../../../utils/CloudinaryService';
import {
BottomContainer,
HideDiv1,
HideDiv2,
IconButtonWrapper,
InnerContainer,
LeftBottomContainer,
MyHR,
ProfileInnerContainer,
RightBottomContainer,
StyledLink,
TopContainer,
TopLeftBottomContainer,
UpperCardSection,
Wrapper,
} from './SettingsStyles';
export default function Settings() {
const { credentials } = useSelector(state => state.user);
const imgUrl = useSelector(state => state.user.credentials.image_url);
const uploadProfileImg = useAction(action.uploadProfileImg);
const logoutUser = useAction(action.logoutUser);
const history = useHistory();
const [open1, setOpen1] = useState(false);
const [open2, setOpen2] = useState(false);
const [open3, setOpen3] = useState(false);
const [open4, setOpen4] = useState(false);
const [open5, setOpen5] = useState(false);
const handleButtonClick1 = () => {
setOpen1(!open1);
};
const handleButtonClick2 = () => {
setOpen2(!open2);
};
const handleButtonClick3 = () => {
setOpen3(!open3);
};
const handleButtonClick4 = () => {
setOpen4(!open4);
};
const handleButtonClick5 = () => {
setOpen5(!open5);
};
const loadProfileImg = () => {
openUploadWidget(
['profile image'],
`${credentials.full_name}_${credentials.id}`,
error => {
// eslint-disable-next-line no-console
console.log(error);
},
imageUrl => {
uploadProfileImg(imageUrl);
},
);
};
return (
<Wrapper>
<TopContainer>
<ProfileImageDiv>
<ProfileInnerContainer>
<RoundedImage
image={imgUrl || profileDefault}
alt="User's profile"
imageHeight="100"
imageWidth="100"
roundedSize="1"
roundedColor="#FFF"
/>
<MdCloudUpload size="3.5em" color="grey" onClick={loadProfileImg} />
</ProfileInnerContainer>
<H1>{credentials.full_name}</H1>
<P>{credentials.email}</P>
</ProfileImageDiv>
</TopContainer>
<BottomContainer>
<LeftBottomContainer>
<InnerContainer>
<UpperCardSection>
<H1 fontSize="2em" lineHeight="1em">
Profile Management
</H1>
<IconButtonWrapper rotate={open1} onClick={handleButtonClick1}>
<MdKeyboardArrowDown
size="3.5em"
color="grey"
onClick={handleButtonClick1}
/>
</IconButtonWrapper>
</UpperCardSection>
<MyHR />
{open1 && <ProfileManagementForm />}
</InnerContainer>
<InnerContainer className="mobileDiv2">
<HideDiv2>
<UpperCardSection>
<H1 fontSize="2em" lineHeight="0em">
Password Management
</H1>
<IconButtonWrapper rotate={open3} onClick={handleButtonClick3}>
<MdKeyboardArrowDown
size="3.5em"
color="grey"
onClick={handleButtonClick3}
/>
</IconButtonWrapper>
</UpperCardSection>
<MyHR />
{open3 && <PasswordManagementForm />}
</HideDiv2>
</InnerContainer>
<InnerContainer>
<UpperCardSection>
<H1 fontSize="2em" lineHeight="1em">
Account Management
</H1>
<IconButtonWrapper rotate={open2} onClick={handleButtonClick2}>
<MdKeyboardArrowDown
size="3.5em"
color="grey"
onClick={handleButtonClick2}
/>
</IconButtonWrapper>
</UpperCardSection>
<MyHR />
{open2 && (
<>
<TopLeftBottomContainer>
<H2
fontSize="2.5em"
style={{ cursor: 'pointer' }}
color="red"
onClick={handleButtonClick5}
>
Delete Account
</H2>
{open5 && <AccountManagementForm history={history} />}
</TopLeftBottomContainer>
<>
<UpperCardSection>
<H2 fontSize="2em" lineHeight="1em">
Version
</H2>
<P>Beta 0.3.0</P>
</UpperCardSection>
<H2
color="#3399FF"
style={{ cursor: 'pointer' }}
onClick={handleButtonClick4}
>
Help Center
</H2>
{open4 && <HelpCenterForm />}
</>
</>
)}
</InnerContainer>
<InnerContainer className="mobileDiv1">
<HideDiv1>
<LogoutButton>
<StyledLink to="/login" onClick={() => logoutUser(history)}>
<H3 color="#444140">Log Out</H3>
</StyledLink>
</LogoutButton>
</HideDiv1>
</InnerContainer>
</LeftBottomContainer>
<RightBottomContainer>
<InnerContainer className="mobileDiv1">
<HideDiv1>
<UpperCardSection>
<H1 fontSize="2em" lineHeight="1em">
Password Management
</H1>
<IconButtonWrapper rotate={open3} onClick={handleButtonClick3}>
<MdKeyboardArrowDown
size="3.5em"
color="grey"
onClick={handleButtonClick3}
/>
</IconButtonWrapper>
</UpperCardSection>
<MyHR />
{open3 && <PasswordManagementForm />}
</HideDiv1>
</InnerContainer>
<InnerContainer className="mobileDiv2">
<HideDiv2>
<LogoutButton>
<StyledLink to="/login" onClick={() => logoutUser(history)}>
<H3 color="#444140">Log Out</H3>
</StyledLink>
</LogoutButton>
</HideDiv2>
</InnerContainer>
</RightBottomContainer>
</BottomContainer>
</Wrapper>
);
}
| 31.807692 | 80 | 0.52022 |
29c74ec2954ead16a5a8cc1fd17470fa6447217d | 217 | js | JavaScript | vue2/src/routes.js | ONEGISER/web-frame | ef5c63b1a38e5ffa228d33e1f1beb3f611d3ce63 | [
"MIT"
] | null | null | null | vue2/src/routes.js | ONEGISER/web-frame | ef5c63b1a38e5ffa228d33e1f1beb3f611d3ce63 | [
"MIT"
] | null | null | null | vue2/src/routes.js | ONEGISER/web-frame | ef5c63b1a38e5ffa228d33e1f1beb3f611d3ce63 | [
"MIT"
] | 2 | 2021-11-17T10:04:32.000Z | 2022-01-26T06:05:26.000Z | import HelloWorld from './components/HelloWorld.vue';
import TreeViewer from './components/TreeViewer.vue';
export default [
{ path: '/', component: HelloWorld },
{ path: '/viewer', component: TreeViewer },
] | 31 | 53 | 0.695853 |
29c7b346f72c35197303f1ab37400a63e0eb6eb3 | 524 | js | JavaScript | JavaScript_Advanced/15.DESIGN_PATTERNS_AND_BEST_PRACTICES/Projects/First_From_Video/singleton.js | VladislavPenchev/JavaScript | 3faa5cb39da9ffde092f6646c9735528f252d319 | [
"MIT"
] | null | null | null | JavaScript_Advanced/15.DESIGN_PATTERNS_AND_BEST_PRACTICES/Projects/First_From_Video/singleton.js | VladislavPenchev/JavaScript | 3faa5cb39da9ffde092f6646c9735528f252d319 | [
"MIT"
] | 4 | 2021-03-10T20:32:34.000Z | 2021-05-11T16:13:48.000Z | JavaScript_Advanced/15.DESIGN_PATTERNS_AND_BEST_PRACTICES/Projects/First_From_Video/singleton.js | VladislavPenchev/JavaScript | 3faa5cb39da9ffde092f6646c9735528f252d319 | [
"MIT"
] | null | null | null | // class Data {
// static getInstance(){
// this._instance = this._instance || new Data();
// return this._instance;
// }
// //behavior
// }
// Data.getInstance();
let instance = null;
const data = (function() {
class Data {
//behavior
}
const getInstance = () => {
instalnce = instance || new Data();
return instance;
};
return {
getInstance,
}
}());
class DataFactory {
createData() {
return data.getInstance();
}
} | 15.878788 | 57 | 0.51145 |