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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0654b6e9225c8ea0c143cfbb30cfc28f3514d287 | 525 | js | JavaScript | src/types/input.js | IgorLesnevskiy/table2excel | 6633279bc0b2968595194ac6e6326b2013fc41eb | [
"MIT"
] | 85 | 2016-08-02T09:16:05.000Z | 2022-03-26T10:26:56.000Z | src/types/input.js | IgorLesnevskiy/table2excel | 6633279bc0b2968595194ac6e6326b2013fc41eb | [
"MIT"
] | 16 | 2016-12-07T09:53:45.000Z | 2021-08-30T17:15:25.000Z | src/types/input.js | IgorLesnevskiy/table2excel | 6633279bc0b2968595194ac6e6326b2013fc41eb | [
"MIT"
] | 95 | 2016-11-15T12:03:45.000Z | 2022-03-26T10:27:00.000Z | /**
* Generates a cell object for an input field cell.
*
* @param {HTMLTableCellElement} cell - The cell.
*
* @returns {object} - A cell object of the cell or `null` if the cell doesn't
* fulfill the criteria of an input field cell.
*/
export default cell => {
let input = cell.querySelector('input[type="text"], textarea');
if (input) return { t: 's', v: input.value };
input = cell.querySelector('select');
if (input) return { t: 's', v: input.options[input.selectedIndex].textContent };
return null;
};
| 29.166667 | 82 | 0.664762 |
d1d2882028faa0e9e9858750888e1f22a8d3a0ff | 198 | js | JavaScript | src/modules/actions/index.js | bajajmohit19/ant-dummie | 80a687706f1c7b299141009854d05f4b7f4bbba4 | [
"MIT"
] | null | null | null | src/modules/actions/index.js | bajajmohit19/ant-dummie | 80a687706f1c7b299141009854d05f4b7f4bbba4 | [
"MIT"
] | 3 | 2020-09-06T15:20:40.000Z | 2022-02-12T17:35:03.000Z | src/modules/actions/index.js | bajajmohit19/ant-dummie | 80a687706f1c7b299141009854d05f4b7f4bbba4 | [
"MIT"
] | 1 | 2020-10-08T05:29:18.000Z | 2020-10-08T05:29:18.000Z | export * from './userActions'
export const showLoader = () => {
return { type: 'SHOW_BTN_LOADING' }
}
export const hideLoader = () => {
return { type: 'HIDE_BTN_LOADING' }
}
export default {} | 18 | 37 | 0.646465 |
d1d3c8f0cee13dc9830e53e70713f869f9ea9bde | 430 | js | JavaScript | lib/overseasClaimDetailsObject.js | dwp/gysp-agent-ui | 94a05e7a0a99eb63172aebde9bc326906a3c60c5 | [
"MIT"
] | null | null | null | lib/overseasClaimDetailsObject.js | dwp/gysp-agent-ui | 94a05e7a0a99eb63172aebde9bc326906a3c60c5 | [
"MIT"
] | 1 | 2020-08-18T11:42:17.000Z | 2020-08-18T11:42:17.000Z | lib/overseasClaimDetailsObject.js | dwp/gysp-agent-ui | 94a05e7a0a99eb63172aebde9bc326906a3c60c5 | [
"MIT"
] | 2 | 2020-08-28T12:11:40.000Z | 2021-04-10T22:14:58.000Z | const moment = require('moment');
module.exports = {
formatter(details) {
const claimDate = moment(details.claimDate);
const statePensionDate = moment(details.statePensionDate);
return {
statePensionDate: statePensionDate.format('DD MMM YYYY'),
claimDate: claimDate.format('DD MMM YYYY'),
niNumber: details.nino,
surname: details.surname,
inviteKey: details.inviteKey,
};
},
};
| 25.294118 | 63 | 0.674419 |
d1d45ed6988e5317445cdb762b36102067598706 | 1,587 | js | JavaScript | src/bootstrap.js | ri/news-emote | feff8b39366d110acf76ad9e79f1f98b2cf1dd12 | [
"MIT"
] | 5 | 2017-04-20T09:29:26.000Z | 2017-10-29T22:58:04.000Z | src/bootstrap.js | ri/news-emote | feff8b39366d110acf76ad9e79f1f98b2cf1dd12 | [
"MIT"
] | null | null | null | src/bootstrap.js | ri/news-emote | feff8b39366d110acf76ad9e79f1f98b2cf1dd12 | [
"MIT"
] | null | null | null | // global css
import './theme/theme.scss'
// classes you want to use immediately
import {App} from './App'
import reqwest from 'reqwest'
import queryString from 'query-string'
// import './vendor/scrollsnap-polyfill.bundled'
/**
* entrance code for SPA
*/
function main() {
document.title = 'Loading...'
// Query string format: ?loc=us|au&filter=bad|good|mixed
var dom = document.querySelector('.content')
var hash = queryString.parse(location.search)
var loc = 'au'
var filter = null
var lang = navigator.language || navigator.userLanguage
if (hash.loc === 'us' || (!hash.loc && lang.toLowerCase() === 'en-us')) {
loc = 'us'
} else if (hash.loc === 'uk') {
loc = 'uk'
}
if (hash.filter === 'neg' | hash.filter === 'pos' | hash.filter === 'mixed') {
filter = hash.filter
}
const app = new App({
dom: dom
})
reqwest({
url: `https://s3.amazonaws.com/data.newsemote/${loc}/latest.json`,
type: 'json',
crossOrigin: true,
success: (resp) => app.render(resp, loc, filter)
})
// we can make requests to multiple domains, check out proxy/rules.js
// send request to github.com
// http.get('https://s3.amazonaws.com/data.newsemote/us/latest.json').then((res) => {
// const data = JSON.parse(res)
// app.render(data)
// document.title = 'App Started'
// })
// // send request to npmjs.org
// http.get('/node-1').then((json) => console.log('From npmjs.org: ', json))
// console.log([1, 2, 3, 4].includes(1)) // ES7: Array.prototype.includes
}
document.addEventListener('DOMContentLoaded', main)
| 26.898305 | 87 | 0.62949 |
d1d4be45cde88d2e5dfa0361578d4deb0c9f08cf | 3,275 | js | JavaScript | src/components/book/BookPage.js | sribysana/book_Inventory_ui_app | 53b1b75c65e0fbedfb80e4207dd6a9dd9450b31f | [
"MIT"
] | null | null | null | src/components/book/BookPage.js | sribysana/book_Inventory_ui_app | 53b1b75c65e0fbedfb80e4207dd6a9dd9450b31f | [
"MIT"
] | null | null | null | src/components/book/BookPage.js | sribysana/book_Inventory_ui_app | 53b1b75c65e0fbedfb80e4207dd6a9dd9450b31f | [
"MIT"
] | null | null | null | import React, {Component, PropTypes} from 'react';
import {List,Map} from 'immutable';
import {Modal} from 'react-bootstrap';
import {getBook, toggleModal, toggleBookEditModal } from './bookActions';
import {getUser, addToCart, removeFromCart} from '../../common/user/userActions';
import Book from './components/Book';
import BookForm from './components/BookEditForm/BookForm';
export default class BookPage extends Component {
constructor(props) {
super(props);
this.addToCart = this.addToCart.bind(this);
this.removeFromCart = this.removeFromCart.bind(this);
this.onCloseBookEditModal = this.onCloseBookEditModal.bind(this);
this.editModalToChange = this.editModalToChange.bind(this);
}
componentWillMount() {
this.props.dispatch(getBook());
this.props.dispatch(getUser());
}
addToCart(bookId) {
this.props.dispatch(addToCart(bookId));
}
removeFromCart(bookId) {
this.props.dispatch(removeFromCart(bookId));
}
editModalToChange(id) {
console.log('id >>>>',id)
this.props.dispatch(getBook(id, true));
this.props.dispatch(toggleBookEditModal(true))
}
onCloseBookEditModal(){
this.props.dispatch(toggleBookEditModal(false))
}
render() {
if (this.props.books.size === 0) {
return <div>no books found</div>;
}
console.log(this.props.editBook);
return (
<div>
<h1>Book Page </h1>
<strong>Enabled: {this.props.isModalEnabled}</strong>
<ul className="list-group">
{
this.props.books.map((e) => {
const availableInCart = !!this.props.cart.find(c => c.get('id') === e.get('_id'));
return (<Book
key={e.get('_id')}
book={e}
isAddToCartBtn={availableInCart}
addToCart={this.addToCart}
editModalToChange={this.editModalToChange}
editModalEnabled={this.props.editModalEnabled}
removeFromCart={this.removeFromCart}/>);
})
}
</ul>
<div>
{
(this.props.isModalEnabled)
? <button onClick={() => this.props.dispatch(toggleModal(false))}>Disable</button>
: <button onClick={() => this.props.dispatch(toggleModal(true))}>Enable</button>
}
</div>
<div>
<Modal show={this.props.editModalEnabled} onHide={this.onCloseBookEditModal}>
<Modal.Header closeButton>
<Modal.Title>Book Edit Model</Modal.Title>
</Modal.Header>
<Modal.Body>
<BookForm book={this.props.editBook}/>
</Modal.Body>
<Modal.Footer>
<div>
<button type="save" className="btn btn-primary" >Save</button>
<button type="button" className="btn btn-default">Cancel</button>
</div>
</Modal.Footer>
</Modal>
</div>
</div>
);
}
}
BookPage.propTypes = {
books: PropTypes.instanceOf(List).isRequired,
cart: PropTypes.instanceOf(List).isRequired,
dispatch: PropTypes.func.isRequired,
editBook:PropTypes.instanceOf(Map),
editModalEnabled: PropTypes.bool.isRequired,
};
// 71ee71d863fd18c963409bd2f6b644126bc99819
| 30.896226 | 96 | 0.606107 |
d1d70435e46b7f32333cad0fd97c9b43f15ca52b | 1,265 | js | JavaScript | client/src/models/Points.js | czarekowyxjs/agar.io-clone-multiplayer | 600d4a8f428c68a519dbb12fcbf632952baa683c | [
"MIT"
] | null | null | null | client/src/models/Points.js | czarekowyxjs/agar.io-clone-multiplayer | 600d4a8f428c68a519dbb12fcbf632952baa683c | [
"MIT"
] | null | null | null | client/src/models/Points.js | czarekowyxjs/agar.io-clone-multiplayer | 600d4a8f428c68a519dbb12fcbf632952baa683c | [
"MIT"
] | null | null | null | class Points {
constructor(ctx, canvas, points) {
this.ctx = ctx;
this.canvas = canvas;
this.points = points;
this.heroData = {};
this.logged = false;
}
draw() {
for(let i = 0;i < this.points.length;++i) {
this.drawPoint(this.points[i]);
}
}
drawPoint(point) {
const halfCanvasWidth = this.canvas.width/2;
const halfCanvasHeight = this.canvas.height/2;
const pointX = point.x;
const pointY = point.y;
const heroX = this.heroData.pos.x;
const heroY = this.heroData.pos.y;
const diffX = heroX-pointX;
const diffY = heroY-pointY;
let x, y = 0;
if(diffX > 0) {
x = halfCanvasWidth-diffX;
} else if(diffX < 0) {
x = halfCanvasWidth+Math.abs(diffX);
}
if(diffY > 0) {
y = halfCanvasHeight-diffY;
} else if(diffY < 0) {
y = halfCanvasHeight+Math.abs(diffY);
}
let newRadius = point.r-(this.heroData.points/300);
if(newRadius < 4) {
newRadius = 4;
}
//
this.ctx.fillStyle = point.color;
this.ctx.beginPath();
this.ctx.arc(x, y, newRadius, 0, 2*Math.PI);
this.ctx.fill();
//
}
inject(data, type) {
switch(type) {
case "hero":
this.heroData = data;
break;
case "points":
this.points = data;
break;
default:
return;
}
}
}
export default Points; | 18.880597 | 53 | 0.61581 |
d1d9002cf403598c696e8436db6804a5374838ea | 218 | js | JavaScript | gameplay-api/html/search/enumvalues_67.js | j4m3z0r/GamePlay | 02ca734e5734d2fbc9d00a7eff65ed2656f26975 | [
"Apache-2.0",
"Unlicense"
] | 1 | 2021-09-02T01:45:24.000Z | 2021-09-02T01:45:24.000Z | gameplay-api/html/search/enumvalues_67.js | j4m3z0r/GamePlay | 02ca734e5734d2fbc9d00a7eff65ed2656f26975 | [
"Apache-2.0",
"Unlicense"
] | null | null | null | gameplay-api/html/search/enumvalues_67.js | j4m3z0r/GamePlay | 02ca734e5734d2fbc9d00a7eff65ed2656f26975 | [
"Apache-2.0",
"Unlicense"
] | null | null | null | var searchData=
[
['ghost_5fobject',['GHOST_OBJECT',['../classgameplay_1_1_physics_collision_object.html#a99aa09f043883dcd33865cd582de463ead53b782e6493799fe204347a135c5b0f',1,'gameplay::PhysicsCollisionObject']]]
];
| 43.6 | 196 | 0.834862 |
d1dbb9200527daa5b74d0a6431b4f25b8758f275 | 497 | js | JavaScript | node_modules/mdi-material-ui/FolderOpen.js | wh00sh/Tanda-DAPP | c8b21ca87dfa5e88ea6e975311e15e9009c48f75 | [
"Apache-2.0"
] | null | null | null | node_modules/mdi-material-ui/FolderOpen.js | wh00sh/Tanda-DAPP | c8b21ca87dfa5e88ea6e975311e15e9009c48f75 | [
"Apache-2.0"
] | null | null | null | node_modules/mdi-material-ui/FolderOpen.js | wh00sh/Tanda-DAPP | c8b21ca87dfa5e88ea6e975311e15e9009c48f75 | [
"Apache-2.0"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _createIcon = _interopRequireDefault(require("./util/createIcon"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _default = (0, _createIcon["default"])('M19,20H4C2.89,20 2,19.1 2,18V6C2,4.89 2.89,4 4,4H10L12,6H19A2,2 0 0,1 21,8H21L4,8V18L6.14,10H23.21L20.93,18.5C20.7,19.37 19.92,20 19,20Z');
exports["default"] = _default; | 35.5 | 183 | 0.704225 |
d1dd10e1fb66b531da03459c6b75f9e894f90ba5 | 2,160 | js | JavaScript | packages/extension/src/background/storage/index-db.js | Temmyogunbo/source | cc99cf038010017c8f47ea453256b97f7b156865 | [
"MIT"
] | 4 | 2019-09-30T19:51:40.000Z | 2019-10-05T22:00:08.000Z | packages/extension/src/background/storage/index-db.js | Temmyogunbo/source | cc99cf038010017c8f47ea453256b97f7b156865 | [
"MIT"
] | 104 | 2019-09-30T20:44:22.000Z | 2020-06-05T17:50:54.000Z | packages/extension/src/background/storage/index-db.js | Temmyogunbo/source | cc99cf038010017c8f47ea453256b97f7b156865 | [
"MIT"
] | 3 | 2019-10-04T02:53:30.000Z | 2019-10-24T14:06:58.000Z | import { Util } from '@mujo/utils'
import { openDB } from 'idb'
import {
DATABASE_NAME,
DATABASE_VERSION,
DATABASE_STORE,
LAST_ACTIVITY_TABLE,
ACTIVITY_NUMBER_KEY,
VALUE_CHANGED,
} from '../../constants'
import { broadcaster } from './broadcast'
import { migrate } from './migrations'
import { types } from './types'
const { set } = Util
export const open = async () =>
openDB(DATABASE_NAME, DATABASE_VERSION, {
upgrade: async (db, lastVersion, currentVersion, transaction) => {
// initial setup
db.createObjectStore(DATABASE_STORE)
const activityStore = db.createObjectStore(
LAST_ACTIVITY_TABLE,
{
keyPath: 'id',
autoIncrement: true,
}
)
activityStore.createIndex('date', 'date')
// migrations - not ran in test unless directly
if (process.env.NODE_ENV !== 'test') {
await migrate(lastVersion, currentVersion, transaction)
}
},
})
export const database = open()
export const createMethods = (db, store) => ({
async get(key) {
return (await db).get(store, key)
},
async set(key, value) {
const ret = await (await db).put(store, value, key)
broadcaster.broadcast({ key, value, event: VALUE_CHANGED })
return ret
},
async delete(key) {
return (await db).delete(store, key)
},
async clear() {
return (await db).clear(store)
},
async keys() {
return (await db).getAllKeys(store)
},
})
export const store = createMethods(database, DATABASE_STORE)
export const addLatestActivity = async date => {
const db = await database
const activityNumber = (await store.get(ACTIVITY_NUMBER_KEY)) || 0
return db.add(LAST_ACTIVITY_TABLE, {
date,
activityNumber,
})
}
export const getActivity = async () =>
(await database).getAllFromIndex(LAST_ACTIVITY_TABLE, 'date')
export const resetActivity = async () =>
(await database).clear(LAST_ACTIVITY_TABLE)
export default {
getters: types.reduce((accum, type) => {
set(accum, type, store.get)
return accum
}, {}),
setters: types.reduce((accum, type) => {
set(accum, type, store.set)
return accum
}, {}),
}
| 24.827586 | 70 | 0.65 |
d1debc4a847eb24709475b10570030308e56dfab | 1,969 | js | JavaScript | test/unit/client/web/geolocation.js | brentlintner/incubator-ripple | 86385ad34dbea5a08c3313ebc9f45b11bd097956 | [
"Apache-2.0"
] | 56 | 2015-01-05T19:21:10.000Z | 2018-04-20T12:49:06.000Z | test/unit/client/web/geolocation.js | SidYa/ripple | 394ce6b3a77efceedb963795ca174474f4a50250 | [
"Apache-2.0"
] | 36 | 2015-01-30T15:16:55.000Z | 2015-10-19T18:06:30.000Z | test/unit/client/web/geolocation.js | isabella232/incubator-retired-ripple | e208b483a835f4df2e886ae4ca39e92c6cc76f21 | [
"Apache-2.0"
] | 31 | 2015-01-17T11:19:21.000Z | 2016-05-12T00:22:45.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
describe("w3c_geolocation", function () {
var w3c = "w3c/1.0/",
web = "platform/web/default/",
spec = ripple(web + 'spec'),
ui = ripple(web + 'spec/ui');
describe("spec", function () {
it("includes require modules", function () {
expect(spec.objects.Coordinates.path).toEqual(w3c + "Coordinates");
expect(spec.objects.Position.path).toEqual(w3c + "Position");
expect(spec.objects.PositionError.path).toEqual(w3c + "PositionError");
expect(spec.objects.navigator.children.geolocation.path).toEqual(w3c + "geolocation");
});
describe("ui", function () {
it("uses web/spec/ui module", function () {
expect(spec.ui.plugins).toEqual(ui.plugins);
});
it("includes geoView plugin", function () {
function includesGeoViewPlugin() {
return ui.plugins.some(function (plugin) {
return plugin === "geoView";
});
}
expect(includesGeoViewPlugin()).toBe(true);
});
});
});
});
| 38.607843 | 98 | 0.615541 |
d1dec348cc8e324aea027eb6465a219b91d4e510 | 1,238 | js | JavaScript | pages/booking-link-page/accordion-body-content/BookingLinkPageContentRow.js | Jero786/react-redux-next-example | 73755cdc652b79b5fc0051edc37762ca9c24c67b | [
"MIT"
] | null | null | null | pages/booking-link-page/accordion-body-content/BookingLinkPageContentRow.js | Jero786/react-redux-next-example | 73755cdc652b79b5fc0051edc37762ca9c24c67b | [
"MIT"
] | null | null | null | pages/booking-link-page/accordion-body-content/BookingLinkPageContentRow.js | Jero786/react-redux-next-example | 73755cdc652b79b5fc0051edc37762ca9c24c67b | [
"MIT"
] | null | null | null | import './BookingLinkPageContentRow.scss';
import React from 'react';
import PropTypes from 'prop-types';
import {get} from 'lodash/object';
import Textfield from 'components/textfield/Textfield';
export default class BookingLinkPageContentRow extends React.PureComponent {
render() {
const {rule} = this.props;
const ruleContentId = get(rule, 'id');
const opportunityOwner = get(rule, 'opportunityOwner');
const active = get(rule, 'active');
const operation = get(rule, 'operation');
const ruleNumber = get(rule, 'ruleNumber');
return (
<div className="ch-booking-link-page-content-row">
<span className="ch-booking-link-page-content-row__id">
<span className="ch-booking-link-page-content-row__id-number">{ruleContentId}</span>
</span>
<span><Textfield text={opportunityOwner} /></span>
<span><Textfield text={active} /></span>
<span><Textfield style={{maxWidth: '30px'}} text={operation} /></span>
<span><Textfield style={{maxWidth: '30px'}} text={ruleNumber} /></span>
</div>
);
}
}
BookingLinkPageContentRow.propTypes = {
rule: PropTypes.object,
}; | 38.6875 | 98 | 0.629241 |
d1df38543621018ffc3a97961652c527be8a37c5 | 107 | js | JavaScript | script.js | Rezi121w/AhilesShop | 0aaee24bf055736020df05ad9c64da97c6252c02 | [
"Apache-2.0"
] | null | null | null | script.js | Rezi121w/AhilesShop | 0aaee24bf055736020df05ad9c64da97c6252c02 | [
"Apache-2.0"
] | null | null | null | script.js | Rezi121w/AhilesShop | 0aaee24bf055736020df05ad9c64da97c6252c02 | [
"Apache-2.0"
] | null | null | null | var market = localStorage.getItem("Market")
if(market != 1){
window.location.replace("index.html")
}
| 21.4 | 43 | 0.682243 |
d1e052065c57eca49f8c90a46d2984596e4820b8 | 295 | js | JavaScript | src/routes/Affiliate/components/AffiliateRuleRow/AffiliateRuleRow.js | mouhsinelonly/el-student-spa | 8009a0df8896edf19f69c65445cdce4d173ca4ef | [
"MIT"
] | null | null | null | src/routes/Affiliate/components/AffiliateRuleRow/AffiliateRuleRow.js | mouhsinelonly/el-student-spa | 8009a0df8896edf19f69c65445cdce4d173ca4ef | [
"MIT"
] | null | null | null | src/routes/Affiliate/components/AffiliateRuleRow/AffiliateRuleRow.js | mouhsinelonly/el-student-spa | 8009a0df8896edf19f69c65445cdce4d173ca4ef | [
"MIT"
] | null | null | null | // @flow
import React from 'react'
import './AffiliateRuleRow.scss'
type PropsType = {
text: string
};
const AffiliateRuleRow = (props: PropsType): React.Element<'li'> =>
<li className='AffiliateRuleRow' dangerouslySetInnerHTML={{ __html: props.text }} />
export default AffiliateRuleRow
| 22.692308 | 86 | 0.732203 |
d1e0d0f7625a27d5dcabee924b462a85400215cb | 5,480 | js | JavaScript | common/core/test/core.test.js | Vonage/vivid | d73b307cb3204f1ccde5493947bde32815a3aa9d | [
"Apache-2.0"
] | 11 | 2021-10-12T20:08:24.000Z | 2022-02-24T03:09:17.000Z | common/core/test/core.test.js | Vonage/vivid | d73b307cb3204f1ccde5493947bde32815a3aa9d | [
"Apache-2.0"
] | 202 | 2021-09-25T18:49:17.000Z | 2022-03-30T20:04:04.000Z | common/core/test/core.test.js | Vonage/vivid | d73b307cb3204f1ccde5493947bde32815a3aa9d | [
"Apache-2.0"
] | 2 | 2021-12-12T03:10:15.000Z | 2022-03-04T07:22:04.000Z | import {
randomAlpha,
getFrameLoadedInjected,
cleanFrame,
} from '../../../test/test-helpers.js';
import {
assertBaseVarsMatch,
PRINCIPAL_SCHEME_VARIABLES_FILTER,
} from '../../../test/style-utils.js';
const CONTEXT_ATTR = 'data-vvd-context';
const CORE_SETUP_HTML_TAG = 'coreSetupTest';
const LIGHT = 'light';
const DARK = 'dark';
const NONE = 'none';
describe('vvd-core service', () => {
/* eslint-disable no-undef */
after(() => {
cleanFrame(CORE_SETUP_HTML_TAG);
});
describe('basic APIs', () => {
it('is should init to default', async () => {
const r = randomAlpha();
const vvdCore = (await import(`../vvd-core.js?t=${r}`)).default;
assert.isDefined(vvdCore, 'core service is defined');
assert.isObject(vvdCore, 'core service is a defaultly exported object');
assert.isFunction(vvdCore.set, 'core service has "set" API method');
assert.isDefined(
vvdCore.settled,
'core service has "settled" object (Promise)'
);
assert.isFunction(
vvdCore.settled.then,
'core service has "settled" object - ensure it is Promise'
);
});
it('should init to none', async () => {
document.documentElement.setAttribute(CONTEXT_ATTR, 'none');
const r = randomAlpha();
const vvdCore = (await import(`../vvd-core.js?t=${r}`)).default;
document.documentElement.removeAttribute(CONTEXT_ATTR);
try {
await vvdCore.settled;
} catch (e) {
expect(e).exist;
expect(e.includes('auto-init unavailable')).true;
}
});
it('should init to dark', async () => {
document.documentElement.setAttribute(CONTEXT_ATTR, `theme:${DARK}`);
const r = randomAlpha();
const vvdCore = (await import(`../vvd-core.js?t=${r}`)).default;
document.documentElement.removeAttribute(CONTEXT_ATTR);
const coreInitResult = await vvdCore.settled;
assertInitResult(coreInitResult, DARK);
});
it('should perform set', async () => {
const r = randomAlpha();
const vvdCore = (await import(`../vvd-core.js?t=${r}`)).default;
const coreInitResult = await vvdCore.set({ scheme: LIGHT });
assertInitResult(coreInitResult, LIGHT);
});
it('should not fail on abnormal calls', async () => {
document.documentElement.setAttribute(
CONTEXT_ATTR,
`illegal theme:${DARK} theme:${LIGHT}`
);
const r = randomAlpha();
const vvdCore = (await import(`../vvd-core.js?t=${r}`)).default;
document.documentElement.removeAttribute(CONTEXT_ATTR);
let coreInitResult = await vvdCore.settled;
assertInitResult(coreInitResult, DARK);
coreInitResult = await vvdCore.set({
scheme: DARK,
illegal: { some: null },
});
assertInitResult(coreInitResult, DARK);
});
});
describe('switch flows in encapsulated environment and assert variables set', () => {
it('should perform auto-init to default when no data-vvd-context provided', async function () {
this.timeout(8000);
await getFrameLoadedInjected(CORE_SETUP_HTML_TAG, async (iframe) => {
const iframeWindow = iframe.contentWindow;
await iframeWindow.executeSetup();
const coreInitResult = await iframeWindow.vvdCore.settled;
assertInitResult(coreInitResult, LIGHT);
assertBaseVarsMatch(
LIGHT,
PRINCIPAL_SCHEME_VARIABLES_FILTER,
iframe.contentDocument.body
);
});
});
it('should perform auto-init to a value in data-vvd-context, when provided', async function () {
this.timeout(8000);
const vvdContextTheme = DARK;
await getFrameLoadedInjected(CORE_SETUP_HTML_TAG, async (iframe) => {
iframe.contentDocument.documentElement.setAttribute(
CONTEXT_ATTR,
`theme:${vvdContextTheme}`
);
const iframeWindow = iframe.contentWindow;
await iframeWindow.executeSetup();
const coreInitResult = await iframeWindow.vvdCore.settled;
assertInitResult(coreInitResult, vvdContextTheme);
assertBaseVarsMatch(
vvdContextTheme,
PRINCIPAL_SCHEME_VARIABLES_FILTER,
iframe.contentDocument.body
);
});
});
it('should NOT perform auto-init when data-vvd-context is "none"', async function () {
this.timeout(8000);
const vvdContextNone = NONE;
await getFrameLoadedInjected(CORE_SETUP_HTML_TAG, async (iframe) => {
iframe.contentDocument.documentElement.setAttribute(
CONTEXT_ATTR,
vvdContextNone
);
const iframeWindow = iframe.contentWindow;
await iframeWindow.executeSetup();
try {
await iframeWindow.vvdCore.settled;
} catch (e) {
expect(e).exist;
expect(e.includes('auto-init unavailable')).true;
}
});
});
it('should perform init to a first value in data-vvd-context, when many provided', async function () {
this.timeout(8000);
const vvdContextTheme = LIGHT;
await getFrameLoadedInjected(CORE_SETUP_HTML_TAG, async (iframe) => {
iframe.contentDocument.documentElement.setAttribute(
CONTEXT_ATTR,
`theme:${vvdContextTheme} theme:${DARK}`
);
const iframeWindow = iframe.contentWindow;
await iframeWindow.executeSetup();
const coreInitResult = await iframeWindow.vvdCore.settled;
assertInitResult(coreInitResult, vvdContextTheme);
assertBaseVarsMatch(
vvdContextTheme,
PRINCIPAL_SCHEME_VARIABLES_FILTER,
iframe.contentDocument.body
);
});
});
});
});
function assertInitResult(tested, expectedScheme) {
expect(tested).exist;
expect(tested.scheme).exist;
expect(tested.scheme.option).equal(expectedScheme);
expect(tested.scheme.scheme).equal(expectedScheme);
}
| 29.621622 | 104 | 0.692883 |
d1e24de1b4b64ef3d2bb8681ba44d192fb3f9084 | 5,674 | js | JavaScript | test/index.js | chmanie/jeton | cb0147fbe4536ce4e640c2f2483e45120822146a | [
"Unlicense",
"MIT"
] | null | null | null | test/index.js | chmanie/jeton | cb0147fbe4536ce4e640c2f2483e45120822146a | [
"Unlicense",
"MIT"
] | null | null | null | test/index.js | chmanie/jeton | cb0147fbe4536ce4e640c2f2483e45120822146a | [
"Unlicense",
"MIT"
] | null | null | null | // Load modules
var Lab = require('lab');
var Code = require('code');
// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;
var after = lab.after;
var describe = lab.experiment;
var it = lab.test;
var expect = Code.expect;
var sinon = require('sinon');
describe('Token storage', function() {
var Catbox = require('catbox');
describe('general functions and initialization', function () {
it('initializes without options', function (done) {
expect(function () {
require('../lib').storage();
}).not.to.throw();
done();
});
it('initializes with options', function (done) {
expect(function () {
require('../lib').storage({
expires: 48*60*60*1000
});
}).not.to.throw();
done();
});
it('generates a token', function (done) {
var token = require('../lib').storage().generate();
expect(token).to.be.a.string();
expect(token).to.have.length(64);
done();
});
it('starts and stops the token storage', function (done) {
var token = require('../lib').storage();
token.start(function (err) {
if (err) throw err;
token.stop(done);
done();
});
});
it('errors on catbox engine start error', function (done) {
var token = require('../lib').storage();
sinon.stub(Catbox.Client.prototype, 'start', function (cb) {
cb(new Error('Fake err'));
});
token.start(function (err) {
expect(err).to.be.instanceof(Error);
Catbox.Client.prototype.start.restore();
done();
});
});
});
describe('token CRI', function () {
var tokenStorage = require('../lib').storage();
before(function (done) {
tokenStorage.start(done);
});
after(function (done) {
tokenStorage.stop();
done();
});
it('creates tokens', function (done) {
tokenStorage.store('me@me.com', function (err, token) {
expect(token).to.be.a.string();
expect(token).to.have.length(64);
done();
});
});
it('creates tokens with additional data', function (done) {
tokenStorage.store('me@me.com', { type: 'forgot' }, function (err, token) {
expect(token).to.be.a.string();
expect(token).to.have.length(64);
done();
});
});
it('errors on policy error', function (done) {
sinon.stub(Catbox.Policy.prototype, 'set', function (key, value, ttl, cb) {
cb(new Error('Fake err'));
});
tokenStorage.store('me@me.com', function (err) {
expect(err).to.be.instanceof(Error);
Catbox.Policy.prototype.set.restore();
done();
});
});
it('retrieves token data', function (done) {
tokenStorage._policy.set('mytoken', {
identity: 'me@me.com',
foo: 'bar'
}, 5000, function (err) {
if (err) return done(err);
tokenStorage.retrieve('mytoken', 'me@me.com', function (err, data) {
if (err) {
return done(err);
}
expect(data.foo).to.equal('bar');
done();
});
});
});
it('does not retrieve token data if it does not exist', function (done) {
tokenStorage.retrieve('myothertoken', 'me@me.com', function (err, data) {
expect(data).to.be.null();
done();
});
});
it('does not retrieve token data if identity is wrong', function (done) {
tokenStorage._policy.set('mytoken', {
identity: 'me@me.com'
}, 5000, function (err) {
if (err) return done(err);
tokenStorage.retrieve('mytoken', 'me@moo.com', function (err, data) {
expect(err).to.be.instanceof(Error);
expect(err.message).to.contain('Invalid identity');
done();
});
});
});
it('retrieves token data without identity if checkIdentity is false', function (done) {
tokenStorage.config.checkIdentity = false;
tokenStorage._policy.set('mytoken', {
identity: 'me@me.com'
}, 5000, function (err) {
if (err) return done(err);
tokenStorage.retrieve('mytoken', function (err, data) {
expect(data).to.be.an.object();
expect(data.identity).to.equal('me@me.com');
tokenStorage.config.checkIdentity = true;
done();
});
});
});
it('errors when trying to get token without identity when checkIdentity is true', function (done) {
tokenStorage._policy.set('mytoken', {
identity: 'beep@boop.com'
}, 5000, function (err) {
if (err) return done(err);
tokenStorage.retrieve('mytoken', function (err, data) {
expect(err).to.be.instanceof(Error);
expect(err.message).to.contain('Identity has to be provided');
done();
});
});
});
it('invalidates tokens', function (done) {
var dropSpy = sinon.spy(Catbox.Policy.prototype, 'drop');
tokenStorage.invalidate('mytoken', function () {
expect(dropSpy.calledWith('mytoken')).to.be.true();
done();
});
});
});
});
| 25.908676 | 107 | 0.504759 |
d1e2d2d0a605da6aab8f7be2dfd40a7b0cecd2b0 | 11,156 | js | JavaScript | libs/tagText.js | GabrielFDuarte/DICOM-Explorer | 3afa2e8277ddde387c450e90f91f9ebc018d18f8 | [
"MIT"
] | 4 | 2020-08-17T05:56:28.000Z | 2020-10-07T11:08:31.000Z | libs/tagText.js | GabrielFDuarte/DICOM-Explorer | 3afa2e8277ddde387c450e90f91f9ebc018d18f8 | [
"MIT"
] | null | null | null | libs/tagText.js | GabrielFDuarte/DICOM-Explorer | 3afa2e8277ddde387c450e90f91f9ebc018d18f8 | [
"MIT"
] | 3 | 2020-10-09T19:00:56.000Z | 2021-08-05T15:20:33.000Z | var tagText = {
'x00020000':'Number of bytes following this File Meta Element (end of the Value field) up to and including the last File Meta Element of the Group 2 File Meta Information.',
'x00020001':'This is a two byte field where each bit identifies a version of this File Meta Information header. In version 1 the first byte value is 00H and the second value byte value is 01H.',
'x00020002':'Uniquely identifies the SOP Class associated with the Data Set.',
'x00020003':'Uniquely identifies the SOP Instance associated with the Data Set placed in the file and following the File Meta Information.',
'x00020010':'Uniquely identifies the Transfer Syntax used to encode the following Data Set. This Transfer Syntax does not apply to the File Meta Information.',
'x00020012':'Uniquely identifies the implementation that wrote this file and its content. It provides an unambiguous identification of the type of implementation that last wrote the file in the event of interchange problems.',
'x00020013':'Identifies a version for an Implementation Class UID (0002,0012) using up to 16 characters of the repertoire identified in Section 8.5 of DICOM Standard.',
'x00020016':'The DICOM Application Entity (AE) Title of the AE that wrote this file\'s content (or last updated it). If used, it allows the tracing of the source of errors in the event of media interchange problems.',
'x00080005':'Character Set that expands or replaces the Basic Graphic Set. Required if an expanded or replacement character set is used.',
'x00080008':'Image identification characteristics.',
'x00080016':'Uniquely identifies the SOP Class.',
'x00080018':'Uniquely identifies the SOP Instance.',
'x00080020':'Date the Study started.',
'x00080021':'Date the Series started.',
'x00080022':'The date the acquisition of data that resulted in this image started.',
'x00080023':'The date the image pixel data creation started. Required if image is part of a Series in which the images are temporally related. May be present otherwise.',
'x00080030':'Time the Study started.',
'x00080031':'Time the Series started.',
'x00080032':'The time the acquisition of data that resulted in this image started',
'x00080033':'The time the image pixel data creation started. Required if image is part of a Series in which the images are temporally related. May be present otherwise.',
'x00080050':'A RIS generated number that identifies the order for the Study.',
'x00080060':'Type of equipment that originally acquired the data used to create the images in this Series.',
'x00080070':'Manufacturer of the equipment that contributed to the composite instance.',
'x00080080':'Institution where the equipment that contributed to the composite instance is located.',
'x00080081':'Address of the institution where the equipment that contributed to the composite instance is located.',
'x00080090':'Patient\'s primary referring physician for this Visit',
'x00081010':'User defined name identifying the machine that contributed to the composite instance.',
'x00081030':'Institution-generated description or classification of the Study (component) performed.',
'x0008103E':'User provided description of the Series.',
'x00081070':'Name(s) of the operator(s) supporting the Series.',
'x00081090':'Manufacturer\'s model name of the equipment that contributed to the composite instance.',
'x00081140':'Other images significantly related to this image (e.g., post-localizer CT image or Mammographic biopsy or partial view images). One or more Items are permitted in this Sequence.',
'x00081150':'Uniquely identifies the referenced SOP Class.',
'x00081155':'Uniquely identifies the referenced SOP Instance.',
'x00082111':'A text description of how this image was derived.',
'x00089215':'A coded description of how this image was derived. One or more Items are permitted in this Sequence. More than one Item indicates that successive derivation steps have been applied.',
'x00080100':'The identifier of the Coded Entry. Shall be present if the code value length is 16 characters or less, and the code value is not a URN or URL.',
'x00080102':'The identifier of the coding scheme in which the Coded Entry is defined. Shall be present if Code Value (0008,0100) or Long Code Value (0008,0119) is present. May be present otherwise.',
'x00080104':'Text that conveys the meaning of the Coded Entry.',
'x00100010':'Patient\'s full name.',
'x00100020':'Primary identifier for the patient.',
'x00100030':'Date of birth of the named Patient.',
'x00100040':'Sex of the named Patient. Enumerated Values: M - male, F - female, O - other.',
'x00101010':'Age of the Patient.',
'x00180015':'Text description of the part of the body examined. See Annex L “Correspondence of Anatomic Region Codes and Body Part Examined Defined Terms” in PS3.16 at DICOM Standard for Defined Terms',
'x00180050':'Nominal reconstructed slice thickness, in mm.',
'x00180060':'Peak kilo voltage output of the X-Ray generator used.',
'x00181000':'Manufacturer\'s serial number of the equipment that contributed to the composite instance.',
'x00181020':'Manufacturer\'s designation of the software version of the equipment that contributed to the composite instance.',
'x00181030':'User-defined description of the conditions under which the Series was performed.',
'x00181110':'Distance in mm from source to detector center.',
'x00181111':'Distance in mm from source to the table, support or bucky side that is closest to the Imaging Subject, as measured along the central ray of the X-Ray beam.',
'x00181120':'Nominal angle of tilt in degrees of the scanning gantry. Not intended for mathematical computations.',
'x00181130':'The distance in mm of the top of the patient table to the center of rotation; below the center is positive.',
'x00181140':'Direction of rotation of the source when relevant, about nearest principal axis of equipment. Enumerated Values: CW - clockwise, CC - counter clockwise.',
'x00181160':'Label for the type of filter inserted into the x-ray beam.',
'x00181170':'Power in kW to the x-ray generator.',
'x00181190':'Size of the focal spot in mm. For devices with variable focal spot or multiple focal spots, small dimension followed by large dimension.',
'x00181200':'Date when the image acquisition device calibration was last changed in any way. Multiple entries may be used for additional calibrations at other times.',
'x00181201':'Time when the image acquisition device calibration was last changed in any way. Multiple entries may be used.',
'x00181210':'A label describing the convolution kernel or algorithm used to reconstruct the data.',
'x00185100':'Patient position descriptor relative to the equipment. Required for images where Patient Orientation Code Sequence (0054,0410) is not present and whose SOP Class is one of the following: CT ("1.2.840.10008.5.1.4.1.1.2") or MR ("1.2.840.10008.5.1.4.1.1.4") or Enhanced CT ("1.2.840.10008.5.1.4.1.1.2.1") or Enhanced MR Image ("1.2.840.10008.5.1.4.1.1.4.1") or Enhanced Color MR Image ("1.2.840.10008.5.1.4.1.1.4.3") or MR Spectroscopy ("1.2.840.10008.5.1.4.1.1.4.2") Storage SOP Classes. May be present for other SOP Classes if Patient Orientation Code Sequence (0054,0410) is not present.',
'x0020000D':'Unique identifier for the Study. Required if Type of Instances (0040,E020) is DICOM',
'x0020000E':'Unique identifier for the Series that is part of the Study identified in Study Instance UID (0020,000D), if present, and contains the referenced object instance(s). Required if Type of Instances (0040,E020) is DICOM',
'x00200010':'User or equipment generated Study identifier.',
'x00200011':'A number that identifies this Series.',
'x00200012':'A number identifying the single continuous gathering of data over a period of time that resulted in this image.',
'x00200013':'A number that identifies this Composite object instance.',
'x00200032':'The x, y, and z coordinates of the upper left hand corner (center of the first voxel transmitted) of the image, in mm.',
'x00200037':'The direction cosines of the first row and the first column with respect to the patient.',
'x00200052':'Uniquely identifies the Frame of Reference for a Series.',
'x00201040':'Part of the imaging target used as a reference.',
'x00204000':'User-defined comments about the image.',
'x00280002':'Number of samples (planes) in this image.',
'x00280004':'Specifies the intended interpretation of the pixel data.',
'x00280006':'Indicates whether the pixel data are encoded color-by-plane or color-by-pixel. Required if Samples per Pixel (0028,0002) has a value greater than 1.',
'x00280008':'Number of frames in a Multi-frame Image.',
'x00280010':'Number of rows in the image.',
'x00280011':'Number of columns in the image.',
'x00280030':'Physical distance in the patient between the center of each pixel, specified by a numeric pair - adjacent row spacing (delimiter) adjacent column spacing in mm.',
'x00280100':'Number of bits allocated for each pixel sample. Each sample shall have the same number of bits allocated. Bits Allocated (0028,0100) shall be either 1, or a multiple of 8.',
'x00280101':'Number of bits stored for each pixel sample. Each sample shall have the same number of bits stored.',
'x00280102':'Most significant bit for pixel sample data. Each sample shall have the same high bit. High Bit (0028,0102) shall be one less than Bits Stored (0028,0101).',
'x00280103':'Data representation of the pixel samples. Each sample shall have the same pixel representation. Enumerated Values: 0000H - unsigned integer ,0001H - 2\'s complement',
'x00281050':'Window Center for display. Required if VOI LUT Sequence (0028,3010) is not present. May be present otherwise.',
'x00281051':'Window Width for display. Required if Window Center (0028,1050) is present.',
'x00281052':'The value b in relationship between stored values (SV) and the output units specified in Rescale Type (0028,1054). Output units = m*SV + b. Required if Modality LUT Sequence (0028,3000) is not present. Shall not be present otherwise.',
'x00281053':'m in the equation specified by Rescale Intercept (0028,1052). Required if Rescale Intercept is present.',
'x00281054':'Specifies the output units of Rescale Slope (0028,1053) and Rescale Intercept (0028,1052). Required if Rescale Intercept is present.',
'x00281055':'Free form explanation of the meaning of the Window Center and Width. Multiple values correspond to multiple Window Center and Width values.',
'x00282110':'Specifies whether an Image has undergone lossy compression (at a point in its lifetime). Enumerated Values: 00 - Image has NOT been subjected to lossy compression. 01 - Image has been subjected to lossy compression. Once this value has been set to 01 it shall not be reset.'
}; | 119.956989 | 608 | 0.743994 |
d1e33b4abeb303f0a5dc317717e3b47f7a56b219 | 940 | js | JavaScript | src/mongo/db.js | Mrlhz/puppeteer | 4f67c582a800e7bff143c447bac21bdd971d58a2 | [
"MIT"
] | 3 | 2020-03-13T05:34:10.000Z | 2020-12-21T22:50:21.000Z | src/mongo/db.js | Mrlhz/puppeteer | 4f67c582a800e7bff143c447bac21bdd971d58a2 | [
"MIT"
] | null | null | null | src/mongo/db.js | Mrlhz/puppeteer | 4f67c582a800e7bff143c447bac21bdd971d58a2 | [
"MIT"
] | null | null | null | const mongoose = require('mongoose')
const movie = require('../models/movie')
const movieBrief = require('../models/movieBrief')
const bookBrief = require('../models/bookBrief')
const bookTags = require('../models/bookTags')
const tvBrief = require('../models/tvBrief')
const log = console.log
function connect(database) {
if (!database) throw new Error('database can\'t be null or undefined')
const connectDb = 'mongodb://localhost/' + database
mongoose.set('useFindAndModify', false) // https://mongoosejs.com/docs/deprecations.html
mongoose.connect(connectDb, {
useNewUrlParser: true,
useUnifiedTopology: true
}, () => log('mongodb connect success: ' + database))
// 让 mongoose 使用全局 Promise 库
mongoose.Promise = global.Promise
// 取得默认连接
const db = mongoose.connection
// 将连接与错误事件绑定(以获得连接错误的提示)
db.on('error', console.error.bind(console, 'MongoDB 连接错误:'))
return db
}
module.exports = {
connect
}
| 27.647059 | 90 | 0.707447 |
d1e34cd9b3b292773cf39768551ca5f5d9f1257c | 471 | js | JavaScript | js/custom.js | koderjoker/jiitodc.github.io | be0bb870e23fd1b74c47d8dd29978f4610b7c12b | [
"MIT"
] | null | null | null | js/custom.js | koderjoker/jiitodc.github.io | be0bb870e23fd1b74c47d8dd29978f4610b7c12b | [
"MIT"
] | null | null | null | js/custom.js | koderjoker/jiitodc.github.io | be0bb870e23fd1b74c47d8dd29978f4610b7c12b | [
"MIT"
] | null | null | null | const title = document.getElementById("head-text");
const typewriter = new Typewriter(title, {
loop: true,
});
typewriter
.typeString("JODC")
.pauseFor(2500)
.deleteAll()
.typeString("JIIT Open Dev Circle ")
.start();
const topNav = document.querySelector(".topnav");
topNav.addEventListener('click', function(event) {
if (topNav.className === "topnav") {
topNav.className += " responsive";
}
else {
topNav.className = "topnav";
}
});
| 19.625 | 51 | 0.656051 |
d1e37e0a6935d265f0445a78c573ed7c844e08ba | 1,328 | js | JavaScript | back/patches/004_lowerCaseName/index.js | mpech/mangatrack | 5ad0a4abdbb1b60960efb675a8cd1bc05ae04bfe | [
"WTFPL"
] | null | null | null | back/patches/004_lowerCaseName/index.js | mpech/mangatrack | 5ad0a4abdbb1b60960efb675a8cd1bc05ae04bfe | [
"WTFPL"
] | 9 | 2020-05-16T10:15:18.000Z | 2022-03-03T06:40:42.000Z | back/patches/004_lowerCaseName/index.js | mpech/mangatrack | 5ad0a4abdbb1b60960efb675a8cd1bc05ae04bfe | [
"WTFPL"
] | null | null | null | import MangaModel from '../../models/mangaModel.js'
import ChapterModel from '../../models/chapterModel.js'
export default async () => {
const res = await MangaModel.aggregate([
{
$project: {
minName: {
$toLower: '$nameId'
},
manga: '$$ROOT'
}
},
{
$group: {
_id: '$minName',
mangaIds: {
$push: '$manga._id'
},
manga: { $first: '$manga' }
}
},
{
$match: {
'mangaIds.1': { $exists: true }
}
}
])
for (const { _id, mangaIds, manga } of res) {
const chapters = await ChapterModel.find({ mangaId: { $in: mangaIds } }).lean()
// from->Map<num, chap>
const fromToChapters = {}
chapters.forEach(chap => {
fromToChapters[chap.from] = fromToChapters[chap.from] || new Map()
chap.chapters.forEach(c => {
fromToChapters[chap.from].set(c.num, c)
})
})
await Promise.all([
MangaModel.deleteMany({ _id: { $in: mangaIds } }),
ChapterModel.deleteMany({ mangaId: { $in: mangaIds } })
])
for (const from in fromToChapters) {
const chapters = [...fromToChapters[from].values()]
// canonicalize
manga.nameId = _id
manga.chapters = chapters
await MangaModel.upsertManga(manga, from)
}
}
}
| 24.145455 | 83 | 0.534639 |
d1e468151313b01a4a10b91f8192695d93453948 | 2,171 | js | JavaScript | admin/src/pages/Category/index.js | ismail-klc/mern-ecommerce | 3e7ef0a467526b350733d4d6b04224cf58c85327 | [
"MIT"
] | null | null | null | admin/src/pages/Category/index.js | ismail-klc/mern-ecommerce | 3e7ef0a467526b350733d4d6b04224cf58c85327 | [
"MIT"
] | null | null | null | admin/src/pages/Category/index.js | ismail-klc/mern-ecommerce | 3e7ef0a467526b350733d4d6b04224cf58c85327 | [
"MIT"
] | null | null | null | import { Box, Button, List, ListItem, ListItemIcon, ListSubheader, makeStyles } from '@material-ui/core';
import React,{useEffect} from 'react'
import Dashboard from '../../components/Layout/Layout'
import { useDispatch, useSelector } from 'react-redux';
import AddCategoryForm from './components/AddCategoryForm';
import CategoryItem from './components/CategoryItem';
const useStyles = makeStyles((theme) => ({
root: {
margin: 'auto',
width: '70%',
backgroundColor: theme.palette.background.paper,
},
nested: {
paddingLeft: theme.spacing(4),
},
}));
function Category() {
const classes = useStyles();
const [open, setOpen] = React.useState(true);
const [openAddModal, setOpenAddModal] = React.useState(false)
const category = useSelector(state => state.category)
useEffect(() => {
}, [category.categories])
return (
<Dashboard>
<Box marginBottom={3}>
<Button
style={{marginLeft: '15%'}}
onClick={() => setOpenAddModal(true)}
variant="contained"
color="primary" >
Add New Category
</Button>
<AddCategoryForm
open={openAddModal}
handleClose={() => setOpenAddModal(false)}
/>
</Box>
<List
component="nav"
aria-labelledby="nested-list-subheader"
subheader={
<ListSubheader component="div" id="nested-list-subheader">
Categories
</ListSubheader>
}
className={classes.root}
>
{category.categories.map((cat, index) => (
cat.parentId ? null :
<CategoryItem
key={index}
category={cat}
/>
))}
</List>
</Dashboard>
)
}
export default Category
| 31.926471 | 106 | 0.481806 |
d1e4c4cb20f2c8248d632c86fb46554ec853af60 | 2,527 | js | JavaScript | day02/02_lineIntersection/sketch.js | ajbajb/ARTTECH3135-spring2019 | ecce35823dbdb37ad6d1071a6e0c290d5d795b2e | [
"MIT"
] | 1 | 2019-01-24T05:03:27.000Z | 2019-01-24T05:03:27.000Z | day02/02_lineIntersection/sketch.js | ajbajb/ARTTECH3135-spring2019 | ecce35823dbdb37ad6d1071a6e0c290d5d795b2e | [
"MIT"
] | null | null | null | day02/02_lineIntersection/sketch.js | ajbajb/ARTTECH3135-spring2019 | ecce35823dbdb37ad6d1071a6e0c290d5d795b2e | [
"MIT"
] | 1 | 2019-04-11T18:26:18.000Z | 2019-04-11T18:26:18.000Z |
//line intersection
//'use strict';
function setup() {
createCanvas( 400, 400 );
}
function draw() {
background( 250, 250, 235 );
strokeWeight( 5 );
// dynamic mouse conrolled line
stroke( 0, 100, 255, 100 );
line( 0, 0, mouseX, mouseY );
// static line
// check if it intersects with out dynamic line
// if it does, color it red else green
let intersect = new p5.Vector();
let intersectionDetected = segmentIntersection( 0, 0, mouseX, mouseY, 100, 300, 200, 100, intersect );
if ( intersectionDetected ) {
stroke( 0, 150 );
ellipse( intersect.x, intersect.y, 5, 5 );
console.log( intersect.x );
stroke( 255, 50, 0, 100 );
} else {
stroke( 0, 255, 100, 100 );
}
line( 100, 300, 200, 100 );
}
// write up docs for this
/// \brief Determine the intersection between two lines.
/// \param lineAstartX, lineAstartY - Start points for first line.
/// \param lineAendX, lineAendY - End point for first line.
/// \param lineBstartX, lineBstartY - Starting points for second line.
/// \param lineBendX, lineBendY - End points for second line.
/// \param intersection - p5.vector or object reference in which to store the computed intersection point.
/// \returns True if the lines intersect.
function segmentIntersection( lineAstartX, lineAstartY, lineAendX, lineAendY,
lineBstartX, lineBstartY, lineBendX, lineBendY, intersection ) {
let diffLAx, diffLAy;
let diffLBx, diffLBy;
let compareA, compareB;
diffLAx = lineAendX - lineAstartX;
diffLAy = lineAendY - lineAstartY;
diffLBx = lineBendX - lineBstartX;
diffLBy = lineBendY - lineBstartY;
compareA = ( diffLAx * lineAstartY ) - ( diffLAy * lineAstartX );
compareB = ( diffLBx * lineBstartY ) - ( diffLBy * lineBstartX );
if (
(
( ( diffLAx * lineBstartY - diffLAy * lineBstartX ) < compareA ) ^
( ( diffLAx * lineBendY - diffLAy * lineBendX ) < compareA )
)
&&
(
( ( diffLBx * lineAstartY - diffLBy * lineAstartX ) < compareB ) ^
( ( diffLBx * lineAendY - diffLBy * lineAendX ) < compareB )
)
)
{
let lDetDivInv = 1 / ( ( diffLAx * diffLBy ) - ( diffLAy * diffLBx ) );
intersection.x = - ( ( diffLAx * compareB ) - ( compareA * diffLBx ) ) * lDetDivInv;
intersection.y = - ( ( diffLAy * compareB ) - ( compareA * diffLBy ) ) * lDetDivInv;
return true;
}
return false;
}
| 26.6 | 106 | 0.609418 |
d1e4eb87853971c92b79a03b1d784638435530f7 | 612 | js | JavaScript | src/store/categories.js | 401-advanced-javascript-AhmadMamdouh/storefront | f48c9953876113a789491bd393499adaccde316a | [
"MIT"
] | null | null | null | src/store/categories.js | 401-advanced-javascript-AhmadMamdouh/storefront | f48c9953876113a789491bd393499adaccde316a | [
"MIT"
] | null | null | null | src/store/categories.js | 401-advanced-javascript-AhmadMamdouh/storefront | f48c9953876113a789491bd393499adaccde316a | [
"MIT"
] | null | null | null | const initialState = {
categories: [
{ name: 'electronics', displayName: 'Elecronics' },
{ name: 'food', displayName: 'Food' },
{ name: 'clothing', displayName: 'Clothing' },
],
activeCategory: 'food',
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case 'change':
return { categories: state.categories, activeCategory: payload };
default:
return state;
}
};
export const changeActiveCategory = category => {
return {
type: 'change',
payload: category,
};
}; | 24.48 | 71 | 0.576797 |
d1e708ef3160231bc8d24fe5544decffcc9a2c83 | 1,008 | js | JavaScript | dist/skylark-threejs-ex/nodes/accessors/ResolutionNode.js | skylark-integration/skylark-threejs-ex | f73cac27980c3f1eb18f96a24f1984b14ddd9c9e | [
"MIT"
] | null | null | null | dist/skylark-threejs-ex/nodes/accessors/ResolutionNode.js | skylark-integration/skylark-threejs-ex | f73cac27980c3f1eb18f96a24f1984b14ddd9c9e | [
"MIT"
] | null | null | null | dist/skylark-threejs-ex/nodes/accessors/ResolutionNode.js | skylark-integration/skylark-threejs-ex | f73cac27980c3f1eb18f96a24f1984b14ddd9c9e | [
"MIT"
] | null | null | null | /**
* skylark-threejs-ex - A version of threejs extentions library that ported to running on skylarkjs
* @author Hudaokeji, Inc.
* @version v0.9.0
* @link https://github.com/skylark-integration/skylark-threejs-ex/
* @license MIT
*/
define(["skylark-threejs","../inputs/Vector2Node"],function(e,t){"use strict";function r(){t.call(this),this.size=new e.Vector2}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.prototype.nodeType="Resolution",r.prototype.updateFrame=function(e){if(e.renderer){e.renderer.getSize(this.size);var t=e.renderer.getPixelRatio();this.x=this.size.width*t,this.y=this.size.height*t}else console.warn("ResolutionNode need a renderer in NodeFrame")},r.prototype.copy=function(e){return t.prototype.copy.call(this,e),this.renderer=e.renderer,this},r.prototype.toJSON=function(e){var t=this.getJSONNode(e);return t||((t=this.createJSONNode(e)).renderer=this.renderer.uuid),t},r});
//# sourceMappingURL=../../sourcemaps/nodes/accessors/ResolutionNode.js.map
| 100.8 | 693 | 0.762897 |
d1e98971c2d406fdb4b80f9b328b5986c38257ff | 2,263 | js | JavaScript | src/core/display/cores/materialCore.js | tsherif/scenejs | 8866a02794a703057b0f354e7399eb23e0dff6c1 | [
"MIT"
] | 394 | 2015-01-02T02:15:44.000Z | 2021-12-07T10:30:41.000Z | src/core/display/cores/materialCore.js | kasunv/scenejs | fd99d6ccbdf9f8b64675eb0569cbf65738a4cc67 | [
"MIT"
] | 154 | 2015-01-02T14:08:07.000Z | 2018-01-16T14:16:29.000Z | src/core/display/cores/materialCore.js | kasunv/scenejs | fd99d6ccbdf9f8b64675eb0569cbf65738a4cc67 | [
"MIT"
] | 139 | 2015-01-22T05:58:25.000Z | 2022-03-31T19:23:56.000Z | SceneJS_CoreFactory.createCoreType("material", {
init : function(params) {
},
setBaseColor : function(color) {
var defaultBaseColor = defaultCore.baseColor;
this.core.baseColor = color ? [
color.r != undefined && color.r != null ? color.r : defaultBaseColor[0],
color.g != undefined && color.g != null ? color.g : defaultBaseColor[1],
color.b != undefined && color.b != null ? color.b : defaultBaseColor[2]
] : defaultCore.baseColor;
},
getBaseColor : function() {
return {
r: this.core.baseColor[0],
g: this.core.baseColor[1],
b: this.core.baseColor[2]
};
},
setSpecularColor : function(color) {
var defaultSpecularColor = defaultCore.specularColor;
this.core.specularColor = color ? [
color.r != undefined && color.r != null ? color.r : defaultSpecularColor[0],
color.g != undefined && color.g != null ? color.g : defaultSpecularColor[1],
color.b != undefined && color.b != null ? color.b : defaultSpecularColor[2]
] : defaultCore.specularColor;
},
getSpecularColor : function() {
return {
r: this.core.specularColor[0],
g: this.core.specularColor[1],
b: this.core.specularColor[2]
};
},
setSpecular : function(specular) {
this.core.specular = (specular != undefined && specular != null) ? specular : defaultCore.specular;
},
getSpecular : function() {
return this.core.specular;
},
setShine : function(shine) {
this.core.shine = (shine != undefined && shine != null) ? shine : defaultCore.shine;
},
getShine : function() {
return this.core.shine;
},
setEmit : function(emit) {
this.core.emit = (emit != undefined && emit != null) ? emit : defaultCore.emit;
},
getEmit : function() {
return this.core.emit;
},
setAlpha : function(alpha) {
this.core.alpha = (alpha != undefined && alpha != null) ? alpha : defaultCore.alpha;
this._engine.display.imageDirty = true;
return this;
},
getAlpha : function() {
return this.core.alpha;
}
}); | 29.776316 | 107 | 0.56783 |
d1e99cd30cd0121436a9195488d8c64fb795b09b | 2,206 | js | JavaScript | examples/terrain/texture_worker_pool.js | rogerscg/era-engine | d812516dca5fa8fa76f9cc1fdb385c719cf2f475 | [
"MIT"
] | 68 | 2020-01-01T23:53:22.000Z | 2021-12-30T15:51:28.000Z | examples/terrain/texture_worker_pool.js | davchezt/era-engine | d812516dca5fa8fa76f9cc1fdb385c719cf2f475 | [
"MIT"
] | 8 | 2020-01-20T17:41:15.000Z | 2021-02-04T16:20:05.000Z | examples/terrain/texture_worker_pool.js | davchezt/era-engine | d812516dca5fa8fa76f9cc1fdb385c719cf2f475 | [
"MIT"
] | 5 | 2020-01-06T15:23:43.000Z | 2021-09-25T17:00:47.000Z | /**
* @author rogerscg / https://github.com/rogerscg
*/
import { WorkerPool } from '../../build/era';
import * as Comlink from 'comlink';
/**
* Controls pre-warmed texture workers and their usage by tiles.
*/
class TextureWorkerPool {
constructor() {
this.capacity = 20;
this.workers = new Set();
// Set of available workers.
this.availableWorkers = [];
// A queue of resolvers.
this.queue = [];
// A set of reservations from the core worker pool.
this.reservations = new Set();
}
/**
* Loads `capacity` number of workers.
*/
async prewarm() {
for (let i = 0; i < this.capacity; i++) {
const reservation = await WorkerPool.get().getWorkerReservation();
this.reservations.add(reservation);
const worker = new Worker('./texture_worker.js', {
type: 'module',
});
const TextureGenerator = Comlink.wrap(worker);
this.workers.add(worker);
this.availableWorkers.push(TextureGenerator);
}
}
/**
* Destroys the pool.
*/
drain() {
this.workers.forEach((worker) => worker.terminate());
this.reservations.forEach((uuid) => WorkerPool.get().releaseWorker(uuid));
this.availableWorkers = [];
this.queue = [];
}
/**
* Checks if there is an available worker.
* @returns {boolean}
*/
hasAvailability() {
return this.availableWorkers.length > 0;
}
/**
* Waits for an open worker slot. Returns a worker when available.
* @returns {Worker}
* @async
*/
async getWorker() {
if (this.hasAvailability()) {
return this.availableWorkers.shift();
}
await this.waitForOpening_();
return this.availableWorkers.shift();
}
/**
* Adds a reservation to the queue, whose promise resolves when an opening is
* available.
* @private
* @async
*/
async waitForOpening_() {
return new Promise((resolve) => this.queue.push(resolve));
}
/**
* Releases a worker back into the pool.
* @param {Worker} worker
*/
releaseWorker(worker) {
this.availableWorkers.push(worker);
const resolver = this.queue.shift();
if (resolver) {
resolver();
}
}
}
export default new TextureWorkerPool();
| 23.72043 | 79 | 0.621487 |
d1ea3874c4577d32c8b49295fa626ad45a93c7ed | 1,122 | js | JavaScript | src/routes/resources/store.js | saejs/sae-framework | b8fdcef0c5acd96084bbbe98578211ae1790792d | [
"MIT"
] | null | null | null | src/routes/resources/store.js | saejs/sae-framework | b8fdcef0c5acd96084bbbe98578211ae1790792d | [
"MIT"
] | null | null | null | src/routes/resources/store.js | saejs/sae-framework | b8fdcef0c5acd96084bbbe98578211ae1790792d | [
"MIT"
] | null | null | null | const arr = require("rhinojs/support/arr");
module.exports = (app, resource, middlewares) => {
app.post(resource.uri, async (req, res) => {
var t = await resource.__transaction();
try {
var json = req.body;
var obj = new resource.model();
// Aplicar parent
var parent = resource.getParentId(req);
if ((parent) && (parent.value)) {
obj[parent.attr] = parent.value;
}
// Aplicar atributos
arr.each(json, (key, value) => {
obj[key] = value;
});
// Verificar se foi implementado uma macro de controller (before store)
await resource.macro('creating', [req, res, resource, obj]);
await obj.save();
// Verificar se foi implementado uma macro de controller (after store)
await resource.macro('created', [req, res, resource, obj]);
await t.commit();
res.json(obj);
} catch (err) {
await t.rollback();
throw err;
}
}, middlewares);
}
| 28.769231 | 83 | 0.508913 |
d1ead5376cf3c7c531bf49092485d29eb5b40034 | 773 | js | JavaScript | src/EmailPage/__tests__/EmailPage.test.js | kiwicom/smart-faq | 2131be6290020a11dc6ad236eb82c5bde75945d8 | [
"MIT"
] | 12 | 2018-03-06T10:50:20.000Z | 2018-08-11T18:04:27.000Z | src/EmailPage/__tests__/EmailPage.test.js | jalbertsr/smart-faq | 2131be6290020a11dc6ad236eb82c5bde75945d8 | [
"MIT"
] | 554 | 2018-03-06T10:41:32.000Z | 2018-10-03T18:49:49.000Z | src/EmailPage/__tests__/EmailPage.test.js | jalbertsr/smart-faq | 2131be6290020a11dc6ad236eb82c5bde75945d8 | [
"MIT"
] | 7 | 2018-09-26T08:30:25.000Z | 2021-02-16T07:45:49.000Z | // @flow
import * as React from 'react';
import { render } from 'enzyme';
import { CheckRecoveryLink, CheckMagicLink } from '../index';
describe('EmailPage', () => {
const props = {
text: 'link',
location: {
state: {
email: 'kiwi@email.com',
},
},
};
it('should render recovery link', () => {
const wrapper = render(<CheckRecoveryLink {...props} />);
expect(wrapper.find('.text > span').text()).toEqual(
'smartfaq.email_page.recovery_link_subtitle kiwi@email.com.',
);
});
it('should render magic link', () => {
const wrapper = render(<CheckMagicLink {...props} />);
expect(wrapper.find('.text > span').text()).toEqual(
'smartfaq.email_page.magic_link_subtitle kiwi@email.com.',
);
});
});
| 25.766667 | 67 | 0.592497 |
d1eb25a1d469a72fc655d57f17e3fcdcd461f7ce | 6,375 | js | JavaScript | HadoopConnect/appserver/static/job_list.js | mshensg/hadoop-connect-for-splunk | 14afd1eb83753d6e1f95dcae49a27e3002070bbe | [
"Apache-2.0"
] | 1 | 2021-11-09T07:33:42.000Z | 2021-11-09T07:33:42.000Z | HadoopConnect/appserver/static/job_list.js | mshensg/hadoop-connect-for-splunk | 14afd1eb83753d6e1f95dcae49a27e3002070bbe | [
"Apache-2.0"
] | 2 | 2021-09-02T23:48:40.000Z | 2021-11-09T07:35:27.000Z | HadoopConnect/appserver/static/job_list.js | mshensg/hadoop-connect-for-splunk | 14afd1eb83753d6e1f95dcae49a27e3002070bbe | [
"Apache-2.0"
] | 2 | 2021-03-15T20:34:58.000Z | 2022-03-27T09:49:26.000Z |
var curPage = 0;
var pager = $(".REDJobs .Paginator");
var itemsPerPage = parseInt(pager.data('count'));
var pages;
function updatePagerCount(from, to, total) {
if(total) pager.find('span.count').html(['Showing <span>', from, '-', to, '</span> of ', total, total !== 1 ? ' results' : ' result'].join(''));
else pager.find('span.count').html('');
}
function paginateJobs() {
var items = $('.REDJobs .splTable tbody tr');
var from = curPage * itemsPerPage,
to = Math.min(curPage * itemsPerPage + itemsPerPage, items.length),
total = items.length;
updatePagerCount(from + 1, to, total);
pager.find('li').not('.previous,.next').remove();
pages = Math.ceil(items.length / itemsPerPage);
if (pages && curPage >= pages) {
curPage = 0;
paginateJobs();
return;
}
if (pages > 1) {
for (var i = pages; i > 0; i--) {
var a = $('<a></a>').text(String(i)).data('page', i - 1).attr('href', 'page-' + i);
var li = $('<li></li>').addClass('page').append(a);
if (i - 1 === curPage) {
a.addClass('active');
li.addClass('active');
}
li.insertAfter(pager.find('ul li.previous'));
}
}
pager.find('li.previous>a')[ total === 0 || curPage === 0 ? 'addClass' : 'removeClass' ]('disabled');
pager.find('li.next>a')[ total === 0 || curPage >= pages - 1 ? 'addClass' : 'removeClass' ]('disabled');
items.each(function (i) {
$(this)[ i >= from && i < to ? 'show' : 'hide']();
});
}
$('.REDJobs .Paginator a').live('click', function (e) {
e.preventDefault();
var a = $(this);
if (a.is('.disabled,.active')) {
return;
}
if (a.is('.next>a')) {
curPage = Math.min(curPage + 1, pages - 1);
} else if (a.is('.previous>a')) {
curPage = Math.max(0, curPage - 1);
} else {
var p = parseInt(a.data('page'));
if (p !== void(0)) {
curPage = p;
}
}
paginateJobs();
reloadJobs();
});
function showErrorMessage(msg) {
var el = $('<p class="error"></p>');
el.text(msg);
$('.REDJobs .messages').prepend(el);
setTimeout(function () {
el.remove();
}, 10000);
}
function reloadJobs() {
$('.REDJobs .splTable tbody').load(Splunk.util.make_url('/custom/HadoopConnect/exportjobs/list') + '?_=' + new Date().getTime(), paginateJobs);
}
$('.REDJobs a.action').live('click', function (e) {
e.preventDefault();
if ($(this).is('.confirm')) {
if (!confirm($(this).data('confirm-text'))) {
return;
}
}
var el = $(this);
el.addClass('disabled');
$.ajax({
url: $(this).attr('href'),
type: 'POST',
data: {
id: $(this).data('id')
},
dataType: 'json',
success: function (data) {
if (data && data.success) {
reloadJobs();
} else {
el.removeClass('disabled');
showErrorMessage(data.error || _('ERROR'))
}
}
});
});
$('.REDJobs a.edit').live('click', function(e){
e.preventDefault();
var el = $('<div></div>').addClass('red-edit-popup').appendTo(document.body);
$('<h2></h2>').text('Edit Scheduled Export').appendTo(el);
var content = $('<div></div>').addClass('content').appendTo(el);
content.load($(this).attr('href'), function() {
applyContextHelp(content);
$('.datetime', content).bind('change', function(evt) {
$('.starttime', content).val($(this).datepicker('getDate').valueOf() / 1000 );
});
var dateFormat = $.datepicker._defaults['dateFormat'];
var defaultDate = new Date();
$(".datetime", content).datepicker({
currentText: '',
defaultDate: defaultDate,
prevText: '',
nextText: ''
});
var curDv = $('.starttime', content).val();
if(curDv) {
$(".datetime", content).datepicker('setDate', new Date(parseInt(curDv)*1000));
}
});
var btn = $('<div></div>').addClass('ButtonRow').appendTo(el);
var cancelButton = $('<a></a>').addClass('splButton-secondary');
cancelButton.append($('<span></span>').text('Cancel')).appendTo(btn);
var submitButton = $('<a></a>').addClass('splButton-primary');
submitButton.append($('<span></span>').text('Save')).appendTo(btn);
var editPopup = new Splunk.Popup(el, {
cloneFlag: false,
pclass: 'configPopup'
});
cancelButton.click(editPopup.destroyPopup.bind(editPopup));
function submitExportJob(e) {
if(e) e.preventDefault();
var form = el.find('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function() {
editPopup.destroyPopup();
reloadJobs();
},
error: function(xhr) {
var msgs = ['Unknown error occurred'];
if(xhr.status === 500) {
try {
var json = JSON.parse(xhr.responseText);
if(json && json.errors.length) {
msgs = json.errors;
}
} catch(e){}
}
content.find('p.error').remove();
$.each(msgs, function(i, msg){
$('<p class="error"></p>').text(msg).prependTo(content);
});
}
});
}
submitButton.click(submitExportJob);
$('form', el).submit(submitExportJob);
});
paginateJobs();
| 35.416667 | 152 | 0.451137 |
d1eba2b4e1c32fa5d3e361d8873df1d2cdff9109 | 228 | js | JavaScript | src/pages/index.js | TheBlankness/unifi-reseller-1 | 47afbb938f58baeba411ccd06375114790244d21 | [
"MIT"
] | null | null | null | src/pages/index.js | TheBlankness/unifi-reseller-1 | 47afbb938f58baeba411ccd06375114790244d21 | [
"MIT"
] | 2 | 2021-05-11T04:00:38.000Z | 2022-02-27T00:04:09.000Z | src/pages/index.js | TheBlankness/unifi-reseller-1 | 47afbb938f58baeba411ccd06375114790244d21 | [
"MIT"
] | null | null | null | import React from "react"
import { Link } from "gatsby"
import BackgroundSection from "../components/BackgroundSection"
import App from "../components/App"
const IndexPage = () => (
<App/>
)
export default IndexPage
| 12.666667 | 63 | 0.697368 |
d1ebf2c2fda9d6b81007d8e7f2e7c5e440c1cb32 | 991 | js | JavaScript | webapp/views/App/views/Users/UsersAccessRequest/UsersAccessRequest.js | openforis/arena | d4918e7e218bac36a038511f9236b68ce7bdd1ba | [
"MIT"
] | 10 | 2019-06-03T19:30:57.000Z | 2022-03-19T03:30:18.000Z | webapp/views/App/views/Users/UsersAccessRequest/UsersAccessRequest.js | openforis/arena | d4918e7e218bac36a038511f9236b68ce7bdd1ba | [
"MIT"
] | 650 | 2018-07-11T18:23:34.000Z | 2022-03-31T09:09:51.000Z | webapp/views/App/views/Users/UsersAccessRequest/UsersAccessRequest.js | openforis/arena | d4918e7e218bac36a038511f9236b68ce7bdd1ba | [
"MIT"
] | 5 | 2020-01-06T12:47:35.000Z | 2021-11-14T01:08:58.000Z | import './UsersAccessRequest.scss'
import React, { useCallback, useState } from 'react'
import * as UserAccessRequest from '@core/user/userAccessRequest'
import Table from '@webapp/components/Table/Table'
import ColumnHeaders from './ColumnHeaders'
import Row from './Row'
import {TableHeaderLeft} from './TableHeaderLeft'
export const UsersAccessRequest = () => {
const [requestedAt, setRequestedAt] = useState(Date.now())
const onRowChange = useCallback(() => {
// reload table content
setRequestedAt(Date.now())
}, [])
return (
<Table
module="users-access-request"
moduleApiUri="/api/users/users-access-request"
restParams={{ requestedAt }}
className="users-access-request-list"
gridTemplateColumns={`20rem repeat(${UserAccessRequest.editableFields.length}, 1fr) 5rem 5rem`}
headerLeftComponent={TableHeaderLeft}
rowHeaderComponent={ColumnHeaders}
rowComponent={Row}
rowProps={{ onRowChange }}
/>
)
}
| 28.314286 | 101 | 0.702321 |
d1eda0497faf099c16234353b397eee8a8c5a941 | 246 | js | JavaScript | seeds/WebKit/microbenchmarks/setter.js | gustavopinto/entente | 19b65d8cafd77c198c9c441f4f5e01503360309b | [
"BSD-2-Clause"
] | 16 | 2020-03-23T12:53:10.000Z | 2021-10-11T02:31:50.000Z | seeds/WebKit/microbenchmarks/setter.js | gustavopinto/entente | 19b65d8cafd77c198c9c441f4f5e01503360309b | [
"BSD-2-Clause"
] | 14 | 2018-04-09T20:16:00.000Z | 2019-06-11T12:31:10.000Z | seeds/WebKit/microbenchmarks/setter.js | gustavopinto/entente | 19b65d8cafd77c198c9c441f4f5e01503360309b | [
"BSD-2-Clause"
] | 12 | 2018-04-06T00:52:24.000Z | 2018-07-10T19:44:16.000Z | (function() {
var o = {_f:42};
o.__defineSetter__("f", function(value) { this._f = value; });
var n = 2000000;
for (var i = 0; i < n; ++i)
o.f = i;
if (o._f != n - 1)
throw "Error: bad result: " + o._f;
})();
| 22.363636 | 66 | 0.455285 |
d1edeed025b3b14b290e84031406dc7854c7fac2 | 1,279 | js | JavaScript | Kwikker/App/Routes/ProfileStackNavigator.js | aymanElakwah/kwikker-react-native | 64ef47de06fc2c8e2f285a688ad55ffb17504db3 | [
"Apache-2.0"
] | null | null | null | Kwikker/App/Routes/ProfileStackNavigator.js | aymanElakwah/kwikker-react-native | 64ef47de06fc2c8e2f285a688ad55ffb17504db3 | [
"Apache-2.0"
] | 3 | 2020-09-06T07:58:42.000Z | 2022-02-12T16:07:09.000Z | Kwikker/App/Routes/ProfileStackNavigator.js | aymanElakwah/kwikker-react-native | 64ef47de06fc2c8e2f285a688ad55ffb17504db3 | [
"Apache-2.0"
] | 3 | 2019-08-29T15:13:57.000Z | 2020-06-11T21:37:01.000Z | import React, { Component } from 'react';
import { createStackNavigator, CreateAppContainer } from 'react-navigation';
import Profile from '../Screens/Profile/Profile';
import FollowerList from '../Screens/FollowerList/FollowersList';
import FollowingList from '../Screens/FollowingList/FollowingList';
import EditProfileNavigator from './EditProfileNavigation';
import KweekExtendedView from '../Screens/KweekExtendedView/KweekExtendedView';
import CreateTweet from '../Screens/CreateTweet/CreateTweet';
import ConversationScreen from '../Screens/ConversationScreen/ConversationScreen';
const ProfileStackNavigator = createStackNavigator({
Profile: { screen: Profile,
navigationOptions: {
header: null,
}, },
FollowerList: { screen: FollowerList,
navigationOptions: {
header: null,
}, },
FollowingList: { screen: FollowingList,
navigationOptions: {
header: null,
}, },
EditProfileNavigator: { screen: EditProfileNavigator,
navigationOptions: {
header: null,
}, },
KweekExtendedView: {
screen: KweekExtendedView,
navigationOptions: {
title: 'Kweek',
}
},
CreateTweet: { screen: CreateTweet },
ConversationScreen: { screen: ConversationScreen },
});
export default ProfileStackNavigator; | 32.794872 | 82 | 0.729476 |
d1ee0b0308bc88dad727baf28126aa2f2d9c91a6 | 216 | js | JavaScript | Es6/Set&Map/mapBaseUse.js | xszlq/foundation | d8d2860b8c95d95b81fb8c68078ace8591ffd8e4 | [
"MIT"
] | null | null | null | Es6/Set&Map/mapBaseUse.js | xszlq/foundation | d8d2860b8c95d95b81fb8c68078ace8591ffd8e4 | [
"MIT"
] | null | null | null | Es6/Set&Map/mapBaseUse.js | xszlq/foundation | d8d2860b8c95d95b81fb8c68078ace8591ffd8e4 | [
"MIT"
] | 1 | 2018-08-02T06:18:06.000Z | 2018-08-02T06:18:06.000Z | const o1 = {},
o2 = {};
const map1 = new Map();
map1.set(o1, "o1");
map1.set(o2, "o2");
console.log(map1.get(o1));
/*
构造函数
*/
const map2 = new Map([[o1, "ao1"], [o2, "ao2"]]);
console.log(map2.get(o2)); | 13.5 | 49 | 0.523148 |
d1ee5c70219a29acacb9ba07bf0e3c81af0f99a0 | 860 | js | JavaScript | index.js | adelonzeta/email-scripts | 31460504548e8fae31bde59c0c12d34ec85d4e76 | [
"0BSD"
] | null | null | null | index.js | adelonzeta/email-scripts | 31460504548e8fae31bde59c0c12d34ec85d4e76 | [
"0BSD"
] | null | null | null | index.js | adelonzeta/email-scripts | 31460504548e8fae31bde59c0c12d34ec85d4e76 | [
"0BSD"
] | null | null | null | #!/usr/bin/env node
const { series, parallel } = require('gulp')
const Panini = require('./config/Panini')
const Sass = require('./config/Sass')
const Prepare = require('./config/Prepare')
const Serve = require('./config/Serve')
const Watch = require('./config/Watch')
const Purge = require('./config/Purge')
const Inliner = require('./config/Inliner')
const Clean = require('./config/Clean')
const Assets = require('./config/Assets')
const Publish = require('./config/Publish')
const Send = require('./config/Send')
const compile = series(Prepare, parallel(Panini, Sass))
const serve = series(compile, Serve, Watch)
const build = series(compile, Purge, Inliner, Clean, Assets)
const deploy = series(build, Publish)
switch (process.argv.slice(2)[0]) {
case 'build':
build.call()
break;
default:
serve.call()
break;
} | 30.714286 | 62 | 0.676744 |
d1eeb09cbb525fa63c533e0fb776fa4d7a756cad | 7,309 | js | JavaScript | src/passport.js | rockyromano/doorsync | 1382da18b12554d2e0aa51c490a2ccb5cb981a0a | [
"MIT"
] | null | null | null | src/passport.js | rockyromano/doorsync | 1382da18b12554d2e0aa51c490a2ccb5cb981a0a | [
"MIT"
] | null | null | null | src/passport.js | rockyromano/doorsync | 1382da18b12554d2e0aa51c490a2ccb5cb981a0a | [
"MIT"
] | null | null | null | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/**
* Passport.js reference implementation.
* The database schema used in this sample is available at
* https://github.com/membership/membership.db/tree/master/postgres
*/
import passport from 'passport';
import { Strategy as FacebookStrategy } from 'passport-facebook';
import { Strategy as HubSpotStrategy } from 'passport-hubspot-oauth2.0';
import { Strategy as TokenStrategy } from './security/strategy';
//import { Strategy as CookieStrategy } from 'passport-cookie';
import { User, UserLogin, UserClaim, UserProfile } from './data/models';
import config from './config';
import jwt from 'jsonwebtoken';
/*
*/
const hubspotAuth = {
url: 'https://app.hubspot.com/oauth/authorize/',
clientId: 'c2011ac8-12fe-4d52-8cde-1283087babcf',
clientSecret: '6bf12e11-e5cb-45ee-a5ba-81534e6a0bef',
redirectUri: 'https://2f1ad374.ngrok.io/login/hubspot/return',
scope: ['contacts'],
responseType: 'code',
accessType: 'offline',
};
passport.use(
new HubSpotStrategy(
{
clientID: hubspotAuth.clientId,
clientSecret: hubspotAuth.clientSecret,
callbackURL: hubspotAuth.redirectUri,
scope: hubspotAuth.scope,
passReqToCallback: true
},
(req, accessToken, refreshToken, profile, done) => {
//ISSUE: This is never called
console.log('&&&&&&&&&&&&&&&&&');
console.log('&&&&&&&&&&&&&&&&&');
console.log('&&&&&&&&&&&&&&&&&');
console.log('&&&&&&&&&&&&&&&&&');
console.log('&&&&&&&&&&&&&&&&&');
console.log('&&&&&&&&&&&&&&&&&');
console.log('req.query.code: ', req.query.code);
// Verify callback.
done(null, { accessToken, refreshToken });
},
),
);
passport.use(
new TokenStrategy(function authenticate(req, token, done) {
console.log('@@@@@@@@@@@@@@@@@@@ jwt: ', jwt);
console.log('@@@@@@@@@@@@@@@@@@@ req.cookies.access_token:', req.cookies.access_token);
console.log('@@@@@@@@@@@@@@@@@@@ config.auth.jwt.secret:', config.auth.jwt.secret);
jwt.verify(req.cookies.access_token, config.auth.jwt.secret, (err, decoded) => {
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!! req: ' + req);
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!');
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!! decoded: ' + decoded.access_code);
//TODO: Would like this to not be here
req.headers.authorization = 'Bearer ' + decoded.access_code;
done(null, { code: decoded.access_code });
});
/*req.getInstance('AuthService').authorize(token)
.then(userInfo =>
userInfo ?
req.getInstance('UserRepository').retrieveById(userInfo.userId)
.then(([user]) => ({user, ...userInfo}))
:
null
)
.then(({user, roles, profileId, companyId, statusGroups, contactStatusGroups, companyStatusList}) => !user ?
logInvalid(done) :
done(null, {
..._.omit(user, ['password']),
roles,
profileId,
companyId,
statusGroups,
contactStatusGroups,
companyStatusList
}, {}))
.catch(logError(done));*/
}.bind(this))
);
/**
* Sign in with Facebook.
*/
passport.use(
new FacebookStrategy(
{
clientID: config.auth.facebook.id,
clientSecret: config.auth.facebook.secret,
callbackURL: '/login/facebook/return',
profileFields: [
'displayName',
'name',
'email',
'link',
'locale',
'timezone',
],
passReqToCallback: true,
},
(req, accessToken, refreshToken, profile, done) => {
/* eslint-disable no-underscore-dangle */
const loginName = 'facebook';
const claimType = 'urn:facebook:access_token';
const fooBar = async () => {
if (req.user) {
const userLogin = await UserLogin.findOne({
attributes: ['name', 'key'],
where: { name: loginName, key: profile.id },
});
if (userLogin) {
// There is already a Facebook account that belongs to you.
// Sign in with that account or delete it, then link it with your current account.
done();
} else {
const user = await User.create(
{
id: req.user.id,
email: profile._json.email,
logins: [{ name: loginName, key: profile.id }],
claims: [{ type: claimType, value: profile.id }],
profile: {
displayName: profile.displayName,
gender: profile._json.gender,
picture: `https://graph.facebook.com/${
profile.id
}/picture?type=large`,
},
},
{
include: [
{ model: UserLogin, as: 'logins' },
{ model: UserClaim, as: 'claims' },
{ model: UserProfile, as: 'profile' },
],
},
);
done(null, {
id: user.id,
email: user.email,
});
}
} else {
const users = await User.findAll({
attributes: ['id', 'email'],
where: { '$logins.name$': loginName, '$logins.key$': profile.id },
include: [
{
attributes: ['name', 'key'],
model: UserLogin,
as: 'logins',
required: true,
},
],
});
if (users.length) {
const user = users[0].get({ plain: true });
done(null, user);
} else {
let user = await User.findOne({
where: { email: profile._json.email },
});
if (user) {
// There is already an account using this email address. Sign in to
// that account and link it with Facebook manually from Account Settings.
done(null);
} else {
user = await User.create(
{
email: profile._json.email,
emailConfirmed: true,
logins: [{ name: loginName, key: profile.id }],
claims: [{ type: claimType, value: accessToken }],
profile: {
displayName: profile.displayName,
gender: profile._json.gender,
picture: `https://graph.facebook.com/${
profile.id
}/picture?type=large`,
},
},
{
include: [
{ model: UserLogin, as: 'logins' },
{ model: UserClaim, as: 'claims' },
{ model: UserProfile, as: 'profile' },
],
},
);
done(null, {
id: user.id,
email: user.email,
});
}
}
}
};
fooBar().catch(done);
},
),
);
export default passport;
| 32.629464 | 114 | 0.504036 |
d1eefec9d0caa8d1220189dfc7bda2d1008ac3c1 | 10,258 | js | JavaScript | dist/src/twp.yaml.js | livingyang/tiny-websocket-protocol | 27eb6dfdcd79ecdbde897c2875a93c95a7bda459 | [
"MIT"
] | null | null | null | dist/src/twp.yaml.js | livingyang/tiny-websocket-protocol | 27eb6dfdcd79ecdbde897c2875a93c95a7bda459 | [
"MIT"
] | null | null | null | dist/src/twp.yaml.js | livingyang/tiny-websocket-protocol | 27eb6dfdcd79ecdbde897c2875a93c95a7bda459 | [
"MIT"
] | null | null | null | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Message = (function () {
function Message() {
}
Message.prototype.getId = function () {
return (this.buffer != null && this.buffer.length > 0) ? this.buffer[0] : -1;
};
return Message;
}());
exports.Message = Message;
// ------------ Message Generator
exports.MessageMap = {};
function GenerateMessage(buffer) {
if (buffer != null && exports.MessageMap[buffer[0]] != null) {
var message = new exports.MessageMap[buffer[0]];
if (message.buffer.length === buffer.length) {
message.buffer = buffer;
return message;
}
}
return null;
}
exports.GenerateMessage = GenerateMessage;
var WebSocketMessageHandle = (function () {
function WebSocketMessageHandle() {
this.eventInvokerMap = {};
}
WebSocketMessageHandle.prototype.emit = function (message) {
if (message != null) {
for (var _i = 0, _a = this.getInvokerList(message.getId()); _i < _a.length; _i++) {
var invoker = _a[_i];
invoker.handler.call(invoker.target, message);
}
}
};
WebSocketMessageHandle.prototype.getInvokerList = function (event) {
return this.eventInvokerMap[event] || [];
};
WebSocketMessageHandle.prototype.on = function (event, target, handler) {
if (handler === void 0) { handler = target[event]; }
if (handler == null) {
throw "Client.on event: " + event + ", handle is null";
}
if (this.eventInvokerMap[event] == null) {
this.eventInvokerMap[event] = [];
}
if (target != null) {
this.eventInvokerMap[event].push({ target: target, handler: handler });
}
};
WebSocketMessageHandle.prototype.off = function (event, target, handler) {
if (handler === void 0) { handler = target[event]; }
if (this.eventInvokerMap[event] != null) {
this.eventInvokerMap[event] = this.eventInvokerMap[event].filter(function (v, i, a) {
return (target !== v.target || handler !== v.handler);
});
}
};
return WebSocketMessageHandle;
}());
exports.WebSocketMessageHandle = WebSocketMessageHandle;
// ------------- WebSocket Message
(function (MessageId) {
MessageId[MessageId["LoginRsp"] = 0] = "LoginRsp";
MessageId[MessageId["FrameNotice"] = 1] = "FrameNotice";
MessageId[MessageId["UserDataNotice"] = 2] = "UserDataNotice";
MessageId[MessageId["MatchingSuccessRsp"] = 3] = "MatchingSuccessRsp";
MessageId[MessageId["GetWalletReq"] = 4] = "GetWalletReq";
MessageId[MessageId["TestObjectReq"] = 5] = "TestObjectReq";
})(exports.MessageId || (exports.MessageId = {}));
var MessageId = exports.MessageId;
var TypedWebSocketMessageHandle = (function (_super) {
__extends(TypedWebSocketMessageHandle, _super);
function TypedWebSocketMessageHandle() {
_super.apply(this, arguments);
}
TypedWebSocketMessageHandle.prototype.onLoginRsp = function (target, handle) {
this.on(MessageId.LoginRsp, target, handle);
};
TypedWebSocketMessageHandle.prototype.offLoginRsp = function (target, handle) {
this.off(MessageId.LoginRsp, target, handle);
};
TypedWebSocketMessageHandle.prototype.onFrameNotice = function (target, handle) {
this.on(MessageId.FrameNotice, target, handle);
};
TypedWebSocketMessageHandle.prototype.offFrameNotice = function (target, handle) {
this.off(MessageId.FrameNotice, target, handle);
};
TypedWebSocketMessageHandle.prototype.onUserDataNotice = function (target, handle) {
this.on(MessageId.UserDataNotice, target, handle);
};
TypedWebSocketMessageHandle.prototype.offUserDataNotice = function (target, handle) {
this.off(MessageId.UserDataNotice, target, handle);
};
TypedWebSocketMessageHandle.prototype.onMatchingSuccessRsp = function (target, handle) {
this.on(MessageId.MatchingSuccessRsp, target, handle);
};
TypedWebSocketMessageHandle.prototype.offMatchingSuccessRsp = function (target, handle) {
this.off(MessageId.MatchingSuccessRsp, target, handle);
};
TypedWebSocketMessageHandle.prototype.onGetWalletReq = function (target, handle) {
this.on(MessageId.GetWalletReq, target, handle);
};
TypedWebSocketMessageHandle.prototype.offGetWalletReq = function (target, handle) {
this.off(MessageId.GetWalletReq, target, handle);
};
TypedWebSocketMessageHandle.prototype.onTestObjectReq = function (target, handle) {
this.on(MessageId.TestObjectReq, target, handle);
};
TypedWebSocketMessageHandle.prototype.offTestObjectReq = function (target, handle) {
this.off(MessageId.TestObjectReq, target, handle);
};
return TypedWebSocketMessageHandle;
}(WebSocketMessageHandle));
exports.TypedWebSocketMessageHandle = TypedWebSocketMessageHandle;
var LoginRsp = (function (_super) {
__extends(LoginRsp, _super);
function LoginRsp() {
_super.apply(this, arguments);
this.buffer = [MessageId.LoginRsp];
}
LoginRsp.prototype.LoginRsp = function () { };
return LoginRsp;
}(Message));
exports.LoginRsp = LoginRsp;
exports.MessageMap[MessageId.LoginRsp] = LoginRsp;
var FrameNotice = (function (_super) {
__extends(FrameNotice, _super);
function FrameNotice() {
_super.apply(this, arguments);
this.buffer = [MessageId.FrameNotice, 0];
}
FrameNotice.prototype.FrameNotice = function () { };
Object.defineProperty(FrameNotice.prototype, "ms", {
get: function () {
return this.buffer[1];
},
set: function (ms) {
this.buffer[1] = ms;
},
enumerable: true,
configurable: true
});
return FrameNotice;
}(Message));
exports.FrameNotice = FrameNotice;
exports.MessageMap[MessageId.FrameNotice] = FrameNotice;
var UserDataNotice = (function (_super) {
__extends(UserDataNotice, _super);
function UserDataNotice() {
_super.apply(this, arguments);
this.buffer = [MessageId.UserDataNotice, ""];
}
UserDataNotice.prototype.UserDataNotice = function () { };
Object.defineProperty(UserDataNotice.prototype, "account", {
get: function () {
return this.buffer[1];
},
set: function (account) {
this.buffer[1] = account;
},
enumerable: true,
configurable: true
});
return UserDataNotice;
}(Message));
exports.UserDataNotice = UserDataNotice;
exports.MessageMap[MessageId.UserDataNotice] = UserDataNotice;
var MatchingSuccessRsp = (function (_super) {
__extends(MatchingSuccessRsp, _super);
function MatchingSuccessRsp() {
_super.apply(this, arguments);
this.buffer = [MessageId.MatchingSuccessRsp, "", [""]];
}
MatchingSuccessRsp.prototype.MatchingSuccessRsp = function () { };
Object.defineProperty(MatchingSuccessRsp.prototype, "selfAccount", {
get: function () {
return this.buffer[1];
},
set: function (selfAccount) {
this.buffer[1] = selfAccount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatchingSuccessRsp.prototype, "accountList", {
get: function () {
return this.buffer[2];
},
set: function (accountList) {
this.buffer[2] = accountList;
},
enumerable: true,
configurable: true
});
return MatchingSuccessRsp;
}(Message));
exports.MatchingSuccessRsp = MatchingSuccessRsp;
exports.MessageMap[MessageId.MatchingSuccessRsp] = MatchingSuccessRsp;
var GetWalletReq = (function (_super) {
__extends(GetWalletReq, _super);
function GetWalletReq() {
_super.apply(this, arguments);
this.buffer = [MessageId.GetWalletReq, 0, 0];
}
GetWalletReq.prototype.GetWalletReq = function () { };
Object.defineProperty(GetWalletReq.prototype, "money", {
get: function () {
return this.buffer[1];
},
set: function (money) {
this.buffer[1] = money;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GetWalletReq.prototype, "diamond", {
get: function () {
return this.buffer[2];
},
set: function (diamond) {
this.buffer[2] = diamond;
},
enumerable: true,
configurable: true
});
return GetWalletReq;
}(Message));
exports.GetWalletReq = GetWalletReq;
exports.MessageMap[MessageId.GetWalletReq] = GetWalletReq;
var TestObjectReq = (function (_super) {
__extends(TestObjectReq, _super);
function TestObjectReq() {
_super.apply(this, arguments);
this.buffer = [MessageId.TestObjectReq, { "num": 1 }, [{ "str": "", "subArray": [0], "subObj": { "num": 1 } }], null];
}
TestObjectReq.prototype.TestObjectReq = function () { };
Object.defineProperty(TestObjectReq.prototype, "obj", {
get: function () {
return this.buffer[1];
},
set: function (obj) {
this.buffer[1] = obj;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TestObjectReq.prototype, "array", {
get: function () {
return this.buffer[2];
},
set: function (array) {
this.buffer[2] = array;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TestObjectReq.prototype, "nullobj", {
get: function () {
return this.buffer[3];
},
set: function (nullobj) {
this.buffer[3] = nullobj;
},
enumerable: true,
configurable: true
});
return TestObjectReq;
}(Message));
exports.TestObjectReq = TestObjectReq;
exports.MessageMap[MessageId.TestObjectReq] = TestObjectReq;
//# sourceMappingURL=twp.yaml.js.map | 37.032491 | 126 | 0.62985 |
d1efef530482557064823da2751fb7ca5d9bdaca | 1,439 | js | JavaScript | client/src/entry-client.js | deoxxa/don | 75625eace8d13e512c7d3d12ab26418bdc456814 | [
"BSD-3-Clause"
] | 199 | 2017-04-06T15:20:50.000Z | 2020-10-16T12:32:56.000Z | client/src/entry-client.js | deoxxa/don | 75625eace8d13e512c7d3d12ab26418bdc456814 | [
"BSD-3-Clause"
] | 9 | 2017-04-09T03:07:11.000Z | 2017-04-11T02:23:18.000Z | client/src/entry-client.js | deoxxa/don | 75625eace8d13e512c7d3d12ab26418bdc456814 | [
"BSD-3-Clause"
] | 8 | 2017-04-09T04:49:00.000Z | 2018-07-17T15:55:04.000Z | import axios from 'axios';
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { BrowserRouter } from 'react-router-dom';
import Redbox from 'redbox-react';
import Root from './root';
import { setupAxios, setupStore } from './setup';
function main() {
let initialState = undefined;
const reduxStateElement = document.getElementById('redux-state');
if (reduxStateElement) {
try {
initialState = JSON.parse(reduxStateElement.innerText);
} catch (e) {
// do nothing
}
}
const store = setupStore(initialState);
setupAxios(axios, store);
const reactRoot = document.getElementById('react-root');
render(
<AppContainer errorReporter={Redbox}>
<BrowserRouter>
<Root store={store} history={history} />
</BrowserRouter>
</AppContainer>,
reactRoot
);
if (
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test'
) {
if (module.hot) {
module.hot.accept('./root', () => {
const NextApp = require('./root').default;
render(
<AppContainer errorReporter={Redbox}>
<BrowserRouter>
<NextApp />
</BrowserRouter>
</AppContainer>,
reactRoot
);
});
}
}
}
if (document.readyState === 'complete') {
main();
} else {
document.addEventListener('DOMContentLoaded', main);
}
| 23.590164 | 76 | 0.613621 |
d1f095dad4027689f11a2e234e71ed4ae4e29a62 | 1,316 | js | JavaScript | app/sagas/note.js | ricsam/stickynotespp | cc2c7fe9a36f80a8448ec14020361ee52b101190 | [
"MIT"
] | null | null | null | app/sagas/note.js | ricsam/stickynotespp | cc2c7fe9a36f80a8448ec14020361ee52b101190 | [
"MIT"
] | null | null | null | app/sagas/note.js | ricsam/stickynotespp | cc2c7fe9a36f80a8448ec14020361ee52b101190 | [
"MIT"
] | null | null | null | import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import {ipcRenderer} from 'electron';
let channel_index = 0,
cb_list = {};
const addChannelListener = (id, cb) => {
cb_list[id] = (status) => {
cb(status);
delete cb_list[id]
}
};
ipcRenderer.on('NOTE_CONTENT_SAVED', (event, data) => {
cb_list[data.id](data.status);
});
function saveContent(content) { return new Promise((resolve, reject) => {
channel_index++;
addChannelListener(channel_index, (status) => {
resolve(status);
});
ipcRenderer.send('SAVE_NOTE_CONTENT', {
content: content,
id: channel_index
});
resolve();
})};
// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
try {
const content = yield call(saveContent, action.content);
yield put({type: "CONTENT_SAVE_SUCCEEDED", content: content});
} catch (e) {
yield put({type: "CONTENT_SAVE_FAILED", message: e.message});
}
}
/*
Alternatively you may use takeLatest.
Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
dispatched while a fetch is already pending, that pending fetch is cancelled
and only the latest one will be run.
*/
function* noteSaga() {
yield takeLatest("UPDATE_CONTENT", fetchUser);
}
export default noteSaga;
| 23.087719 | 78 | 0.683891 |
d1f0f07d819a96fc97b2c957d781c4d3da9ef873 | 697 | js | JavaScript | src/main/webapp/app/entities/diet/diet-delete-dialog.controller.js | tomkasp/fitapp | 85df019eaa0fc3f68b8e23f0f7378fafae37c10d | [
"Apache-2.0"
] | null | null | null | src/main/webapp/app/entities/diet/diet-delete-dialog.controller.js | tomkasp/fitapp | 85df019eaa0fc3f68b8e23f0f7378fafae37c10d | [
"Apache-2.0"
] | null | null | null | src/main/webapp/app/entities/diet/diet-delete-dialog.controller.js | tomkasp/fitapp | 85df019eaa0fc3f68b8e23f0f7378fafae37c10d | [
"Apache-2.0"
] | 1 | 2022-02-15T14:13:15.000Z | 2022-02-15T14:13:15.000Z | (function() {
'use strict';
angular
.module('fitappApp')
.controller('DietDeleteController',DietDeleteController);
DietDeleteController.$inject = ['$uibModalInstance', 'entity', 'Diet'];
function DietDeleteController($uibModalInstance, entity, Diet) {
var vm = this;
vm.diet = entity;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear () {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete (id) {
Diet.delete({id: id},
function () {
$uibModalInstance.close(true);
});
}
}
})();
| 24.034483 | 75 | 0.527977 |
d1f23b14a15a1766e9b8843d27d72e28068f2d8d | 176 | js | JavaScript | tests/lib/utils.js | lukeapage/eslint-plugin-switch-case | 0f7a6984d93dcf3aeca0d210baf79a80da52c68c | [
"MIT"
] | 12 | 2016-07-17T17:51:36.000Z | 2021-11-27T15:42:36.000Z | tests/lib/utils.js | lukeapage/eslint-plugin-switch-case | 0f7a6984d93dcf3aeca0d210baf79a80da52c68c | [
"MIT"
] | 3 | 2016-07-19T06:52:14.000Z | 2022-03-19T11:13:16.000Z | tests/lib/utils.js | coderaiser/eslint-plugin-destructuring | 3e95bca51245f6c3f10d06048859537b53452448 | [
"MIT"
] | 6 | 2017-02-07T14:48:50.000Z | 2021-08-30T09:28:14.000Z | import defaults from 'lodash.defaults';
export function test(t) {
return defaults(t, {
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
},
});
}
| 16 | 39 | 0.607955 |
d1f261f45581b08b7adf7713b38181641aff3cc9 | 199 | js | JavaScript | engine/jscripts/tiny_mce/plugins/autosave/langs/nn.js | vicegirls/OpenSerene | ee6f126355b35470ee1ef05e177f7861e223037b | [
"Apache-2.0"
] | null | null | null | engine/jscripts/tiny_mce/plugins/autosave/langs/nn.js | vicegirls/OpenSerene | ee6f126355b35470ee1ef05e177f7861e223037b | [
"Apache-2.0"
] | 1 | 2015-12-01T09:15:03.000Z | 2015-12-01T09:15:03.000Z | engine/jscripts/tiny_mce/plugins/autosave/langs/nn.js | vicegirls/OpenSerene | ee6f126355b35470ee1ef05e177f7861e223037b | [
"Apache-2.0"
] | null | null | null | // nn = Norwegian (nynorsk) lang variables by Knut B. Jacobsen
tinyMCE.addToLang('',{
autosave_unload_msg : 'Forandringene du gjorde forsvinner om du velger å forlate denne siden.'
});
| 28.428571 | 101 | 0.723618 |
d1f29d0e0576bcd2ce5aad890064ecd87289c9a4 | 545 | js | JavaScript | app/components/Link.js | ianmetcalf/redux-saga-demo-app | bdbb0faa5df7c4c8b95e5d5d40bfd9b1c7d2f53c | [
"MIT"
] | null | null | null | app/components/Link.js | ianmetcalf/redux-saga-demo-app | bdbb0faa5df7c4c8b95e5d5d40bfd9b1c7d2f53c | [
"MIT"
] | null | null | null | app/components/Link.js | ianmetcalf/redux-saga-demo-app | bdbb0faa5df7c4c8b95e5d5d40bfd9b1c7d2f53c | [
"MIT"
] | null | null | null | import m from 'mithril';
import history from '../history';
const Link = {
view({attrs: {to = '', ...attrs}, children}) {
return (
<a
{...attrs}
href={history.createHref({pathname: to})}
onclick={e => {
const modified = e.metaKey || e.altKey || e.ctrlKey || e.shiftKey;
if (!modified && e.button === 0 && !e.defaultPrevented) {
e.preventDefault();
history.push(to);
}
}}
>
{children}
</a>
);
},
};
export default Link;
| 20.961538 | 76 | 0.477064 |
d1f3aa7115b71796cb577b51f6004a6d34c55dd9 | 15,450 | js | JavaScript | js/app.js | JacobGregor/cookie-stand | 75fa53a6fc713dcc8e649d70eed0f8495e2c4967 | [
"MIT"
] | null | null | null | js/app.js | JacobGregor/cookie-stand | 75fa53a6fc713dcc8e649d70eed0f8495e2c4967 | [
"MIT"
] | null | null | null | js/app.js | JacobGregor/cookie-stand | 75fa53a6fc713dcc8e649d70eed0f8495e2c4967 | [
"MIT"
] | null | null | null | 'use strict'
const cityDiv = document.getElementById('city');
const hoursOfOperation = [' 6:00am ', ' 7:00am ', ' 8:00am ', ' 9:00am ', ' 10:00am ', ' 11:00am ', ' 12:00pm ', ' 1:00pm ', ' 2:00pm ', ' 3:00pm ', ' 4:00pm ', ' 5:00pm ', ' 6:00pm ', ' 7:00pm ']
/////// Restaurant Location Constructor //////////
function Restaurant(name,minCustomer,maxCustomer,avg) {
this.name = name;
this.minCustomer = minCustomer;
this.maxCustomer = maxCustomer;
this.avg = avg;
this.cookieSalesArray = []
Restaurant.locationArray.push(this)
}
Restaurant.locationArray = [];
// New Objects for each city //
new Restaurant('Seattle',23,65,6.3);
new Restaurant('Tokyo',3,22,1.2,);
new Restaurant('Dubai',11,38,3.7);
new Restaurant('Paris',20,38,2.3);
new Restaurant('Lima',2,16,4.6);
///////////Generates Customer////////////////
Restaurant.prototype.generateCustomer = function(minCustomer,maxCustomer) {
minCustomer = this.minCustomer
maxCustomer = this.maxCustomer
return Math.floor(Math.random() * (maxCustomer - minCustomer) + minCustomer);
}
////////////////Prototype that generates cookie per/hr sales array//////////
Restaurant.prototype._generateCookieSalesArray = function() {
for(let i = 0; i < hoursOfOperation.length; i++) {
let cookiesPerHour = this.generateCustomer() * this.avg
this.cookieSalesArray.push(Math.round(cookiesPerHour))
}
}
/////////////// function that refactors _generateCookiesSalesArray and returns data for all cities.////////////////
function renderSalesArrayAll() {
for(let i = 0; i < Restaurant.locationArray.length; i++) {
const currentInstance = Restaurant.locationArray[i];
currentInstance._generateCookieSalesArray();
}
}
renderSalesArrayAll();
//////// Create a function to create new elements/////////////
function createElement (tag, parent,text) {
let element = document.createElement(tag);
parent.appendChild(element);
if (text) {
element.textContent = text;
}
return element;
}
////////////////////Render our location data per/location per/hour./////////////
Restaurant.prototype.renderLocationData = function(body) {
let total = 0;
/////Makes a row and appends to the body//////
const trEl = document.createElement('tr')
body.appendChild(trEl);
const thEl = createElement('th', trEl, this.name)
////Generates Cookie Per Hour Data///////
for(let i = 0; i < hoursOfOperation.length; i++) {
let cookieHourData = this.cookieSalesArray[i];
total += cookieHourData
createElement('td', trEl, cookieHourData)
}
createElement('td', trEl, total)
}
// Renders ^^^ the above function which renders a single location, for all of the locations in the locationArray. //
function renderAllLocationData () {
let tbodyEl = createElement('tbody', cityDiv, null);
for(let i = 0; i < Restaurant.locationArray.length; i++) {
Restaurant.locationArray[i].renderLocationData(tbodyEl)
}
}
// Create Footer //
function createFooter() {
const tfootEl = createElement('tbody', cityDiv, null);
const trEl = createElement('tr', tfootEl, null);
createElement('th', trEl, 'Hourly Total')
let hourTotal = 0
let dayTotal = 0
for(let i = 0; i < hoursOfOperation.length; i++) {
for(let j = 0; j < Restaurant.locationArray.length; j++) {
let currentLocation = Restaurant.locationArray[j];
hourTotal += currentLocation.cookieSalesArray[i];
}
createElement('td', trEl, hourTotal);
dayTotal += hourTotal
hourTotal = 0
}
createElement('td', trEl, dayTotal)
}
// Create Header //
function createHeader() {
const theadEl = createElement('thead',cityDiv, null)
const trEl = createElement('tr', theadEl, null);
createElement('th', trEl, ' ');
for(let i = 0; i < hoursOfOperation.length; i++) {
createElement('th', trEl, hoursOfOperation[i]);
}
createElement('th',trEl,'Daily Totals');
};
// Event handler function to store form data and post to table. //
function handleEvent(event) {
event.preventDefault();
let name = event.target.name.value;
let minCustomer = parseInt(event.target.minCustomer.value);
let maxCustomer = parseInt(event.target.maxCustomer.value);
let avg = parseInt(event.target.avg.value);
let newLocation = new Restaurant(name,minCustomer,maxCustomer,avg)
cityDiv.innerHTML = '';
newLocation._generateCookieSalesArray();
renderAllLocationData();
createHeader();
createFooter();
event.target.reset();
}
renderAllLocationData();
createHeader();
createFooter();
document.getElementById('location-form').addEventListener('submit',handleEvent);
/////////////////////////////Old Code Prior to Refctoring how to post to table//////////////////////////////
// //Prototype Method that renders totals//
// Restaurant.prototype._renderTotals = function() {
// let total = 0;
// for(let i = 0; i < hoursOfOperation.length - 1; i++) {
// total += this.cookieSalesArray[i];
// }
// let trElFoot = document.getElementById('totalData')
// const thElTotals = document.createElement('th')
// thElTotals.textContent = total
// trElFoot.appendChild(thElTotals)
// };
// // Renders table header and populates each row with a different hour of operation //
// Restaurant.prototype.renderHeader = function() {
// for(let i = 0; i < hoursOfOperation.length; i++){
// console.log('test 74')
// let trElHours = document.getElementById('hoursData')
// const thElHours = document.createElement('th')
// thElHours.textContent = hoursOfOperation[i];
// trElHours.appendChild(thElHours);
// }
// }
// // Protoyype Method to post cookies per hour data for each location for every hour //
// Restaurant.prototype._renderSalesData = function() {
// //create body of table
// const trElCities = document.createElement('tr');
// let tbodyEl = document.getElementById('data')
// tbodyEl.appendChild(trElCities);
// const thElCities = document.createElement('th')
// trElCities.id="citiesData"
// thElCities.textContent = this.name;
// trElCities.appendChild(thElCities);
// for(let i = 0; i < hoursOfOperation.length; i++){
// const tdElSales = document.createElement('td')
// tdElSales.textContent = this.cookieSalesArray[i];
// trElCities.appendChild(tdElSales)
// }
// }
// // Prototype to render the totals for each location for every hour.
// //
// function renderTable() {
// //Create Article//
// const articleEl = document.createElement('article');
// let cityDiv = document.getElementById('city');
// cityDiv.appendChild(articleEl);
// //Create Table//
// const tableEl = document.createElement('table');
// articleEl.appendChild(tableEl);
// //Creates Table Head//
// const tableHeadEl = document.createElement('thead')
// tableEl.appendChild(tableHeadEl);
// //Create Table Row//
// const trElHours = document.createElement('tr');
// trElHours.id = 'hoursData'
// tableHeadEl.appendChild(trElHours);
// // create body//
// const tbodyEl = document.createElement('tbody')
// tbodyEl.id='data'
// tableEl.appendChild(tbodyEl)
// //Creates Table Footer//
// const tableFootEl = document.createElement('tfoot')
// tableEl.appendChild(tableFootEl);
// //Create Table Row//
// const trElFoot = document.createElement('tr');
// trElFoot.id = 'totalData'
// tableFootEl.appendChild(trElFoot);
// }
// renderTable();
// //Render Data for Seattle//
// // seattle._cookiesPerHour()
// seattle._generateCookieSalesArray()
// seattle._renderTotals()
// seattle._renderSalesData()
// seattle.renderHeader();
// //Render Data for Tokyo//
// // tokyo._cookiesPerHour()
// tokyo._generateCookieSalesArray()
// tokyo._renderTotals()
// tokyo._renderSalesData()
// //Render data for Dubai
// // dubai._cookiesPerHour()
// dubai._generateCookieSalesArray()
// dubai._renderTotals()
// dubai._renderSalesData()
// //Render data for Paris
// // paris._cookiesPerHour()
// paris._generateCookieSalesArray()
// paris._renderTotals()
// paris._renderSalesData()
// //Render data for Lima
// // lima._cookiesPerHour()
// lima._generateCookieSalesArray()
// lima._renderTotals()
// lima._renderSalesData()
//////////////////////Line 159 Below is all day 1 Code. formatting on a lot of it got messed up.. its a mess. Will delete////////////////
// Objects
// const seattle = {
// name: 'Seattle',
// minCustomer: 23,
// maxCustomer: 65,
// avg: 6.3,
// cookiePerHourArray: [],
// // Function to generate random Customer/Hour
// calcCustomerHour: function (){
// return getMinMax(this.minCustomer,this.maxCustomer);
// },
// //Function calculate average cookies per/hour based on Avg. Cookie * Random Customer/hr function.
// calcCookieHourAvg: function () {
// return this.calcCustomerHour() * this.avg
// },
// function renderCity (city) {
// //Function that loops 13 times generating a variable Hour which = startHour variable (6) and adds our Index value + either 'am' or 'pm' depending on the if(peramiter). On each iteration we generate a cookies sold per hour value based on our object value of (this.calcCookieHourAvg()) which is a function that runs calcCustomerHour() and multiples the value by our this.avg (which is our objects avg cookies sold per customer value). Our loop then generates an empty hourObject {}; and fills this object with 'Hour + 'am'/'pm' and a cookiePerHourAvg number. we then push this data into our empty object array above named cookiePerHourArray [].
// cookieHourlySales: function () {
// let startHour = 6
// for(let i = 0; i < 14; i++) {
// let hour = startHour + i;
// if (hour < 12) {
// hour = hour + 'am';
// } else if (hour === 12) {
// hour = hour + 'pm'
// } else if (hour > 12) {
// hour = (hour - 12) + 'pm';
// }
// let cookiesSold = Math.round(this.calcCookieHourAvg())
// let hourObject = {};
// hourObject[hour] = cookiesSold //////////////////////////// Whats going on here. Ask Jonathan.///////////////////
// this.cookiePerHourArray.push(hourObject);
// }
// }
// };
// const tokyo = {
// name: 'Tokyo',
// minCustomer: 3,
// maxCustomer: 24,
// avg: 1.2,
// cookiePerHourArray: [],
// calcCustomerHour: function (){
// return getMinMax(this.minCustomer,this.maxCustomer);
// },
// //Function calculate average cookies per/hour based on Avg. Cookie * Random Customer/hr function.
// calcCookieHourAvg: function () {
// return this.calcCustomerHour() * this.avg
// },
// cookieHourlySales: function () {
// let startHour = 6
// for(let i = 0; i < 14; i++) {
// let hour = startHour + i;
// if (hour < 12) {
// hour = hour + 'am';
// } else if (hour === 12) {
// hour = hour + 'pm'
// } else if (hour > 12) {
// hour = (hour - 12) + 'pm';
// }
// let cookiesSold = Math.round(this.calcCookieHourAvg())
// let hourObject = {};
// hourObject[hour] = cookiesSold
// this.cookiePerHourArray.push(hourObject);
// }
// }
// };
// const dubai = {
// name: 'Dubai',
// minCustomer: 11,
// maxCustomer: 38,
// avg: 3.7,
// cookiePerHourArray: [],
// calcCustomerHour: function (){
// return getMinMax(this.minCustomer,this.maxCustomer);
// },
// //Function calculate average cookies per/hour based on Avg. Cookie * Random Customer/hr function.
// calcCookieHourAvg: function () {
// return this.calcCustomerHour() * this.avg
// },
// cookieHourlySales: function () {
// let startHour = 6
// for(let i = 0; i < 14; i++) {
// let hour = startHour + i;
// if (hour < 12) {
// hour = hour + 'am';
// } else if (hour === 12) {
// hour = hour + 'pm'
// } else if (hour > 12) {
// hour = (hour - 12) + 'pm';
// }
// let cookiesSold = Math.round(this.calcCookieHourAvg())
// let hourObject = {};
// hourObject[hour] = cookiesSold
// this.cookiePerHourArray.push(hourObject);
// }
// }
// };
// const paris = {
// name: 'Paris',
// minCustomer: 20,
// maxCustomer: 38,
// avg: 2.3,
// cookiePerHourArray: [],
// calcCustomerHour: function (){
// return getMinMax(this.minCustomer,this.maxCustomer);
// },
// calcCookieHourAvg: function () {
// return this.calcCustomerHour() * this.avg
// },
// cookieHourlySales: function () {
// let startHour = 6
// for(let i = 0; i < 14; i++) {
// let hour = startHour + i;
// if (hour < 12) {
// hour = hour + 'am';
// } else if (hour === 12) {
// hour = hour + 'pm'
// } else if (hour > 12) {
// hour = (hour - 12) + 'pm';
// }
// let cookiesSold = Math.round(this.calcCookieHourAvg())
// let hourObject = {};
// hourObject[hour] = cookiesSold
// this.cookiePerHourArray.push(hourObject);
// }
// }
// };
// const lima = {
// name: 'Lima',
// minCustomer: 2,
// maxCustomer: 16,
// avg: 4.6,
// cookiePerHourArray: [],
// calcCustomerHour: function (){
// return getMinMax(this.minCustomer,this.maxCustomer);
// },
// //Function calculate average cookies per/hour based on Avg. Cookie * Random Customer/hr function.
// calcCookieHourAvg: function () {
// avg
// },
// cookieHourlySales: function () {
// let startHour = 6
// for(let i = 0; i < 14; i++) {
// hour = startHour + i;
// if (hour < 12) {
// hour = hour + 'am';
// } else if (hour === 12) {
// hour = hour + 'pm'
// } else if (hour > 12) {
// hour = (hour - 12) + 'pm';
// }
// let cookiesSold = Math.ceil(this.calcCookieHourAvg())
// let hourObject = {};
// hourObject[hour] = cookiesSold
// cookiePerHourArray.push(hourObject);
// }
// }
// };
// function generateCities (city){
// const thElCities = document.createElement('th')
// thElCities.textContent = this.name;
// trElCities.appendChild(thElCities);
// console.log(thElCities)
// };
// for(let i = 0; i < Restaurant.restaurantArray.length[i]; i++) {
// const thElCities = document.createElement('th')
// thElCities.textContent = this.restaurantArray[0];
// trElCities.appendChild(thElCities);
// console.log(thElCities)
// //create city row for each iteration//
// for (let i = 0; i < Restaurant.restaurantArray.length[i]; i++){
// }
/////////////////Delete this later/////////////////////
//posts time and cookie totals/////////
// const liEl = document.createElement('li')
// liEl.textContent = `${this.hoursOfOperation[i]} ${this.cookieSalesArray[i]} cookies`
// ulEl.appendChild(liEl);
//Generates Hours of Operation to table//
// const thElHours = document.createElement('th')
// thElHours.textContent = this.hoursOfOperation[i];
// trElHours.appendChild(thElHours);
//Generates Cities to table//
///////////////////////////renders totals////
// const liEltotal = document.createElement('li');
// liEltotal.textContent = `Total: ${total} cookies`;
// ulEl.appendChild(liEltotal);
// //Function to Generate Random Customer count.
// function getMinMax(minCustomer,maxCustomer) {
// minCustomer = Math.ceil(minCustomer)
// maxCustomer = Math.floor(maxCustomer)
// return Math.floor(Math.random() * (maxCustomer - minCustomer) + minCustomer);
// }
// city.calcCustomerHour();
// city.calcCookieHourAvg();
// }
// generateCities(seattle);
// generateCities(tokyo)
// generateCities(dubai)
// generateCities(paris)
// generateCities(lima)
// renderCity(seattle)
// renderCity(dubai)
// renderCity(tokyo)
// renderCity(paris)
// renderCity(lima)
| 32.254697 | 658 | 0.640129 |
d1f40e90ef71547042f7423e358627012b110f9c | 1,157 | js | JavaScript | app/javascript/helpers/api_routes.js | calblueprint/HomePointrCIC | b8d2cc6ac4fe66a1b4fdc272d93ccf4f73034369 | [
"MIT"
] | 3 | 2018-09-22T01:04:20.000Z | 2019-04-06T17:16:50.000Z | app/javascript/helpers/api_routes.js | calblueprint/HomePointrCIC | b8d2cc6ac4fe66a1b4fdc272d93ccf4f73034369 | [
"MIT"
] | 172 | 2018-09-27T23:51:05.000Z | 2022-02-26T09:58:18.000Z | app/javascript/helpers/api_routes.js | calblueprint/HomePointrCIC | b8d2cc6ac4fe66a1b4fdc272d93ccf4f73034369 | [
"MIT"
] | 3 | 2019-06-01T08:11:59.000Z | 2019-06-03T15:17:48.000Z | class ApiRoutes {
get properties() {
return {
create: '/api/properties',
update: (id) => '/api/properties/' + id,
delete: (id) => '/api/properties/' + id,
delete_image: (image_id) => '/api/properties/delete_image_attachment/' + image_id,
categories: `/properties/categories`,
}
}
get tenants() {
return {
create: '/api/tenants',
update: (id) => '/api/tenants/' + id,
delete: (id) => '/api/tenants/' + id,
categories: `/tenants/categories`,
}
}
get users() {
return {
delete: () => '/users/sign_out',
}
}
get sessions() {
return {
create: () => '/users/sign_in',
}
}
get landlords() {
return {
update: (id) => '/landlords/' + id,
delete: (id) => '/landlords/' + id,
}
}
get referral_agencies() {
return {
update: (id) => '/referral_agencies/' + id,
delete: (id) => '/referral_agencies/' + id,
}
}
get applications() {
return {
create: '/api/applications',
update: (id) => '/api/applications/' + id,
}
}
}
const APIRoutes = new ApiRoutes();
export default APIRoutes;
| 20.660714 | 88 | 0.527226 |
d1f490867c2b26285395e21fa4b053a09074fd4b | 330 | js | JavaScript | js/axios/src/index.js | tanlinhua/WebTestDemo | 9a67e0978601939b46977c1a619afe6c79231f53 | [
"Apache-2.0"
] | null | null | null | js/axios/src/index.js | tanlinhua/WebTestDemo | 9a67e0978601939b46977c1a619afe6c79231f53 | [
"Apache-2.0"
] | null | null | null | js/axios/src/index.js | tanlinhua/WebTestDemo | 9a67e0978601939b46977c1a619afe6c79231f53 | [
"Apache-2.0"
] | null | null | null | import axios from "axios";
axios.get("http://localhost/get.php?a=1&b=2").then((result) => {
console.log('get', result.data);
}).catch((err) => {
console.log(err);
});
axios.post('http://localhost/post.php', "a=1&b=2").then((result) => {
console.log('post', result.data);
}).catch((err) => {
console.log(err);
}); | 25.384615 | 69 | 0.584848 |
d1f6878ad892d5c065bcf53104594eec26700b04 | 4,361 | js | JavaScript | lib/profiler.js | Slayer95/osu-accuracy | b72ceb95dccc45360004adb2e0d3f9f6548123b0 | [
"MIT"
] | null | null | null | lib/profiler.js | Slayer95/osu-accuracy | b72ceb95dccc45360004adb2e0d3f9f6548123b0 | [
"MIT"
] | null | null | null | lib/profiler.js | Slayer95/osu-accuracy | b72ceb95dccc45360004adb2e0d3f9f6548123b0 | [
"MIT"
] | null | null | null | "use strict";
const util = require('./util');
function sumdt(dt1, dt2) {
return [dt1[0] + dt2[0], dt1[1] + dt2[1]];
}
function getdt(t1, t2) {
return [t2[0] - t1[0], t2[1] - t1[1]];
}
const LIMITED_EVENTS = new Map([
['osu_network_rtt', 4],
]);
class ActionLog {
constructor() {
this.counters = new Map();
this.times = new Map();
this.parallelQueued = null;
this.debugMode = false;
}
setDebug(value) {
this.debugMode = !!value;
}
setParallel(value) {
const queued = this.parallelQueued;
if (queued && !value) {
for (const [key, {count, startTime, endTime}] of queued) {
try {
if (!this.counters.has(key)) {
this.counters.set(key, count);
this.times.set(key, getdt(startTime, endTime));
} else {
const prevCount = this.counters.get(key);
this.counters.set(key, prevCount + count);
if (!LIMITED_EVENTS.has(key) || prevCount + count <= LIMITED_EVENTS.get(key)) {
this.times.set(key, sumdt(this.times.get(key), getdt(startTime, endTime)));
} else if (prevCount <= LIMITED_EVENTS.get(key)) {
LIMITED_EVENTS.set(key, prevCount);
}
}
} catch (err) {
console.error(`Bad key: ${key}`);
console.error(err.stack);
}
}
}
this.parallelQueued = value ? new Map() : null;
}
logN(key, nEvents, t0, forceSync) {
nEvents = ~~nEvents;
if (nEvents <= 0) return;
if (this.debugMode) {
console.error(`[${util.getTimestamp()}] PLOG ${nEvents} ${key}`);
}
if (this.parallelQueued && !forceSync) {
const t1 = process.hrtime();
key = `${key}_parallel`;
if (!this.parallelQueued.has(key)) {
this.parallelQueued.set(key, {count: 0, startTime: t0, endTime: null});
}
const entry = this.parallelQueued.get(key);
entry.count += nEvents;
entry.endTime = t1;
} else {
const dt = t0 ? process.hrtime(t0) : null;
if (!this.counters.has(key)) {
this.counters.set(key, nEvents);
this.times.set(key, dt);
return this;
}
const prevCount = this.counters.get(key);
this.counters.set(key, prevCount + nEvents);
if (!LIMITED_EVENTS.has(key) || prevCount + nEvents <= LIMITED_EVENTS.get(key)) {
this.times.set(key, dt ? sumdt(this.times.get(key), dt) : null);
} else if (prevCount <= LIMITED_EVENTS.get(key)) {
LIMITED_EVENTS.set(key, prevCount);
}
}
}
log(key, t0) {
if (!t0 && this.parallelQueued) {
throw new Error(`Profiler in parallel mode: Use logSync() if not timing`);
}
return this.logN(key, 1, t0, false);
}
logSync(key, t0) {
return this.logN(key, 1, t0, true);
}
logTime(key, dt) {
this.times.set(key, dt);
}
getTime(key) {
if (!this.times.has(key)) {
throw new Error(`key ${key} not found`);
}
const dt = this.times.get(key);
if (!dt || LIMITED_EVENTS.has(key)) return null;
return (dt[0] * 1E3 + dt[1] / 1E6); // ms
}
getAverageTime(key) {
if (!this.counters.has(key) || !this.times.has(key)) {
throw new Error(`key ${key} not found`);
}
const count = this.counters.get(key);
const dt = this.times.get(key);
if (!dt) return null;
return (dt[0] * 1E3 + dt[1] / 1E6) / (LIMITED_EVENTS.has(key) ? Math.min(count, LIMITED_EVENTS.get(key)) : count); // ms
}
toString() {
const cellWidths = [25, 6, 10, 10];
const contents = [];
for (const key of this.counters.keys()) {
const timesRaw = [this.getTime(key), this.getAverageTime(key)];
const timesFormatted = timesRaw.map(x => x === null ? `N/A` : `${x.toFixed(2)}ms`);
if (key.length > cellWidths[0]) cellWidths[0] = key.length;
if (timesFormatted[0].length > cellWidths[2]) cellWidths[2] = timesFormatted[0].length;
if (timesFormatted[1].length > cellWidths[3]) cellWidths[3] = timesFormatted[1].length;
contents.push([key, this.counters.get(key), ...timesFormatted]);
}
const formatCell = (cell, index) => util.padString(` ${cell}`, cellWidths[index] + 1); // +1 to compensate left padding
const formatRow = row => row.map(formatCell).join(`|`);
const headers = [`Action`, `Count`, `Time`, `Average`];
const output = [];
output.push(formatRow(headers));
output.push(Array.from({length: 4}, (_, index) => '-'.repeat(cellWidths[index] + 1)).join(`|`));
for (const row of contents) {
output.push(formatRow(row));
}
return output.join(`\n`);
}
}
const Profiler = new ActionLog();
module.exports = Profiler;
| 27.25625 | 122 | 0.620041 |
d1f716414a4b6fe99b9e689288e7ecef9af3e765 | 189 | js | JavaScript | src/js/teamModule/controllers/teamCtrl.js | lostdalek/angular-lazyload-boilerplate | 9258e27edbdc76d7ace0f495010fc6df9e444d60 | [
"MIT"
] | 1 | 2015-09-07T18:41:47.000Z | 2015-09-07T18:41:47.000Z | src/js/teamModule/controllers/teamCtrl.js | lostdalek/angular-lazyload-boilerplate | 9258e27edbdc76d7ace0f495010fc6df9e444d60 | [
"MIT"
] | null | null | null | src/js/teamModule/controllers/teamCtrl.js | lostdalek/angular-lazyload-boilerplate | 9258e27edbdc76d7ace0f495010fc6df9e444d60 | [
"MIT"
] | null | null | null | 'use strict';
angular.module('teamModule')
.controller('TeamCtrl', ['$scope', '$state', 'TeamRepository', function ($scope, $state, TeamRepository) {
// abstract route
}]);
| 31.5 | 110 | 0.62963 |
d1f85bac07af77e61fa97e41c580ac201892c6d8 | 277 | js | JavaScript | src/features/imagePick/imagePickReducer.js | bunkerchat/bunker | d646aadb8ab97659ee5f28a520c05fe32de7a807 | [
"MIT"
] | 12 | 2015-04-12T19:02:02.000Z | 2021-01-29T03:57:37.000Z | src/features/imagePick/imagePickReducer.js | bunkerchat/bunker | d646aadb8ab97659ee5f28a520c05fe32de7a807 | [
"MIT"
] | 47 | 2015-04-23T12:51:51.000Z | 2022-02-18T16:27:47.000Z | src/features/imagePick/imagePickReducer.js | bunkerchat/bunker | d646aadb8ab97659ee5f28a520c05fe32de7a807 | [
"MIT"
] | 13 | 2015-05-19T17:00:40.000Z | 2018-12-20T19:43:13.000Z | const handlers = {
"images/received": (state, action) => ({
message: action.message,
images: action.images
}),
"images/close": () => null
};
export default function(state = null, action) {
return handlers[action.type] ? handlers[action.type](state, action) : state;
}
| 23.083333 | 77 | 0.66787 |
d1f886faa1b7510d1d2d75eee9bafbb54928e82e | 1,472 | js | JavaScript | examples/index.js | iwaimai-bi-fe/vc-button | 5ae69fc7b50c90384ef972856b19962bf8353aff | [
"MIT"
] | 2 | 2016-09-02T03:01:34.000Z | 2016-09-06T09:54:52.000Z | examples/index.js | iwaimai-bi-fe/vc-button | 5ae69fc7b50c90384ef972856b19962bf8353aff | [
"MIT"
] | null | null | null | examples/index.js | iwaimai-bi-fe/vc-button | 5ae69fc7b50c90384ef972856b19962bf8353aff | [
"MIT"
] | null | null | null | import Vue from 'vue'
import vcButton from '../src'
new Vue({
el: '#app',
data () {
return {
bools: {
'true': true,
'false': false
},
iconStr: 'remove', // demo only
label: 'use label, no slot',
type: "warning",
htmlType: 'button',
loading: false,
loadingText: 'loading中',
size: 'middle',
icon: 'remove',
shape: '',
disabled: false,
style: {}
}
},
methods: {
handleClick (...args) {
alert('click ' + args[0])
console.log(args)
},
toggleIcon () {
if (!this.icon) {
this.icon = this.iconStr
} else {
this.icon = null
}
},
toggleIconShape () {
if (this.shape === 'circle') {
this.shape = ''
} else {
this.shape = 'circle'
}
},
setIcon () {
this.icon = this.iconStr
},
toggleLoading () {
this.loading = !this.loading
},
sl () {
this.size = 'large'
},
sm () {
this.size = 'middle'
},
ss () {
this.size = 'small'
},
disabledFn () {
this.disabled = true
}
},
components: {
vcButton
}
})
| 21.647059 | 43 | 0.36481 |
d1f92ff85b14cb632957afac6865e813b358c0af | 2,491 | js | JavaScript | public/backend/library/attribute.js | githtvietnam/laravel | 229724cdef9596a776e300abfdea9ba738427fd6 | [
"MIT"
] | null | null | null | public/backend/library/attribute.js | githtvietnam/laravel | 229724cdef9596a776e300abfdea9ba738427fd6 | [
"MIT"
] | 3 | 2021-03-09T19:15:28.000Z | 2022-02-26T18:27:33.000Z | public/backend/library/attribute.js | githtvietnam/laravel | 229724cdef9596a776e300abfdea9ba738427fd6 | [
"MIT"
] | null | null | null | $(document).ready(function(){
//===================album ảnh===================
if($('.colorpicker-element').length){
console.log(1);
$('.demo1').colorpicker();
var divStyle = $('#demo_apidemo')[0].style;
$('.demo1').colorpicker({
color: divStyle.backgroundColor
}).on('changeColor', function(ev) {
divStyle.backgroundColor = ev.color.toHex();
});
$('.clockpicker').clockpicker();
}
$(document).on('change','.catalogueid', function(){
let _this = $(this);
let id=_this.val();
if(id==2){
$('.color').show();
}else{
$('.color').hide();
}
if(id==7){
$('.price_range').show();
}else{
$('.price_range').hide();
}
});
// Cập nhật trạng thái
$(document).on('click','.pagination li a', function(){
let _this = $(this);
let page = _this.attr('data-ci-pagination-page');
let keyword = $('.keyword').val();
let perpage = $('.perpage').val();
let catalogueid = $('.catalogueid').val();
let object = {
'keyword' : keyword,
'perpage' : perpage,
'catalogueid' : catalogueid,
'page' : 1,
}
clearTimeout(time);
if(keyword.length > 2){
time = setTimeout(function(){
get_list_object(object);
},500);
}else{
time = setTimeout(function(){
get_list_object(object);
},500);
}
return false;
});
$(document).on('change','.publish',function(){
let _this = $(this);
let objectid = _this.attr('data-id');
let formURL = 'article/ajax/catalogue/status';
$.post(formURL, {
objectid: objectid},
function(data){
});
});
var time;
$(document).on('keyup change','.filter', function(){
let keyword = $('.keyword').val();
let perpage = $('.perpage').val();
let catalogueid = $('.catalogueid').val();
let object = {
'keyword' : keyword,
'perpage' : perpage,
'page' : 1,
'catalogueid':catalogueid,
}
keyword = keyword.trim();
clearTimeout(time);
if(keyword.length > 2){
time = setTimeout(function(){
get_list_object(object);
},500);
}else{
time = setTimeout(function(){
get_list_object(object);
},500);
}
});
});
function get_list_object(param){
let ajaxUrl = 'attribute/ajax/attribute/listAttribute';
$.get(ajaxUrl, {
perpage: param.perpage, keyword: param.keyword, page: param.page, catalogueid: param.catalogueid},
function(data){
let json = JSON.parse(data);
$('#ajax-content').html(json.html);
$('#pagination').html(json.pagination);
$('#total_row').html(json.total_row);
});
}
| 23.280374 | 100 | 0.588519 |
d1f937f56696becb903d7fce1b8109fc4697858b | 1,941 | js | JavaScript | assets/js/app.js | axelclark/ex338 | 3fb3c260d93bda61f7636ee1a677770d2dc1b89a | [
"MIT"
] | 17 | 2016-12-22T06:39:26.000Z | 2021-01-20T13:51:13.000Z | assets/js/app.js | axelclark/ex338 | 3fb3c260d93bda61f7636ee1a677770d2dc1b89a | [
"MIT"
] | 608 | 2016-08-06T18:57:58.000Z | 2022-03-01T02:48:17.000Z | assets/js/app.js | axelclark/ex338 | 3fb3c260d93bda61f7636ee1a677770d2dc1b89a | [
"MIT"
] | 6 | 2017-11-21T22:35:45.000Z | 2022-01-11T21:37:40.000Z | // We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import css from "../css/app.css"
// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import dependencies
//
import "alpinejs"
import "phoenix_html"
import { Socket } from "phoenix"
import NProgress from "nprogress"
import LiveSocket from "phoenix_live_view"
// LiveView polyfills for IE11
import "mdn-polyfills/NodeList.prototype.forEach"
import "mdn-polyfills/Element.prototype.closest"
import "mdn-polyfills/Element.prototype.matches"
import "url-search-params-polyfill"
import "formdata-polyfill"
// Import local files
//
// Local files can be imported directly using relative paths, for example:
// import socket from "./socket"
import "./filter_players"
import "./filter_trade_form"
import "./filter_players_list"
import "./confirm_submit"
let csrfToken = document
.querySelector("meta[name='csrf-token']")
.getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
dom: {
onBeforeElUpdated(from, to) {
if (from.__x) {
window.Alpine.clone(from.__x, to)
}
},
},
params: { _csrf_token: csrfToken },
})
// Show progress bar on live navigation and form submits
window.addEventListener("phx:page-loading-start", (info) => NProgress.start())
window.addEventListener("phx:page-loading-stop", (info) => NProgress.done())
// connect if there are any LiveViews on the page
liveSocket.connect()
// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000)
window.liveSocket = liveSocket
import StandingsChart from "./standings_chart.js"
let standingsChartElement = document.getElementById("standings-chart")
standingsChartElement && StandingsChart.buildChart()
| 29.409091 | 81 | 0.745492 |
d1f97329cb5f666cea2524e0529b14e5e927311e | 925 | js | JavaScript | index.js | fess932/childrenAttendance | fa2295fe01ec66d5ec020f195d2127e92e5157d1 | [
"MIT"
] | null | null | null | index.js | fess932/childrenAttendance | fa2295fe01ec66d5ec020f195d2127e92e5157d1 | [
"MIT"
] | null | null | null | index.js | fess932/childrenAttendance | fa2295fe01ec66d5ec020f195d2127e92e5157d1 | [
"MIT"
] | null | null | null | const children = require('./children.js')
const days = require('./days.js')
const path = require('path')
const express = require('express')
const app = express()
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))
const port = process.env.PORT || '8000'
app.get('/', function (r, w) {
w.render('index')
})
app.get('/children', children.renderChildren)
app.get('/children/add', children.renderAddChildren)
app.post('/children/add', children.addChildren)
app.get('/days', days.renderDays)
app.get('/days/byid/:id', days.getByID)
app.get('/days/muster', days.musterGet)
app.post('/days/muster', days.musterPost)
app.listen(port, (err) => {
if (err) {
return console.log('произошла ошибка при запуске', err)
}
console.log(`приложение доступно по адресу http://localhost:${port}`)
})
| 26.428571 | 71 | 0.688649 |
d1fa9aa2f9936c5fe4007be8ef445f57efe90160 | 45 | js | JavaScript | target/doc/libc/types/os/common/bsd43/sidebar-items.js | pegasos1/numbers | 8d7d054d353ac63b2bd003252ef10b4b68a95651 | [
"MIT"
] | 1 | 2019-04-07T18:51:19.000Z | 2019-04-07T18:51:19.000Z | target/doc/libc/types/os/common/bsd43/sidebar-items.js | pegasos1/numbers | 8d7d054d353ac63b2bd003252ef10b4b68a95651 | [
"MIT"
] | null | null | null | target/doc/libc/types/os/common/bsd43/sidebar-items.js | pegasos1/numbers | 8d7d054d353ac63b2bd003252ef10b4b68a95651 | [
"MIT"
] | null | null | null | initSidebarItems({"struct":[["rusage",""]]}); | 45 | 45 | 0.622222 |
d1fb1a49688eac893eb44268b2a541961e1f4be9 | 1,077 | js | JavaScript | src/common/ButtonBox.js | littlematch0123/react-admin | 2b80726449e7339ffe2ebebae40435b00fe72680 | [
"MIT"
] | 80 | 2018-06-04T02:36:03.000Z | 2022-02-06T02:46:49.000Z | src/common/ButtonBox.js | wyp0712/blog-admin | 2b80726449e7339ffe2ebebae40435b00fe72680 | [
"MIT"
] | 1 | 2021-08-05T16:14:08.000Z | 2021-08-05T16:14:08.000Z | src/common/ButtonBox.js | wyp0712/blog-admin | 2b80726449e7339ffe2ebebae40435b00fe72680 | [
"MIT"
] | 32 | 2018-06-26T07:57:16.000Z | 2021-06-10T04:53:17.000Z | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import history from '@/utils/history'
import BaseButton from './BaseButton'
import ButtonInverted from './ButtonInverted'
const ButtonBox = ({ className, textForConfirm, textForCancle, onConfirmClick, cancelColor, ...rest }) =>
(
<Wrap className={className} {...rest} >
<BaseButton onClick={onConfirmClick}>{textForConfirm}</BaseButton>
<ButtonInverted onClick={() => { history.goBack() }} cancelColor={cancelColor} >{textForCancle}</ButtonInverted>
</Wrap>
)
ButtonBox.propTypes = {
className: PropTypes.string,
textForConfirm: PropTypes.string,
textForCancle: PropTypes.string,
onConfirmClick: PropTypes.func.isRequired,
cancelColor: PropTypes.string
}
ButtonBox.defaultProps = {
className: '',
textForConfirm: '确定',
textForCancle: '取消',
cancelColor: ''
}
export default ButtonBox
const Wrap = styled.div`
display: flex;
justify-content: center;
align-items: center;
min-width: 100px;
& button {
width: auto;
}
`
| 26.268293 | 118 | 0.717734 |
d1fb453227f0d957876545ee4eb4f9e27c1050aa | 1,276 | js | JavaScript | src/js/components/TeaStats.js | EricVignola/tea-timer | 1ef8852bf17f1b569ce96a46d683e556180daff7 | [
"MIT"
] | null | null | null | src/js/components/TeaStats.js | EricVignola/tea-timer | 1ef8852bf17f1b569ce96a46d683e556180daff7 | [
"MIT"
] | 2 | 2017-12-19T04:26:39.000Z | 2017-12-19T04:46:32.000Z | src/js/components/TeaStats.js | EricVignola/tea-timer | 1ef8852bf17f1b569ce96a46d683e556180daff7 | [
"MIT"
] | null | null | null | import React from 'react';
import ReactDom from 'react-dom';
class TeaStats extends React.Component {
constructor(props){
super(props);
}
render(){
console.log(this.props.showGongFu);
if(this.props.showGongFu){
return(
<div>
<ul style={this.props.style}>
<li style = {{listStyleType: "none"}}>{"Initial Brew (Gong Fu): " + this.props.teas.gongFuInfo.firstInfusion}</li>
<li style = {{listStyleType: "none"}}>{"Subsequent Brew (Gong Fu): " + this.props.teas.gongFuInfo.subsequentInfusion}</li>
</ul>
</div>
);
} else {
return(
<div>
<ul style={this.props.style}>
<li style = {{listStyleType: "none"}}>{"Initial Brew (Western): " + this.props.teas.westernInfo.firstInfusion}</li>
<li style = {{listStyleType: "none"}}>{"Subsequent Brew (Western): " + this.props.teas.westernInfo.subsequentInfusion}</li>
</ul>
</div>
);
}
}
}
export default TeaStats; | 37.529412 | 151 | 0.464734 |
d1fed7161723d92c2853b13f7b06372b3b81acb3 | 1,665 | js | JavaScript | public/template-assets/js/pages/form-masks.js | shahzad001/talent | 7e96bc607c055b1ae8fbcfed23dad4874013fb1c | [
"MIT"
] | null | null | null | public/template-assets/js/pages/form-masks.js | shahzad001/talent | 7e96bc607c055b1ae8fbcfed23dad4874013fb1c | [
"MIT"
] | null | null | null | public/template-assets/js/pages/form-masks.js | shahzad001/talent | 7e96bc607c055b1ae8fbcfed23dad4874013fb1c | [
"MIT"
] | null | null | null | /*
File : form-masks.js
Associated file : form-masks.html
Plugin dependency : plugins/formatter.js/jquery.formatter.min.js
*/
/* =========== Date & Time ================= */
$('#date-input').formatter({
'pattern': '{{9999}}-{{99}}-{{99}}'
});
$('#date-input1').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}'
});
$('#time-demo1').formatter({
'pattern': '{{99}}:{{99}}'
});
$('#date-time').formatter({
'pattern': '{{9999}}/{{99}}/{{99}} {{99}}:{{99}}:{{99}}'
});
$('#time-demo2').formatter({
'pattern': '{{99}}:{{99}}:{{99}}'
});
/* ------------------------------------------------ */
/* =========== Text ================= */
$('#characters-demo').formatter({
'pattern': '{{aaaaaaaaaa}}'
});
/* ------------------------------------------------ */
/* =========== Phone ================= */
$('#phone-demo').formatter({
'pattern': '({{999}}) {{999}}-{{9999}}',
'persistent': true
});
$('#phone-code').formatter({
'pattern': '+91 {{99}}-{{99}}-{{999999}}',
'persistent': true
});
/* ------------------------------------------------ */
/* =========== Currency ================= */
$('#currency-demo').formatter({
'pattern': '$ {{999}}-{{999}}-{{999}}.{{99}}',
'persistent': true
});
/* ------------------------------------------------ */
/* =========== Misc ================= */
$('#credit-demo').formatter({
'pattern': '{{9999}}-{{9999}}-{{9999}}-{{9999}}',
'persistent': true
});
$('#product-key').formatter({
'pattern': 'm{{*}}-{{999}}-{{999}}-C{{99}}',
'persistent': true
});
$('#purchase-code').formatter({
'pattern': 'ISBN{{9999}}-{{9999}}-{{9999}}-{{9999}}',
'persistent': true
});
/* ------------------------------------------------ */ | 26.854839 | 64 | 0.390991 |
d1ff0858d59a2b82a10a192db4dc0e9cc1899bb6 | 1,924 | js | JavaScript | lib/serializer/json.js | rd-uk/rduk-cache | 1fdf54e8c9eb450fe36c16013910b0141bd37142 | [
"MIT"
] | null | null | null | lib/serializer/json.js | rd-uk/rduk-cache | 1fdf54e8c9eb450fe36c16013910b0141bd37142 | [
"MIT"
] | null | null | null | lib/serializer/json.js | rd-uk/rduk-cache | 1fdf54e8c9eb450fe36c16013910b0141bd37142 | [
"MIT"
] | null | null | null | /**
* MIT License
*
* Copyright (c) 2017 Kim Ung <k.ung@rduk.fr>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
'use strict';
var util = require('util');
var errors = require('rduk-errors');
var base = require('./base');
var Promise = require('bluebird');
var JSON_PREFIX = 'data:application/json;base64, ';
var JsonSerializer = function JsonSerializer() {
JsonSerializer.super_.call(this);
};
util.inherits(JsonSerializer, base);
JsonSerializer.prototype.serialize = function(obj) {
return Promise.resolve(JSON_PREFIX + (new Buffer(JSON.stringify(obj))).toString('base64'));
};
JsonSerializer.prototype.deserialize = function(str) {
if (!str || str.indexOf(JSON_PREFIX) < 0) {
errors.throwArgumentError('str', str);
}
return Promise.resolve(JSON.parse((new Buffer(str.split(', ')[1], 'base64')).toString('utf8')));
};
module.exports = JsonSerializer;
| 36.301887 | 100 | 0.730249 |
0600f3a92e2b8a78388088b547c168d297eceb50 | 1,691 | js | JavaScript | src/App.js | conglt10/phonefarm-web | 311182a14e92ed00778b7dfab93de916c47f3509 | [
"MIT"
] | 2 | 2020-11-12T07:33:54.000Z | 2022-03-08T19:42:41.000Z | src/App.js | conglt10/phonefarm-web | 311182a14e92ed00778b7dfab93de916c47f3509 | [
"MIT"
] | null | null | null | src/App.js | conglt10/phonefarm-web | 311182a14e92ed00778b7dfab93de916c47f3509 | [
"MIT"
] | 8 | 2020-10-26T04:24:47.000Z | 2021-03-06T07:07:08.000Z | import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { PageTransition } from '@steveeeie/react-page-transition';
import './App.css';
import PhoneLayout from './Layouts/PhoneLayout';
import LandingPage from './pages/LandingPage';
import Home from './pages/Home';
import Stake from './pages/Stake';
import BuyPhone from 'pages/BuyPhone';
import BuyIphone from 'pages/BuyIphone';
import IphoneCollection from 'pages/IphoneCollection';
function App() {
return (
<Router>
<div className='App'>
{/* <HeaderPage /> */}
<Switch>
<Route exact path='/' component={LandingPage} />
<Route exact path='/phone' component={PhoneLayout} />
{/* Route pages */}
<Route
render={({ location }) => {
let query = new URLSearchParams(location.search);
let preset = query.get('preset') ? query.get('preset') : '';
return (
<PageTransition preset={preset} transitionKey={location.pathname}>
<Switch location={location}>
<Route exact path='/home' component={Home} />
<Route exact path='/stake' component={Stake} />
<Route exact path='/buy-Phone' component={BuyPhone} />
<Route exact path='/buy-Iphone' component={BuyIphone} />
<Route exact path='/collection' component={IphoneCollection} />
</Switch>
</PageTransition>
);
}}
/>
</Switch>
{/* <FooterPage /> */}
</div>
</Router>
);
}
export default App;
| 34.510204 | 83 | 0.558841 |
060142610f5adc33bfd1a8a33c84a8e3b4e89c8f | 635 | js | JavaScript | src/Book.js | timothymcgrath/bookreview | f9674eb7edd27d04206f4ec9865c4e0fc01bcc8a | [
"MIT"
] | null | null | null | src/Book.js | timothymcgrath/bookreview | f9674eb7edd27d04206f4ec9865c4e0fc01bcc8a | [
"MIT"
] | null | null | null | src/Book.js | timothymcgrath/bookreview | f9674eb7edd27d04206f4ec9865c4e0fc01bcc8a | [
"MIT"
] | null | null | null | import './Book.css';
import React, { Component } from 'react';
class Book extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="book">
<div className="bookTitle">{this.props.book.title}</div>
<div className="bookAuthor">{this.props.book.author}</div>
<div>
<span className="bookRating">{this.props.book.rating} out of 5</span>
<span className="bookFinished">{this.props.book.finishedDate}</span>
</div>
<div className="bookReview">{this.props.book.review}</div>
</div>
);
}
}
export default Book;
| 23.518519 | 79 | 0.60315 |
0601cec5b0e85ae341e58eebcf1bdd25c235fa1a | 940 | js | JavaScript | search/files_0.js | open-power-sdk/pveclib.github.io | b414886e2e6cabe765eefd94503e4ebe29683669 | [
"Apache-2.0"
] | null | null | null | search/files_0.js | open-power-sdk/pveclib.github.io | b414886e2e6cabe765eefd94503e4ebe29683669 | [
"Apache-2.0"
] | 1 | 2020-07-18T00:09:33.000Z | 2020-07-18T00:09:33.000Z | search/files_0.js | open-power-sdk/pveclib.github.io | b414886e2e6cabe765eefd94503e4ebe29683669 | [
"Apache-2.0"
] | null | null | null | var searchData=
[
['vec_5fbcd_5fppc_2eh',['vec_bcd_ppc.h',['../vec__bcd__ppc_8h.html',1,'']]],
['vec_5fchar_5fppc_2eh',['vec_char_ppc.h',['../vec__char__ppc_8h.html',1,'']]],
['vec_5fcommon_5fppc_2eh',['vec_common_ppc.h',['../vec__common__ppc_8h.html',1,'']]],
['vec_5ff128_5fppc_2eh',['vec_f128_ppc.h',['../vec__f128__ppc_8h.html',1,'']]],
['vec_5ff32_5fppc_2eh',['vec_f32_ppc.h',['../vec__f32__ppc_8h.html',1,'']]],
['vec_5ff64_5fppc_2eh',['vec_f64_ppc.h',['../vec__f64__ppc_8h.html',1,'']]],
['vec_5fint128_5fppc_2eh',['vec_int128_ppc.h',['../vec__int128__ppc_8h.html',1,'']]],
['vec_5fint16_5fppc_2eh',['vec_int16_ppc.h',['../vec__int16__ppc_8h.html',1,'']]],
['vec_5fint32_5fppc_2eh',['vec_int32_ppc.h',['../vec__int32__ppc_8h.html',1,'']]],
['vec_5fint512_5fppc_2eh',['vec_int512_ppc.h',['../vec__int512__ppc_8h.html',1,'']]],
['vec_5fint64_5fppc_2eh',['vec_int64_ppc.h',['../vec__int64__ppc_8h.html',1,'']]]
];
| 62.666667 | 87 | 0.676596 |
06028d504b326f541ec362ac7bc05f1bd297a965 | 522 | js | JavaScript | test/testRedisConn.js | RajithaKumara/Best-Fit-Job-Server | 35d6c8199c85b7a1401748cb8eab12030f026f62 | [
"MIT"
] | 4 | 2020-07-29T17:42:17.000Z | 2021-12-14T12:44:17.000Z | test/testRedisConn.js | RajithaKumara/Best-Fit-Job-Server | 35d6c8199c85b7a1401748cb8eab12030f026f62 | [
"MIT"
] | 3 | 2019-06-03T17:25:59.000Z | 2019-07-13T17:59:52.000Z | test/testRedisConn.js | RajithaKumara/Best-Fit-Job-Server | 35d6c8199c85b7a1401748cb8eab12030f026f62 | [
"MIT"
] | null | null | null | const redis = require('redis');
const { redisDbLocalURI } = require('./testData');
class RedisConn {
constructor() {
}
getConnection() {
this.client = redis.createClient(redisDbLocalURI || process.env.REDIS_TEST_URL);
this.client.on("error", function (err) {
console.log("Redis_Error: ", err);
});
this.client.select(1);
return this.client;
}
closeConnection(client) {
try {
client.quit();
} catch (e) {
console.log(e);
}
}
}
module.exports = RedisConn; | 18 | 84 | 0.611111 |
060302fc7edb045cd8bb72ab6a9ea2415fc7bdd3 | 328 | js | JavaScript | models/listItem.js | BingKui/wechat_splider | 17a63d7039e80eadc25d9fb5e1d496136f568e85 | [
"MIT"
] | null | null | null | models/listItem.js | BingKui/wechat_splider | 17a63d7039e80eadc25d9fb5e1d496136f568e85 | [
"MIT"
] | null | null | null | models/listItem.js | BingKui/wechat_splider | 17a63d7039e80eadc25d9fb5e1d496136f568e85 | [
"MIT"
] | null | null | null | let mongolass = require('../common/mongo');
let ListItem = mongolass.model('listItem', {
name: {
type: 'string'
},
account: {
type: 'string'
},
desc: {
type: 'string'
},
date: {
type: 'string'
},
url: {
type: 'string'
}
});
ListItem.index({
name: 1
}, {
unique: true
}).exec();
module.exports = ListItem; | 12.615385 | 44 | 0.573171 |
0603f3fe4bf6f8e33e982eb7c15f1cb01e2a247d | 2,651 | js | JavaScript | lib/datatypes.js | NeoXiD/modelize | e50884c2e887330d2e83078c49c14a53a3b70819 | [
"Apache-2.0"
] | 1 | 2015-11-05T15:38:17.000Z | 2015-11-05T15:38:17.000Z | lib/datatypes.js | NeoXiD/modelize | e50884c2e887330d2e83078c49c14a53a3b70819 | [
"Apache-2.0"
] | null | null | null | lib/datatypes.js | NeoXiD/modelize | e50884c2e887330d2e83078c49c14a53a3b70819 | [
"Apache-2.0"
] | null | null | null | var DataTypes = (function() {
/**
* A basic data type
* @interface
* @private
*/
function DataType() {}
DataType.prototype = {
/**
* Name of the data type
* @type {String}
*/
name: 'undefined',
/**
* Checks if the data is valid
* @param data Data to check
* @return {Boolean}
*/
isValid: function(data) {
return true;
}
};
/**
* String data type
* @constructor
* @implements DataType
* @private
*/
var TypeString = function() {};
TypeString.prototype = Object.create(DataType);
TypeString.prototype.name = 'string';
TypeString.prototype.isValid = function(data) {
return typeof(data) == 'string';
};
/**
* Number data type
* @constructor
* @implements DataType
* @private
*/
var TypeNumber = function() {};
TypeNumber.prototype = Object.create(DataType);
TypeNumber.prototype.name = 'number';
TypeNumber.prototype.isValid = function(data) {
return typeof !isNaN(data) && isFinite(data);
};
/**
* Array data type
* @constructor
* @implements DataType
* @private
*/
var TypeArray = function() {};
TypeArray.prototype = Object.create(DataType);
TypeArray.prototype.name = 'array';
TypeArray.prototype.isValid = function(data) {
return data && data.constructor == Array;
};
/**
* Object data type
* @constructor
* @implements DataType
* @private
*/
var TypeObject = function() {};
TypeObject.prototype = Object.create(DataType);
TypeObject.prototype.name = 'object';
TypeObject.prototype.isValid = function(data) {
return data && data.constructor == Object;
};
/**
* Object which contains all the valid property types
* @type {Object}
* @private
*/
var types = {
string: new TypeString(),
number: new TypeNumber(),
array: new TypeArray(),
object: new TypeObject()
};
return {
/**
* Checks if the specified type is valid
* @param {String} type Data type to check
* @return {Boolean}
*/
isValidType: function(type) {
return types.hasOwnProperty(type);
},
getType: function(type) {
// Check if type is valid
if(!this.isValidType(type)) {
throw new Error('Invalid data type: ' + type);
}
return types[type];
}
};
})();
module.exports = DataTypes; | 24.1 | 62 | 0.53791 |
0604940899d1b1d19803ac17d17002b765d626d2 | 780 | js | JavaScript | app/assets/javascripts/table_for.js | PauSentis/ct_table_for | 7a0d493fc675e1d1a01b8030d3cf5f549957092a | [
"MIT"
] | 2 | 2017-05-04T06:49:38.000Z | 2019-11-15T21:55:34.000Z | app/assets/javascripts/table_for.js | PauSentis/ct_table_for | 7a0d493fc675e1d1a01b8030d3cf5f549957092a | [
"MIT"
] | 16 | 2017-09-29T11:50:12.000Z | 2021-02-19T16:12:29.000Z | app/assets/javascripts/table_for.js | PauSentis/ct_table_for | 7a0d493fc675e1d1a01b8030d3cf5f549957092a | [
"MIT"
] | 7 | 2017-05-04T07:59:51.000Z | 2019-08-26T12:54:57.000Z | // Clickable table rows.
// Set the class 'table-clickable' in table and
// in tr set 'data-link' and (optional) 'data-target'
// in td set 'data-link-enabled' to false for disable in specicif cells
$('table.table-clickable').each(function(index, table){
$(table).find('tbody tr').each(function(index, trow){
$(trow).click(function(evnt){
var link = $(this).attr('data-link');
var linkTarget = $(this).attr('data-target');
var linkEnabled = true
if( $(evnt.target).attr('data-link-enabled') == 'false' ||
$(evnt.target).parents('td[data-link-enabled="false"]').length > 0 ){
linkEnabled= false
}
if( !linkTarget ){ linkTarget = '_self'; }
if( link && linkEnabled){ window.open(link, linkTarget); }
});
});
}); | 39 | 77 | 0.615385 |
0604ce4ee1ef125a3b54085b65895fabc3aa1a58 | 400 | js | JavaScript | controller/BaseController.js | lukasrochaaraujo/base-web-js-core | c94c46872e279ff803af1c990df2e7052275df70 | [
"MIT"
] | null | null | null | controller/BaseController.js | lukasrochaaraujo/base-web-js-core | c94c46872e279ff803af1c990df2e7052275df70 | [
"MIT"
] | null | null | null | controller/BaseController.js | lukasrochaaraujo/base-web-js-core | c94c46872e279ff803af1c990df2e7052275df70 | [
"MIT"
] | null | null | null | class BaseController {
/**
* BaseController
* @param {Object} view - instância de uma classe View
* @param {Object} service - instância de uma classe Service
*/
constructor(serviceInstance, viewInstance) {
this._service = serviceInstance;
this._view = viewInstance;
}
start() {
}
stop() {
this._service.abortRequests();
}
} | 21.052632 | 65 | 0.5925 |
0605510130432dd04f5e46468ff288e41a633c21 | 491 | js | JavaScript | komutlar/function.js | ahmetysl/zerotwo | 084b74592c7b6bab348f30712823ddb4a4a781c1 | [
"Apache-2.0"
] | null | null | null | komutlar/function.js | ahmetysl/zerotwo | 084b74592c7b6bab348f30712823ddb4a4a781c1 | [
"Apache-2.0"
] | null | null | null | komutlar/function.js | ahmetysl/zerotwo | 084b74592c7b6bab348f30712823ddb4a4a781c1 | [
"Apache-2.0"
] | null | null | null | module.exports = ({
name: "function",
code: ` $title[$jsonRequest[https://dbdjs.leref.ga/functions/$message;name]] $description[ **Kullanım:** $jsonRequest[https://dbdjs.leref.ga/functions/$message;usage]
**Açıklama:** $jsonRequest[https://dbdjs.leref.ga/functions/$message;description]]
$color[WHİTE]
$onlyif[$jsonRequest[https://dbdjs.leref.ga/functions/$message;name]!=;Hata, komut bulunamadı!]
$footer[Kullanım ve açıklama gibi bazı satırlar boş olabilir.]
$addtimestamp`
})
| 35.071429 | 170 | 0.731161 |
06055a12d92c40c05d48c4969793b82bc1650264 | 1,213 | js | JavaScript | windi.config.js | dieUrbans/uniform | ce6c7f3dbca22738f1d5dcec4d1019e809483748 | [
"MIT"
] | 4 | 2022-02-17T14:19:39.000Z | 2022-03-22T14:32:04.000Z | windi.config.js | dieUrbans/uniform | ce6c7f3dbca22738f1d5dcec4d1019e809483748 | [
"MIT"
] | 14 | 2022-03-15T14:38:40.000Z | 2022-03-24T08:44:57.000Z | windi.config.js | dieUrbans/uniform | ce6c7f3dbca22738f1d5dcec4d1019e809483748 | [
"MIT"
] | null | null | null | module.exports = {
shortcuts: {
'border-radius': 'rounded-2xl',
'error': 'bg-white border-red-600 text-red-600 hover:shadow-red-300 hover:border-red-700 transition-all duration-200',
'error-fill': 'bg-red-600 text-light-200 hover:bg-red-700',
'success': 'bg-white border-green-500 text-green-500 hover:shadow-green-300 hover:border-green-600 transition-all duration-200',
'success-fill': 'bg-green-500 text-light-200 hover:bg-green-600',
'warning': 'bg-white border-yellow-400 text-yellow-600 hover:shadow-yellow-300 hover:border-yellow-500 transition-all duration-200',
'warning-fill': 'bg-yellow-400 text-dark-200 hover:bg-yellow-500',
'primary': 'bg-white border-blue-500 text-blue-500 hover:shadow-blue-300 hover:border-blue-600 transition-all duration-200',
'primary-fill': 'bg-blue-500 text-light-200 hover:bg-blue-600',
'secondary': 'bg-white border-blue-gray-200 text-blue-gray-500 hover:shadow-blue-gray-200 hover:border-blue-gray-300 transition-all duration-200',
'secondary-fill': 'bg-blue-gray-200 text-dark-200 hover:bg-blue-gray-300',
},
plugins: [
require('@windicss/plugin-icons'),
]
} | 67.388889 | 154 | 0.685078 |
06058b566778cdec3f095450785d7830bd8a3ac4 | 74 | js | JavaScript | packages/babel-parser/test/fixtures/estree/class-method/typescript/input.js | wuweiweiwu/babel | 296d8ce179cac84f981933efcd892ec0c6e2a93b | [
"MIT"
] | 42,609 | 2015-02-15T11:13:42.000Z | 2022-03-31T23:15:22.000Z | packages/babel-parser/test/fixtures/estree/class-method/typescript/input.js | wuweiweiwu/babel | 296d8ce179cac84f981933efcd892ec0c6e2a93b | [
"MIT"
] | 12,279 | 2015-02-15T11:12:05.000Z | 2022-03-31T20:55:01.000Z | packages/babel-parser/test/fixtures/estree/class-method/typescript/input.js | wuweiweiwu/babel | 296d8ce179cac84f981933efcd892ec0c6e2a93b | [
"MIT"
] | 7,321 | 2015-02-15T15:45:23.000Z | 2022-03-31T20:04:22.000Z | abstract class TSAbstractClass {
abstract foo(name: string): boolean;
}
| 18.5 | 38 | 0.756757 |
0605bda08a60b3e2b86a277a6fbb640357ee0ef1 | 2,067 | js | JavaScript | client/js/controllers/questionsModal-controller.js | Tumne/apartmate | 75de7f4134cf13de80a5bfe2604d23fdd3746a9e | [
"MIT"
] | null | null | null | client/js/controllers/questionsModal-controller.js | Tumne/apartmate | 75de7f4134cf13de80a5bfe2604d23fdd3746a9e | [
"MIT"
] | null | null | null | client/js/controllers/questionsModal-controller.js | Tumne/apartmate | 75de7f4134cf13de80a5bfe2604d23fdd3746a9e | [
"MIT"
] | null | null | null | angular.module('angular-client-side-auth')
.controller('QuestionsModalCtrl',
['$rootScope', '$scope', '$location', '$window', '$modalInstance', 'questions', 'Auth', 'QuestionsListing', function($rootScope, $scope, $location, $window, $modalInstance, questions, Auth, QuestionsListing) {
$scope.questions = questions;
console.log($scope.questions);
$scope.qIndex = 0;
var completed = false;
function initAnswerInput(){
angular.forEach($scope.questions[$scope.qIndex].options, function (item) {
item.selected = false;
});
$scope.result = {
qid: $scope.questions[$scope.qIndex].qid,
answer:null,
acceptable: [],
importance: null
};
}
initAnswerInput();
$scope.submitQuestion = function(){
if($scope.questions.length - 1 == $scope.qIndex) completed = true;
QuestionsListing.addQuestionById({
email: $rootScope.user.emailAddress,
result: $scope.result,
completed: completed
},
function(res) {
console.log(res.propertySaved);
console.log(res.userSaved);
if($scope.qIndex < $scope.questions.length - 1){
$scope.qIndex++;
initAnswerInput();
} else {
console.log("close modal");
$modalInstance.close();
}
},
function(err) {
$rootScope.error = err.message;
});
};
$scope.clickAcceptable = function(_id, $event){
var checkbox = $event.target;
if(checkbox.checked){
$scope.result.acceptable.push({"id": _id});
} else {
var i = -1;
angular.forEach($scope.result.acceptable, function(value, key){
if(value.id == _id){
i = key;
}
});
if(i != -1 ) {
$scope.result.acceptable.splice(i, 1);
}
}
};
$scope.clickImportance = function(_value){
console.log(_value);
$scope.result.importance = _value;
};
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
| 22.225806 | 209 | 0.585389 |
06065f08a4b7ace4d8490a50b08e889e0f6bb5f6 | 1,434 | js | JavaScript | CORS/server/index.js | pfortuna/appsec-training | 7f5cc49344480259a0c0770e74f257a3b6dcb2de | [
"MIT"
] | null | null | null | CORS/server/index.js | pfortuna/appsec-training | 7f5cc49344480259a0c0770e74f257a3b6dcb2de | [
"MIT"
] | null | null | null | CORS/server/index.js | pfortuna/appsec-training | 7f5cc49344480259a0c0770e74f257a3b6dcb2de | [
"MIT"
] | null | null | null | var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
var allowedOrigins = ['http://foo.com',
'http://not-example.org'];
app.options('/delete/:id', function(req, res, next) {
console.log("options request!");
next();
});
app.use(cors({
origin: function(origin, callback){
// allow requests with no origin
// (like mobile apps or curl requests)
if(!origin) return callback(null, true);
console.log("Checking origin: "+origin);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/auth', function(req, res) {
var username = req.body.username;
var password = req.body.password;
var response = `${username} authenticated with password ${password}`;
console.log(response);
res.send(response);
});
app.delete('/delete/:id', function(req, res, next) {
console.log('delete attempt of ' + req.params.id);
res.send(req.params.id + ' deleted!');
});
app.get('/', function(req, res) {
res.send("http://bar.com:3000/");
});
app.listen(3000, function() {
console.log('Server is running at PORT 3000');
});
| 27.576923 | 71 | 0.633891 |
0606c37733b8124f68adc67401d9dbd4c740e94c | 1,539 | js | JavaScript | build/parser/SyntaxRuleSet.js | FabianLauer/tsxml | 8430adffb7994a9b94ea4452a27814d8d8ebf8c3 | [
"MIT"
] | 4 | 2017-08-28T16:32:00.000Z | 2021-06-14T00:34:13.000Z | build/parser/SyntaxRuleSet.js | FabianLauer/tsxml | 8430adffb7994a9b94ea4452a27814d8d8ebf8c3 | [
"MIT"
] | 18 | 2016-05-05T13:28:50.000Z | 2020-08-11T14:09:56.000Z | build/parser/SyntaxRuleSet.js | FabianLauer/tsxml | 8430adffb7994a9b94ea4452a27814d8d8ebf8c3 | [
"MIT"
] | 5 | 2016-12-22T05:42:20.000Z | 2021-08-03T09:28:46.000Z | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SyntaxRuleSet = /** @class */ (function () {
function SyntaxRuleSet() {
this.tagSyntaxRules = [];
}
/**
* Creates an instance of the syntax rule set class this static method is called on.
*/
SyntaxRuleSet.createInstance = function () {
return new this();
};
SyntaxRuleSet.isSyntaxRuleSetClass = function (candidate) {
return (typeof candidate === 'function' && candidate._syntaxRuleSetBrand_ === SyntaxRuleSet._syntaxRuleSetBrand_);
};
SyntaxRuleSet.prototype.hasTagSyntaxRule = function (rule) {
return this.tagSyntaxRules.indexOf(rule) !== -1;
};
SyntaxRuleSet.prototype.getAllTagSyntaxRules = function () {
return [].concat(this.tagSyntaxRules);
};
/**
* @chainable
*/
SyntaxRuleSet.prototype.addTagSyntaxRule = function (rule) {
if (!this.hasTagSyntaxRule(rule)) {
this.tagSyntaxRules.push(rule);
}
return this;
};
/**
* @chainable
*/
SyntaxRuleSet.prototype.addTagSyntaxRules = function () {
var _this = this;
var rules = [];
for (var _i = 0; _i < arguments.length; _i++) {
rules[_i] = arguments[_i];
}
rules.forEach(function (rule) { return _this.addTagSyntaxRule(rule); });
return this;
};
SyntaxRuleSet._syntaxRuleSetBrand_ = Math.random();
return SyntaxRuleSet;
}());
exports.SyntaxRuleSet = SyntaxRuleSet;
| 32.744681 | 122 | 0.615335 |
060708491ad6174921f7fcf30cf96363072022db | 1,765 | js | JavaScript | lib/partition.js | jhermsmeier/node-ramdisk | 18c640571c0137b91bb6bdf1e2f370ba036f39fa | [
"MIT"
] | 3 | 2015-04-23T23:03:38.000Z | 2022-03-31T07:59:56.000Z | lib/partition.js | jhermsmeier/node-ramdisk | 18c640571c0137b91bb6bdf1e2f370ba036f39fa | [
"MIT"
] | null | null | null | lib/partition.js | jhermsmeier/node-ramdisk | 18c640571c0137b91bb6bdf1e2f370ba036f39fa | [
"MIT"
] | 1 | 2015-11-07T09:33:11.000Z | 2015-11-07T09:33:11.000Z | /**
* Partition Constructor
* @param {Object} options
* @property {Number} firstLBA
* @property {Number} lastLBA
* @return {Partition}
*/
function Partition( device, options ) {
if( !(this instanceof Partition) )
return new Partition( device, options )
this.device = device
this.firstLBA = options.firstLBA || 0
this.lastLBA = options.lastLBA || -1
}
/**
* Partition Prototype
* @type {Object}
*/
Partition.prototype = {
constructor: Partition,
__OOB: function( lba ) {
return lba < this.firstLBA ||
lba > this.lastLBA
},
get blockSize() {
return this.device.blockSize
},
get sectors() {
return this.lastLBA - this.firstLBA
},
get size() {
return this.sectors * this.blockSize
},
readBlocks: function( from, to, buffer, callback ) {
callback = callback.bind( this )
from = from + this.firstLBA
to = to + this.firstLBA
if( this.__OOB( from ) || this.__OOB( to ) ) {
var msg = 'Block address out of bounds: ' +
'['+from+','+to+'] not in range ' +
'['+this.firstLBA+','+this.lastLBA+']'
return callback( new Error( msg ) )
}
this.device.readBlocks( from, to, buffer, callback )
return this
},
writeBlocks: function( from, data, callback ) {
callback = callback.bind( this )
from = from + this.firstLBA
if( this.__OOB( from ) ) {
var msg = 'Block address out of bounds: ' +
'['+from+','+to+'] not in range ' +
'['+this.firstLBA+','+this.lastLBA+']'
return callback( new Error( msg ) )
}
this.device.writeBlocks( from, data, callback )
return this
},
}
// Exports
module.exports = Partition
| 20.056818 | 56 | 0.573371 |
0608b28d2b15f7bba46dacf83c16bceb4e7d271c | 1,153 | js | JavaScript | app/components/header/header.js | namnhtc/web-app | 4e4a3f48c6d9379cf5a213c4ee09cb5ac0151b0b | [
"MIT"
] | null | null | null | app/components/header/header.js | namnhtc/web-app | 4e4a3f48c6d9379cf5a213c4ee09cb5ac0151b0b | [
"MIT"
] | null | null | null | app/components/header/header.js | namnhtc/web-app | 4e4a3f48c6d9379cf5a213c4ee09cb5ac0151b0b | [
"MIT"
] | null | null | null | (function(angular) {
'use strict';
function HeaderCtrl($scope, $rootScope, $location, AuthService, $modal) {
$scope.$on('$routeChangeSuccess', function() {
$scope.path = $location.path();
});
$scope.logout = function() {
AuthService.logout();
};
$scope.menus = [{
'title': 'Trang chủ',
'link': '/'
},
// {'title': 'Thảo luận', 'link': '/discussion'}
];
$scope.showShortcutPopup = function() {
var modalInstance = $modal.open({
templateUrl: 'components/header/_keyboard.html',
controller: 'ModalInstanceCtrl',
windowClass: 'box-shortcuts"'
});
modalInstance.result.then(function(msg) {
if ($scope[msg] instanceof Function) $scope[msg]();
});
};
}
angular.module('header', []);
angular.module('header').controller('HeaderCtrl', ['$rootScope', '$scope', '$location', 'AuthService', '$modal', HeaderCtrl])
.controller('ModalInstanceCtrl', ['$scope','$modalInstance', function($scope, $modalInstance) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
}(window.angular)); | 27.452381 | 127 | 0.584562 |
0608f61a64f2c7b4e94db3ba10cbdcfd5d7966e1 | 1,769 | js | JavaScript | node_modules/plivo/dist/utils/restException.js | plivo/actions-call | 05b41a249ca3a10359da9efda191193079f26a73 | [
"MIT"
] | 10 | 2021-05-25T12:17:26.000Z | 2021-12-17T12:17:45.000Z | node_modules/plivo/dist/utils/restException.js | plivo/actions-call | 05b41a249ca3a10359da9efda191193079f26a73 | [
"MIT"
] | 1 | 2021-05-24T13:59:29.000Z | 2021-05-24T13:59:29.000Z | node_modules/plivo/dist/utils/restException.js | plivo/actions-sms | 653e8158d5330321a08a5399fc928f35dd31f632 | [
"MIT"
] | null | null | null | 'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var PlivoRestError = function (_Error) {
_inherits(PlivoRestError, _Error);
function PlivoRestError(response) {
_classCallCheck(this, PlivoRestError);
response = response.response;
var body;
var _this = _possibleConstructorReturn(this, (PlivoRestError.__proto__ || Object.getPrototypeOf(PlivoRestError)).call(this, '[HTTP ' + response.status + '] Failed to execute request'));
try {
body = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
} catch (err) {
body = { "error": response.data, "api_id": '' };
}
_this.status = response.status;
_this.statusText = response.statusText;
_this.message = body.error;
_this.apiID = body.api_id;
_this.moreInfo = response.config.data;
return _this;
}
return PlivoRestError;
}(Error);
module.exports = PlivoRestError; | 49.138889 | 494 | 0.710006 |
060a63178111f380aaffe5846e3d719cca08b4f5 | 14,020 | js | JavaScript | 12-Binary-Search-Tree/03-BST-Iterative.js | aditya43/data-structures-algorithms | 211f60f43ea6f50fa9ce2e335fa2e2bfedbe6228 | [
"MIT"
] | null | null | null | 12-Binary-Search-Tree/03-BST-Iterative.js | aditya43/data-structures-algorithms | 211f60f43ea6f50fa9ce2e335fa2e2bfedbe6228 | [
"MIT"
] | null | null | null | 12-Binary-Search-Tree/03-BST-Iterative.js | aditya43/data-structures-algorithms | 211f60f43ea6f50fa9ce2e335fa2e2bfedbe6228 | [
"MIT"
] | null | null | null | // Binary Search Tree - iterative version
// Write a function on the BinarySearchTree class
// insert
// This function should accept a value and insert it into the BST in the correct
// position. It should return the binary search tree.
// find
// This function should find a node in a binary tree. It should return the node
// if found, otherwise return `null`.
// remove
// This function should remove a node from a binary search tree.
// Your remove function should be able to handle removal of the root node,
// removal of a node with one child and removal of a node with two children.
// The function should return the node removed.
// findSecondLargest
// This function should find 2nd largest node.
// isBalanced
// This function should return true if the BST is balanced, otherwise false.
// A balanced tree is defined as a tree where the depth of all leaf nodes or
// nodes with single children differ by no more than one.
// breadthFirstSearch
// This function should search through each node in the binary search tree
// using breadth first search and return an array containing each node's value.
// depthFirstSearchPreOrder
// This function should search through each node in the binary search tree using
// pre-order depth first search and return an array containing each node's value.
// depthFirstSearchPostOrder
// This function should search through each node in the binary search tree using
// post-order depth first search and return an array containing each node's value.
// depthFirstSearchInOrder
// This function should search through each node in the binary search tree using
// in-order depth first search and return an array containing each node's value.
// Additionally, the following methods are implemented on the class:
// getHeight - returns the height of the tree
// findMin/Max - returns node with min/max value in the binary tree
// invert - invert the current tree structure (produce a tree that is equivalently
// the mirror image of the current tree)
class BinarySearchTreeNode {
constructor (data) {
this.data = data;
this.left = null;
this.right = null;
}
};
class QueueNode {
constructor (val) {
this.val = val;
this.next = null;
}
}
class Queue {
constructor () {
this.size = 0;
this.head = this.tail = null;
}
enqueue (val) {
const node = new QueueNode(val);
if (this.size === 0) {
this.head = this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
return ++this.size;
}
dequeue () {
if (this.size === 0) {
return -1;
}
const node = this.head;
if (this.size === 1) {
this.head = this.tail = null;
} else {
this.head = node.next;
}
this.size--;
return node;
}
}
class StackNode {
constructor (val) {
this.val = val;
this.next = null;
}
}
class Stack {
constructor () {
this.size = 0;
this.first = null;
this.last = null;
}
push (val) {
const node = new StackNode(val);
if (this.size === 0) {
this.first = this.last = node;
} else {
node.next = this.first;
this.first = node;
}
return ++this.size;
}
pop () {
if (this.size === 0) {
return null;
}
const node = this.first;
if (this.size === 1) {
this.first = this.last = null;
} else {
this.first = this.first.next;
}
this.size--;
return node;
}
}
class BinarySearchTree {
constructor () {
this.root = null;
}
getHeight (node = this.root) {
if (!node) return 0;
let height = 1;
const queue = new Queue();
queue.enqueue(node);
queue.enqueue('stop');
while (queue.size > 1) {
const currentNode = queue.dequeue();
if (currentNode === 'stop') {
height++;
queue.enqueue('stop');
} else {
if (currentNode.left) queue.enqueue(currentNode.left);
if (currentNode.right) queue.enqueue(currentNode.right);
}
}
return height;
}
isBalanced (node = this.root) {
if (!node) return true;
const stack = new Stack();
const depths = new Map();
stack.push([node, false]);
while (stack.size) {
const [currentNode, seen] = stack.pop();
if (!seen) {
stack.push([currentNode, true]);
if (currentNode.right) stack.push([currentNode.right, 0]);
if (currentNode.left) stack.push([currentNode.left, 0]);
} else {
const left = depths.get(currentNode.left) || 0;
const right = depths.get(currentNode.right) || 0;
if (Math.abs(left - right) > 1) return false;
depths.set(currentNode, Math.max(left, right) + 1);
}
}
return true;
}
insert (data, node = this.root) {
const newNode = new BinarySearchTreeNode(data);
if (!node) {
this.root = newNode;
return this;
}
let currentNode = node;
while (true) {
if (newNode.data === currentNode.data) return this;
if (newNode.data < currentNode.data) {
if (!currentNode.left) {
currentNode.left = newNode;
return this;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = newNode;
return this;
}
currentNode = currentNode.right;
}
}
}
find (data, node = this.root) {
let currentNode = node;
while (currentNode) {
if (data === currentNode.data) return currentNode;
if (data < currentNode.data) currentNode = currentNode.left;
else currentNode = currentNode.right;
}
return null;
}
contains (data, node = this.root) {
return !!this.find(data, node);
}
findMin (node = this.root) {
if (!node) return null;
let currentNode = node;
while (currentNode.left) {
currentNode = currentNode.left;
}
return currentNode;
}
findMax (node = this.root) {
if (!node) return null;
let currentNode = node;
while (currentNode.right) {
currentNode = currentNode.right;
}
return currentNode;
}
findSecondLargest (node = this.root) {
if (!node) return null;
let parent = null;
let currentNode = node;
while (currentNode.right) {
parent = currentNode;
currentNode = currentNode.right;
}
return currentNode.left ? this.findMax(currentNode.left) : parent;
}
invert (node = this.root) {
if (!node) return null;
const queue = new Queue();
queue.enqueue(node);
while (queue.size) {
const currentNode = queue.dequeue();
if (currentNode.left) queue.enqueue(currentNode.left);
if (currentNode.right) queue.enqueue(currentNode.right);
[currentNode.left, currentNode.right] = [currentNode.right, currentNode.left];
}
return node;
}
findNodeWithParent (data) {
let parentNode = null;
let currentNode = this.root;
while (currentNode) {
if (data === currentNode.data) break;
parentNode = currentNode;
if (data < currentNode.data) currentNode = currentNode.left;
else currentNode = currentNode.right;
}
return { parentNode, currentNode };
}
findNextBigNodeWithParent (node = this.root) {
let nextBigNodeParent = node;
if (!nextBigNodeParent || !nextBigNodeParent.right) {
return { nextBigNodeParent, nextBigNode: null };
}
let nextBigNode = node.right;
while (nextBigNode.left) {
nextBigNodeParent = nextBigNode;
nextBigNode = nextBigNode.left;
}
return { nextBigNodeParent, nextBigNode };
}
remove (data) {
const { parentNode, currentNode } = this.findNodeWithParent(data);
if (!currentNode) return null;
const removedNode = Object.assign({}, currentNode,
{ left: null, right: null });
// Node has no children.
if (!currentNode.left && !currentNode.right) {
// Node is the root and has no parent
if (!parentNode) {
this.root = null;
// Node is the left child
} else if (parentNode.left && parentNode.left.data === data) {
parentNode.left = null;
// Node is the right child
} else if (parentNode.right && parentNode.right.data === data) {
parentNode.right = null;
}
// Node has two children.
} else if (currentNode.left && currentNode.right) {
// Find the next biggest node (minimum node in the right branch)
// to replace current node with.
const { nextBigNode, nextBigNodeParent } = this.findNextBigNodeWithParent(currentNode);
currentNode.data = nextBigNode.data;
// Node is direct parent of the next biggest node
if (nextBigNodeParent === currentNode) nextBigNodeParent.right = nextBigNode.right;
// Node is not direct parent of the next biggest node
else nextBigNodeParent.left = nextBigNode.right;
// Node has only one child.
} else {
const nextNode = currentNode.left || currentNode.right;
currentNode.data = nextNode.data;
currentNode.left = nextNode.left;
currentNode.right = nextNode.right;
}
return removedNode;
}
breadthFirstSearch (node = this.root) {
const data = [];
if (!node) return data;
const queue = new Queue();
queue.enqueue(node);
while (queue.size) {
const currentNode = queue.dequeue();
if (currentNode.left) queue.enqueue(currentNode.left);
if (currentNode.right) queue.enqueue(currentNode.right);
data.push(currentNode.data);
}
return data;
}
depthFirstSearchPreOrder (node = this.root) {
const data = [];
if (!node) return data;
const stack = new Stack();
stack.push(node);
while (stack.size) {
const currentNode = stack.pop();
if (currentNode.right) stack.push(currentNode.right);
if (currentNode.left) stack.push(currentNode.left);
data.push(currentNode.data);
}
return data;
}
depthFirstSearchPostOrder (node = this.root) {
const data = [];
if (!node) return data;
const stack = new Stack();
stack.push(node);
while (stack.size) {
const currentNode = stack.pop();
if (currentNode.left) stack.push(currentNode.left);
if (currentNode.right) stack.push(currentNode.right);
data.push(currentNode.data);
}
data.reverse();
return data;
}
depthFirstSearchInOrder (node = this.root) {
const stack = new Stack();
const data = [];
let currentNode = node;
while (currentNode || stack.size) {
while (currentNode) {
stack.push(currentNode);
currentNode = currentNode.left;
}
currentNode = stack.pop();
data.push(currentNode.data);
currentNode = currentNode.right;
}
return data;
}
}
const binarySearchTree1 = new BinarySearchTree();
binarySearchTree1.insert(15).insert(20)
.insert(10)
.insert(12)
.insert(8)
.insert(13);
console.log('min', binarySearchTree1.findMin().data); // 8
console.log('max', binarySearchTree1.findMax().data); // 20
console.log(binarySearchTree1.contains(10)); // true
console.log(binarySearchTree1.remove(10)); // { data: 10, left: null, right: null }
console.log(binarySearchTree1.root.data); // 15
console.log(binarySearchTree1.root.left.data); // 12
console.log(binarySearchTree1.root.left.right.data); // 13
console.log(binarySearchTree1.root.left.left.data); // 8
console.log(binarySearchTree1.getHeight()); // 3
console.log(binarySearchTree1.isBalanced()); // true
const binarySearchTree2 = new BinarySearchTree();
binarySearchTree2.insert(22).insert(49)
.insert(85)
.insert(66)
.insert(95)
.insert(90)
.insert(100)
.insert(88)
.insert(93)
.insert(89);
binarySearchTree2.remove(85);
console.log(binarySearchTree2.root.data); // 22
console.log(binarySearchTree2.root.right.right.data); // 88
console.log(binarySearchTree2.root.right.right.right.left.left.data); // 89
console.log(binarySearchTree2.findSecondLargest().data); // 95
console.log(binarySearchTree2.breadthFirstSearch()); // [ 22, 49, 88, 66, 95, 90, 100, 89, 93 ]
console.log(binarySearchTree2.depthFirstSearchPreOrder()); // [ 22, 49, 88, 66, 95, 90, 89, 93, 100 ]
console.log(binarySearchTree2.depthFirstSearchPostOrder()); // [ 66, 89, 93, 90, 100, 95, 88, 49, 22 ]
console.log(binarySearchTree2.depthFirstSearchInOrder()); // [ 22, 49, 66, 88, 89, 90, 93, 95, 100 ]
console.log(binarySearchTree2.getHeight()); // 6
console.log(binarySearchTree2.isBalanced()); // false
binarySearchTree2.invert();
console.log(binarySearchTree2.depthFirstSearchInOrder()); // [ 100, 95, 93, 90, 89, 88, 66, 49, 22 ]
| 27.984032 | 102 | 0.577817 |
060ac3da91baf8aa9eaaa02849de495d02ec34b5 | 781 | js | JavaScript | fns/getAppInfo.js | robinfehr/cf-adapter | 70aa01b0a694323b747db6103801dda12e699d99 | [
"Apache-2.0"
] | 5 | 2016-04-29T16:22:45.000Z | 2020-05-20T07:36:18.000Z | fns/getAppInfo.js | robinfehr/cf-adapter | 70aa01b0a694323b747db6103801dda12e699d99 | [
"Apache-2.0"
] | 3 | 2016-09-13T14:05:13.000Z | 2020-07-15T19:45:24.000Z | fns/getAppInfo.js | robinfehr/cf-adapter | 70aa01b0a694323b747db6103801dda12e699d99 | [
"Apache-2.0"
] | 4 | 2019-04-29T12:00:55.000Z | 2020-10-13T11:17:12.000Z | module.exports = (api) => {
return (options, callback) => {
options = options || {};
if (!options.name) {
return callback(new Error('Please provide a name! \n' + JSON.stringify(options, null, 2)));
}
if (!api.spaceGuid) {
return callback(new Error('Please provide a space! \n' + JSON.stringify(options, null, 2)));
}
api.graceRequest({
method: 'GET',
uri: `/v2/spaces/${api.spaceGuid}/apps`,
qs: {
'q': `name:${options.name}`
}
}, (err, response, result) => {
if (err) {
return callback(err);
}
if (!result || result.total_results !== 1) {
return callback(new Error(`No app found ${options.name}!`));
}
callback(null, result.resources[0]);
});
};
};
| 24.40625 | 98 | 0.535211 |
060af272c7246fb25dbc9a42fb8a65c792a07621 | 360 | js | JavaScript | src/fn-retry-with-fibonacci/get-fibonacci-sequence.js | vadimkorr/fn-retry | 89449f762247cf06facbdf1fe4371c1da044d6c1 | [
"MIT"
] | 7 | 2020-07-24T22:29:14.000Z | 2022-02-15T11:14:04.000Z | src/fn-retry-with-fibonacci/get-fibonacci-sequence.js | vadimkorr/fn-retry | 89449f762247cf06facbdf1fe4371c1da044d6c1 | [
"MIT"
] | null | null | null | src/fn-retry-with-fibonacci/get-fibonacci-sequence.js | vadimkorr/fn-retry | 89449f762247cf06facbdf1fe4371c1da044d6c1 | [
"MIT"
] | null | null | null | export const getFibonacciSequence = len => {
const sequenceFn = {
0: () => [],
1: () => [1],
2: () => [1, 1],
rest: len => {
const sequence = [1, 1]
for (let i = 2; i < len; i++) {
sequence[i] = sequence[i - 1] + sequence[i - 2]
}
return sequence
},
}
return sequenceFn[len <= 2 ? len : 'rest'](len)
}
| 22.5 | 55 | 0.452778 |
060bd7c91292cb61dd67c5d7edc6fe999e36fb2f | 509 | js | JavaScript | cyberweb/public/Cyberweb_Documentation/html/search/functions_6e.js | sumukh210991/Cyberweb | 297bd54c9e223d38818b802087055e397c403f1c | [
"Apache-2.0"
] | null | null | null | cyberweb/public/Cyberweb_Documentation/html/search/functions_6e.js | sumukh210991/Cyberweb | 297bd54c9e223d38818b802087055e397c403f1c | [
"Apache-2.0"
] | null | null | null | cyberweb/public/Cyberweb_Documentation/html/search/functions_6e.js | sumukh210991/Cyberweb | 297bd54c9e223d38818b802087055e397c403f1c | [
"Apache-2.0"
] | null | null | null | var searchData=
[
['name',['name',['../classcyberweb_1_1lib_1_1basejob_1_1_base_job.html#ab7cf13a8852ec43970e2c6f616845872',1,'cyberweb::lib::basejob::BaseJob.name()'],['../classcyberweb_1_1lib_1_1jodis_1_1base_1_1_jodis_job.html#ab3522fd5cc5ea768a71ea4ff96644c0e',1,'cyberweb::lib::jodis::base::JodisJob.name()']]],
['news',['news',['../classcyberweb_1_1controllers_1_1homepage_1_1_homepage_controller.html#a40baa1cf25ae848b2f035aa8a9c64d37',1,'cyberweb::controllers::homepage::HomepageController']]]
];
| 84.833333 | 300 | 0.801572 |
060cd6fe587f20db46fb3e5c8792348639f39dee | 5,928 | js | JavaScript | front-end/src/app/routes/promotion/components/PromotionFilter.js | simejisan/osip-web-app | 525afdd0a5ea62a5d0b04086dff44843ff5952d8 | [
"MIT"
] | null | null | null | front-end/src/app/routes/promotion/components/PromotionFilter.js | simejisan/osip-web-app | 525afdd0a5ea62a5d0b04086dff44843ff5952d8 | [
"MIT"
] | null | null | null | front-end/src/app/routes/promotion/components/PromotionFilter.js | simejisan/osip-web-app | 525afdd0a5ea62a5d0b04086dff44843ff5952d8 | [
"MIT"
] | 2 | 2021-01-01T08:25:12.000Z | 2021-07-19T05:06:27.000Z | import React from 'react';
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import Input from "@material-ui/core/Input";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import {PROMOTION_PROVINCES, PROMOTION_SCREEN_TYPE, PROMOTION_SORT_TYPES} from 'constants/utils/PromotionUtils'
import {Card, CardBody} from "reactstrap";
import {
changeFilterInfo,
clearPromotions,
getAllPromotion,
hidePromotionLoader,
showPromotionLoader
} from 'actions/Promotion';
import {connect} from "react-redux";
import Button from "@material-ui/core/Button";
class PromotionFilter extends React.Component {
componentDidMount() {
this.props.hidePromotionLoader();
this.handleGetAllPromotions()
}
handleGetAllPromotions() {
const {filterInfo} = this.props;
this.props.clearPromotions();
this.props.showPromotionLoader();
this.props.getAllPromotion(filterInfo);
}
render() {
const {filterInfo} = this.props;
return (
<Card className="shadow border-0">
<CardBody className="pt-2">
<div className="row">
<div className="col-md-12">
<FormControl className="w-100 mt-3 mb-2">
<InputLabel htmlFor="screenType">Danh mục</InputLabel>
<Select
value={filterInfo.screenType}
onChange={(event) => this.props.changeFilterInfo({
...filterInfo,
screenType: event.target.value
})}
input={<Input id="screenType"/>}
>
{
PROMOTION_SCREEN_TYPE.map((type, index) => {
return (
<MenuItem key={index} value={type.value}>{type.text}</MenuItem>
)
})
}
</Select>
</FormControl>
</div>
<div className="col-md-12">
<FormControl className="w-100 mt-3 mb-2">
<InputLabel htmlFor="sortType">Sắp xếp</InputLabel>
<Select
value={filterInfo.sortType}
onChange={(event) => this.props.changeFilterInfo({
...filterInfo,
sortType: event.target.value
})}
input={<Input id="sortType"/>}
>
{
PROMOTION_SORT_TYPES.map((type, index) => {
return (
<MenuItem key={index} value={type.value}>{type.text}</MenuItem>
)
})
}
</Select>
</FormControl>
</div>
<div className="col-md-12">
<FormControl className="w-100 mt-3 mb-2">
<InputLabel htmlFor="province">Thành phố</InputLabel>
<Select
value={filterInfo.province}
onChange={(event) => this.props.changeFilterInfo({
...filterInfo,
province: event.target.value
})}
input={<Input id="province"/>}
>
{
PROMOTION_PROVINCES.map((type, index) => {
return (
<MenuItem key={index} value={type.value}>{type.text}</MenuItem>
)
})
}
</Select>
</FormControl>
</div>
<div className="col-md-12">
<Button variant="contained" color="primary"
className="jr-btn text-uppercase text-white btn-block mt-3"
onClick={() => {
this.props.clearPromotions();
this.handleGetAllPromotions()
}}
>
<i className="zmdi zmdi-search zmdi-hc-lg"/>
<span>Lọc khuyến mãi</span>
</Button>
</div>
</div>
</CardBody>
</Card>
)
}
}
const mapStateToProps = ({promotion}) => {
const {filterInfo} = promotion;
return {filterInfo}
};
export default connect(mapStateToProps,
{
showPromotionLoader,
hidePromotionLoader,
getAllPromotion,
clearPromotions,
changeFilterInfo
}
)(PromotionFilter);
| 43.911111 | 111 | 0.380567 |
060d9d8cd811bb1bf7724ad0b9537faee4a7ecf6 | 1,350 | js | JavaScript | src/components/OpenGraph/OpenGraph.js | BerlinChan/blog | 6e0fecbf626a43d365456964bbbdd75270fd4ed4 | [
"MIT"
] | 1 | 2021-08-24T21:52:29.000Z | 2021-08-24T21:52:29.000Z | src/components/OpenGraph/OpenGraph.js | BerlinChan/blog | 6e0fecbf626a43d365456964bbbdd75270fd4ed4 | [
"MIT"
] | 7 | 2019-10-15T07:42:40.000Z | 2022-03-09T01:22:28.000Z | src/components/OpenGraph/OpenGraph.js | BerlinChan/blog | 6e0fecbf626a43d365456964bbbdd75270fd4ed4 | [
"MIT"
] | null | null | null | import React from 'react'
import { Helmet } from 'react-helmet'
import { useSiteMetadata } from '../../hooks'
const OpenGraph = (props) => {
const { title: siteTitle, author: { name: siteAuthorName } } = useSiteMetadata()
const { title, url, description, type, image } = props
return (
<Helmet>
{description && <meta name="description" content={description}/>}
{/* Open Graph for Facebook & Twitter */}
{url && <meta property="og:url" content={url}/>}
<meta property="og:site_name" content={siteTitle}/>
{type && <meta property="og:type" content={type}/>}
<meta property="article:author" content={siteAuthorName}/>
{title && <meta property="og:title" content={title}/>}
{description && <meta property="og:description" content={description}/>}
{image && <meta property="og:image" content={image.url}/>}
{image && <meta property="og:image:secure_url" content={image.url}/>}
{image && <meta property="og:image:width" content={image.width}/>}
{image && <meta property="og:image:height" content={image.height}/>}
{/*twitter card*/}
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:site" content="@BerlinChanCom"/>
<meta name="twitter:creator" content="@BerlinChanCom"/>
</Helmet>
)
}
export default OpenGraph
| 39.705882 | 82 | 0.64 |
060f4f960544ccfba267a8af8ac4e92262287e1b | 261 | js | JavaScript | demos/loading/demos/progress.js | isogon/styled-mdl-website | 98ab525c8e7961151b8db95c37d014e1508dc6b9 | [
"Unlicense"
] | null | null | null | demos/loading/demos/progress.js | isogon/styled-mdl-website | 98ab525c8e7961151b8db95c37d014e1508dc6b9 | [
"Unlicense"
] | null | null | null | demos/loading/demos/progress.js | isogon/styled-mdl-website | 98ab525c8e7961151b8db95c37d014e1508dc6b9 | [
"Unlicense"
] | null | null | null | import React from 'react'
import { Progress } from 'styled-mdl'
const demo = () => <Progress percent={0.4} width="300px" />
const caption = 'Default Progress Bar'
const code = '<Progress percent="40%" width="300px" />'
export default { demo, caption, code }
| 26.1 | 59 | 0.678161 |
06103aa9d1d6a9b982122a6acfcc1e14229d7004 | 796 | js | JavaScript | src/components/Review/Review.js | BloomTech-Labs/where-to-code-fe | ad63e75ea722305d38aa52da64e9828e626c6517 | [
"MIT"
] | 5 | 2019-08-14T02:01:15.000Z | 2020-01-29T02:35:54.000Z | client/src/components/Review/Review.js | MrT3313/WhereToCode | 45e95724c3571ebee6f6c90a52e6d07c33bee631 | [
"MIT"
] | 11 | 2019-08-16T02:34:27.000Z | 2022-02-26T16:36:59.000Z | client/src/components/Review/Review.js | MrT3313/WhereToCode | 45e95724c3571ebee6f6c90a52e6d07c33bee631 | [
"MIT"
] | 9 | 2020-01-29T02:35:22.000Z | 2020-03-12T18:35:29.000Z | // IMPORTS
import React from "react";
import styled from "styled-components";
// IMPORT COMPONENTS
import Tabs from "./Tabs";
// STYLED COMPONENTS
const StyleModal = styled.div`
font-size: 12px;
`;
const Close = styled.div`
cursor: pointer;
position: absolute;
display: block;
padding: 2px 5px;
line-height: 20px;
right: -10px;
top: -10px;
font-size: 24px;
background: #ffffff;
border-radius: 18px;
border: 1px solid #cfcece;
`;
export default props => (
<StyleModal>
<Close>
<a Close onClick={props.close}>
×
</a>
</Close>
<Tabs
address={props.address}
close={props.close}
details={props.details}
hours={props.hours}
locationId={props.locationId}
icon={props.icon}
/>
</StyleModal>
);
| 18.090909 | 39 | 0.626884 |
06123fa3cfeaad2a969fa884efb4c1a4e3e148ae | 2,092 | js | JavaScript | index.js | mat-sz/whiteboard | 5ff09a3ab030b52504873a7cec76fc17b081ce0f | [
"BSD-3-Clause-Clear"
] | null | null | null | index.js | mat-sz/whiteboard | 5ff09a3ab030b52504873a7cec76fc17b081ce0f | [
"BSD-3-Clause-Clear"
] | null | null | null | index.js | mat-sz/whiteboard | 5ff09a3ab030b52504873a7cec76fc17b081ce0f | [
"BSD-3-Clause-Clear"
] | null | null | null | const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5000 });
const { createCanvas } = require('canvas');
const canvasWidth = 800;
const canvasHeight = 800;
const canvas = createCanvas(canvasWidth, canvasHeight);
const ctx = canvas.getContext('2d');
function prepareCanvas() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.lineCap = 'round';
}
prepareCanvas();
let clients = [];
wss.on('connection', function connection(ws) {
clients.push(ws);
ws.send(JSON.stringify({
type: 'initialData',
dataURL: canvas.toDataURL('image/png'),
width: canvasWidth,
height: canvasHeight,
}));
ws.on('message', function incoming(data) {
try {
const json = JSON.parse(data);
let broadcast = false;
if (json && json.type) {
switch (json.type) {
case 'lineSegment':
if (!json.x1 || !json.x2 || !json.y1 || !json.y2) return;
ctx.strokeStyle = json.color ? json.color : 'red';
ctx.lineWidth = json.width ? json.width : 10;
ctx.beginPath();
ctx.moveTo(json.x1, json.y1);
ctx.lineTo(json.x2, json.y2);
ctx.stroke();
ctx.closePath();
broadcast = true;
break;
case 'clear':
prepareCanvas();
broadcast = true;
break;
case 'chat':
broadcast = true;
break;
}
}
if (broadcast) {
for (let client of clients.filter((client) => client != ws)) {
client.send(data);
}
}
} catch (e) {}
});
});
setInterval(() => {
clients = clients.filter((client) => client.readyState <= 1);
}, 5000);
| 28.657534 | 81 | 0.458891 |
1bb2aae967ae1c56b687d2ea28175eb7b049552e | 989 | js | JavaScript | commands/close.js | TalicZealot/speedrun-race-discord-bot | 737706db56868bdd11f284bfc1c6208b51c077f6 | [
"MIT"
] | null | null | null | commands/close.js | TalicZealot/speedrun-race-discord-bot | 737706db56868bdd11f284bfc1c6208b51c077f6 | [
"MIT"
] | 3 | 2021-08-15T23:43:43.000Z | 2021-08-15T23:43:46.000Z | commands/close.js | TalicZealot/speedrun-race-discord-bot | 737706db56868bdd11f284bfc1c6208b51c077f6 | [
"MIT"
] | 2 | 2019-10-01T12:40:49.000Z | 2020-02-16T19:58:08.000Z | const { SlashCommandBuilder } = require('@discordjs/builders');
const config = require('../config.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('close')
.setDescription(`Closes the current race.`),
async execute(interaction, client, race) {
if (race.finished) {
await interaction.reply({ content: 'No active race!', ephemeral: true });
return;
}
if (!race.includes(interaction.user.id)) {
await interaction.reply({ content: 'Cannot close if you are not participating!', ephemeral: true });
return;
}
if (race.tournament && !interaction.member.roles.cache.find(x => x.id === config.refereeRoleId)) {
await interaction.reply({ content: 'Only referees can close tournament races!', ephemeral: true });
return;
}
race.close();
await interaction.reply({ content: 'Race closed!', ephemeral: true });
},
}; | 36.62963 | 112 | 0.598584 |
1bb357e5065f00ac27edcf8578c722afdede0a76 | 740 | js | JavaScript | test/cypress/stubs/transaction-summary-stubs.js | alphagov-mirror/pay-selfservice | 687826a5f5eefaa743fe90fa396b779f3329bed5 | [
"MIT"
] | 20 | 2017-08-23T03:09:00.000Z | 2021-08-16T23:03:58.000Z | test/cypress/stubs/transaction-summary-stubs.js | alphagov-mirror/pay-selfservice | 687826a5f5eefaa743fe90fa396b779f3329bed5 | [
"MIT"
] | 579 | 2017-08-11T11:03:14.000Z | 2022-03-29T09:08:40.000Z | test/cypress/stubs/transaction-summary-stubs.js | uk-gov-mirror/alphagov.pay-selfservice | d3fad8b3ebd6a21c82083e46dcff4a7295a8ea9a | [
"MIT"
] | 16 | 2017-08-22T18:47:29.000Z | 2021-05-12T20:17:49.000Z | 'use strict'
const ledgerFixture = require('../../fixtures/ledger-transaction.fixtures')
const { stubBuilder } = require('./stub-builder')
function getDashboardStatistics (opts = {}) {
const path = '/v1/report/transactions-summary'
return stubBuilder('GET', path, 200, {
response: ledgerFixture.validTransactionSummaryDetails(opts)
})
}
function getDashboardStatisticsWithFromDate (fromDate, opts = {}) {
const path = '/v1/report/transactions-summary'
return stubBuilder('GET', path, 200, {
query: {
from_date: fromDate
},
response: ledgerFixture.validTransactionSummaryDetails(opts),
deepMatchRequest: false
})
}
module.exports = {
getDashboardStatistics,
getDashboardStatisticsWithFromDate
}
| 26.428571 | 75 | 0.725676 |
1bb3c387e737d57c7f4d564b25b3eb6f442f3068 | 282 | js | JavaScript | node_modules/nest-cli/lib/tasks/away.js | ramirez456/nest-js | 57cb50f8b06ac8bd9cd51920f216e6a36ac4dc10 | [
"MIT"
] | 15 | 2015-08-21T02:23:10.000Z | 2020-09-15T02:59:08.000Z | node_modules/nest-cli/lib/tasks/away.js | ramirez456/nest-js | 57cb50f8b06ac8bd9cd51920f216e6a36ac4dc10 | [
"MIT"
] | 6 | 2015-08-26T03:27:06.000Z | 2021-08-30T06:51:07.000Z | node_modules/nest-cli/lib/tasks/away.js | ramirez456/nest-js | 57cb50f8b06ac8bd9cd51920f216e6a36ac4dc10 | [
"MIT"
] | 4 | 2015-08-26T03:22:07.000Z | 2018-03-09T06:32:27.000Z | 'use strict';
const TaskClass = require('./-base');
class AwayTask extends TaskClass {
run(structureId, mode) {
const ui = this.ui;
return this.app.api.structure.away(structureId, mode).then((res) => {
ui.writeLine(res);
});
}
}
module.exports = AwayTask;
| 17.625 | 73 | 0.638298 |
1bb506fe4d0f92b0782c4e1c658d075c1156a5cc | 263 | js | JavaScript | config/business-objects.js | marmarosi/bocs-poc | 651f0f6fc38076dd0e89fb8bc3e7de34151f8ecf | [
"MIT"
] | null | null | null | config/business-objects.js | marmarosi/bocs-poc | 651f0f6fc38076dd0e89fb8bc3e7de34151f8ecf | [
"MIT"
] | null | null | null | config/business-objects.js | marmarosi/bocs-poc | 651f0f6fc38076dd0e89fb8bc3e7de34151f8ecf | [
"MIT"
] | null | null | null | 'use strict';
module.exports = {
connectionManager: '/data/connection-manager.js',
daoBuilder: '/data/dao-builder.js',
userReader: '/data/get-user.js',
localeReader: '/data/get-locale.js',
pathOfLocales: '/locales',
noAccessBehavior: 'throwError'
};
| 23.909091 | 51 | 0.69962 |
1bb732f0678dea2240772b555955f22af3e55638 | 534 | js | JavaScript | docs/doc/implementors/nohash_hasher/trait.IsEnabled.js | AtlDragoon/Fennel-Protocol | f5f1a87d1564543484f27b4819a7a196fe91994f | [
"Unlicense"
] | null | null | null | docs/doc/implementors/nohash_hasher/trait.IsEnabled.js | AtlDragoon/Fennel-Protocol | f5f1a87d1564543484f27b4819a7a196fe91994f | [
"Unlicense"
] | null | null | null | docs/doc/implementors/nohash_hasher/trait.IsEnabled.js | AtlDragoon/Fennel-Protocol | f5f1a87d1564543484f27b4819a7a196fe91994f | [
"Unlicense"
] | null | null | null | (function() {var implementors = {};
implementors["nohash_hasher"] = [];
implementors["yamux"] = [{"text":"impl <a class=\"trait\" href=\"nohash_hasher/trait.IsEnabled.html\" title=\"trait nohash_hasher::IsEnabled\">IsEnabled</a> for <a class=\"struct\" href=\"yamux/struct.StreamId.html\" title=\"struct yamux::StreamId\">StreamId</a>","synthetic":false,"types":["yamux::frame::header::StreamId"]}];
if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() | 133.5 | 327 | 0.728464 |
1bb76e47cf0864c0ef5baac6cfc2ca1b3ba35e6f | 2,853 | js | JavaScript | server.js | bamorim/moviemashup | 5a2681d0c58ad694d0f952b4d1ea95778fa0fd7c | [
"Unlicense"
] | null | null | null | server.js | bamorim/moviemashup | 5a2681d0c58ad694d0f952b4d1ea95778fa0fd7c | [
"Unlicense"
] | null | null | null | server.js | bamorim/moviemashup | 5a2681d0c58ad694d0f952b4d1ea95778fa0fd7c | [
"Unlicense"
] | null | null | null | var express = require('express'),
http = require('http'),
app = express(),
engine = require('ejs-locals');
const api_key = process.env.TMDB_API_KEY;
const forbiddenWords = "a e i o u é à as os um uma umas uns há em ou de da do para desde que das dos no na nos nas i ii iii iv v vi vii".split(" ");
const allowedRegex = /(?=[^\d])\w/;
const isAllowed = function(word){
return word.match(allowedRegex) && forbiddenWords.indexOf(word.toLowerCase()) < 0;
};
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
app.engine('ejs',engine);
app.set('view engine','ejs');
app.get('/',function(req,res){
res.render('index');
});
app.get("/:word/:movieId/:wordIndex",function(req,res,next){
var options = {
host: 'api.themoviedb.org',
port: 80,
path: '/3/movie/'+req.params.movieId+'?api_key='+api_key+'&language=pt'
};
http.get(options,function(resp){
var dataStr = "";
resp.on('data',function(chunk){
dataStr = dataStr + chunk.toString();
});
resp.on('end',function(){
var movie = JSON.parse(dataStr);
var titleWords = movie.title.split(" ");
titleWords[req.params.wordIndex] = req.params.word.capitalize();
var newMovieTitle = titleWords.join(" ");
res.render('results',{title: newMovieTitle, movie: movie, locals:{ word: req.params.word }});
});
}).on('error',next);
});
function randomReplace(title, word){
var movieTitleWords = title.split(" ");
var allowedWords = movieTitleWords.filter(isAllowed);
var wordToBeChanged = allowedWords[parseInt(allowedWords.length*Math.random())];
movieTitleWords[movieTitleWords.indexOf(wordToBeChanged)] = word.capitalize();
return movieTitleWords.join(" ");
}
function movieIsAllowed(movie){
return (
(movie.original_language === "pt" || movie.title !== movie.original_title) &&
movie.title.split(/\s+/).filter(isAllowed).length > 1
);
}
app.get('/:word',function(req,res,next){
var page = parseInt(Math.random() * 100) + 1;
var options = {
host: 'api.themoviedb.org',
port: 80,
path: '/3/discover/movie?sort_by=popularity.desc&api_key='+api_key+'&language=pt&page='+page
}
http.get(options,function(resp){
var dataStr = "";
resp.on('data',function(chunk){
dataStr = dataStr + chunk.toString();
});
resp.on('end',function() {
var data = JSON.parse(dataStr);
var movies = data.results.filter(movieIsAllowed);
if(movies.length == 0) return res.redirect('.');
var movie = movies[parseInt(movies.length*Math.random())];
res.render('results',{title: randomReplace(movie.title,req.params.word), movie: movie, locals:{ word: req.params.word }});
});
}).on('error',next);
});
var port = process.env.PORT || 3000;
console.log("App listening on ",port);
app.listen(port);
| 31.351648 | 148 | 0.651244 |
1bb77fb1213b8fa8f950cd4d8587f227833f5d6b | 3,872 | js | JavaScript | app.js | anna-majka/memory-game | 3fc0d1e7fad74a30ae9220a88c8cccd85bf46cbe | [
"Unlicense"
] | null | null | null | app.js | anna-majka/memory-game | 3fc0d1e7fad74a30ae9220a88c8cccd85bf46cbe | [
"Unlicense"
] | null | null | null | app.js | anna-majka/memory-game | 3fc0d1e7fad74a30ae9220a88c8cccd85bf46cbe | [
"Unlicense"
] | null | null | null | //I start by creating 12 cards, then I add all the objects in an array
const cardArray =[
{
name:'midge',
img: 'images/midge.png',
},
{
name:'susie',
img: 'images/susie.png',
},
{
name:'shybaldwin',
img: 'images/shybaldwin.png',
},
{
name:'abeandrose',
img: 'images/abeandrose.png',
},
{
name:'sophie',
img: 'images/sophie.png',
},
{
name:'lenny',
img: 'images/lenny.png',
},
{
name:'midge',
img: 'images/midge.png',
},
{
name:'susie',
img: 'images/susie.png',
},
{
name:'shybaldwin',
img: 'images/shybaldwin.png',
},
{
name:'abeandrose',
img: 'images/abeandrose.png',
},
{
name:'sophie',
img: 'images/sophie.png',
},
{
name:'lenny',
img: 'images/lenny.png',
}
]
//I need to sort my objects in cardsArray randomly, so I use Math.random method
cardArray.sort(() => 0.5 - Math.random());
const gridDisplay = document.querySelector('#grid');//I create a board
const resultDisplay = document.querySelector('#result')
let cardsChosen = [];
let cardsChosenIds = [];
const cardsWon = []
//I create an images board
function createBoard(){
for(let i = 0; i < cardArray.length ; i++){
const card = document.createElement('img')//create an card
card.setAttribute('src', 'images/blank.png')//add an image to the card
card.setAttribute('data-id', i)//create data-id for each card
card.addEventListener('click', flipCard)//if I click on a card I want it to flip
gridDisplay.appendChild(card)//added 12 cards to my grid
}
}
createBoard();
//I check for matches
function checkMatch(){
const cards = document.querySelectorAll('img')//all the images in my grid
const optionOneId = cardsChosenIds[0]//1st card choice
const optionTwoId = cardsChosenIds[1]//2nd card choice
if(optionOneId == optionTwoId){//I'm checking if two cards match
cards[optionOneId].setAttribute('src', 'images/blank.png');
cards[optionTwoId].setAttribute('src', 'images/blank.png');
alert("You haved clicked the same image!")
}
if(cardsChosen[0] === cardsChosen[1]){//I'm checking if two cards match
alert ("It's a match!");//they do match
cards[optionOneId].setAttribute('src', 'images/black.png');//if it's a match, the image flips to black
cards[optionTwoId].setAttribute('src', 'images/black.png');// and it's out of game
cards[optionOneId].removeEventListener('click', flipCard);//EventListener stops listening out for clicks
cards[optionTwoId].removeEventListener('click', flipCard);//it removes the possibility to click on the card
cardsWon.push(cardsChosen) ;
}else{
cards[optionOneId].setAttribute('src', 'images/blank.png');//if they don't match, the image flips to blank
cards[optionTwoId].setAttribute('src', 'images/blank.png');//if they don't match, the image flips to blank
alert("Sorry, try again!")
}
resultDisplay.textContent = cardsWon.length;//show the score
cardsChosen = []//start the whole process again
cardsChosenIds = []//start the whole process again
//what will happen if I get all the matches
if(cardsWon.length == cardArray.length/2){//I have 6 pairs of cards hence "cardArray.length/2"
resultDisplay.textContent = "Congratulations you found them all !"//result message
}
}
//function to flip my cards
function flipCard(){
const cardId = this.getAttribute('data-id');
cardsChosen.push(cardArray[cardId].name)
cardsChosenIds.push(cardId);
cardArray[cardId];
this.setAttribute('src', cardArray[cardId].img);//images appear if I click on a card
if(cardsChosen.length === 2){//if I click 2 cards, I'm checking if they match
setTimeout(checkMatch, 500)//setTimeout will call my function after 500ms
}
}
| 32.537815 | 112 | 0.655475 |
1bb7a2ec25dd4a565318022af8df37bf269c9d3e | 3,929 | js | JavaScript | src/atmf/engine/core/functions.js | skito/ATMF-JS | b126344cfa2af1ee7dd9dd1f89a658d2fb1f1719 | [
"Apache-2.0"
] | null | null | null | src/atmf/engine/core/functions.js | skito/ATMF-JS | b126344cfa2af1ee7dd9dd1f89a658d2fb1f1719 | [
"Apache-2.0"
] | null | null | null | src/atmf/engine/core/functions.js | skito/ATMF-JS | b126344cfa2af1ee7dd9dd1f89a658d2fb1f1719 | [
"Apache-2.0"
] | null | null | null | import ATMFCulture from "./culture.js";
import ATMFVariables from "./variables.js";
class ATMFFunctions {
static #lastConditionResults = [];
constructor() {}
static ProcessTag(sender, tagName, args) {
switch (tagName) {
case '#template':
const name = args[0] || '';
const template = sender.GetTemplate(name);
return template || '';
case '#use':
const path = args[0] || '';
const operator = args[1] || 'as';
if (path != '' && operator == 'as') {
const keypath = path.length > 1 ? path.substr(1).trim() : '';
const alias = args[2] || keypath;
if (keypath != '') {
ATMFCulture.AddAlias(sender, alias, keypath);
}
}
return '';
case '#if':
var result = false;
const matchAll = !args.includes(['||']);
for (const arg of args) {
const argns = arg.trim();
if (['', '&&', '||'].includes('argns')) continue;
result = false;
const cmd = argns.substr(0, 1);
const reverseCond = (cmd == '!');
var argValue = reverseCond ? argns.substr(1) : argns;
if (reverseCond && argValue.length > 1) cmd = argValue.substr(0, 1);
if (argValue == '') continue;
else if (cmd == '$') {
result = ATMFVariables.ProcessTag(sender, argValue, []);
}
else if (cmd == '@')
result = ATMFFunctions.ProcessTag(sender, argValue, []);
if (reverseCond)
result = !result;
if (matchAll && !result)
break;
}
ATMFFunctions.#lastConditionResults.push(!result);
return result ? '<%:block_start%><%:show%>' : '<%:block_start%><%:hide%>';
case '#endif':
case '#end':
if (ATMFFunctions.#lastConditionResults.length > 0)
ATMFFunctions.#lastConditionResults.pop();
return '<%:block_end%>';
case '#else':
const count = ATMFFunctions.#lastConditionResults.length;
const lastCondResult = count > 0 ? ATMFFunctions.#lastConditionResults[count - 1] : false;
return lastCondResult ? '<%:block_end%><%:block_start%><%:show%>' : '<%:block_end%><%:block_start%><%:hide%>';
case '#each':
if (args.length == 3 && ['as', 'in'].includes(args[1].trim())) {
const operator = args[1].trim();
const collection = (operator == 'as' ? args[0] : args[2]).trim();
const item = (operator == 'as' ? args[2] : args[0]).trim();
if (collection.length < 2 || item.length < 2) {
console.error('ATMF Error: Wrong #each syntax!');
return '';
}
else return '<%:block_start%><%:each%><%:' + collection.substr(1) + ':' + item.substr(1) + '%>';
}
else {
console.error('ATMF Error: Wrong #each syntax!');
return '';
}
}
return '';
}
static SetTag(sender, tagName, args, value) {
switch (tagName) {
case '#template':
const name = args[0] || '';
if (name != '') {
sender.SetTemplate(name, value);
return true;
}
else return false;
}
return false;
}
}
export default ATMFFunctions; | 39.29 | 126 | 0.428353 |
1bb8ab88ac90c7d29707dd972da730f35a94c5ec | 848 | js | JavaScript | packages/next-swc/crates/core/tests/fixture/remove-console/all/simple/input.js | blomqma/next.js | 7db6aa2fde34699cf319d30980c2ee38bb53f20d | [
"MIT"
] | 51,887 | 2016-10-25T15:48:01.000Z | 2020-05-27T17:47:07.000Z | packages/next-swc/crates/core/tests/fixture/remove-console/all/simple/input.js | blomqma/next.js | 7db6aa2fde34699cf319d30980c2ee38bb53f20d | [
"MIT"
] | 13,333 | 2020-05-27T18:15:25.000Z | 2022-03-31T23:48:59.000Z | packages/next-swc/crates/core/tests/fixture/remove-console/all/simple/input.js | blomqma/next.js | 7db6aa2fde34699cf319d30980c2ee38bb53f20d | [
"MIT"
] | 14,796 | 2020-05-27T18:07:16.000Z | 2022-03-31T23:55:30.000Z | console.log("remove console test at top level");
export function shouldRemove() {
console.log("remove console test in function");
console.error("remove console test in function / error");
}
export function locallyDefinedConsole() {
let console = {
log: () => { },
};
console.log();
}
export function capturedConsole() {
let console = {
log: () => { },
};
function innerFunc() {
console.log();
}
}
export function overrideInParam(console) {
console.log("")
}
export function overrideInParamObjectPatPropAssign({ console }) {
console.log("")
}
export function overrideInParamObjectPatPropKeyValue({ c: console }) {
console.log("")
}
export function overrideInParamObjectPatPropKeyValueNested({ c: { console } }) {
console.log("")
}
export function overrideInParamArray([ console ]) {
console.log("")
}
| 19.72093 | 80 | 0.678066 |
1bb9d733d799f6c089b5856148044a04f04cf410 | 596 | js | JavaScript | src/gatsby-theme-carbon/components/LeftNav/ResourceLinks.js | redux-mvc/docs | d6fff0fcbf5d155f2f4bcc1645f436790950e693 | [
"Apache-2.0"
] | null | null | null | src/gatsby-theme-carbon/components/LeftNav/ResourceLinks.js | redux-mvc/docs | d6fff0fcbf5d155f2f4bcc1645f436790950e693 | [
"Apache-2.0"
] | null | null | null | src/gatsby-theme-carbon/components/LeftNav/ResourceLinks.js | redux-mvc/docs | d6fff0fcbf5d155f2f4bcc1645f436790950e693 | [
"Apache-2.0"
] | null | null | null | import React from 'react';
import ResourceLinks from 'gatsby-theme-carbon/src/components/LeftNav/ResourceLinks';
const links = [
{
title: 'github',
href: 'https://github.com/redux-mvc/core',
},
{
title: 'npm',
href: 'https://www.npmjs.com/package/@redux-mvc/core',
},
{ href: 'https://join.slack.com/t/redux-mvc/shared_invite/zt-flv1buf9-v~5kZ9yleC3c44i4d3FqHg', title: 'slack' },
];
// shouldOpenNewTabs: true if outbound links should open in a new tab
const CustomResources = () => <ResourceLinks shouldOpenNewTabs links={links} />;
export default CustomResources;
| 29.8 | 114 | 0.701342 |
1bb9ef447b960d91e9a066d778791582398e50a9 | 12,007 | js | JavaScript | react/src/pages/DatasetView.js | CLOSER-Cohorts/archivist | ef4ea8738126601236a8ae25fd6851fc30c4115f | [
"MIT"
] | 15 | 2016-02-18T07:42:56.000Z | 2020-08-30T19:19:58.000Z | react/src/pages/DatasetView.js | CLOSER-Cohorts/archivist | ef4ea8738126601236a8ae25fd6851fc30c4115f | [
"MIT"
] | 524 | 2016-01-12T14:56:50.000Z | 2022-03-31T15:30:10.000Z | react/src/pages/DatasetView.js | CLOSER-Cohorts/archivist | ef4ea8738126601236a8ae25fd6851fc30c4115f | [
"MIT"
] | 11 | 2016-06-01T12:06:46.000Z | 2021-03-26T11:32:28.000Z | import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'
import { Dataset, DatasetVariable, Topics } from '../actions'
import { Dashboard } from '../components/Dashboard'
import { DatasetHeading } from '../components/DatasetHeading'
import { Loader } from '../components/Loader'
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import TableFooter from '@material-ui/core/TableFooter';
import TablePagination from '@material-ui/core/TablePagination';
import Divider from '@material-ui/core/Divider';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';
import { get, isEmpty, isNil } from 'lodash'
import { makeStyles } from '@material-ui/core/styles';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import { Alert, AlertTitle } from '@material-ui/lab';
import SearchBar from "material-ui-search-bar";
import { ObjectStatus } from '../components/ObjectStatusBar'
const TopicList = (props) => {
const {topicId, datasetId, variableId} = props
const dispatch = useDispatch()
const topics = useSelector(state => state.topics);
const classes = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
const handleChange = (event, value, reason) => {
dispatch(DatasetVariable.topic.set(datasetId, variableId, event.target.value));
}
if(isEmpty(topics)){
return 'Fetching topics'
}else if(isNil(topicId)){
return (
<div>
<FormControl className={classes.formControl}>
<InputLabel htmlFor="grouped-native-select">Topic</InputLabel>
<Select native id="grouped-native-select" onChange={handleChange}>
<option aria-label="None" value="" />
{Object.values(topics).map((topic) => (
<option key={topic.id} value={topic.id}>{(topic.level === 1) ? topic.name : '--' + topic.name }</option>
))}
</Select>
</FormControl>
</div>
)
}else{
return (
<div>
<FormControl className={classes.formControl}>
<InputLabel htmlFor="grouped-native-select">Topic</InputLabel>
<Select native defaultValue={topicId} id="grouped-native-select" onChange={handleChange}>
<option aria-label="None" value="" />
{Object.values(topics).map((topic) => (
<option key={topic.id} value={topic.id}>{(topic.level === 1) ? topic.name : '--' + topic.name }</option>
))}
</Select>
</FormControl>
</div>
)
}
}
const DatasetView = (props) => {
const dispatch = useDispatch()
const datasetId = get(props, "match.params.dataset_id", "")
const statuses = useSelector(state => state.statuses);
const dataset = useSelector(state => get(state.datasets, datasetId));
const variables = useSelector(state => get(state.datasetVariables, datasetId,{}));
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(20);
const [search, setSearch] = useState("");
const [filteredValues, setFilteredValues] = useState([]);
useEffect(() => {
setFilteredValues(
Object.values(variables).filter((value) => {
const nameMatch = value['name'] && value['name'].toLowerCase().includes(search.toLowerCase())
const labelMatch = value['label'] && value['label'].toLowerCase().includes(search.toLowerCase())
const topic = get(value,'topic', {name: ''})
const topicMatch = topic && topic['name'] && topic['name'].toLowerCase().includes(search.toLowerCase())
const sources = get(value,'sources', [])
const sourcesStr = sources.map((s)=>{ return s['label'] }).join(' ')
const sourcesMatch = sourcesStr && sourcesStr.toLowerCase().includes(search.toLowerCase())
return nameMatch || labelMatch || topicMatch || sourcesMatch
}).sort((el)=> el.id).reverse()
);
}, [search, variables]);
const rows: RowsProp = filteredValues;
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const [dataLoaded, setDataLoaded] = useState(false);
useEffect(() => {
Promise.all([
dispatch(Dataset.show(datasetId)),
dispatch(DatasetVariable.all(datasetId)),
dispatch(Topics.all())
]).then(() => {
setDataLoaded(true)
});
// eslint-disable-next-line react-hooks/exhaustive-deps
},[]);
const VariableTableRow = (props) => {
const { row } = props;
const status = ObjectStatus(row.id, 'DatasetVariable')
var errorMessage = null;
if (status.error) {
errorMessage = status.errorMessage
} else if (row.errors) {
errorMessage = row.errors
}
return (
<TableRow key={row.id}>
<TableCell>{row.id}</TableCell>
<TableCell>{row.name}</TableCell>
<TableCell>{row.label}</TableCell>
<TableCell>{row.var_type}</TableCell>
<TableCell></TableCell>
<TableCell>
<SourcesList sources={row.sources} sourceOptions={get(dataset, 'questions', [])} datasetId={datasetId} variable={row} />
</TableCell>
<TableCell>
<TopicList topicId={get(row.topic, 'id')} datasetId={datasetId} variableId={row.id} />
{!isNil(row.sources_topic) && (
<em>Resolved topic from sources - {get(row.sources_topic, 'name')}</em>
)}
</TableCell>
</TableRow>
)
}
const SourcesList = (props) => {
const { sources, datasetId, variable } = props
let { sourceOptions } = props
if (get(variable.topic, 'id') !== 0 && (!isEmpty(variable.topic) || !isEmpty(variable.sources_topic)) ){
sourceOptions = sourceOptions.filter(opt => {
return (
get(opt.topic, 'id') == get(variable.topic, 'id') ||
get(opt.resolved_topic, 'id') == get(variable.topic, 'id') ||
(get(opt.topic, 'id') === 0 && get(opt.resolved_topic, 'id') === 0) || (opt.topic === null && opt.resolved_topic === null)
)
})
}
const variableId = variable.id
const dispatch = useDispatch()
const handleAddSource = (newSources) => {
dispatch(DatasetVariable.add_source(datasetId, variableId, newSources));
}
const handleRemoveSource = (oldSources) => {
oldSources.map((source)=>{
dispatch(DatasetVariable.remove_source(datasetId, variableId, source));
})
}
var difference = []
const handleChange = (event, value, reason) => {
switch (reason) {
case 'select-option':
difference = value.filter(x => !sources.includes(x));
if(!isEmpty(difference)){
return handleAddSource(difference.map((source) => { return source.label }))
};
break;
case 'remove-option':
difference = sources.filter(x => !value.includes(x));
if(!isEmpty(difference)){
return handleRemoveSource(difference)
};
break;
default:
return null;
}
}
if(isEmpty(sources)){
return (
<div>
<Autocomplete
multiple
id="tags-outlined"
options={Object.values(sourceOptions)}
getOptionLabel={(option) => option.label}
onChange={handleChange}
value={[]}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Sources"
placeholder="Add source"
multiline
/>
)}
/>
</div>
)
}else{
return (
<div>
<Autocomplete
multiple
id="tags-outlined"
options={Object.values(sourceOptions)}
getOptionLabel={(option) => option.label || option.name }
onChange={handleChange}
value={sources}
getOptionSelected= {(option, value) => (
option.id === value.id
)}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Sources"
placeholder="Add source"
/>
)}
/>
</div>
)
}
}
return (
<div style={{ height: 500, width: '100%' }}>
<Dashboard title={'Datasets'}>
<DatasetHeading dataset={dataset} mode={'view'} />
{!dataLoaded
? <Loader />
: (
<>
<span style={{ margin: 16 }}/>
<SearchBar
placeholder={`Search by name, label, source or topic (press return to perform search)`}
onRequestSearch={(newValue) =>
setSearch(newValue)
}
onCancelSearch={() => {
setSearch('')
}}
/>
<Divider style={{ margin: 16 }} variant="middle" />
<Table size="small">
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Name</TableCell>
<TableCell>Label</TableCell>
<TableCell>Type</TableCell>
<TableCell>Used by</TableCell>
<TableCell>Sources</TableCell>
<TableCell>Topic</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => {
const key = 'DatasetVariable:' + row.id
const status = get(statuses, key, {})
var errorMessage = null;
if(status.error){
errorMessage = status.errorMessage
}else if(row.errors){
errorMessage = row.errors
}
return (
<>
{ !isEmpty(errorMessage) && (
<TableRow>
<TableCell colSpan={7} style={{ border: '0'}}>
<Alert severity="error">
<AlertTitle>Error</AlertTitle>
{errorMessage}
</Alert>
</TableCell>
</TableRow>
)}
<VariableTableRow row={row} />
</>
)
})}
</TableBody>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions={[20, 50, 100, { label: 'All', value: -1 }]}
colSpan={3}
count={rows.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
SelectProps={{
inputProps: { 'aria-label': 'rows per page' },
native: true,
}}
/>
</TableRow>
</TableFooter>
</Table>
</>
)}
</Dashboard>
</div>
);
}
export default DatasetView;
| 34.014164 | 132 | 0.539685 |
1bbaf721aa5ac95f4fa1f50475463687a4b60eb6 | 3,001 | js | JavaScript | source/index.js | kemitchell/generic-authentication-server | e257d4e35940c4d0c937ff578b190d6e6829d0aa | [
"Apache-2.0"
] | null | null | null | source/index.js | kemitchell/generic-authentication-server | e257d4e35940c4d0c937ff578b190d6e6829d0aa | [
"Apache-2.0"
] | null | null | null | source/index.js | kemitchell/generic-authentication-server | e257d4e35940c4d0c937ff578b190d6e6829d0aa | [
"Apache-2.0"
] | null | null | null | var ndjson = require('ndjson');
var password = require('bcrypt-password');
var through2 = require('through2');
var OK = null;
var hasString = function(argument, key) {
var value = argument[key];
return (
argument.hasOwnProperty('name') &&
typeof value === 'string' &&
value.length > 3 &&
!/^\s/.test(value) &&
!/\s$/.test(value) &&
/^[A-Za-z0-9-_]+$/.test(value)
);
};
var hasCredentials = function(argument) {
return (
hasString(argument, 'name') &&
hasString(argument, 'password')
);
};
module.exports = function(level) {
return function(request, response) {
response.setHeader('content-type', 'application/x-ndjson');
request
.pipe(ndjson.parse())
.pipe(through2.obj(function(object, encoding, callback) {
if (hasCredentials(object)) {
var action = object.action;
if (action === 'update') {
password.hash(object.password, function(error, digest) {
if (error) {
callback(OK, [error.message]);
} else {
level.put(
object.name,
JSON.stringify({password: digest}),
function(error) {
if (error) {
callback(OK, {
action: action,
name: object.name,
result: [error.message]
});
} else {
callback(OK, {
action: action,
name: object.name,
result: [OK, true]
});
}
}
);
}
});
} else if (action === 'authenticate') {
level.get(object.name, function(error, data) {
if (error) {
callback(OK, {
action: object.action,
name: action.name,
result: [error.message]
});
} else {
password.check(
object.password,
JSON.parse(data).password,
function(error, match) {
if (error) {
callback(OK, {
action: object.action,
name: object.name,
result: [error.message]
});
} else {
callback(OK, {
action: object.action,
name: object.name,
result: [OK, match]
});
}
}
);
}
});
} else {
callback(OK, ['Invalid action']);
}
} else {
callback(OK, ['Invalid action']);
}
}))
.pipe(ndjson.stringify())
.pipe(response);
};
};
| 29.712871 | 68 | 0.400533 |
1bbc48071d6c2a9f3cad4c804149d6245a2eb1f7 | 4,377 | js | JavaScript | screens/ChatScreen.js | tfung5/codenames | 8a071e223ace6ef37ca2bff00e6a600e962322c4 | [
"MIT"
] | null | null | null | screens/ChatScreen.js | tfung5/codenames | 8a071e223ace6ef37ca2bff00e6a600e962322c4 | [
"MIT"
] | 3 | 2021-10-06T11:49:49.000Z | 2022-02-26T23:35:05.000Z | screens/ChatScreen.js | tfung5/Codenames-React-Native | 8a071e223ace6ef37ca2bff00e6a600e962322c4 | [
"MIT"
] | null | null | null | /**
* Credit: https://github.com/FaridSafi/react-native-gifted-chat/issues/1272
* for help fixing the keyboard hiding GiftedChat input
*/
import React from "react";
import { NavigationActions } from "react-navigation";
import CombinedContext from "../components/CombinedContext";
import ProvideCombinedContext from "../components/ProvideCombinedContext";
import { GiftedChat } from "react-native-gifted-chat";
import {
CHAT_MESSAGE,
FETCH_PLAYER_INFO,
GET_MESSAGES,
SAVE_LATEST_TIME,
UPDATE_NOTIFICATION,
UPDATE_PLAYER_INFO,
} from "../constants/Actions";
class ChatScreen extends React.Component {
static contextType = CombinedContext;
constructor(props) {
super(props);
this.state = {
messages: [],
user: {
_id: 1,
name: "Player",
avatar: "",
},
};
this.onReceivedMessage = this.onReceivedMessage.bind(this);
}
componentDidMount = () => {
this._isMounted = true;
if (this.isRedirectToHomeNeeded()) {
this.navigateToHomeScreen();
} else {
this.runSetup();
}
};
componentWillUnmount = () => {
this._isMounted = false;
this.updateTimeOfLastReadMessage();
this.socket.emit(UPDATE_NOTIFICATION);
};
updateTimeOfLastReadMessage = () => {
this.context.GameContext.game.timeOfLastReadMessage = Date.now();
};
runSetup = async () => {
await this.saveSocket();
await this.subscribeToPlayerUpdates();
await this.getPlayerInfo();
await this.subscribeToChatMessageUpdates();
await this.loadEarlierMessages();
await this.getMessages();
await this.updateTimeOfLastReadMessage();
};
saveSocket = () => {
this.socket = this.context.SocketContext.socket;
};
isRedirectToHomeNeeded = () => {
/**
* Returns true if there is no game in progress
* If the user did not come from the LobbyScreen, then there is no game in progress
*/
return !this.context.GameContext.game.isGameInProgress;
};
navigateToHomeScreen = () => {
this.props.navigation.navigate(
"HomeStack",
{},
NavigationActions.navigate({
routeName: "Home",
})
);
};
getMessages = () => {
this.socket.emit(GET_MESSAGES);
};
loadEarlierMessages = () => {
this.socket.on(GET_MESSAGES, (payload) => {
for (let i = 0; i < payload.length; i++) {
this.onReceivedMessage(payload[i]);
}
});
};
//Get messages
subscribeToChatMessageUpdates = () => {
this.socket.on(CHAT_MESSAGE, this.onReceivedMessage);
};
getPlayerInfo = () => {
this.socket.emit(FETCH_PLAYER_INFO);
};
subscribeToPlayerUpdates = () => {
this.socket.on(UPDATE_PLAYER_INFO, (player) => {
const { id, name } = player;
if (this._isMounted) {
this.setState({
user: {
_id: id,
name: name,
},
});
}
});
};
subscribeToGameUpdates = () => {
this.socket.on(UPDATE_GAME, (payload) => {
const {
currentTeam,
board,
redCardCounter,
blueCardCounter,
guessCounter,
winningTeam,
} = payload;
if (this._isMounted) {
this.setState({
currentTeam,
board,
redCardCounter,
blueCardCounter,
guessCounter,
winningTeam,
});
}
});
};
//When the server sends a message to this, store it in this component's state.
onReceivedMessage(messages) {
if (this._isMounted) {
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, messages),
};
});
this.updateTimeOfLastReadMessage();
}
}
//Send messages
//When a message is sent, send the message to the server.
onSend(messages = []) {
let dateNow = Date.now();
this.socket.emit(CHAT_MESSAGE, messages[0]);
this.socket.emit(SAVE_LATEST_TIME, dateNow);
}
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={(messages) => this.onSend(messages)}
renderUsernameOnMessage={true}
user={this.state.user}
/>
);
}
}
const WrappedChatScreen = (props) => {
return (
<ProvideCombinedContext>
<ChatScreen {...props} />
</ProvideCombinedContext>
);
};
export default WrappedChatScreen;
| 23.281915 | 87 | 0.610921 |
1bbccd2aefcab6ae0f3270a7fce45031fce44d32 | 11,681 | js | JavaScript | softwerkskammer/test/groupsAndMembers/groupsAndMembersService_test.js | c089/agora | 55ba7e5262a482a759637474d9a281b56b75cd1b | [
"MIT"
] | null | null | null | softwerkskammer/test/groupsAndMembers/groupsAndMembersService_test.js | c089/agora | 55ba7e5262a482a759637474d9a281b56b75cd1b | [
"MIT"
] | null | null | null | softwerkskammer/test/groupsAndMembers/groupsAndMembersService_test.js | c089/agora | 55ba7e5262a482a759637474d9a281b56b75cd1b | [
"MIT"
] | null | null | null | 'use strict';
const sinon = require('sinon').sandbox.create();
const beans = require('../../testutil/configureForTest').get('beans');
const expect = require('must-dist');
const Member = beans.get('member');
const dummymember = new Member().initFromSessionUser({authenticationId: 'hada', profile: {emails: [{value: 'email'}]}});
const dummymember2 = new Member().initFromSessionUser({authenticationId: 'hada2', profile: {emails: [{value: 'email'}]}});
const Group = beans.get('group');
const GroupA = new Group({id: 'GroupA', longName: 'Gruppe A', description: 'Dies ist Gruppe A.', type: 'Themengruppe'});
const GroupB = new Group({id: 'GroupB', longName: 'Gruppe B', description: 'Dies ist Gruppe B.', type: 'Regionalgruppe'});
const memberstore = beans.get('memberstore');
const membersService = beans.get('membersService');
const groupsService = beans.get('groupsService');
const groupstore = beans.get('groupstore');
const groupsAndMembersService = beans.get('groupsAndMembersService');
describe('Groups and Members Service (getMemberWithHisGroups or getMemberWithHisGroupsByMemberId)', () => {
afterEach(() => {
sinon.restore();
});
describe('- getMemberWithHisGroups -', () => {
it('returns no member when there is no member for the given nickname', done => {
sinon.stub(memberstore, 'getMember').callsFake((nickname, callback) => {
callback(null, null);
});
groupsAndMembersService.getMemberWithHisGroups('nickname', (err, member) => {
expect(member).to.not.exist();
done(err);
});
});
it('returns the member and his groups when there is a member for the given nickname', done => {
sinon.stub(memberstore, 'getMember').callsFake((nickname, callback) => {
callback(null, dummymember);
});
sinon.stub(groupsService, 'getSubscribedGroupsForUser').callsFake((userMail, globalCallback) => {
globalCallback(null, [GroupA, GroupB]);
});
groupsAndMembersService.getMemberWithHisGroups('nickname', (err, member) => {
expect(member).to.equal(dummymember);
expect(member.subscribedGroups).to.not.be(null);
expect(member.subscribedGroups.length).to.equal(2);
expect(member.subscribedGroups[0]).to.equal(GroupA);
expect(member.subscribedGroups[1]).to.equal(GroupB);
done(err);
});
});
});
describe('- getMemberWithHisGroupsByMemberId -', () => {
it('returns no member when there is no member for the given memberID', done => {
sinon.stub(memberstore, 'getMemberForId').callsFake((memberID, callback) => {
callback(null, null);
});
groupsAndMembersService.getMemberWithHisGroupsByMemberId('id', (err, member) => {
expect(member).to.not.exist();
done(err);
});
});
it('returns the member and his groups when there is a member for the given memberID', done => {
sinon.stub(memberstore, 'getMemberForId').callsFake((memberID, callback) => {
callback(null, dummymember);
});
sinon.stub(groupsService, 'getSubscribedGroupsForUser').callsFake((userMail, globalCallback) => {
globalCallback(null, [GroupA, GroupB]);
});
groupsAndMembersService.getMemberWithHisGroupsByMemberId('id', (err, member) => {
expect(member).to.equal(dummymember);
expect(member.subscribedGroups).to.not.be(null);
expect(member.subscribedGroups.length).to.equal(2);
expect(member.subscribedGroups[0]).to.equal(GroupA);
expect(member.subscribedGroups[1]).to.equal(GroupB);
done(err);
});
});
});
});
describe('Groups and Members Service (getGroupAndMembersForList)', () => {
beforeEach(() => {
sinon.stub(memberstore, 'allMembers').callsFake(callback => { callback(null, null); });
});
afterEach(() => {
sinon.restore();
});
it('returns no group when there is no group and no mailing-list', done => {
sinon.stub(memberstore, 'getMembersForEMails').callsFake((member, callback) => { callback(); });
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, []); });
sinon.stub(groupstore, 'getGroup').callsFake((groupname, callback) => { callback(null, null); });
groupsAndMembersService.getGroupAndMembersForList('unbekannteListe', (err, group) => {
expect(group).to.not.exist();
done(err);
});
});
it('returns no group when there is no group but a mailing-list', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => {
callback(null, ['user1@mail1.com', 'user2@mail2.com']);
});
sinon.stub(memberstore, 'getMembersForEMails').callsFake((member, callback) => {
callback(null, [dummymember, dummymember2]);
});
sinon.stub(groupstore, 'getGroup').callsFake((groupname, callback) => { callback(null, null); });
groupsAndMembersService.getGroupAndMembersForList('mailingListWithoutGroup', (err, group) => {
expect(group).to.not.exist();
done(err);
});
});
it('returns the group with the given name and an empty list of subscribed users when there is no mailing-list or when there are no subscribers', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, []); });
sinon.stub(groupstore, 'getGroup').callsFake((groupname, callback) => {
callback(null, GroupA);
});
sinon.stub(memberstore, 'getMembersForEMails').callsFake((member, callback) => {
callback(null, []);
});
groupsAndMembersService.getGroupAndMembersForList('GroupA', (err, group) => {
expect(group).to.equal(GroupA);
expect(group.members).to.not.be(null);
expect(group.members.length).to.equal(0);
done(err);
});
});
it('returns the group with the given name and a list of one subscribed user when there is one subscriber in mailinglist', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, ['user@email.com']); });
sinon.stub(groupstore, 'getGroup').callsFake((groupname, callback) => {
callback(null, GroupA);
});
sinon.stub(memberstore, 'getMembersForEMails').callsFake((member, callback) => {
callback(null, [dummymember]);
});
sinon.stub(membersService, 'putAvatarIntoMemberAndSave').callsFake((member, callback) => {
callback();
});
groupsAndMembersService.getGroupAndMembersForList('GroupA', (err, group) => {
expect(group).to.equal(GroupA);
expect(group.members).to.not.be(null);
expect(group.members.length).to.equal(1);
expect(group.members[0]).to.equal(dummymember);
done(err);
});
});
it('fails gracefully if groupsService has an error', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(new Error()); });
sinon.stub(groupstore, 'getGroup').callsFake((groupname, callback) => {
callback(null, GroupA);
});
groupsAndMembersService.getGroupAndMembersForList('GroupA', err => {
expect(err).to.exist();
done();
});
});
});
describe('Groups and Members Service (addMembercountToGroup)', () => {
afterEach(() => {
sinon.restore();
});
it('returns no group when the group is null', done => {
groupsAndMembersService.addMembercountToGroup(null, (err, group) => {
expect(group).to.not.exist();
done(err);
});
});
it('returns no group when the group is undefined', done => {
groupsAndMembersService.addMembercountToGroup(undefined, (err, group) => {
expect(group).to.not.exist();
done(err);
});
});
it('adds zero to group if there are no subscribers', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, []); });
groupsAndMembersService.addMembercountToGroup({}, (err, group) => {
expect(group.membercount).to.equal(0);
done(err);
});
});
it('adds the number of subscribers to the group', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, ['1', '2', '4']); });
groupsAndMembersService.addMembercountToGroup({}, (err, group) => {
expect(group.membercount).to.equal(3);
done(err);
});
});
});
describe('Groups and Members Service (addMembersToGroup)', () => {
beforeEach(() => {
sinon.stub(memberstore, 'allMembers').callsFake(callback => { callback(null, null); });
});
afterEach(() => {
sinon.restore();
});
it('returns no group when the group is null', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake(() => undefined);
sinon.stub(memberstore, 'getMembersForEMails').callsFake(() => undefined);
groupsAndMembersService.addMembersToGroup(null, (err, group) => {
expect(group).to.not.exist();
done(err);
});
});
it('returns no group when the group is undefined', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake(() => undefined);
sinon.stub(memberstore, 'getMembersForEMails').callsFake(() => undefined);
groupsAndMembersService.addMembersToGroup(undefined, (err, group) => {
expect(group).to.not.exist();
done(err);
});
});
it('returns the group with an empty list of subscribed users when there are no subscribers', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, []); });
sinon.stub(memberstore, 'getMembersForEMails').callsFake((member, callback) => {
callback(null, []);
});
groupsAndMembersService.addMembersToGroup(GroupA, (err, group) => {
expect(group).to.equal(GroupA);
expect(group.members).to.not.be(null);
expect(group.members.length).to.equal(0);
expect(group.membercount).to.equal(0);
delete group.members;
done(err);
});
});
it('returns the group with a list of one subscribed user when there is one subscriber in mailinglist', done => {
sinon.stub(groupsService, 'getMailinglistUsersOfList').callsFake((ignoredErr, callback) => { callback(null, ['user@email.com']); });
sinon.stub(memberstore, 'getMembersForEMails').callsFake((member, callback) => {
callback(null, [dummymember]);
});
sinon.stub(membersService, 'putAvatarIntoMemberAndSave').callsFake((member, callback) => {
callback();
});
groupsAndMembersService.addMembersToGroup(GroupA, (err, group) => {
expect(group).to.equal(GroupA);
expect(group.members).to.not.be(null);
expect(group.members.length).to.equal(1);
expect(group.membercount).to.equal(1);
expect(group.members[0]).to.equal(dummymember);
delete group.members;
done(err);
});
});
});
describe('Groups and Members Service (memberIsInMemberList)', () => {
it('returns false if the user id is undefined', () => {
expect(groupsAndMembersService.memberIsInMemberList(undefined, [dummymember, dummymember2])).to.be(false);
});
it('returns false if the member list is empty', () => {
expect(groupsAndMembersService.memberIsInMemberList('hada', [])).to.be(false);
});
it('returns false if the user is not in the member list', () => {
expect(groupsAndMembersService.memberIsInMemberList('trallala', [dummymember])).to.be(false);
});
it('returns true if the user is in the member list', () => {
expect(groupsAndMembersService.memberIsInMemberList('hada', [dummymember, dummymember2])).to.be(true);
});
});
| 38.173203 | 156 | 0.659533 |
1bbd5ed1a752c590770fbfeac19060e78f6c234c | 3,466 | js | JavaScript | recommendation-engine/email_client.js | CDCgov/GaTech-Fall2017-Goodman-HealthWeight-TeamScienceFreaks | 5d95771e691fd5892ea48a2519dbafc3142d792c | [
"Apache-2.0"
] | null | null | null | recommendation-engine/email_client.js | CDCgov/GaTech-Fall2017-Goodman-HealthWeight-TeamScienceFreaks | 5d95771e691fd5892ea48a2519dbafc3142d792c | [
"Apache-2.0"
] | null | null | null | recommendation-engine/email_client.js | CDCgov/GaTech-Fall2017-Goodman-HealthWeight-TeamScienceFreaks | 5d95771e691fd5892ea48a2519dbafc3142d792c | [
"Apache-2.0"
] | 1 | 2020-12-21T22:28:12.000Z | 2020-12-21T22:28:12.000Z | const nodemailer = require('nodemailer');
const mail_server = process.env.MAIL_SERVER;
const mail_port = process.env.MAIL_PORT || 587;
const from_address = process.env.FROM_ADDRESS || '';
const subject_line = process.env.SUBJECT_LINE || '';
module.exports.sendTestMessage = function sendMessage(emailAddress, plainMessage, htmlMessage) {
var promise = new Promise(function (resolve, reject) {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
nodemailer.createTestAccount((err, account) => {
if (err) {
reject(err);
}
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: account.user, // generated ethereal user
pass: account.pass // generated ethereal password
}
});
// setup email data with unicode symbols
let mailOptions = {
from: '"The Clinic" <doctor@clinic.com>', // sender address
to: emailAddress, // list of receivers
subject: 'Recommendations From Your Doctor', // Subject line
text: plainMessage, // plain text body
html: htmlMessage // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
reject(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
resolve(nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@blurdybloop.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});
});
});
return promise;
}
module.exports.sendMessage = function sendMessage(emailAddress, plainMessage, htmlMessage) {
var promise = new Promise(function (resolve, reject) {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: mail_server,
port: mail_port,
secure: false, // true for 465, false for other ports
auth: {
user: '', // generated ethereal user
pass: '' // generated ethereal password
}
});
// setup email data with unicode symbols
let mailOptions = {
from: from_address, // sender address
to: emailAddress, // list of receivers
subject: subject_line, // Subject line
text: plainMessage, // plain text body
html: htmlMessage // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
reject(error);
}
console.log('Message sent: %s', info.messageId);
});
});
return promise;
} | 40.776471 | 96 | 0.568667 |
1bbdd94fabb1f79ebbc016a75169709d73e229f9 | 286 | js | JavaScript | actions/select-all.js | Daniellop1/paint | b3a661d9efaa123596c87bc28771cf7d1cd83050 | [
"Apache-2.0"
] | null | null | null | actions/select-all.js | Daniellop1/paint | b3a661d9efaa123596c87bc28771cf7d1cd83050 | [
"Apache-2.0"
] | null | null | null | actions/select-all.js | Daniellop1/paint | b3a661d9efaa123596c87bc28771cf7d1cd83050 | [
"Apache-2.0"
] | null | null | null | import { updateContext } from '../helpers/update-context.js';
export class SelectAllAction {
execute(drawingContext) {
const { width, height } = drawingContext.canvas;
drawingContext.selection = { x: 0, y: 0, width, height };
updateContext(drawingContext.element);
}
}
| 28.6 | 61 | 0.699301 |
1bbdfccdf012294584ec2d7f4a07a9ffc74ddb01 | 1,371 | js | JavaScript | lang/ms.js | themanyone/speechpad | e71283f96a37a2025fe8d5e44cddd841e28ea79e | [
"Apache-2.0"
] | 1 | 2019-04-23T23:10:30.000Z | 2019-04-23T23:10:30.000Z | lang/ms.js | themanyone/speechplus | e71283f96a37a2025fe8d5e44cddd841e28ea79e | [
"Apache-2.0"
] | null | null | null | lang/ms.js | themanyone/speechplus | e71283f96a37a2025fe8d5e44cddd841e28ea79e | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2017-2020, Henry Kroll III of thenerdshow.com. All rights reserved.
*/
CKEDITOR.plugins.setLang( 'speech', 'ms', {
xabout: 'Mengenai SpeechPad Plugin',
xcommands: 'Konfigurasikan Perintah Lisan',
dictation: 'Dikte Pertuturan',
xspoken: 'Perintah yang diucapkan',
xspeech: 'Aktifkan imlak',
editable: 'Perintah yang boleh diedit',
xspecial: 'Watak Khas',
saythis: 'Katakan ini',
dothis: 'Untuk membuat ini',
typethis: 'Untuk menaip ini',
punctnote: 'Tanda baca tersedia dalam bahasa Jerman, Inggeris, <br> Sepanyol, Perancis, Itali dan Rusia',
http: 'Garis miring kolon HTTP',
comma: 'subseksyen',
period: 'tempoh',
fullstop: 'noktah',
colon: 'usus besar',
dollars: 'dolar',
exclamation: 'tanda seru',
newline: 'baris baru',
newpara: 'perenggan baru',
percent: 'peratus',
times: 'kali',
slash: 'garis miring',
ellipses: 'elips',
atsign: 'pada tanda',
asterisk: 'tanda bintang',
hashtag: 'Hashtag',
ampersand: 'ampersand',
backslash: 'garis belakang',
semicolon: 'titik koma',
curlybracket: 'pendakap kerinting',
squarebracket: 'pendakap persegi',
parentheses: 'kurungan',
quotationmark: 'tanda petikan',
longdash: 'puting panjang',
dash: 'sengkang',
underscore: 'garis bawah',
} );
| 31.883721 | 108 | 0.642597 |