text
stringlengths 7
3.69M
|
|---|
// Code for the right hand side panel
var Panel = ReactBootstrap.Panel;
/*
var RightPanelBody = React.createClass({
render: function() {
// Style the div to 500px height because the canvas otherwise won't
// look like it is inside the panel
return (
<div className="panel-body" style={{height:'500px'}}>
<GraphTimeSeries data={this.props.data} title={this.props.title} />
</div>
);
}
});
*/
var RightPanel = React.createClass({
// Set initial state
getInitialState: function() {
//console.log("rightPanel-getInitialState ", this.props.meterID);
return {
data: this.getData(this.props.meterID),
};
},
/* Not too nice this one. Making GET operation synchronous, but I am not sure how to handle it AJAX style?? */
getData: function(meterID) {
//var that = this;
var mydata = [];
// http://stackoverflow.com/questions/13009755/getjson-synchronous
$.ajaxSetup({
async: false
});
var jqxhr = $.getJSON( "/api/values/"+meterID )
.done(function(data) {
//console.log("rightPanel-getData-JSON recv: ",data);
//that.setState({ data : data });
mydata = data;
})
.fail(function() {
alert( "error: Failed to get graph data from server");
//that.setState({ data : [] });
});
$.ajaxSetup({
async: true
});
//console.log("returning data");
return mydata;
},
componentDidMount: function() {
//console.log("rightPanel-componentDidMount ", this.props.meterID);
this.setState({data: this.getData(this.props.meterID)});
},
/* TODO: Move state to main?? */
componentWillReceiveProps: function(nextProps) {
//console.log("rightPanel-componentWillReceiveProps ", nextProps.meterID);
this.setState({data: this.getData(nextProps.meterID)});
},
render: function() {
const title = (
<h3>Graphs</h3>
);
//console.log("rightPanel-render", this.state);
return (
<div id="rightpane" className="col-md-8">
<Panel bsStyle="primary" header={title}>
<GraphTimeSeries data={this.state.data} title={"Data for meter "+this.props.meterID} height="500px" />
</Panel>
</div>
);
// {JSON.stringify(this.state.data, null, 2) }
/*
return (
<div id="rightpane" className="col-md-8">
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">Panel title {this.props.meterID}</h3>
</div>
<RightPanelBody data={this.state.data} title={"Data for meter "+this.props.meterID}/>
</div>
</div>
);
*/
}
});
|
var fs = require('fs');
// npm i mmap-io
var mmap = require('mmap-io');
// open /dev/mem with read write permission
fs.open('/dev/mem', 'r+', function (status, fd) {
if (status) {
console.error(status.message);
return;
}
// physical address
const offset = 0x41200000;
// number of bytes
const len = 1;
// map the physical address to a virtual address
const page_base = Math.floor(offset / mmap.PAGESIZE) * mmap.PAGESIZE;
const page_offset = offset - page_base;
const mem = mmap.map(page_offset + len, mmap.PROT_WRITE, mmap.MAP_SHARED, fd, page_base);
mmap.advise(mem, mmap.MADV_RANDOM);
// read
var data = mem[0];
// write
mem[0] = 0x00;
});
|
$('.rule__btn').on('click', function() {
$('.rule__select').toggleClass('closed');
});
$('.rule__select-item').on('click', function() {
$('.rule__select-item').removeClass('selected');
$(this).addClass('selected');
let newText = $(this).text();
$('.rule__btn span').text(newText);
$('.rule__select').toggleClass('closed');
});
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('contact-input', 'Integration | Component | contact input', {
integration: true
});
test('class name applied', function(assert) {
this.render(hbs`{{contact-input fieldName='foo'}}`);
assert.ok(this.$('input').hasClass('foo'), 'fieldName applied as class');
});
test('id and name computed', function(assert) {
this.render(hbs`{{contact-input fieldName='foo'}}`);
assert.equal(this.$('input').attr('id'), 'cd-foo', 'id set');
assert.equal(this.$('input').attr('name'), 'cd-foo', 'name set');
});
|
import { createSlice } from '@reduxjs/toolkit'
import { SERVER_URL } from '../Constants/api';
import dialogContent from '../Constants/dialog';
const initialState = {
user: JSON.parse(localStorage.getItem('user')),
conversations: null,
messages: {},
isLoadingConversation: true,
dialog: {
show:false,
content: dialogContent.NEW_CONVERSATION
},
toasts:[]
}
const appSlice = createSlice({
name: 'app',
initialState,
reducers: {
setUser: (state, action) => {
let user = action.payload
const newState = { ...state, user }
localStorage.setItem('user', JSON.stringify(user))
return newState
},
setConversations: (state, action) => {
const usersState = {}
action.payload.forEach(conv => {
conv.users.forEach(user=>{
usersState[user._id] = user.isActive ?? false
})
});
return {
...state,
conversations: action.payload,
isLoadingConversation: false,
usersState
}
},
createConversation: (state, action) => {
const conversation = action.payload.data
if(action.payload.exists) return {...state,dialog:{show:false,content: dialogContent.NEW_CONVERSATION}}
return { ...state, conversations: [conversation,...state.conversations ],dialog:{show:false,content: dialogContent.NEW_CONVERSATION} }
},
receiveMessage: (state, action) => {
const message = action.payload
const messages = [
...state.messages[message.conv_id],
message
]
const conv = {...state.conversations?.find(c => c._id === message.conv_id), last_msg:message}
return {
...state,
conversations:[
conv,
...state.conversations.filter(c=> c._id !== message.conv_id)
],
messages: {
...state.messages,
[message.conv_id]: messages
}
}
},
receiveMessages: (state, action) => {
const conv_id = action.payload.conv_id
const messages = action.payload.messages
return {
...state,
messages: {
...state.messages,
[conv_id]: messages
}
}
},
seenMessage: (state, action) => {
const {conv_id,msg_id,uId} = action.payload
const conversations = [...state.conversations]
const convIndex = conversations.findIndex(c => c._id === conv_id)
const conv = {...conversations[convIndex]}
const read = [...conv.read.filter(r=>r.user!==uId),{user:uId,msg:msg_id}]
conv.read = read
conversations[convIndex] = conv
return {
...state,
conversations
}
},
showDialog: (state, action) => {
return { ...state, dialog: {...state.dialog, ...action.payload} }
},
updateProfilePhoto: (state,action)=>{
let {img,isGrp,conv_id} = action.payload
img = img.startsWith('http')?img:SERVER_URL+img
if(isGrp){
const conversations = [...state.conversations]
const index = conversations.findIndex(conv => conv._id === conv_id)
conversations[index] = {...conversations[index],img}
return {...state,conversations}
}
let user = {...state.user,img}
localStorage.setItem('user',JSON.stringify(user))
return {...state,user}
},
logout: (state,action) =>{
localStorage.removeItem('user')
return {...initialState,user:null}
},
showToast: (state,action) =>{
return {...state,toasts: [...state.toasts,action.payload]}
},
hideToast: (state,action)=>{
const toasts = [...state.toasts]
toasts.shift()
return {...state,toasts}
},
updateProfile: (state,action)=>{
const user = {...state.user,...action.payload}
localStorage.setItem('user',JSON.stringify(user))
return {...state,user}
},
updateUserState: (state,action) =>{
const {uId,isActive} = action.payload
return {
...state,
usersState:{...state.usersState,[uId]:isActive}
}
}
}
});
export const { setUser,
createConversation,
setConversations,
receiveMessage,
receiveMessages,
showDialog,
updateProfilePhoto,
logout,
showToast,
hideToast,
updateProfile,
seenMessage,
updateUserState,
} = appSlice.actions
export default appSlice.reducer
|
let red = 100;
let green = 100;
let blue = 100;
document.body.style.backgroundColor = `rgb(${red}, ${green}, ${blue})`;
const changeColor = (e) => {
console.log(e.keyCode, e.which) //key down 40, keyup 38
//IF
// if (e.keyCode === 40 && red > 0) {
// red--
// green--
// blue--
// } else if (e.keyCode === 38 && red < 0) {
// red++
// green++
// blue++
// }
//SWITCH
switch (e.keyCode) {
case 38:
console.log("strzalka w gore");
document.body.style.backgroundColor = `rgb(${red<=255? red++:red}, ${green<=255?green++:green}, ${blue<=255?blue++:blue})`;
break;
case 40:
console.log("strzałka w dół");
document.body.style.backgroundColor = `rgb(${red>0?red--:red}, ${green>0?green--:green}, ${blue>0?blue--:blue})`;
break;
}
document.body.style.backgroundColor = `rgb(${red}, ${green}, ${blue})`;
}
window.addEventListener("keydown", changeColor);
|
/*
David Jensen
SDI Section #3
for Loops
2015/01/26
*/
//alert("Testing to see if the JS file is attached to the HTML.");
//while loops
console.log("--------------------Loops--------------------");
//while loops
var b = 10; //sets up the index
while (b > 0){ //checks the condition
console.log(b +" kegs on the wall");
b --; //increments or decrements the index
}
console.log("--------------------Do While Loops--------------------");
//do while loops
var c = 10;
do{
console.log(c +" kegs on the wall"); //code runs before the condition
c--; //
}
while (c > 0); //runs after code
/*
NOTICED!!! while: while this condition is true run those instructions.
NOTICED!!! do while: do those instruction while this condition is true.
*/
//for loops
console.log("--------------------For Loops--------------------");
for (var i= 10; i > 0; i --){
console.log(i +" kegs on the wall.");
}
//WORKING WITH LOOPS
console.log("--------------------WHILE LOOPS--------------------");
var a = 1;
while (a < 1);{
console.log(a);
a++
}
//WORKING WITH LOOPS
console.log("--------------------DO WHILE LOOPS--------------------");
var a = 100;
do{
console.log(a);
a++
}while (a < 10);
var i = 1; //setup of index
while (i < 10){ //check the condition
//
//
//
i++; //incrementing the index
}
//WORKING WITH LOOPS
console.log("--------------------FOR LOOPS--------------------");
for ( var i = 1 ; i < 10 ; i++ ){ //( setup index ; check condition ; increment index )
//
//
//
}
// the "break". Jumps us out of the loop
for (var i = 1;i < 5000;i++){
//
//
if (i == 101){
break;
}
//
}
// the "continue". Done with current iteration, starts back up at top.
|
import React from 'react'
const getEntries = obj => Object.entries(obj)
const Section = ({ name, data = {} }) => {
const entries = getEntries(data)
return <section id={name}>
<h2>{name}</h2>
<table>
<tbody>
{entries.map((entry, i) => <tr key={i}>
<th>{entry[0].toLocaleUpperCase()}:</th>
<td>{entry[1]}</td>
</tr>)}
</tbody>
</table>
</section>
}
export default Section
|
import React from "react";
import Feeds from "./Feeds";
import Post from "./Post";
const PostFeeds = () => {
return (
<div>
<Post />
<Feeds />
</div>
);
};
export default PostFeeds;
|
import { changeProfile } from './Twiter';
describe('Testing Twitter actions', () => {
it('When no profile should change profile to Trump', () => {
expect(changeProfile()).toEqual({
name: 'Donald Trump',
profile: 'realDonaldTrump',
});
});
it('When Trump should change profile to Hilary', () => {
expect(changeProfile('realDonaldTrump')).toEqual({
name: 'Hillary Clinton',
profile: 'HillaryClinton',
});
});
it('When Hilary should change profile to Trump', () => {
expect(changeProfile('HillaryClinton')).toEqual({
name: 'Donald Trump',
profile: 'realDonaldTrump',
});
});
});
|
var Utils = function(){};
var utils = {
constructor:Utils,
load:function(){
Object.prototype.isEmpty = this.__isEmpty;
},
__isEmpty:function() {
for(var key in this) {
if(this.hasOwnProperty(key))
return false;
}
return true;
},
};
|
describe('Sample Test:', () => {
it('check game rules', () => {
cy.visit('index.html');
cy.get('.cell[data-cell-index="0"]').click();
cy.get('.cell[data-cell-index="1"]').click();
cy.get('.cell[data-cell-index="3"]').click();
cy.get('.cell[data-cell-index="4"]').click();
cy.get('.cell[data-cell-index="6"]').click();
cy.get('.cell[data-cell-index="5"]').click().should('have.text', '');
cy.get('.game--status')
.should('contain', 'X')
.should('not.contain', 'O')
.should('contain', 'won');
cy.get('.game--restart').click();
cy.get('.game--status')
.should('contain', 'X')
.should('not.contain', 'O')
.should('contain', 'turn');
cy.get('.cell[data-cell-index="0"]').click();
cy.get('.cell[data-cell-index="2"]').click();
cy.get('.cell[data-cell-index="8"]').click();
cy.get('.cell[data-cell-index="4"]').click();
cy.get('.cell[data-cell-index="5"]').click();
cy.get('.cell[data-cell-index="6"]').click();
cy.get('.game--status')
.should('contain', 'O')
.should('not.contain', 'X')
.should('contain', 'won');
cy.visit('index.html');
cy.get('.cell[data-cell-index="0"]').click();
cy.get('.cell[data-cell-index="3"]').click();
cy.get('.cell[data-cell-index="1"]').click();
cy.get('.cell[data-cell-index="4"]').click();
cy.get('.cell[data-cell-index="2"]').click();
cy.get('.cell[data-cell-index="5"]').click().should('have.text', '');
cy.get('.game--status')
.should('contain', 'X')
.should('not.contain', 'O')
.should('contain', 'won');
cy.get('.game--restart').click();
cy.get('.game--status')
.should('contain', 'X')
.should('not.contain', 'O')
.should('contain', 'turn');
cy.get('.cell[data-cell-index="0"]').click();
cy.get('.cell[data-cell-index="1"]').click();
cy.get('.cell[data-cell-index="2"]').click();
cy.get('.cell[data-cell-index="3"]').click();
cy.get('.cell[data-cell-index="7"]').click();
cy.get('.cell[data-cell-index="8"]').click();
cy.get('.cell[data-cell-index="5"]').click();
cy.get('.cell[data-cell-index="4"]').click();
cy.get('.cell[data-cell-index="6"]').click();
cy.get('.game--status')
.should('contain', 'draw')
.should('not.contain', 'X')
.should('not.contain', 'O');
});
});
|
/**
* Created by lys on 2017/2/24.
*/
$(function () {
var fullPages=document.getElementById("fullpage");
var menu=document.getElementById("menu");
$("#menu>li").on("mouseover", function () {
$(this).addClass('animated tada');
})
$("#menu>li").on("mouseout", function () {
$(this).removeClass('animated tada');
})
var circleMenu=document.getElementById("circleMenu");
fullPage(fullPages,menu);
fullPage(fullPages,circleMenu);
window.onscroll= function () {
if(window.pageYOffset>menu.offsetTop){
menu.className="fixed";
}
if(window.pageYOffset<50){
menu.className="absoluted";
}
}
var mySwiper = new Swiper ('.swiper-container', {
//水平还是垂直,vertical
direction: 'horizontal',
// direction: 'vertical',
loop: true,
//最初是第几页0表示第一页
initialSlide :0,
// 如果需要分页器
pagination: '.swiper-pagination',
//点击分页器的时候是否切换
paginationClickable :true,
//是否要自动播放,后面跟播放时间差
autoplay : 3000,
//用户操作过后是否停止滑动
autoplayDisableOnInteraction : false,
//滑动一下的时间
speed:300,
//鼠标放上去变成小手
grabCursor : true,
effect : 'coverflow',
slidesPerView: 2,
centeredSlides: true,
coverflow: {
rotate: 30,
stretch: 0,
depth: 100,
modifier: 2,
slideShadows : true
},
//是否支持键盘控制
keyboardControl : true,
//是否支持滚轮
mousewheelControl : true,
// 如果需要前进后退按钮
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
})
circle(300,100,80,288);
circle(500,100,80,10);
circle(700,100,80,10);
circle(900,100,80,10);
circle(1100,100,80,10);
circle(1300,100,80,10);
function circle(x,y,r,reg){
var canvas=document.getElementById("cas");
var ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.arc(x,y,r,0,360*Math.PI/180);
ctx.closePath();
ctx.fillStyle="hotpink";
ctx.fill();
ctx.beginPath();
ctx.moveTo(x,y);
ctx.arc(x,y,r,-90*Math.PI/180,(reg-90)*Math.PI/180);
ctx.closePath();
ctx.fillStyle="white";
ctx.fill();
ctx.beginPath();
ctx.arc(x,y,r-10,0,360*Math.PI/180);
ctx.closePath();
ctx.fillStyle="#34353a";
ctx.fill();
}
})
|
import coinApi from "../apis/coinApi";
export const fetchCoins = (page) => async dispatch => {
const response = await coinApi.get(`/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=25&page=${page}&sparkline=false`);
dispatch({
type: 'FETCH_COINS',
payload: response.data
});
};
export const fetchCoinDetails = (id) => async dispatch => {
const response = await coinApi.get(`/coins/${id}`);
dispatch({
type: 'FETCH_COIN_DETAILS',
payload: response.data
});
};
export const fetchCoinChart = (id, duration) => async dispatch => {
const response = await coinApi.get(`/coins/${id}/market_chart?vs_currency=usd&days=${duration}`);
dispatch({
type: 'FETCH_COIN_CHART',
payload: response.data
});
};
export const selectDuration = (duration) => {
return({
type: 'SELECT_DURATION',
payload: duration
});
};
export const setPage = (page) => {
return({
type: 'SET_PAGE',
payload: page
});
};
|
import React, { Component } from "react";
import { Row, Col } from "react-bootstrap";
import Logo from "../../components/common/Logo";
// import "./style.css";
//Components
import ResetPass from "../../components/ResetPass/index";
import Footer from "../../components/common/Footer/Footer"
class Reset extends Component {
// state = {
// text: ""
// };
render() {
return (
<section className="mainbg">
<Row>
<Col />
<Col><Logo></Logo></Col>
<Col />
</Row>
<Row>
<Col></Col>
</Row>
<Row>
<Col></Col>
<Col><ResetPass /></Col>
<Col />
</Row>
<Row>
<Col></Col>
<Col><Footer /></Col>
<Col />
</Row>
</section>
);
}
}
export default Reset;
|
const normalPerson = {
firstName : 'Rahim',
lastName : 'Uddin',
salary : 15000,
getFullName : function(){
console.log(this.firstName,this.lastName);
},
chargeBill: function(amount,tax,tips){
this.salary = this.salary - amount - tips - tax;
return this.salary;
}};
const heroPerson = {
firstName: 'Hero',
lastName: 'Balam',
salary: 25000
};
const friendlyPerson = {
firstName:'Hero',
lastName:'Golam',
salary: 20000
};
// normalPerson.chargeBill();
// const heroChargeBill = normalPerson.chargeBill.bind(heroPerson);
// heroChargeBill(10000);
// const friendlyChargeBill = normalPerson.chargeBill.bind(friendlyPerson);
// friendlyChargeBill(3000);
// console.log(friendlyPerson.salary);
// normalPerson.chargeBill.call(heroPerson, 900,100,500);
// console.log(heroPerson.salary);
// normalPerson.chargeBill.call(friendlyPerson, 1000,500,500);
// // console.log(friendlyPerson.salary);
normalPerson.chargeBill.apply(heroPerson, [3000,300,30]);
normalPerson.chargeBill.apply(heroPerson, [4000,400,100]);
normalPerson.chargeBill.apply(friendlyPerson,[3000,1000,1000])
console.log(heroPerson.salary)
// console.log(friendlyPerson.salary);
// const person = {
// firstName: 'Redwan',
// lastName: 'Nirob',
// salary : 20000,
// getFullName: function(){
// console.log(this.firstName,this.lastName);
// },
// chargeBill : function(amount){
// this.salary = this.salary - amount;
// return amount;
// }
// }
// person.chargeBill(5000);
// console.log(person.salary);
|
import { useEffect } from 'react';
import { connect } from 'react-redux';
import EditTaskView from './EditTaskView';
import TaskView from './TaskView';
import { loadTasksThunk } from '../actions/taskThunkActions';
const TaskList = ({ tasks, loadData }) => {
useEffect(loadData,[]);
return (
<div className="p-2 m-2 col-6">
<h5>Tasks List</h5>
{tasks.map(task => (
task.isEdit ?
<EditTaskView key={task.taskId} task={task} /> :
<TaskView key={task.taskId} task={task} />
))}
</div>
);
};
const mapStateToProps = (state) => ({
tasks: state.tasks
});
const mapDispatchToProps = (dispatch) => ({
loadData: () => dispatch(loadTasksThunk())
});
const connectToStore = connect(mapStateToProps, mapDispatchToProps);
export default connectToStore(TaskList);
|
/*
A module that gives that heartbook database
*/
const HeartBookModule = (function () {
//Variabler
let maleProfiles;
let femaleProfiles;
let allPersons;
const profiles = {
personJson: [
{
"firstName": "Arne",
"age": 30,
"sex": "Male",
"imagesrc": "arne.jpg"
},
{
"firstName": "Elise",
"age": 31,
"sex": "Female",
"imagesrc": "elise.jpg"
},
{
"firstName": "Filip",
"age": 32,
"sex": "Male",
"imagesrc": "filip.jpg"
},
{
"firstName": "Ina",
"age": 33,
"sex": "Female",
"imagesrc": "ina.jpg"
},
{
"firstName": "Mark",
"age": 34,
"sex": "Male",
"imagesrc": "mark.jpg"
},
{
"firstName": "Peter",
"age": 35,
"sex": "Male",
"imagesrc": "peter.jpg"
},
{
"firstName": "Randi",
"age": 36,
"sex": "Female",
"imagesrc": "randi.jpg"
},
{
"firstName": " Tone",
"age": 37,
"sex": "Female",
"imagesrc": "tone.jpg"
}
]
};
//function for get all profiles
function allProfiles() {
allPersons = new Array();
$.each(profiles.personJson, function (i, personJson) {
allPersons = profiles.personJson;
});
return allPersons;
};
function allMale() {
maleProfiles = new Array();
$.each(profiles.personJson, function (i, personJson) {
if (personJson.sex === "Male") {
maleProfiles.push(profiles.personJson[i]);
};
});
return maleProfiles;
};
function allFemale() {
femaleProfiles = new Array();
$.each(profiles.personJson, function (i, personJson) {
if (personJson.sex === "Female") {
femaleProfiles.push(profiles.personJson[i]);
};
});
return femaleProfiles;
};
function profile() {
/*(this) funksjon få ut spesifisert profil*/
}
//exposing API
return {
allProfiles,
allMale,
allFemale
}
}());
|
import React from "react";
import { addDecorator, storiesOf } from "@storybook/react";
import { withKnobs, select } from "@storybook/addon-knobs";
import Logo, { logoSizes, assets } from ".";
const stories = storiesOf("01 - Atom/Logo", module);
addDecorator(withKnobs);
stories
.add("Small", () => {
const size = select("size", logoSizes, logoSizes.SM);
return <Logo size={size} asset={assets.MONEYSAFE} />;
})
.add("Medium", () => {
const size = select("size", logoSizes, logoSizes.MD);
return <Logo size={size} asset={assets.MONEYSAFE} />;
})
.add("Large", () => {
const size = select("size", logoSizes, logoSizes.LG);
return <Logo size={size} asset={assets.MONEYSAFE} />;
});
|
import { UPDATE_PAGE } from '../actions/my-app-action.js';
import { ROUTERDEFAULT } from '../components/routes-setting'
const app = (state =
{
page: ROUTERDEFAULT,
params: {}
}, action) => {
switch (action.type) {
case UPDATE_PAGE:
return {
...state,
page: action.page,
params: action.params,
hash: action.hash
};
default:
return state;
}
}
export default app;
|
const User = require('../Model/user');
async function checkUser(email) {
try {
let sql = `SELECT * FROM user WHERE email = ? `
const [{ password }] = await User.getUser(sql, email);
return password;
} catch (error) {
throw 'can not get the user';
}
}
async function createUser(userInfo) {
try {
let sql = `INSERT INTO user SET ?`
const result = await User.CUDUser(sql, userInfo);
return result;
} catch (error) {
console.log('error: ', error);
throw 'operation error'
}
}
module.exports = {
checkUser,
createUser
}
|
import { sm } from '../util'
import Point from './point'
/**
* Place: a Point subclass representing a 'place' that can be rendered on the
* map. A place is a point *other* than a transit stop/station, e.g. a home/work
* location, a point of interest, etc.
*/
export default class Place extends Point {
/**
* the constructor
*/
constructor(data) {
super(data)
if (data && data.place_lat && data.place_lon) {
const xy = sm.forward([data.place_lon, data.place_lat])
this.worldX = xy[0]
this.worldY = xy[1]
}
this.zIndex = 100000
}
/**
* Get Type
*/
getType() {
return 'PLACE'
}
/**
* Get ID
*/
getId() {
return this.place_id
}
/**
* Get Name
*/
getName() {
return this.place_name
}
/**
* Get lat
*/
getLat() {
return this.place_lat
}
/**
* Get lon
*/
getLon() {
return this.place_lon
}
containsSegmentEndPoint() {
return true
}
containsFromPoint() {
return this.getId() === 'from'
}
containsToPoint() {
return this.getId() === 'to'
}
addRenderData(pointInfo) {
this.renderData.push(pointInfo)
}
getRenderDataArray() {
return this.renderData
}
clearRenderData() {
this.renderData = []
}
/**
* Draw a place
*
* @param {Display} display
*/
render(display) {
super.render(display)
const styler = display.styler
if (!this.renderData) return
const displayStyle = styler.compute2('places', 'display', this)
if (displayStyle === 'none') return
this.renderXY = {
x: display.xScale.compute(
display.activeZoomFactors.useGeographicRendering
? this.worldX
: this.graphVertex.x
),
y: display.yScale.compute(
display.activeZoomFactors.useGeographicRendering
? this.worldY
: this.graphVertex.y
)
}
const radius = styler.compute2('places', 'r', this) || 10
display.drawCircle(this.renderXY, {
fill: styler.compute2('places', 'fill', this) || '#fff',
r: radius,
stroke: styler.compute2('places', 'stroke', this) || '#000',
'stroke-width': styler.compute2('places', 'stroke-width', this) || 2
})
this.markerBBox = {
height: radius * 2,
width: radius * 2,
x: this.renderXY.x - radius,
y: this.renderXY.y - radius
}
}
}
|
export default class Game{
constructor(id,name,unitPrice,type){
this.id=id;
this.name=name;
this.unitPrice;
this.type=type;
}
}
|
function walk(numSteps, length, speed){
var pathToSchool = numSteps*length;
pathToSchool/=1000;
var time = (pathToSchool/speed);
time=time*3600;
var hours = Math.floor(time/3600);
time = time - hours*3600;
var minutes = Math.floor(time/60);
minutes+=Math.floor(pathToSchool/0.5);
var seconds = Math.ceil(time%60);
if(String(hours).length==1)
hours='0'+hours;
if(String(seconds).length==1)
seconds='0'+seconds;
if(String(minutes).length==1)
minutes='0'+minutes;
console.log(hours+':'+minutes+':'+seconds);
}
|
var myDataRef = new Firebase('https://mrclutch.firebaseio.com/test');
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
$('#messagesDiv').fadeTo(1000, 1);
});
function displayChatMessage(name, text) {
$('#messagesDiv').prepend(
'<div class=message">' +
'<div class="text">' + text + '</div>' +
'<div class="name">' + name + '</div>' +
'</div>'
);
};
|
'use strict';
// Configuring the Articles module
angular.module('lens').run(['Menus',
function(Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', 'Lenses', 'lens', 'dropdown', '/lens(/create)?');
Menus.addSubMenuItem('topbar', 'lens', 'List Lenses', 'lens');
Menus.addSubMenuItem('topbar', 'lens', 'New Lens', 'lens/create');
}
]);
|
input.onPinPressed(TouchPin.P1, () => {
basic.setLedColor(Colors.Green)
})
input.onPinPressed(TouchPin.P2, () => {
basic.setLedColor(Colors.Red)
})
input.onPinPressed(TouchPin.P3, () => {
basic.setLedColor(Colors.Yellow)
})
input.onPinPressed(TouchPin.P0, () => {
basic.setLedColor(Colors.Blue)
})
|
var searchData=
[
['keysearch',['KEYSEARCH',['../CNanoVDB_8h.html#a36a572ad0b95a45dc62afe7b53dd63eb',1,'CNanoVDB.h']]],
['keysize',['KEYSIZE',['../CNanoVDB_8h.html#a4b0feb025bc871150dd979b04b527dfd',1,'CNanoVDB.h']]]
];
|
/*
* @lc app=leetcode id=48 lang=javascript
*
* [48] Rotate Image
*/
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
const n = ~~(matrix.length / 2);
const a = matrix;
let temp;
for (let i = 0; i < n; i++) {
const l = matrix.length - i - 1;
for (let j = i; j < matrix.length - i - 1; j++) {
temp = a[i][j];
a[i][j] = a[l - j + i][i]; // 上
a[l - j + i][i] = a[l][l - j + i]; // 左
a[l][l - j + i] = a[j][l]; // 下
a[j][l] = temp; // 右
}
}
};
rotate([
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]);
|
import { Record } from 'immutable';
export default Record({
id: null,
host: null,
organization: null,
repository: null,
repositoryId: null,
branch: null,
active: null,
createdTimestamp: null,
updatedTimestamp: null
});
|
// "Write a function that sorts a list of integers by how far they are to 12,
// and if they are the same distance, by their values. For example,
// if we have a list of integers 0, 3, 5, 13, 19, then the result after sorting the list is 13, 5, 19, 3, 0."
const fromTwelve = (arr) => {
// Code here
}
module.exports = fromTwelve
|
import { EventHandler } from '../../core/event-handler.js';
import { platform } from '../../core/platform.js';
import { XrAnchor } from './xr-anchor.js';
/**
* Callback used by {@link XrAnchors#create}.
*
* @callback XrAnchorCreate
* @param {Error|null} err - The Error object if failed to create an anchor or null.
* @param {XrAnchor|null} anchor - The anchor that is tracked against real world geometry.
*/
/**
* Anchors provide an ability to specify a point in the world that needs to be updated to
* correctly reflect the evolving understanding of the world by the underlying AR system,
* such that the anchor remains aligned with the same place in the physical world.
* Anchors tend to persist better relative to the real world, especially during a longer
* session with lots of movement.
*
* ```javascript
* app.xr.start(camera, pc.XRTYPE_AR, pc.XRSPACE_LOCALFLOOR, {
* anchors: true
* });
* ```
* @augments EventHandler
* @category XR
*/
class XrAnchors extends EventHandler {
/**
* @type {boolean}
* @private
*/
_supported = platform.browser && !!window.XRAnchor;
/**
* List of anchor creation requests.
*
* @type {Array<object>}
* @private
*/
_creationQueue = [];
/**
* Index of XrAnchors, with XRAnchor (native handle) used as a key.
*
* @type {Map<XRAnchor,XrAnchor>}
* @ignore
*/
_index = new Map();
/**
* @type {Array<XrAnchor>}
* @ignore
*/
_list = [];
/**
* Map of callbacks to XRAnchors so that we can call its callback once
* an anchor is updated with a pose for the first time.
*
* @type {Map<XrAnchor,XrAnchorCreate>}
* @private
*/
_callbacksAnchors = new Map();
/**
* @param {import('./xr-manager.js').XrManager} manager - WebXR Manager.
* @hideconstructor
*/
constructor(manager) {
super();
this.manager = manager;
if (this._supported) {
this.manager.on('end', this._onSessionEnd, this);
}
}
/**
* Fired when anchor failed to be created.
*
* @event XrAnchors#error
* @param {Error} error - Error object related to a failure of anchors.
*/
/**
* Fired when a new {@link XrAnchor} is added.
*
* @event XrAnchors#add
* @param {XrAnchor} anchor - Anchor that has been added.
* @example
* app.xr.anchors.on('add', function (anchor) {
* // new anchor is added
* });
*/
/**
* Fired when an {@link XrAnchor} is destroyed.
*
* @event XrAnchors#destroy
* @param {XrAnchor} anchor - Anchor that has been destroyed.
* @example
* app.xr.anchors.on('destroy', function (anchor) {
* // anchor that is destroyed
* });
*/
/** @private */
_onSessionEnd() {
// clear anchor creation queue
for (let i = 0; i < this._creationQueue.length; i++) {
if (!this._creationQueue[i].callback)
continue;
this._creationQueue[i].callback(new Error('session ended'), null);
}
this._creationQueue.length = 0;
// destroy all anchors
if (this._list) {
let i = this._list.length;
while (i--) {
this._list[i].destroy();
}
this._list.length = 0;
}
}
/**
* Create anchor with position, rotation and a callback.
*
* @param {import('../../core/math/vec3.js').Vec3} position - Position for an anchor.
* @param {import('../../core/math/quat.js').Quat} [rotation] - Rotation for an anchor.
* @param {XrAnchorCreate} [callback] - Callback to fire when anchor was created or failed to be created.
* @example
* app.xr.anchors.create(position, rotation, function (err, anchor) {
* if (!err) {
* // new anchor has been created
* }
* });
*/
create(position, rotation, callback) {
this._creationQueue.push({
transform: new XRRigidTransform(position, rotation), // eslint-disable-line no-undef
callback: callback
});
}
/**
* @param {*} frame - XRFrame from requestAnimationFrame callback.
* @ignore
*/
update(frame) {
// check if need to create anchors
if (this._creationQueue.length) {
for (let i = 0; i < this._creationQueue.length; i++) {
const request = this._creationQueue[i];
frame.createAnchor(request.transform, this.manager._referenceSpace)
.then((xrAnchor) => {
if (request.callback)
this._callbacksAnchors.set(xrAnchor, request.callback);
})
.catch((ex) => {
if (request.callback)
request.callback(ex, null);
this.fire('error', ex);
});
}
this._creationQueue.length = 0;
}
// check if destroyed
for (const [xrAnchor, anchor] of this._index) {
if (frame.trackedAnchors.has(xrAnchor))
continue;
anchor.destroy();
}
// update existing anchors
for (let i = 0; i < this._list.length; i++) {
this._list[i].update(frame);
}
// check if added
for (const xrAnchor of frame.trackedAnchors) {
if (this._index.has(xrAnchor))
continue;
try {
const tmp = xrAnchor.anchorSpace; // eslint-disable-line no-unused-vars
} catch (ex) {
// if anchorSpace is not available, then anchor is invalid
// and should not be created
continue;
}
const anchor = new XrAnchor(this, xrAnchor);
this._index.set(xrAnchor, anchor);
this._list.push(anchor);
anchor.update(frame);
const callback = this._callbacksAnchors.get(xrAnchor);
if (callback) {
this._callbacksAnchors.delete(xrAnchor);
callback(null, anchor);
}
this.fire('add', anchor);
}
}
/**
* True if Anchors are supported.
*
* @type {boolean}
*/
get supported() {
return this._supported;
}
/**
* List of available {@link XrAnchor}s.
*
* @type {Array<XrAnchor>}
*/
get list() {
return this._list;
}
}
export { XrAnchors };
|
var app = angular.module('acquireApp', [])
class BoardSpace {
#row;
#col;
#label;
title = '';
occupied = false;
company = -1;
constructor(row, col) {
this.#row = row;
this.#col = col;
this.#label = (this.#row + 1).toString() + String.fromCharCode('A'.charCodeAt() + this.#col);
}
get label() {
return this.#label;
}
get class() {
if (this.occupied) {
var classString = 'occupied';
if (this.company >= 0) {
classString += ' company' + this.company;
}
return classString;
} else {
return 'free';
}
}
}
class Corporation {
#id;
#name = '';
#on_board = false;
#stocks_available = 25;
#stock_price = 200;
constructor(id, name) {
this.#id = id;
this.#name = name;
}
get id() {
return this.#id;
}
get name() {
return this.#name;
}
get available() {
return this.#stocks_available;
}
get price() {
if (this.#on_board) {
return '$' + this.#stock_price;
} else {
return '---';
}
}
}
class Tile {
#id;
constructor(id) {
this.#id = id;
}
get id() {
return this.#id;
}
onMouseIn() {
document.getElementById(this.#id).classList.add('hovered');
}
onMouseOut() {
document.getElementById(this.#id).classList.remove('hovered');
}
}
app.controller('boardCtrl', function ($scope, $http) {
$scope.rows = [];
for (row = 0; row < 10; row++) {
$scope.rows.push([]);
for (col = 0; col < 10; col++) {
$scope.rows[row].push(new BoardSpace(row, col));
}
}
$scope.rows[3][2].occupied = true;
$scope.rows[2][4].occupied = true;
$scope.rows[7][7].occupied = true;
$scope.rows[7][7].company = 0;
$scope.rows[7][7].title = 'Techno\nSize: 3 (safe)';
$scope.rows[6][7].occupied = true;
$scope.rows[6][7].company = 0;
$scope.rows[7][6].occupied = true;
$scope.rows[7][6].company = 0;
$scope.rows[5][0].occupied = true;
$scope.rows[5][0].company = 1;
$scope.rows[9][5].occupied = true;
$scope.rows[9][5].company = 2;
$scope.rows[1][8].occupied = true;
$scope.rows[1][8].company = 3;
$scope.rows[4][4].occupied = true;
$scope.rows[4][4].company = 4;
$scope.rows[7][0].occupied = true;
$scope.rows[7][0].company = 5;
$scope.rows[6][3].occupied = true;
$scope.rows[6][3].company = 6;
$scope.rows[7][3].occupied = true;
$scope.rows[7][3].company = 6;
});
app.controller('corporationCtrl', function ($scope, $http) {
$scope.corporations = [
new Corporation(0, 'Techno'),
new Corporation(1, 'Gizmo'),
new Corporation(2, 'Unicorn'),
new Corporation(3, 'DotCom'),
new Corporation(4, 'Avago'),
new Corporation(5, 'Leaf'),
new Corporation(6, 'Progresso')
];
});
app.controller('tilesCtrl', function($scope, $http) {
$scope.tiles = [];
$scope.tiles.push(new Tile('2D'));
$scope.tiles.push(new Tile('5F'));
$scope.tiles.push(new Tile('7A'));
$scope.tiles.push(new Tile('9H'));
$scope.tiles.push(new Tile('8B'));
$scope.tiles.push(new Tile('4G'));
});
|
/**
*
* @author Maurício Generoso
*/
(() => {
'use strict';
describe('Test Factory: MsgFactory', () => {
beforeEach(angular.mock.module('radarApp'))
var _MsgFactory;
beforeEach(inject((MsgFactory) => {
_MsgFactory = MsgFactory;
}));
it('Test if MsgFactory is defined', () => {
expect(_MsgFactory).toBeDefined();
expect(_MsgFactory.addSuccess).toBeDefined();
expect(_MsgFactory.addSuccessWithTitle).toBeDefined();
expect(_MsgFactory.addError).toBeDefined();
expect(_MsgFactory.addErrorWithTitle).toBeDefined();
})
})
})();
|
import { StyleSheet, Dimensions, Platform } from 'react-native';
const window = Dimensions.get('window');
import Constants from 'expo-constants';
import colors from '../../assets/colors';
import theme from '../../assets/theme';
export default styles = StyleSheet.create({
container: {
flex: 1,
padding: 0,
//backgroundColor: colors.background_color,
},
navbarStyle: {
paddingTop: (Platform.OS === 'ios') ? 0 : Constants.statusBarHeight,
height: (Platform.OS === 'ios') ? 0 : Constants.statusBarHeight,
backgroundColor: colors.green,
borderBottomWidth: 1,
borderBottomColor: colors.green,
},
headerItem: {
flexDirection: 'row',
paddingLeft: 16,
paddingRight:16,
paddingBottom: 10,
alignItems: 'center',
marginTop: 10,
width: '100%',
},
divider : {
width: '100%',
height: 1,
backgroundColor: colors.divider,
},
imageLogo: {
height: 20,
width: 20,
tintColor: theme.colorAccent,
marginLeft : 16
},
// profileTxt: {
// fontSize: theme.MediumFont,
// fontFamily: theme.primaryFont,
// color: theme.colorAccent,
// },
// backIcon: {
// height: 20,
// width: 20,
// tintColor: theme.colorAccent,
// },
// toolbarView : {
// width : '100%',
// justifyContent : 'center',
// alignItems : 'center',
// paddingRight : 24
// },
// headerItem : {
// height : 150,
// backgroundColor : theme.height,
// justifyContent : 'center',
// alignItems : 'center',
// },
// touchView : {
// flexDirection : 'row',
// backgroundColor : colors.green,
// alignItems : 'center',
// height : 50,
// paddingLeft : 16,
// position : 'relative',
// bottom : 0,
// },
// imageStyle : {
// height : 60,
// width : 60,
// borderRadius : 100
// },
// logoutIcon : {
// height : 18,
// width : 18,
// tintColor : theme.colorAccent,
// },
// LogoutTxt : {
// fontSize : 14,
// fontFamily : theme.primaryFont,
// color : theme.colorAccent,
// paddingLeft : 8
// },
drawerImageView : {
flexDirection : 'column',
backgroundColor : theme.colorAccent,
height : '25%',
elevation : 1,
shadowColor : theme.primaryTextColor,
shadowOffset : {height : 1, width : 0},
shadowOpacity : 0.25,
shadowRadius : 2.56,
marginBottom: 8,
justifyContent: 'center',
alignItems : 'flex-start',
},
userDetailView : {
flexDirection : 'column',
// paddingTop : 16,
},
txtuser: {
fontFamily : theme.primaryFont,
marginLeft : 15,
},
draweIcon : {
width : 25,
height : 25,
resizeMode : 'contain',
tintColor : theme.primaryColor,
},
txtuserName : {
fontFamily : theme.secondaryFont,
fontSize : theme.MediumFont,
marginLeft : 15,
},
sideMenuContainer: {
width: '100%',
height: '100%',
backgroundColor: theme.colorAccent,
// alignItems: 'center',
// paddingTop: 10,
},
sideMenuProfileIcon: {
resizeMode: 'contain',
width: 60,
height: 70,
marginLeft : 20,
marginVertical: 8
},
navToolbar : {
paddingLeft : 10,
color : theme.colorAccent,
},
imageMore: {
height: 18,
width: 18,
tintColor: colors.white,
},
overflowBtn : {
paddingVertical: 8,
paddingHorizontal: 16,
backgroundColor: theme.primaryColor,
marginRight: 4,
},
txtEmail: {
fontFamily : theme.secondaryFont,
fontSize : theme.MediumFont,
marginLeft : 15,
textAlign: 'center',
}
});
|
var canvas;
var context;
var pacman = {};
var bill;
var binky;
var pinky;
var inky;
var board;
var score;
var pac_color;
var start_time;
var time_elapsed;
var interval;
var loaded = false;
var direction = 0;
var food_put = 0;
var interval_num = 0;
var score2win = 50;
var timeClock;
var extraTimeDelta = 10;
var showingMessage = false;
var backgroundMusic = new Audio("assets/audio/pacman-beginning/Sweet Success.mp3");
pacman.lives = 3;
window.addEventListener("keydown", UpdatePosition, false);
var GameOn = false;
/**
* First Game Start
*/
function startGame() {
display_game();
GameOn = true;
start();
}
function pauseMusic() {
backgroundMusic.pause();
}
/**
* Regular Game start
*/
function start() {
if (GameOn) {
backgroundMusic.loop = true;
backgroundMusic.play();
pacman.lives = 3;
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
board = [
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[4, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 9, 4],
[4, 0, 4, 4, 0, 4, 4, 4, 0, 4, 0, 4, 4, 4, 0, 4, 4, 0, 4],
[4, 0, 4, 4, 0, 4, 4, 4, 0, 4, 0, 4, 4, 4, 0, 4, 4, 0, 4],
[4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
[4, 0, 4, 4, 0, 4, 0, 4, 4, 4, 4, 4, 0, 4, 0, 4, 4, 0, 4],
[4, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 4],
[4, 4, 4, 4, 0, 4, 4, 4, 0, 4, 0, 4, 4, 4, 0, 4, 4, 4, 4],
[4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4],
[4, 0, 4, 4, 0, 4, 0, 4, 4, 4, 0, 4, 0, 4, 0, 4, 4, 0, 4],
[0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0],
[4, 4, 4, 4, 0, 4, 0, 4, 0, 4, 4, 4, 0, 4, 0, 4, 4, 0, 4],
[4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4],
[4, 0, 4, 4, 0, 4, 0, 4, 4, 4, 4, 4, 0, 4, 0, 4, 4, 4, 4],
[4, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 4],
[4, 0, 4, 4, 0, 4, 4, 4, 0, 4, 0, 4, 4, 4, 0, 4, 4, 0, 4],
[4, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4],
[4, 4, 0, 4, 0, 4, 0, 4, 4, 4, 4, 4, 0, 4, 0, 4, 0, 4, 4],
[4, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 4],
[4, 0, 4, 4, 4, 4, 4, 4, 0, 4, 0, 4, 4, 4, 4, 4, 4, 0, 4],
[4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 4],
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
];
interval_num = 0;
score2win = 50;
score = 0;
pac_color = "yellow";
timeClock = {i: 10, j: 10, id: 11, on: 0};
bill = new Ghost(20, 17, 10, "red", 0, 4);
binky = new Ghost(20, 1, 7, "red", 0, 4);
pinky = new Ghost(1, 1, 8, "pink", 0, 4);
inky = new Ghost(1, 17, 9, "cyan", 0, 4);
restart();
var food_remain = num_balls;
start_time = new Date();
while (food_remain >= 0) {
var emptyCell = findRandomEmptyCell(board);
if (food_remain >= 0.4 * num_balls) {
board[emptyCell[0]][emptyCell[1]] = 1;
score2win += 5;
} else if (food_remain >= 0.1 * num_balls) {
board[emptyCell[0]][emptyCell[1]] = 5;
score2win += 15;
} else {
board[emptyCell[0]][emptyCell[1]] = 6;
score2win += 25;
}
food_remain--;
}
keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.which] = true;
}, false);
addEventListener("keyup", function (e) {
keysDown[e.which] = false;
}, false);
}
}
/**
* Restart When Pacman dies
*/
function restart() {
interval = undefined;
keysDown = {};
for (let k = 1; k < board.length - 1; k++) {
for (let l = 1; l < board[0].length - 1; l++) {
if (board[k][l] === 7) {
board[k][l] = binky.on;
}
if (board[k][l] === 8) {
board[k][l] = pinky.on;
}
if (board[k][l] === 9) {
board[k][l] = inky.on;
}
if (board[k][l] === 10) {
board[k][l] = bill.on;
}
}
}
interval_num = 0;
if (bill.color === "red") {
bill = new Ghost(20, 17, 10, "red", 0, 4);
board[bill.i][bill.j] = 10;
}
binky = new Ghost(20, 1, 7, "red", 0, 4);
pinky = new Ghost(1, 1, 8, "pink", 0, 4);
inky = new Ghost(1, 17, 9, "cyan", 0, 4);
board[binky.i][binky.j] = binky.id;
board[pinky.i][pinky.j] = pinky.id;
board[inky.i][inky.j] = inky.id;
let pacx = parseInt(Math.random() * 18) + 2;
let pacy = parseInt(Math.random() * 15) + 2;
while (board[pacx][pacy] !== 0) {
pacx = parseInt(Math.random() * 18) + 2;
pacy = parseInt(Math.random() * 15) + 2;
}
pacman.i = pacx;
pacman.j = pacy;
board[pacx][pacy] = 2;
if (num_monster < 3) {
board[inky.i][inky.j] = 0;
inky = binky;
}
if (num_monster < 2) {
board[pinky.i][pinky.j] = 0;
pinky = binky;
}
if (interval === undefined)
interval = setInterval(UpdatePosition, 125);
}
//todo - Reset button
function findRandomEmptyCell(board) {
var i = Math.floor((Math.random() * 21) + 1);
var j = Math.floor((Math.random() * 18) + 1);
while (board[i][j] !== 0) {
i = Math.floor((Math.random() * 21) + 1);
j = Math.floor((Math.random() * 18) + 1);
}
return [i, j];
}
/**
* @return {number}
*/
function GetKeyPressed() {
if (keysDown[keyUp]) {
direction = 1.5;
return 3;
// return 3;
}
if (keysDown[keyDown]) {
direction = 0.5;
return 1;
// return 4;
}
if (keysDown[keyLeft]) {
direction = 1;
return 2;
// return 1;
}
if (keysDown[keyRight]) {
direction = 0;
return 0;
// return 2;
}
}
function Draw() {
let center = {};
function drawGhost(ghost) {
context.arc(center.x, center.y, 15, Math.PI, 0); // half circle
context.lineTo(center.x, center.y);
context.fillStyle = ghost.color; //color
context.fill();
context.beginPath();
if (interval_num % 10 < 5) {
context.lineTo(center.x - 15, center.y);
context.lineTo(center.x - 15, center.y + 15);
context.lineTo(center.x - 10, center.y + 10);
context.lineTo(center.x - 5, center.y + 15);
context.lineTo(center.x, center.y + 10);
context.lineTo(center.x + 5, center.y + 15);
context.lineTo(center.x + 10, center.y + 10);
context.lineTo(center.x + 15, center.y + 15);
context.lineTo(center.x + 15, center.y);
context.fill()
} else {
context.lineTo(center.x - 15, center.y);
context.lineTo(center.x - 15, center.y + 10);
context.lineTo(center.x - 10, center.y + 15);
context.lineTo(center.x - 5, center.y + 10);
context.lineTo(center.x, center.y + 15);
context.lineTo(center.x + 5, center.y + 10);
context.lineTo(center.x + 10, center.y + 15);
context.lineTo(center.x + 15, center.y + 10);
context.lineTo(center.x + 15, center.y);
context.fill()
}
// context.fillRect(center.x - 15, center.y, 30, 15);
//Eyes
context.beginPath();
context.arc(center.x - 6, center.y - 2.5, 4, 0, 2 * Math.PI); // circle
context.lineTo(center.x, center.y);
context.arc(center.x + 6, center.y - 2.5, 4, 0, 2 * Math.PI); // circle
context.lineTo(center.x, center.y);
context.fillStyle = "white"; //color
context.fill();
context.beginPath();
context.arc(center.x - 4.5, center.y - 2, 2, 0, 2 * Math.PI); // circle
context.lineTo(center.x, center.y);
context.arc(center.x + 4.5, center.y - 2, 2, 0, 2 * Math.PI); // circle
context.lineTo(center.x, center.y);
context.fillStyle = "black"; //color
context.fill();
}
context.clearRect(0, 0, canvas.width, canvas.height); //clean board
lblScore.value = score;
lblTime.value = time_elapsed;
lblLife.value = pacman.lives;
for (let i = 0; i < 19; i++) {
for (let j = 0; j < 22; j++) {
center.x = i * 30 + 15;
center.y = j * 30 + 15;
context.beginPath();
//Pacman
if (board[j][i] === 2) {
context.arc(center.x, center.y, 15, (direction + (0.25 - (0.25 / (0.25 + interval_num % 3)))) * Math.PI, (direction + 1.8) * Math.PI); // half circle
context.lineTo(center.x, center.y);
context.fillStyle = pac_color; //color
context.fill();
context.beginPath();
// Eye
if (direction === 0) { //right
context.arc(center.x + 2.5, center.y - 7.5, 2.5, 0, 2 * Math.PI); // circle
}
if (direction === 0.5) {//down
context.arc(center.x - 7.5, center.y - 2.5, 2.5, 0, 2 * Math.PI); // circle
}
if (direction === 1.5) {//up
context.arc(center.x - 7.5, center.y - 2.5, 2.5, 0, 2 * Math.PI); // circle
}
if (direction === 1) {//left
context.arc(center.x - 2.5, center.y - 7.5, 2.5, 0, 2 * Math.PI); // circle
}
// context.arc(center.x + 2.5, center.y - 7.5, 2.5, 0, 2 * Math.PI); // circle
context.fillStyle = "black"; //color
context.fill();
}
//Binkey
else if (board[j][i] === 7) {
drawGhost(binky);
}
//Pinky
else if (board[j][i] === 8) {
drawGhost(pinky);
}
//Binkey
else if (board[j][i] === 9) {
drawGhost(inky);
}
// Food
//regular (5 points)
else if (board[j][i] === 1) {
context.arc(center.x, center.y, 8, 0, 2 * Math.PI); // circle
context.fillStyle = color_5; //color
context.fill();
context.font = "15px Arial";
context.fillStyle = "white"; //color of text
context.fillText("5", center.x - 4.5, center.y + 5);
} else if (board[j][i] === 5) {
//medium (15 points)
context.arc(center.x, center.y, 12, 0, 2 * Math.PI); // circle
context.fillStyle = color_15; //color
context.fill();
context.font = "18px Arial";
context.fillStyle = "white"; //color of text
context.fillText("15", center.x - 11, center.y + 7);
} else if (board[j][i] === 6) {
//big (25 points)
context.arc(center.x, center.y, 15, 0, 2 * Math.PI); // circle
context.fillStyle = color_25; //color
context.fill();
context.font = "20px Arial";
context.fillStyle = "white"; //color of text
context.fillText("25", center.x - 11, center.y + 8);
} else if (board[j][i] === 4) {
context.rect(center.x - 15, center.y - 15, 30, 30);
context.fillStyle = "grey"; //color
context.fill();
} else if (board[j][i] === 10) {
context.arc(center.x, center.y, 10, 0, 2 * Math.PI); // circle
let my_gradient = context.createLinearGradient(center.x - 7, center.y - 7, center.x + 7, center.y + 7);
my_gradient.addColorStop(0, "red");
my_gradient.addColorStop(0.5, "white");
my_gradient.addColorStop(1, "red");
context.fillStyle = my_gradient;
context.fill();
context.closePath();
context.beginPath();
context.lineTo(center.x, center.y);
context.lineTo(center.x - 15, center.y - 7);
context.lineTo(center.x - 7, center.y - 15);
context.fill();
context.closePath();
context.beginPath();
context.lineTo(center.x, center.y);
context.lineTo(center.x + 15, center.y + 7);
context.lineTo(center.x + 7, center.y + 15);
context.fill();
context.closePath();
} else if (board[j][i] === 11) {
context.arc(center.x - 10, center.y - 14, 6, 0, 2 * Math.PI); // circle
context.fillStyle = "yellow";
context.fill();
context.beginPath();
context.arc(center.x + 10, center.y - 14, 6, 0, 2 * Math.PI); // circle
context.fill();
context.beginPath();
context.fillStyle = "gold";
context.arc(center.x - 13, center.y - 19, 1.5, 0, 2 * Math.PI); // circle
context.fill();
context.beginPath();
context.arc(center.x + 13, center.y - 19, 1.5, 0, 2 * Math.PI); // circle
context.fill();
context.beginPath();
context.arc(center.x, center.y, 18, 0, 2 * Math.PI); // circle
context.fillStyle = "red";
context.fill();
context.beginPath();
context.arc(center.x, center.y, 14, 0, 2 * Math.PI); // circle
context.fillStyle = "white";
context.fill();
context.beginPath();
context.font = "bold 16px Arial";
context.fillStyle = "black";
context.fillText("+", center.x - 12, center.y + 7);
context.fillText("1", center.x - 4, center.y + 6);
context.fillText("0", center.x + 4, center.y + 6);
}
}
}
}
function isGhostPlace(di, dj, ghost) {
let place = board[ghost.i + di][ghost.j + dj];
return !(place === 7 || place === 8 || place === 9 || place === 4 || place === 2 || place === 10);
}
function isValidMove(direction, ghost) {
if (direction === 1 && ghost.i < 21 && isGhostPlace(1, 0, ghost)) {
return true;
}
if (direction === 0 && ghost.j < 18 && isGhostPlace(0, 1, ghost)) {
return true;
}
if (direction === 3 && ghost.i > 0 && isGhostPlace(-1, 0, ghost)) {
return true;
}
return direction === 2 && ghost.i > 0 && isGhostPlace(0, -1, ghost);
}
function moveBill() {
function runAway() {
let res = parseInt(Math.random() * 4) % 4;
while (!isValidMove(res, bill))
res = parseInt(Math.random() * 4) % 4;
return res;
}
board[bill.i][bill.j] = bill.on;
// let next = 2;
let next = runAway();
if (bill.lastMove !== 4)
bill.lastMove = next;
if (next === 0) {
bill.on = board[bill.i][bill.j + 1];
board[bill.i][bill.j + 1] = bill.id;
bill.j++;
}
if (next === 1) {
bill.on = board[bill.i + 1][bill.j];
board[bill.i + 1][bill.j] = bill.id;
bill.i++;
}
if (next === 2) {
bill.on = board[bill.i][bill.j - 1];
board[bill.i][bill.j - 1] = bill.id;
bill.j--;
}
if (next === 3) {
bill.on = board[bill.i - 1][bill.j];
board[bill.i - 1][bill.j] = bill.id;
bill.i--;
}
}
function computeDistance(ghost, pacman) {
let dx = ghost.i - pacman.i;
let dy = ghost.j - pacman.j;
return Math.sqrt((dx * dx) + (dy * dy));
}
function GetNextMove(ghost) {
ghost.j++;
let x0 = computeDistance(ghost, pacman);
ghost.j--;
ghost.i++;
let x1 = computeDistance(ghost, pacman);
ghost.i--;
ghost.j--;
let x2 = computeDistance(ghost, pacman);
ghost.j++;
ghost.i--;
let x3 = computeDistance(ghost, pacman);
ghost.i++;
let shortest = x0;
let res = 0;
if (!isValidMove(res, ghost) || res === ghost.lastMove) {
shortest = x1;
res = 1;
}
if (!isValidMove(res, ghost) || res === ghost.lastMove) {
shortest = x2;
res = 2;
}
if (!isValidMove(res, ghost) || res === ghost.lastMove) {
shortest = x3;
res = 3;
}
if ((x1 <= shortest || res === ghost.lastMove) && isValidMove(1, ghost)) {
shortest = x1;
res = 1;
}
if ((x2 <= shortest || res === ghost.lastMove) && isValidMove(2, ghost)) {
shortest = x2;
res = 2;
}
if ((x3 <= shortest || res === ghost.lastMove) && isValidMove(3, ghost)) {
res = 3;
}
if (!isValidMove(0, ghost) && !isValidMove(1, ghost) && !isValidMove(2, ghost) && !isValidMove(3, ghost))
return 4;//stay
return res;
}
function moveGhost(ghost) {
board[ghost.i][ghost.j] = ghost.on;
let next = GetNextMove(ghost);
if (ghost.lastMove !== 4)
ghost.lastMove = next;
if (next === 0) {
ghost.on = board[ghost.i][ghost.j + 1];
board[ghost.i][ghost.j + 1] = ghost.id;
ghost.j++;
}
if (next === 1) {
ghost.on = board[ghost.i + 1][ghost.j];
board[ghost.i + 1][ghost.j] = ghost.id;
ghost.i++;
}
if (next === 2) {
ghost.on = board[ghost.i][ghost.j - 1];
board[ghost.i][ghost.j - 1] = ghost.id;
ghost.j--;
}
if (next === 3) {
ghost.on = board[ghost.i - 1][ghost.j];
board[ghost.i - 1][ghost.j] = ghost.id;
ghost.i--;
}
}
function moveGhosts() {
moveGhost(binky);
if (num_monster > 1)
moveGhost(pinky);
if (num_monster > 2)
moveGhost(inky);
Draw();
}
function isCaught(ghost) {
return ghost.i === pacman.i && ghost.j === pacman.j;
}
function Caught() {
pacman.lives--;
score -= 10;
score2win -= 10;
board[pacman.i][pacman.j] = 0;
// Draw();
if (pacman.lives > 0) {
// while (window.interval !== undefined && window.interval !== 'undefined')
window.clearTimeout(interval);
window.clearInterval(interval);
// window.alert("You Lost 1 Life,\n" + pacman.lives + " Lives Remain");
// Alert(pacman.lives + " Lives Remain",3000)
restart();
} else {
if (checkIfInGame()) {
// while (window.interval !== undefined && window.interval !== 'undefined')
window.clearTimeout(interval);
window.clearInterval(interval);
GameOn = false;
window.alert("You Lost");
backgroundMusic.pause();
display_settings_menu();
}
}
}
/**
* @return {boolean}
*/
function TimeAboutToStop(time_elpased) {
return (time_elpased >= num_time - extraTimeDelta || num_time - extraTimeDelta <= 0) && extraTimeDelta > 0;
}
function ExtraTime() {
if (timeClock.on === 0) {
let timx = parseInt(Math.random() * 18) + 2;
let timy = parseInt(Math.random() * 15) + 2;
while (board[timx][timy] !== 0 || (Math.abs(timx - pacman.i) + Math.abs(timy - pacman.j) < 3) || (Math.abs(timx - binky.i) + Math.abs(timy - binky.j) < 3) || (Math.abs(timx - pinky.i) + Math.abs(timy - pinky.j) < 3) || (Math.abs(timx - inky.i) + Math.abs(timy - inky.j) < 3)) {
timx = parseInt(Math.random() * 18) + 2;
timy = parseInt(Math.random() * 15) + 2;
}
timeClock.i = timx;
timeClock.j = timy;
board[timx][timy] = 11;
timeClock.on = 11;
Draw();
}
}
function addExtraTime() {
extraTimeDelta--;
num_time += 10;
timeClock.on = 0;
Draw();
}
function checkIfInGame() {
if (document.getElementById("game").style.display === "none") {
return false;
}
return true;
}
function UpdatePosition() {
if (GameOn) {
Draw();
if (interval_num % 5 === 3 && bill.color === "red")
moveBill();
board[pacman.i][pacman.j] = 0;
let x = GetKeyPressed();
if (interval_num % 12 === 11 && interval_num > 16) {
moveGhosts();
}
if (x === 2) {
if (pacman.j > 0 && board[pacman.i][pacman.j - 1] !== 4) {
pacman.j--;
} else if (board[pacman.i][pacman.j - 1] !== 4) {
pacman.j = 18;
}
}
if (x === 0) {
if (pacman.j < 18 && board[pacman.i][pacman.j + 1] !== 4) {
pacman.j++;
} else if (board[pacman.i][pacman.j + 1] !== 4) {
pacman.j = 0;
}
}
if (x === 3) {
if (pacman.i > 0 && board[pacman.i - 1][pacman.j] !== 4) {
pacman.i--;
} else if (board[pacman.i - 1][pacman.j] !== 4) {
pacman.i = 21;
}
}
if (x === 1) {
if (pacman.i < 21 && board[pacman.i + 1][pacman.j] !== 4) {
pacman.i++;
} else if (board[pacman.i + 1][pacman.j] !== 4) {
pacman.i = 0;
}
}
if (board[pacman.i][pacman.j] === 1) {
score += 5;
}
if (board[pacman.i][pacman.j] === 5) {
score += 15;
}
if (board[pacman.i][pacman.j] === 6) {
score += 25;
}
if (board[pacman.i][pacman.j] === 10 || isCaught(bill)) {
if (bill.on === 1)
score += 5;
if (bill.on === 5)
score += 15;
if (bill.on === 6)
score += 25;
score += 50;
bill.color = "blue";
bill.i = 22;
bill.j = 22;
}
if (board[pacman.i][pacman.j] === 11 || (timeClock.i === pacman.i && timeClock.j === pacman.j)) {
addExtraTime();
}
board[pacman.i][pacman.j] = 2;
interval_num++;
let currentTime = new Date();
time_elapsed = (currentTime - start_time) / 1000;
if (TimeAboutToStop(time_elapsed)) {
ExtraTime();
}
//todo - listener for time past
if (time_elapsed >= num_time) {
window.clearTimeout(interval);
window.clearInterval(interval);
if (checkIfInGame()) {
if (score >= 150) {
window.alert("We Have a Winner!");
GameOn = false;
display_settings_menu();
} else {
GameOn = false;
window.alert("You Can Do Better..");
display_settings_menu();
}
}
}
if (score >= 200 && time_elapsed <= 10) {
pac_color = "green";
}
if (isCaught(binky) || isCaught(pinky) || isCaught(inky)) {
Caught();
} else if (board[pacman.i][pacman.j] === 7 || board[pacman.i][pacman.j] === 8 || board[pacman.i][pacman.j] === 9) {
Caught();
}
if (checkIfInGame()) {
if (score === score2win) {
Draw();
window.clearTimeout(interval);
window.clearInterval(interval);
GameOn = false;
const winNotification = window.createNotification({
theme: 'success',
closeOnClick: true,
onclick: false,
positionClass: 'nfc-top-right',
displayCloseButton: true,
showDuration: 4000
});
winNotification({
title: 'Winner!',
message: 'LOOK AT YOU!!'
});
window.alert("Game completed");
} else {
Draw();
}
}
}
}
class Ghost {
constructor(i, j, id, color, on, lastMove) {
this.i = i;
this.j = j;
this.id = id;
this.color = color;
this.on = on;
this.lastMove = lastMove;
}
}
|
#!/usr/bin/env node
const inquirer = require("inquirer")
const chalk = require("chalk")
const fs = require("fs")
const temObj = require(`${__dirname}/../template`)
const options = {
encoding:"utf-8",
flag:"w"
}
const questionList = [
{
type:"input",
name:"temName",
message:"Template you want to delete : ",
validate(val){
if(val===null || val===''){
return "Template name is empty"
}else if(!temObj[val]){
return "Template doesn't exist!"
}else{
return true
}
}
},
]
inquirer
.prompt(questionList).then(answers=>{
let {temName} = answers;
delete temObj[temName]
fs.writeFile(`${__dirname}/../template.json`,JSON.stringify(temObj),options,(err)=>{
if(err){
console.log(err)
}
console.log(chalk.greenBright('\nDeleted successfully!'))
console.log(chalk.yellowBright("now your template list is:"))
console.log(temObj)
})
})
|
'use strict';
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class Rectangle {
constructor(x, y, width, height, label) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.label = label;
}
/**
* Returns the area of intersection with another rectangle
*/
calcIntersectArea(rect) {
// Take the difference in x and y vector lengths
let dx = Math.min(this.x + this.width, rect.x + rect.width) - Math.max(this.x, rect.x);
let dy = Math.min(this.y + this.height, rect.y + rect.height) - Math.max(this.y, rect.y);
// Intersection exists if the difference is greater than zero
return Math.max(0, dx) * Math.max(0, dy);
}
}
class PointMenu {
constructor(elementId) {
this.elementId = elementId;
this.element = document.getElementById(elementId);
this.menu = document.querySelector("#pmMenu");
this.dot = document.querySelector("#originPoint");
this.stem = document.querySelector("#stem");
this.isOpen = false;
// pixel length of connecting stem
this.stemLength = 80;
// the distance the menu will travel when animating in
this.driftLength = 128;
this.hide();
}
set coordinates(point) {
this.element.style.transform = `translate(${point.x}px, ${point.y}px)`;
}
hide() {
this.element.style.display = "none";
}
show() {
this.element.style.display = "block";
}
/**
* Opens the menu at a given coordinate
* @param {Point} pt
*/
openAtPoint(pt) {
this.isOpen = true;
this.show();
let rectMenu = this.element.getBoundingClientRect();
let layout = this.getBestLayout(pt, rectMenu, this.stemLength);
// Move the menu to the most visible location
let ptMenuLocation = layout[0];
let strStemDirection = layout[1];
PointMenu.translate(this.element, ptMenuLocation);
// Move the dot to the location user tapped
let ptDot = PointMenu.globalToLocal(pt, ptMenuLocation);
PointMenu.translate(this.dot, ptDot);
// Orient the stem according to layout
this.orientStem(ptDot, rectMenu, strStemDirection);
// Animate the intro
this.animateIn(strStemDirection);
}
close() {
this.isOpen = false;
TweenMax.killAll();
TweenMax.to(this.element, 0.2, { opacity: 0, ease: Power4.easeOut});
}
/**
* Moves the stem to the correct location. This method is brittle and hacky due to my use of CSS
* tranforms. A better method might use matrix transforms or drawing the line via a canvas
*/
orientStem(ptOrigin, rectMenu, direction) {
let x, y;
if (direction === "N" || direction === "S") {
// x is offset by half the width of the menu
x = rectMenu.width / 2 - this.stemLength / 2 - 1;
y = (ptOrigin.y < 0) ? ptOrigin.y + this.stemLength / 2 : rectMenu.height + this.stemLength / 2;
this.stem.style.transform = `translate(${x}px,${y}px) rotate(90deg)`;
} else {
// y is offset by half the height of the menu
x = (ptOrigin.x < 0) ? ptOrigin.x : rectMenu.width;
PointMenu.translate(this.stem, new Point(x, rectMenu.height / 2 - 1));
}
}
static translate(element, point) {
element.style.transform = `translate(${point.x}px, ${point.y}px)`;
}
static rotate(element, degrees) {
element.style.transform = `rotate(${degrees}deg)`;
}
/**
* Transforms a screen coordinate to a local coordinate
*/
static globalToLocal(ptGlobal, ptLocal) {
let dx = ptGlobal.x - ptLocal.x;
let dy = ptGlobal.y - ptLocal.y;
return new Point(dx, dy);
}
/**
* Returns the amount of translation applied to an element
*
* @return {Point}
*/
static getTranslation(element) {
let match = RegExp(/translate\((-?\d+)px,\s(-?\d+)px\)/, 'g').exec(element.style.transform);
return new Point(match[1], match[2]);
}
animateIn(direction) {
TweenMax.killAll();
this.element.style.opacity = 1;
/*
-----------------------
Animate the menu shape
-----------------------
*/
let pMenu = {
aOpacity: 0,
zOpacity: 1,
aScale: 0.4,
zScale: 1,
aX: 0,
zX: 0,
aY: 0,
zY: 0
}
if (direction === "E" || direction === "W") {
pMenu.aX = (direction === "E") ? -this.driftLength : this.driftLength;
} else {
pMenu.aY = (direction === "N") ? this.driftLength : -this.driftLength;
}
TweenMax.fromTo(this.menu,
0.2, { y: pMenu.aY, x: pMenu.aX, scale: pMenu.aScale }, { y: pMenu.zY, x: pMenu.zX, scale: pMenu.zScale, ease: Power2.easeOut });
/*
--------------------------------------
Animate the dot where the user tapped
--------------------------------------
*/
let ptDot = PointMenu.getTranslation(this.dot);
TweenMax.fromTo(this.dot,
0.25, { x: ptDot.x, y: ptDot.y, scale: 0, opacity: 1 }, { x: ptDot.x, y: ptDot.y, scale: 8, opacity: 0.5 });
TweenMax.to(this.dot,
0.25, { scale: 1, opacity: 1, delay: 0.25 });
/*
--------------------------------------
Animate the stem
--------------------------------------
*/
TweenMax.fromTo(this.stem, 0.2, { opacity: 0 }, { opacity: 1 });
}
/**
* Determines where the point menu should be rendered by optimizing for visible are of the rectangular shape
*
* @param {Point} ptOrigin - the screen coordinates where the user tapped or clicked
* @param {Rectangle} boundingRect - the rectangular shape to be rendered
* @param {int} originOffset - the amount of padding to add between the menu and the interaction point
* @return [{point}, {string}] - an array containing the coordinate and cardinal direction of menu
*/
getBestLayout(ptOrigin, boundingRect, originOffset) {
let rectLayouts = [];
// Calculate four possible regions for placement. The preferred order for usability on touchscreen
// devices is north, west, east, and south. Because the algorithm below will optimize for the last
// item added to rectLayouts[], the order of insertion into the array is important.
// South
rectLayouts.push(new Rectangle(ptOrigin.x - (boundingRect.width / 2),
ptOrigin.y + originOffset,
boundingRect.width,
boundingRect.height,
"S"));
// East
rectLayouts.push(new Rectangle(ptOrigin.x + originOffset,
ptOrigin.y - (boundingRect.height / 2),
boundingRect.width,
boundingRect.height,
"E"));
// West
rectLayouts.push(new Rectangle(ptOrigin.x - boundingRect.width - originOffset,
ptOrigin.y - (boundingRect.height / 2),
boundingRect.width,
boundingRect.height,
"W"));
// North
rectLayouts.push(new Rectangle(ptOrigin.x - (boundingRect.width / 2),
ptOrigin.y - boundingRect.height - originOffset,
boundingRect.width,
boundingRect.height,
"N"));
// Find the rectangle whose area of intersection with the screen is largest
let rectScreen = new Rectangle(0, 0, window.innerWidth, window.innerHeight);
let rectLargestArea = [null, 0];
for (var i = rectLayouts.length - 1; i >= 0; i--) {
let area = rectScreen.calcIntersectArea(rectLayouts[i]);
if (area > rectLargestArea[1]) {
rectLargestArea[0] = rectLayouts[i];
rectLargestArea[1] = area;
}
}
return [new Point(rectLargestArea[0].x, rectLargestArea[0].y), rectLargestArea[0].label];
}
}
function onMapClick(e) {
if (!pm.isOpen) {
pm.openAtPoint(new Point(e.clientX, e.clientY));
} else {
pm.close();
}
}
// Run
let pm = new PointMenu("pm");
let container = document.getElementById("container");
addEventListener("click", onMapClick);
|
angular.module('main').controller('newsurveyCtrl', function ($scope, $http, $timeout) {
$scope.abc = "newsurveyCtrl"
$scope.newpoll = function () {
$http.post("http://poll.theguywithideas.com/api/surveys/create", {
"instructions": $scope.surinstructions,
"surveySubtitle": $scope.surname,
"surveyTitle": $scope.surtitle
})
.success(function (res) {
console.log("posted");
})
.error(function (res) {
});
};
});
|
var city;
function preload() {
var url = 'http://api.openweathermap.org/data/2.5/weather?q=New York,NY'+
'&APPID=f02124924447c73bc1d1626b1bee5f45';
city = loadJSON(url);
}
function setup() {
createCanvas(400,400);
}
function draw() {
}
|
const chalk = require('chalk')
const geocode = require('./utils/geocode')
const forecast = require('./utils/forecast')
const log = console.log
// const readline = require('readline');
// const rl = readline.createInterface({
// input: process.stdin,
// output: process.stdout,
// prompt: `For which city would you like the weather report? `
// });
// rl.prompt()
// rl.on('line', (input) => {
// address = input
// geocode(address)
// rl.close();
// });
geocode(process.argv[2], (err, {latitude, longitude, location}) => {
if(err) {
return log(err)
}
forecast(latitude, longitude, (error, forecastData) => {
if(error) {
return log(error)
}
log(location)
log(forecastData)
})
})
|
import { USER_ORDER_REQUEST, USER_ORDER_FAIL, USER_ORDER_RESET, USER_ORDER_SUCCESS, CREATE_ORDER_FAIL, CREATE_ORDER_REQUEST, CREATE_ORDER_SUCCESS, GET_ORDER_FAIL, GET_ORDER_REQUEST, GET_ORDER_SUCCESS } from "../actions/constants"
export const createOrder = (state = {}, action) => {
const { type, payload } = action
switch(type) {
case CREATE_ORDER_REQUEST:
return { loading: true }
case CREATE_ORDER_SUCCESS:
return { loading: false, success: true, order: payload }
case CREATE_ORDER_FAIL:
return { loading: false, error: payload }
default:
return state
}
}
export const getOrder = (state = { loading: true, orderItems: [], shippingAddress: {} }, action) => {
const { type, payload } = action
switch(type) {
case GET_ORDER_REQUEST:
return {
...state,
loading: true
}
case GET_ORDER_SUCCESS:
return {
loading: false,
order: payload
}
case GET_ORDER_FAIL:
return {
loading: false,
error: payload
}
default:
return state
}
}
export const userOrder = (state = { orders: [] }, action) => {
const { type, payload } = action
switch(type) {
case USER_ORDER_REQUEST:
return { loading: true, orders: [] }
case USER_ORDER_SUCCESS:
return { loading: false, orders: payload }
case USER_ORDER_FAIL:
return { loading: false, error: payload }
case USER_ORDER_RESET:
return { orders: [] }
default:
return state
}
}
|
// import React, { useReducer } from 'react';
// function TestReducer(){
// const [number,]=useReducer
// return(
// );
// }
|
/**
* Created by Tomasz Gabrysiak on 2016-03-12.
*/
var app = angular.module("myRestApp", []);
app.controller("MyRestAppCtrl", ['$scope', 'myRestAppApiService', function ($scope, myRestAppApiService) {
$scope.books = ["Loading..."];
$scope.authors = ["Loading"];
$scope.newAuthor = {
first_name: '',
last_name: '',
description: ''
};
$scope.addAuthor = function () {
myRestAppApiService.addAuthor($scope.newAuthor)
.success(function (response, status) {
$scope.authors.push($scope.newAuthor);
$scope.newAuthor = {
first_name: '',
last_name: '',
description: ''
};
});
};
myRestAppApiService.getBooks()
.success(function (response, status) {
$scope.books = [].concat(response);
});
myRestAppApiService.getAuthors()
.success(function (response, status) {
$scope.authors = [].concat(response);
});
}]);
app.service('myRestAppApiService', ['$http', function ($http) {
var apiUrlMapper = {
getBooks: "http://localhost:8000/books/",
getAuthors: "http://localhost:8000/authors/",
addAuthor: "http://localhost:8000/authors/"
};
var books = [];
var authors = [];
return {
getBooks: function () {
return $http.get(apiUrlMapper.getBooks);
},
getAuthors: function () {
return $http.get(apiUrlMapper.getAuthors);
},
addAuthor: function (author) {
return $http.post(apiUrlMapper.addAuthor, author);
}
};
}]);
|
import React, { Component } from "react";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
class Filter extends Component {
render() {
const { filter } = this.props;
return (
<div className="container f-grid">
<Grid container justify="center">
<FilterButton
md={3}
lg={3}
filter={filter}
category="all"
text="כל הקטלוג"
/>
<FilterButton
md={3}
lg={3}
filter={filter}
category="סט"
text="סטים קסומים"
/>
<FilterButton
md={3}
lg={3}
filter={filter}
category="לוכד חלומות"
text="לוכד חלומות"
/>
<FilterButton
md={3}
lg={3}
filter={filter}
category="מחזיק מפתחות"
text="מחזיק מפתחות"
/>
<FilterButton
md={2}
lg={2}
filter={filter}
category="מפיות"
text="מפיות"
/>
<FilterButton
md={2}
lg={2}
filter={filter}
category="70"
diam
text="70 סמ קוטר"
/>
<FilterButton
md={2}
lg={2}
filter={filter}
category="60"
diam
text="60 סמ קוטר"
/>
<FilterButton
md={2}
lg={2}
filter={filter}
category="50"
diam
text="50 סמ קוטר"
/>
<FilterButton
md={2}
lg={2}
filter={filter}
category="40"
diam
text="40 סמ קוטר"
/>
<FilterButton
md={2}
lg={2}
filter={filter}
category="30"
diam
text="30 סמ קוטר"
/>
</Grid>
</div>
);
}
}
export default Filter;
const FilterButton = ({ md, lg, filter, category, diam = false, text }) => {
return (
<Grid item xs={12} sm={12} md={md} lg={lg}>
<Button
fullWidth
variant="outlined"
color="secondary"
onClick={diam ? () => filter("", category) : () => filter(category)}
>
{text}
</Button>
</Grid>
);
};
|
import React, { Component } from 'react';
import styled from 'styled-components';
import { Image } from 'react-bootstrap';
const ProfileImage = styled(Image)`
height: ${props => (props.size === 'lg' ? '90px' : '32px')};
`;
class Avatar extends Component {
render(){
const { user, size } = this.props;
return (
<ProfileImage src={user.profileImageUrl} size={size} roundedCircle></ProfileImage>
);
}
}
export default Avatar;
|
let Mock = require('mockjs');
let result = Mock.mock({
code: 0,
message: 'success',
"data|5": [{
"id": "@id",
"ip": "@ip",
"name": "@cname",
"userId": "@id",
"stars|2": ["※"],
"avatar": "@image('200*100', 'indianred', '#fff', 'mockjs')",
"createAt": "@datetime"
}]
});
console.log(JSON.stringify(result));
|
'use strict';
import { combineReducers } from 'redux';
import Menu from './MenuReducer';
import SelectProjects from './SelectProjectsReducer';
const rootReducer = combineReducers({
Menu: Menu,
SelectProjects: SelectProjects,
});
export default rootReducer;
|
const {
ChoiceFactory,
ChoicePrompt,
ComponentDialog,
NumberPrompt,
TextPrompt,
WaterfallDialog,
DateTimePrompt
} = require('botbuilder-dialogs');
const { ClientProfile } = require('../class/ClientProfile');
const fetch = require("node-fetch");
const CHOICE_PROMPT = 'CHOICE_PROMPT';
const CONFIRM_PROMPT_FINAL = 'CONFIRM_PROMPT_FINAL';
const NAME_PROMPT = 'NAME_PROMPT';
const AGE_PROMPT = 'AGE_PROMPT';
const CPF_PROMPT = 'CPF_PROMPT';
const CEP_PROMPT = 'CEP_PROMPT';
const BIRTH_PROMPT = 'BIRTH_PROMPT';
const USER_PROFILE = 'USER_PROFILE';
const WATERFALL_DIALOG = 'WATERFALL_DIALOG';
var clientState = '';
var clientCity = '';
var birthday = {day: '', month: ''};
class FormClientDialog extends ComponentDialog{
constructor(id,userState) {
super(id || 'formClientDialog')
this.clientProfile = userState.createProperty(USER_PROFILE);
this.addDialog(new TextPrompt(NAME_PROMPT, this.namePromptValidator));
this.addDialog(new NumberPrompt(AGE_PROMPT, this.agePromptValidator));
this.addDialog(new TextPrompt(CPF_PROMPT, this.cpfPropmtValidator));
this.addDialog(new TextPrompt(CEP_PROMPT, this.cepPromptValidator));
this.addDialog(new DateTimePrompt(BIRTH_PROMPT, this.birthPrompValidator));
this.addDialog(new ChoicePrompt(CONFIRM_PROMPT_FINAL));
this.addDialog(new ChoicePrompt(CHOICE_PROMPT));
this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
this.nameStep.bind(this),
this.ageStep.bind(this),
this.genderStep.bind(this),
this.cpfStep.bind(this),
this.cepStep.bind(this),
this.birthdayStep.bind(this),
this.confirmStep.bind(this),
this.finalStep.bind(this)
]));
this.initialDialogId = WATERFALL_DIALOG;
}
async nameStep(step){
const formDetails = step.options;
console.log(formDetails)
if (!formDetails.name) {
const promptOptions = { prompt: 'Por favor insira seu nome: ', retryPrompt: 'Nome não foi encontrado na base de dados do IBGE. Digite novamente:' };
return await step.prompt(NAME_PROMPT, promptOptions);
}
if (!this.validaNome(formDetails.name)) {
const promptOptions = { prompt: 'Nome informado não foi encontrado na base de dados do IBGE. Digite novamente: ', retryPrompt: 'Nome não foi encontrado na base de dados do IBGE. Digite novamente:' };
return await step.prompt(NAME_PROMPT, promptOptions);
}
return await step.next(formDetails.name)
}
async ageStep(step){
step.values.name = step.result;
const formDetails = step.options;
if (!formDetails.age) {
step.values.name = await this.firstToUperCase(step.result);
const promptOptions = { prompt: 'Por favor digite a sua idade: ', retryPrompt: 'A idade deve ser entre 0 e 150 anos. Digite novamente:' };
return await step.prompt(AGE_PROMPT,promptOptions);
}
return await step.next(formDetails.age)
}
async firstToUperCase(name){
const nameArray = name.toLowerCase().split("");
nameArray[0] = nameArray[0].toUpperCase()
return nameArray.join('')
}
async genderStep(step) {
step.values.age = step.result;
const formDetails = step.options;
if (!formDetails.gender) {
return await step.prompt(CHOICE_PROMPT,
{
prompt: 'Escolha seu gênero: ',
choices: ChoiceFactory.toChoices(['Homem', 'Mulher', 'Outro'])
});
}
return await step.next(formDetails.gender);
}
async cpfStep(step) {
step.values.gender = step.result.value ? step.result.value : step.result;
const promptOptions = { prompt: `Por favor insira seu CPF:\n EX: 02569011616 ou 025.690.116/16`, retryPrompt: 'O CPF esta incorreto. Digite novamente:' };
return await step.prompt(CPF_PROMPT, promptOptions);
}
async cepStep(step) {
step.values.cpf = step.result.toString().replace(/\D/g, '');
const promptOptions = { prompt: `Por favor insira seu CEP (somente números): \n EX: 9212050`, retryPrompt: 'O CEP esta incorreto. Por favor digite novamente:' };
return await step.prompt(CEP_PROMPT, promptOptions);
}
async birthdayStep(step) {
step.values.cep = step.result;
const promptOptions = { prompt: `Insira sua data de nascimento (DD/MM):\n EX: 31/12`, retryPrompt: 'A data esta incorreta. Por favor digite novamente:' };
return await step.prompt(BIRTH_PROMPT, promptOptions);
}
async confirmStep(step) {
step.values.birth = step.result;
return await step.prompt(CONFIRM_PROMPT_FINAL, {
prompt: 'Confirma as informações enviadas: ',
choices: ChoiceFactory.toChoices(['Sim', 'Não'])
});
}
async namePromptValidator (promptContext) {
const nome = promptContext.recognized.value;
return this.validaNome(nome);
}
async validaNome(nome){
await fetch(`https://servicodados.ibge.gov.br/api/v2/censos/nomes/${nome}`)
.then(res => res.json())
.then(data => { if(!data[0]) return false; });
return true;
}
async cpfPropmtValidator (promptContext) {
const cpfSomenteNumeros = promptContext.recognized.value.toString().replace(/\D/g, '');
if (!(cpfSomenteNumeros.length == 11)){
promptContext.options[0].retryPrompt = 'O CPF deve ter 11 digitos!';
return false;
}
return FormClientDialog.prototype.validaDigitosCPF(cpfSomenteNumeros);
}
async agePromptValidator (promptContext) {
return promptContext.recognized.succeeded && promptContext.recognized.value > 0 && promptContext.recognized.value < 150;
}
async birthPrompValidator (promptContext) {
if(!promptContext.recognized.value) return false;
const data = /^(\D{4})[-](\d{2})[-](\d{2})$/.exec(promptContext.recognized.value[0].timex);
if (data) {
const mes = data[2];
const dia = data[3];
birthday.day = dia;
birthday.month = mes;
return true;
} else {
return false;
}
}
async cepPromptValidator (promptContext) {
const cepSomenteNumeros = promptContext.recognized.value.toString().replace(/\D/g, '');
if(!(/^[0-9]{8}$/.test(cepSomenteNumeros))) return false;
var cepValidoNaBase = false;
await fetch(`https://viacep.com.br/ws/${cepSomenteNumeros}/json/`)
.then(res => res.json())
.then(data => {
if(!data.erro){
clientState = data.uf;
clientCity = data.localidade;
cepValidoNaBase = true;
}
}).catch( err => console.log(err))
return cepValidoNaBase
}
async finalStep(step) {
if (step.result.value.toLowerCase() == 'sim') {
const clientProfile = await this.clientProfile.get(step.context, new ClientProfile());
let anoNascimento = this.calculaIdade(step.values.age);
clientProfile.name = step.values.name;
clientProfile.age = step.values.age;
clientProfile.gender = step.values.gender;
clientProfile.cpf = step.values.cpf;
clientProfile.cep = step.values.cep;
clientProfile.birth = new Date(anoNascimento,birthday.month -1,birthday.day);
clientProfile.city = clientCity;
clientProfile.state = clientState;
let cpfFormatted = clientProfile.cpf.toString().replace(/(\d{3})?(\d{3})?(\d{3})?(\d{2})/, "$1.$2.$3-$4");
let msg = `Seu nome é ${ clientProfile.name }, você nasceu no dia ${ clientProfile.birth.getDate() } do ${ clientProfile.birth.getMonth() +1} de ${ clientProfile.birth.getFullYear() },
e seu gênero é ${ clientProfile.gender }.
Seu CPF é ${ cpfFormatted }, e você reside na cidade ${clientProfile.city} - ${clientProfile.state}`;
msg += '.';
await step.context.sendActivity(msg);
return await step.endDialog( clientProfile);
}
return await step.endDialog();
}
calculaIdade(age){
let dataDeHoje = new Date();
let ano = dataDeHoje.getFullYear() - age;
if( (dataDeHoje.getMonth()+1) < birthday.month || (dataDeHoje.getDate() < birthday.day && (dataDeHoje.getMonth()+1) == birthday.month) ){
ano--;
}
return ano;
}
calculaRestoDigitoCPF(cpf, posicao, numMultiplica){
let soma = 0;
for (let i = 0; i <= (posicao-1); i++) {
soma += cpf[i] * numMultiplica;
numMultiplica--;
}
return soma % 11;
}
validaDigitosCPF(cpf){
const cpfArray = cpf.split("");
let numValidadorJ = cpfArray[9];
let numValidadorK = cpfArray[10];
let restoJ = FormClientDialog.prototype.calculaRestoDigitoCPF(cpfArray,9,10);
let restoK = FormClientDialog.prototype.calculaRestoDigitoCPF(cpfArray,10,11);
if((restoJ == 0 || restoJ == 1) || (restoK == 0 || restoK == 1)){
return numValidadorJ == 0 || numValidadorK == 0;
} else if ( (restoJ >= 2 || restoJ <= 10) || (restoK >= 2 || restoK <= 10) ){
return numValidadorJ == (11 - restoJ) || numValidadorK == (11 - restoK);
}else {
return false;
}
}
}
module.exports.FormClientDialog = FormClientDialog;
|
import React from 'react';
import AppBar from '../_base/AppBar';
import Navigation from '../Navigation';
function handleTouchTap() {
// TODO: investigate how to navigate with router 4
console.log('NAVIGATE HOME'); // eslint-disable-line
}
const RightElement = (
<Navigation>
<Navigation.Item
label="nav:home"
path="/"
/>
<Navigation.Item
label="nav:courses"
path="/courses"
/>
<Navigation.Item
label="nav:vision"
path="/vision"
/>
<Navigation.Item
label="nav:contact"
path="/contact"
/>
</Navigation>
);
const Header = () => (
<div>
<AppBar
title="Blockchain Academy"
onTitleTouchTap={handleTouchTap}
iconElementRight={RightElement}
/>
</div>
);
export default Header;
|
import { extend } from '../../core/utils/extend';
import { isString } from '../../core/utils/type';
import messageLocalization from '../../localization/message';
export class FileManagerCommandManager {
constructor(permissions) {
this._actions = {};
this._permissions = permissions || {};
this._initCommands();
}
_initCommands() {
this._commands = [{
name: 'create',
text: messageLocalization.format('dxFileManager-commandCreate'),
icon: 'newfolder',
enabled: this._permissions.create,
noFileItemRequired: true
}, {
name: 'rename',
text: messageLocalization.format('dxFileManager-commandRename'),
icon: 'rename',
enabled: this._permissions.rename,
isSingleFileItemCommand: true
}, {
name: 'move',
text: messageLocalization.format('dxFileManager-commandMove'),
icon: 'movetofolder',
enabled: this._permissions.move
}, {
name: 'copy',
text: messageLocalization.format('dxFileManager-commandCopy'),
icon: 'copy',
enabled: this._permissions.copy
}, {
name: 'delete',
text: messageLocalization.format('dxFileManager-commandDelete'),
icon: 'trash',
enabled: this._permissions.delete
}, {
name: 'download',
text: messageLocalization.format('dxFileManager-commandDownload'),
icon: 'download',
enabled: this._permissions.download
}, {
name: 'upload',
text: messageLocalization.format('dxFileManager-commandUpload'),
icon: 'upload',
enabled: this._permissions.upload,
noFileItemRequired: true
}, {
name: 'refresh',
text: messageLocalization.format('dxFileManager-commandRefresh'),
icon: 'dx-filemanager-i dx-filemanager-i-refresh',
enabled: true,
noFileItemRequired: true
}, {
name: 'thumbnails',
text: messageLocalization.format('dxFileManager-commandThumbnails'),
icon: 'mediumiconslayout',
enabled: true,
noFileItemRequired: true
}, {
name: 'details',
text: messageLocalization.format('dxFileManager-commandDetails'),
icon: 'detailslayout',
enabled: true,
noFileItemRequired: true
}, {
name: 'clearSelection',
text: messageLocalization.format('dxFileManager-commandClearSelection'),
icon: 'remove',
enabled: true
}, {
name: 'showNavPane',
hint: messageLocalization.format('dxFileManager-commandShowNavPane'),
icon: 'menu',
enabled: false,
noFileItemRequired: true
}];
this._commandMap = {};
this._commands.forEach(command => {
this._commandMap[command.name] = command;
});
}
registerActions(actions) {
this._actions = extend(this._actions, actions);
}
executeCommand(command, arg) {
var commandName = isString(command) ? command : command.name;
var action = this._actions[commandName];
if (action) {
return action(arg);
}
}
setCommandEnabled(commandName, enabled) {
var command = this.getCommandByName(commandName);
if (command) {
command.enabled = enabled;
}
}
getCommandByName(name) {
return this._commandMap[name];
}
isCommandAvailable(commandName, itemInfos) {
var command = this.getCommandByName(commandName);
if (!command || !command.enabled) {
return false;
}
if (command.noFileItemRequired) {
return true;
}
var itemsLength = itemInfos && itemInfos.length || 0;
if (itemsLength === 0 || itemInfos.some(item => item.fileItem.isRoot() || item.fileItem.isParentFolder)) {
return false;
}
if (commandName === 'download') {
return itemInfos.every(itemInfo => !itemInfo.fileItem.isDirectory);
}
return !command.isSingleFileItemCommand || itemsLength === 1;
}
}
|
let express = require('express');
let app = express();
let config = require('./config/config');
let port = config.dev.port;
require('./config/express.config')(app);
app.listen(process.env.PORT || 3000, () => {
console.log('review list RESTful API server started on: ' + port);
});
module.exports = app;
|
/////// DEPENDENCIES //////////////////////////////
var express = require('express');
var http = require('http');
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var fs = require('fs');
var port = process.env.PORT || 3000;
////// APP META_INF ////////////////////////////////
/*
* Read and parse package.jon into app.meta
*/
app.meta = JSON.parse(fs.readFileSync('package.json').toString());
////// PREFENCES //////////////////////////////
////// SET DIR PREFENCES
// VIEWS DIR
app.set('views', path.join(__dirname, 'views'));
// PUBLIC DIR
app.use(express.static(__dirname + '/public'));
// SET APP FAVICON
/*
* Uncomment after placing your favicon in /public
*/
//app.use(favicon(__dirname + '/public/favicon.ico'));
// REQUIRE MONGOSE PREFENCES
require('./config/db.js')(mongoose);
// REQUIRE APP PREFENCES
require('./config/prefences.js')(app);
// REQUIRE MIDDLEWARES
require('./config/middlewares.js')(app);
//// CONTROLLERS /////////////////////////////////////
/*
* Automatically load all routes(controllers) in the /controller dir
*/
fs.readdirSync('./controllers').forEach(function(file) {
if (file.substr(-3) == '.js') {
route = require('./controllers/' + file).controller(app);
}
});
///// ERROR HANDLING ////////////////////////////
// Catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
///// DEVELOPMENT ERROR HANDLER:
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('404', {
message: err.message,
error: err
});
});
}
//PRODUCTION ERROR HANDLER:
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('404', {
message: err.message,
error: {}
});
});
//// START APP
app.listen(port);
console.log(app.meta.name + " v" + app.meta.version + " Running on [PORT]: " + port);
|
const { describe, it } = require('mocha')
const assert = require('assert')
const { camelCase } = require('..')
describe('Camel Case', () => {
it('With empty string', () => {
assert.equal(camelCase('', ''), '')
})
it('With string', () => {
assert.equal(camelCase('Foo Bar'), 'fooBar')
assert.equal(camelCase('--foo-bar--'), 'fooBar')
assert.equal(camelCase('__FOO_BAR__'), 'fooBar')
})
it('With unicode', () => {
assert.equal(camelCase('🚀🌑🚀'), '🚀🌑🚀')
})
})
|
const crypto = require('../src/index');
require('webcrypto-test-suite')({
crypto
});
|
import React, {PropTypes} from 'react';
const SectionHeader = ({children}) => (
<h3 className="section-header">
{children}
</h3>
);
SectionHeader.propTypes = {
children: PropTypes.node
};
export default SectionHeader;
|
var GameSceneUI = cc.Layer.extend({
_lifeText : null,
_distanceText : null,
_scoreText : null,
volume : 0.3,
ctor : function(){
this._super();
var size = cc.winSize;
var lifeLabel = new cc.LabelBMFont("L I V E S", res.Font);
this.addChild(lifeLabel);
lifeLabel.x = 360;
lifeLabel.y = size.height - 25;
this._lifeText = new cc.LabelBMFont("0", res.Font);
this.addChild(this._lifeText);
this._lifeText.x = lifeLabel.x;
this._lifeText.y = size.height - 60;
var distanceLabel = new cc.LabelBMFont("D I S T A N C E", res.Font);
this.addChild(distanceLabel);
distanceLabel.x = 680;
distanceLabel.y = lifeLabel.y;
this._distanceText = new cc.LabelBMFont("0", res.Font);
this.addChild(this._distanceText);
this._distanceText.x = distanceLabel.x;
this._distanceText.y = this._lifeText.y;
var scoreLabel = new cc.LabelBMFont("S C O R E ", res.Font);
this.addChild(scoreLabel);
scoreLabel.x = 915;
scoreLabel.y = lifeLabel.y;
this._scoreText = new cc.LabelBMFont("0", res.Font);
this.addChild(this._scoreText);
this._scoreText.x = scoreLabel.x;
this._scoreText.y = this._lifeText.y;
var pauseButton = new cc.MenuItemImage("#pauseButton.png", "#pauseButton.png", this.pauseResume);
var soundButton = SoundButton.sound(this.changeVolume.bind(this));
var menu = new cc.Menu(pauseButton, soundButton);
menu.alignItemsHorizontallyWithPadding(30);
menu.x = 80;
menu.y = size.height - 45;
this.addChild(menu);
return true;
},
_pauseResume : function(){
if(cc.director.isPaused()){
cc.director.resume();
}
else {
cc.director.pause();
}
},
changeVolume : function(){
this.volume += 0.3
if(this.volume > 1){
this.volume = 0;
}
cc.audioEngine.setEffectsVolume(this.volume);
cc.audioEngine.setMusicVolume(this.volume);
},
update : function(){
this._lifeText.setString(Game.user.lives.toString());
this._distanceText.setString(parseInt(Game.user.distance).toString());
this._scoreText.setString(Game.user.score.toString());
}
});
|
'use strict';
var fs = require('fs'),
path = require('path');
var flaschenpost = require('flaschenpost');
var Peer = require('p2p');
var logger = flaschenpost.getLogger(),
peer;
/*eslint-disable no-process-env*/
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
/*eslint-enable no-process-env*/
peer = new Peer({
host: process.env.IP,
port: 3000,
privateKey: fs.readFileSync(path.join(
__dirname,
'node_modules',
'p2p',
'keys',
'localhost.selfsigned',
'privateKey.pem')
),
certificate: fs.readFileSync(path.join(
__dirname,
'node_modules',
'p2p',
'keys',
'localhost.selfsigned',
'certificate.pem')
),
serviceInterval: '1s'
});
peer.on('changed-successor', function (successor) {
logger.info('Changed successor.', {
successor: successor,
status: peer.status()
});
});
peer.on('changed-predecessor', function (predecessor) {
logger.info('Changed predecessor.', {
predecessor: predecessor,
status: peer.status()
});
});
|
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
backendRouter = require('./config/routes.js'),
cookieParser = require('cookie-parser'),
expressValidator = require('express-validator'),
passport = require('passport'),
session = require('express-session');
// Allow Cross-Origin Resource Sharing
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
next();
});
// Parse body of requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(cookieParser());
// Passport and session middleware
app.use(session({
secret: 'secret',
saveUninitialized: false,
resave: false,
}));
app.use(passport.initialize());
app.use(passport.session());
// Use the route file
app.use(backendRouter);
// Start the backend server
app.listen(process.env.PORT || 8080, function () {
console.log('Server started on port: http://localhost:8080/');
});
|
import React from 'react';
const Paginator = (props) => {
/**
* Render the list of all pages
* @returns {*[]}
* @private
*/
const _showPages = () => {
if(props.meta) {
let pages = [];
for(let index = 0; index < props.meta.last_page; index++) {
pages.push(index + 1)
}
return pages.map((page, index) => {
let activeClass = props.meta.current_page === page ? 'active' : '';
return (
<li className={`page-item ${activeClass}`} key={index}>
<a className="page-link" href="#" onClick={ () => props.changePage(page) }>{ page }</a>
</li>
)
})
}
};
/**
* Render the active class if we can go to previous pages
* @returns {string}
*/
const activePrev = () => {
if(props.meta) {
let {current_page, from} = props.meta;
return current_page === from ? 'disabled': '';
}
return '';
};
/**
* Render the active class if we can go to next pages
* @returns {string}
*/
const activeNext = () => {
if(props.meta) {
let {current_page, last_page} = props.meta;
return current_page === last_page ? 'disabled': '';
}
return '';
};
return (
<div>
<ul className="pagination">
<li className={`page-item ${ activePrev() }`}>
<a className="page-link" href="#"
onClick={() => props.changePage(props.meta.current_page - 1)}
>«</a>
</li>
{ _showPages() }
<li className={`page-item ${ activeNext() }`}>
<a className="page-link" href="#"
onClick={() => props.changePage(props.meta.current_page + 1)}
>»</a>
</li>
</ul>
</div>
)
};
export default Paginator;
|
var app = angular.module('myApp', []);
app.directive('ngBindHtmlUnsafe', function () {
return {
restrict: 'A',
scope: {
ngBindHtmlUnsafe: '='
},
link: function( scope , element , attributes ){
element[0].innerHTML = scope.ngBindHtmlUnsafe;
scope.$watch('ngBindHtmlUnsafe', function(newValue){
element[0].innerHTML = newValue;
});
}
};
});
|
/**
* @param {number[]} data The array data set
* @param {number} q The q-quantile order
*
* @returns {number[number[]]} Array of q-quantile groups (partitions)
*/
const quantileGroups = (data, q) => {
const groupIndexes = []
const groups = []
// create memo of the last index of each quantile group
for (let i = 0; i <= q; i++) {
// special 0th quantile case
if (i === 0) {
groupIndexes.push(0)
} else {
groupIndexes.push(Math.ceil(data.length * (i / q)) - 1)
}
}
// iterate over memo and slice accordingly
for (let i = 0; i < groupIndexes.length - 1; i++) {
if (i === 0) {
groups.push(data.slice(0, groupIndexes[i + 1] + 1))
} else {
groups.push(data.slice(groupIndexes[i] + 1, groupIndexes[i + 1] + 1))
}
}
return groups
}
/**
* @param {number[]} data The array data set
* @param {q} q The q-quantile order
*
* @returns {number[]} The array of all quantiles
*/
const quantiles = (data, q) => {
data.sort((a, b) => a - b)
const groups = quantileGroups(data, q)
const quantiles = []
for (let i = 1; i <= q; i++) {
const lastOfGroup = groups[i - 1][groups[i - 1].length - 1]
// The median, for even-numbered data sets and even ordered q-quantiles, is a special case
// 2nd quartile of the 4-quantile, 3rd sextile of the 6-quantile, and so on
// Get the average between the two numbers straddling the median line
if (groups.length % 2 === 0 && groups.length / 2 === i) {
quantiles.push((lastOfGroup + groups[i][0]) / 2)
} else {
quantiles.push(lastOfGroup)
}
}
return quantiles
}
module.exports = { quantiles, quantileGroups }
|
const _ = require('lodash');
const { getPostObjects, mergePostData } = require('utilities/helpers/postHelper');
const { Post, Comment } = require('models');
const { postsUtil } = require('utilities/steemApi');
/**
* Return single post/comment of steem blockchain (if it exist).
* Return merged data of "steem" post/comment with post/comment from Mongo DB,
* merging augment keys and likes from "active_votes"
* Post/comment wrote by guest user through proxy-bot can be
* returned with "guest" user as author and with "proxy-bot" as author,
* related with which author post/comment was requested(guest or proxy-bot)
* @param author
* @param permlink
* @returns {Promise<{post: Object}|{error: Object}>}
*/
module.exports = async (author, permlink) => {
const postResult = await getPost({ author, permlink });
if (_.get(postResult, 'error')) return { error: postResult.error };
if (_.get(postResult, 'post')) return { post: postResult.post };
const commentResult = await getComment({ author, permlink });
if (_.get(commentResult, 'error')) return { error: commentResult.error };
if (_.get(commentResult, 'comment')) return { post: commentResult.comment };
};
const getPost = async ({ author, permlink }) => {
// get post with specified author(ordinary post)
const { result: dbPosts, error: dbError } = await Post.findByBothAuthors({ author, permlink });
if (dbError) return { error: dbError };
const post = _.get(dbPosts, '[0]');
const { post: steemPost } = await postsUtil
.getPost(post ? post.root_author || post.author : author, permlink);
if (!steemPost || steemPost.parent_author) return;
// if( steemError ) return { error: steemError };
let resultPost = steemPost;
const wobjsResult = await getPostObjects(steemPost.root_author, permlink);
resultPost.wobjects = _.get(wobjsResult, 'wobjectPercents', []);
resultPost.fullObjects = _.get(wobjsResult, 'wObjectsData', []);
resultPost = await mergePostData(resultPost, post);
// if post requested with guest name as author -> return post with guest name as author
resultPost.author = author;
return { post: resultPost };
};
const getComment = async ({ author, permlink }) => {
const { result, error } = await Comment.findByCond({
$or: [{ author, permlink }, { 'guestInfo.userId': author, permlink }],
});
if (error) return { error: error || 'Comment not found!' };
// if comment not found in DB, it still might exist in STEEM
if (!_.get(result, '[0]')) {
const { post: comment, error: steemError } = await postsUtil.getPost(author, permlink);
return { comment, error: steemError };
}
return mergeCommentData(result[0]);
};
const mergeCommentData = async (comment) => {
const { post: steemComment, error } = await postsUtil.getPost(comment.author, comment.permlink);
if (error) return { error };
// add guest votes to comment votes (if they exists)
steemComment.active_votes.push(...comment.active_votes);
return { comment: { ...steemComment, guestInfo: comment.guestInfo } };
};
|
const fetch = require("node-fetch");
exports.help={
name: "corona",
description: "Check corona statistics for the specified country",
usage: "corona <country / \"countries\">",
type: "fun"
};
exports.run = async (client, message, args) => {
const Discord = require("discord.js")
const fs = require("fs")
if(!args[0]) return message.channel.send("❌ You need to specify what country you want to see the corona statistics fof.")
let country = args.slice(0).join(" ");
let countries = "";
if((args[0] == "countries")== true){
fetch("https://corona.lmao.ninja/v2/countries")
.then(response => response.json())
.then(data => {
data.forEach(corona1=>{
countries+="\n"+corona1.country
});
fs.writeFile('countries.txt', countries, (error) => console.log(error))
let attachment = new Discord.MessageAttachment("./countries.txt")
message.channel.send(attachment)
})
}else if(args[0] != "countries"){
fetch("https://corona.lmao.ninja/v2/countries/"+country)
.then(response => response.json())
.then(corona => {
if(corona.message != "Country not found or doesn't have any cases"){
let embed = new Discord.MessageEmbed().setTitle(corona.country).setColor("DARK_RED")
.addField("Cases per 1 million", corona.casesPerOneMillion, true)
.addField("Confirmed", corona.cases, true)
.addField("Active cases", corona.active, true)
.addField("Critical cases", corona.critical, true)
.addField("Recovered cases", corona.recovered, true)
.addField("Deaths per 1 million", corona.deathsPerOneMillion, true)
.addField("Deaths", corona.deaths, true)
.setThumbnail(`${corona.countryInfo.flag}`)
.setTimestamp();
message.channel.send(embed)
}else{
message.channel.send("❌ Couldn't find that country")
}
});
}
}
|
/**
* Gestion des préférences de l'application.
*
* @module app
* @submodule app-prefs
* @main App
*/
window.App = window.App || {}
App.Prefs = {
/**
* Indique si le panneau des préférences est prêt à être affiché (construit)
* @property prepared
* @default false
*/
prepared:false,
/**
* Données pour construire le panneau des préférences
*
* @property DATA
* @type {Array}
* @static
*/
DATA:[
/* L'id doit correspondre à celui dans App.preferences */
{id:'general', type:'fieldset', legend:"Générales"},
{id:'autosave', type:'cb', label:"Sauvegarde automatique", indiv:true},
{id:'saveconfig', type:'cb', label:"Sauver la configuration des fiches à chaque sauvegarde", indiv:true},
{id:'general', type:'/fieldset'},
{id:'fiches', type:'fieldset', legend:"Fiches"},
{id:'modeunique', type:'cb',
onclick:"$.proxy(App.Prefs.onchange_mode_unique, App.Prefs, this.checked)()",
label:"Mode “Unique” <span class=\"tiny\">Dans ce mode, un seul livre et une seule page pourront être ouverts, placés toujours au même endroit visible.</span>"},
{id:'snap', type:'cb', label:"Aligner les fiches sur la grille", indiv:true},
{id:'showinfos', type:'cb', label:"Afficher type:id dans pied de page", indiv:true},
'<div>',
{id:'gridbook', type:'cb', label:"Livre rangés " , onchange:"$.proxy(App.Prefs.onchange_livre_ranged,App.Prefs,this.checked)()"},
{id:'dirgridbook',type:'select', style:"visibility:hidden;",
values:[{value:"h",title:"horizontalement"}, {value:"v",title:"verticalement"}]},
'</div>',
{id:'fiches', type:'/fieldset'},
{id:'paragraphes', type:'fieldset', legend:"Paragraphes"},
{id:'masknotprinted', type:'cb', label:"Masquer paragraphe “not printed”", indiv:true,
onchange:"$.proxy(App.Prefs.onchange_masknotprinted, App.Prefs, this.checked)()"},
{id:'paragraphes', type:'/fieldset'}
],
/**
* Au chargement de la collection, règle les préférences qui doivent
* être prises en compte immédiatement.
* Notes
*
* @method set
* @param {Object} prefs Les préférences de l'application, ou null
*/
set:function(prefs){
if(!prefs) return
App.preferences = prefs
window.MODE_UNIQUE = App.preferences.modeunique
},
/**
* Méthode appelée quand on passe en mode unique (ou qu'on en sort, mais elle ne
* fait rien alors).
* La méthode va mettre en place le mode unique, en commençant par fermer tous
* les 'book' et 'page' ouverts (en passant en revue les éléments posés sur la table)
* Elle va définir la valeur de MODE_UNIQUE et rouvrir la dernière fiche trouvée.
* @method onchange_mode_unique
* @param {Boolean} activer True s'il faut activer le mode unique.
*/
onchange_mode_unique:function(activer)
{
if(activer == false)
{
MODE_UNIQUE = false
return
}
var fiche, fiche_open ;
$('section#table').find('fiche.book, fiche.page').each(function(){
fiche = fiche_of_obj($(this))
if((fiche.is_book || fiche.is_page) && fiche._opened){
fiche.close
fiche_open = get_fiche(fiche.id)
}
})
MODE_UNIQUE = true
if(fiche_open) fiche_open.open
},
/**
* Méthode appelée quand on clique sur le cb "livre rangés"
* La méthode affiche ou masque le menu pour choisir l'alignement des livres,
* horizontal ou vertical.
* @method onchange_livre_ranged
* @param {Boolean} coched Etat du coche de la cb
*/
onchange_livre_ranged:function(coched)
{
$('select#pref-dirgridbook').css('visibility', coched?'visible':'hidden')
},
/**
* Méthode appelée quand on clique sur la CB pour masquer/afficher les
* paragraphes "not printed"
* Elle passe en revue les pages ouvertes (elle doit les trouver sur la
* table) et masque ou montre les paragraphes not printed.
* @method onchange_masknotprinted
* @param {Boolean} masquer Si TRUE, on doit les masquer
*/
onchange_masknotprinted:function(masquer)
{
$('section#table > fiche.page').each(function(){
fiche = fiche_of_obj($(this))
if(fiche.enfants)
{
L(fiche.enfants).each(function(child){
child.applique_filtre
})
}
})
},
/**
* Enregistre les préférences de l'application (et reçoit le retour de la
* requête ajax)
*
* Notes
* -----
* * Les préférences sont définies dans {App.preferences}
*
* @method save
* @param {Object} rajax Retour de la requête Ajax (if any)
* @for App.Prefs
*/
save:function(rajax)
{
if(undefined == rajax)
{
this.get_values
Ajax.send(
{
script:'app/save_preferences',
collection:Collection.name,
preferences:App.preferences},
$.proxy(this.save, this)
)
}
else
{
if(rajax.ok)
{
F.show("Préférences enregistrées.")
this.close()
}
else F.error(rajax.message)
}
},
/**
* Ouvre le panneau des préférences
*
* Notes
* -----
* * C'est la méthode principale à appeler. Elle se charge de construire le
* panneau des préférences si nécessaire.
*
* @method show
*
*/
show:function()
{
if(!this.prepared) this.prepare_panneau
this.panneau.show()
},
/**
* Ferme le panneau des préférences
*
* @method close
*/
close:function()
{
this.panneau.hide()
}
}
Object.defineProperties(App.Prefs, {
/**
* Objet DOM du panneau ({jQuerySet})
* @property panneau
* @type {jQuerySet}
*/
"panneau":{
get:function(){
return $('div#preferences')
}
},
/**
* Récupère les valeurs des préférences dans le panneau et les met
* dans App.preferences
*
* @method get_values (complexe)
*
*/
"get_values":{
get:function(){
var id, obj ;
L(this.DATA).each(function(data){
if('string'==typeof data) return
id = data.id
switch(data.type)
{
case 'cb':
obj = $('input#pref-'+id)
App.preferences[id] = obj[0].checked == true
if(id=='autosave')
{
$('input#cb_automatic_save')[0].checked = App.preferences[id]
Collection.enable_automatic_saving(App.preferences[id])
}
else if(id=='gridbook' && App.preferences[id])
{ //=> il faut aligner les livres
UI.align_books($('select#pref-dirgridbook').val())
}
break
// Ne rien faire avec ces types :
case 'fieldset':
case '/fieldset':
break
default:
obj = $(data.type+'#pref-'+id)
App.preferences[id] = obj.val()
}
})
}
},
/**
* Prépare le panneau des préférences
* Notes
* -----
* * C'est une propriété complexe, donc l'appeler sans parenthèses
*
* @method prepare_panneau
*/
"prepare_panneau":{
get:function(){
$('body').append(this.html_panneau)
// On met les valeurs par défaut
var id, obj ;
L(this.DATA).each(function(data){
if('string'==typeof data) return
id = data.id
switch(data.type)
{
case 'cb':
obj = $('input#pref-'+id)
obj[0].checked = App.preferences[id]
break
// Ne rien faire avec ces types :
case 'fieldset':
case '/fieldset':
break
default:
obj = $(data.type+'#pref-'+id)
obj.val(App.preferences[id])
}
})
// Quelques traitements spéciaux
this.onchange_livre_ranged(App.preferences['gridbook'])
this.prepared = true
}
},
/**
* Retourne le code HTML du panneau de préférences
*
* Notes
* -----
* * Cf. le fichier de style `./css/ui/preferences.css` pour l'aspect
*
* @method html_panneau (complexe)
* @return {HTML} Code à insérer dans le body.
*/
"html_panneau":{
get:function(){
return '<div id="preferences">'+
'<div class="titre">Préférences</div>'+
'<div class="fieldsets">'+
this.html_options +
'</div>' +
this.html_buttons +
'</div>'
}
},
/**
* Retourne le code HTML pour la liste des options des préférences
*
* @method liste_options
* @return {HTML} Code à insérer dans le panneau des préférences
*/
"html_options":{
get:function(){
var code = ""
L(this.DATA).each(function(data){
if('string' == typeof data)
{
code += data
return
}
var id = data.id
// Pour préparer les attributs de la balise d'ouverture
var attrs = {id:"pref-"+id}
if(data.onclick) attrs.onclick = data.onclick
if(data.onchange) attrs.onchange = data.onchange
if(data.class) attrs.class = data.class
if(data.style) attrs.style = data.style
switch(data.type)
{
case 'cb':
attrs.type = "checkbox"
if(data.indiv) code += '<div class="div_cb_pref">'
code += "input".to_tag(attrs) +
'<label for="pref-'+id+'">'+data.label+'</label>'
if(data.indiv) code += '</div>'
break
case 'select':
code += "select".to_tag(attrs) +
L(data.values).collect(function(d){
return '<option value="'+d.value+'">'+d.title+'</option>'
}).join("")+'</select>'
break
case 'fieldset':
code += '<fieldset id="prefs-'+id+'"><legend>'+data.legend+'</legend>'
break
case '/fieldset':
code += '</fieldset>'
break
}
})
return code
}
},
/**
* Retourne le code HTML pour les boutons du bas
*
* @method html_buttons
* @return {HTML} Code des boutons dans leur div
*/
"html_buttons":{
get:function(){
return '<div class="buttons">'+
'<input type="button" value="Renoncer" class="fleft" onclick="$.proxy(App.Prefs.close, App.Prefs)()" />' +
'<input type="button" value="Enregistrer" onclick="$.proxy(App.Prefs.save, App.Prefs)()" />' +
'</div>'
}
}
})
|
import React from 'react';
import {
Route,
Redirect,
Switch
} from 'react-router-dom';
const RouterView = ({routes = []})=>{
if(!routes.length) return null;
let redirectViews = routes.filter(item=>item.redirect).map((item,key)=><Redirect from={item.path} to={item.redirect} key={key} />);
routes = routes.filter(item=>!item.redirect);
return <Switch>
{
routes.map((item,key)=>{
return <Route path={item.path} render={(props)=>{
let Com = item.component;
document.title = item.meta.title;
return <Com {...props} routes={item.children} />
}} key={key} />
}).concat(redirectViews)
}
</Switch>
}
export default RouterView;
|
// import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import React from 'react';
import Home from 'app/screens/Home';
import Country from 'app/screens/Country';
import { useSelector, useDispatch } from 'react-redux';
import ignoreWarnings from 'react-native-ignore-warnings';
import { TransitionSpecs, createStackNavigator } from '@react-navigation/stack';
// import {
// // configureFonts,
// // DefaultTheme,
// Provider as PaperProvider,
// } from 'react-native-paper';
// ignoreWarnings('Setting a timer');
// function AuthIsLoaded({ children }) {
// const dispatch = useDispatch();
// const isLoading = useSelector(state => state.loadingReducer.isLoginLoading);
// useEffect(() => {
// let token;
// dispatch(loginActions.enableLoader());
// const bootstrapAsync = async () => {
// let userToken;
// try {
// userToken = await AsyncStorage.getItem('@userToken');
// } catch (e) {
// console.log(e);
// setTimeout(() => {
// Alert.alert('BoilerPlate', e.toString());
// }, 5000);
// }
// setTimeout(() => {
// dispatch(loginActions.onLoginResponse(userToken));
// dispatch(loginActions.disableLoader());
// }, 1500);
// };
// bootstrapAsync();
// }, [dispatch]);
// if (isLoading === true) {
// return <Splash />;
// }
// return children;
// }
const Stack = createStackNavigator();
export default function RNApp() {
// get the token in asyncstorage once usertoken is not null load auth screens and home screens otherwise
// const userToken = useSelector(state => state.loginReducer.id);
return (
<Stack.Navigator mode={'card'} initialRouteName="Home">
<Stack.Screen
name="Home"
component={Home}
options={{
headerShown: false,
// transitionSpec: {
// open: TransitionSpecs.RevealFromBottomAndroidSpec,
// },
}}
/>
<Stack.Screen
name="Country"
component={Country}
options={{
// transitionSpec: {
// open: TransitionSpecs.FadeInFromBottomAndroidSpec,
// close: TransitionSpecs.FadeOutToBottomAndroidSpec,
// },
headerShown: false,
}}
/>
</Stack.Navigator>
);
}
|
const path = require("path");
const webpack = require("webpack");
const webpackMerge = require("webpack-merge");
const glob = require("glob");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VIEWS_SRC = "web/src/views/";
const webpackEntries = getFiles("**/*.js", VIEWS_SRC);
const webpackChunks = Object.keys(webpackEntries);
const webpackConfig = {
entry: webpackEntries,
output: {
path: path.join(__dirname, "web/target/assets/"),
publicPath: "/",
filename: "javascripts/[name].js",
chunkFilename: "javascripts/[name].chunk.js"
},
resolve: {
extensions: [".js", ".scss", ".css"]
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: [__dirname]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
"css-loader",
"postcss-loader",
"sass-loader"
]
})
},
{
test: /\.ejs$/,
loader: "ejs-compiled-loader",
}
]
},
externals: {
jquery: "jQuery",
muu: "muu"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendors",
chunks: webpackChunks,
minChunks: webpackChunks.length
})
]
};
function getFiles( globPattern, dir, ignorePattern ) {
let resolved = {};
glob
.sync(path.join(dir, globPattern), {
ignore: ignorePattern ? path.join(dir, ignorePattern) : ""
})
.forEach(function( file ) {
let extname = path.extname(file);
let basename = path.basename(file, extname);
let dirname = path.dirname(file);
let filePath = basename === "index" && extname === ".js" ? dirname : path.join(dirname, basename);
resolved[filePath.replace(new RegExp(`^${dir}`), "")] = `./${file}`;
});
return resolved;
}
function resolvePageScripts( pageViews ) {
Object.keys(pageViews).forEach(function( page ) {
let opts = {
filename: `../views/${page}.hbs`,
template: `${VIEWS_SRC}${page}.ejs`,
inject: false,
hash: false,
minify: {
removeComments: false,
collapseWhitespace: false,
removeAttributeQuotes: false
},
muuBase: "//img.maihaoche.com/muu/1.0.4"
};
let chunkName = page;
if ( !webpackChunks.includes(chunkName) ) {
chunkName = `${page}/index`;
}
if ( webpackChunks.includes(chunkName) ) {
opts.inject = true;
opts.chunks = ["vendors", chunkName];
}
webpackConfig.plugins.push(new HtmlWebpackPlugin(opts));
});
}
resolvePageScripts(getFiles("**/*.ejs", VIEWS_SRC, "partials/**/*.ejs"));
module.exports = webpackMerge(webpackConfig, {
devtool: '#eval-source-map',
module: {
rules: [
{
test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader",
options: {
name: "fonts/[name].[ext]"
}
},
{
test: /\.(png|jpe?g|gif)$/,
loader: "url-loader",
options: {
limit: 8192,
name: "images/[name].[ext]"
}
}
]
},
plugins: [
new ExtractTextPlugin("stylesheets/[name].css"),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: "development"
}
})
]
});
|
import styled from 'styled-components'
export const FormControl = styled.label`
line-height: 2;
text-align: left;
display: block;
margin-bottom: 15px;
margin-top: 20px;
color: #1e2027;
font-size: 12px;
font-weight: 500;
text-transform: uppercase;
`
|
import React from 'react';
import './index.css';
import Router from '../../router';
import NavBar from '../../components/navbar';
import Info from './info';
import Strip from '../../components/strip';
import { LeftOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
class Mine extends React.Component {
constructor(props) {
super(props);
this.state = {
user: null
}
};
componentDidMount(){
let user = this.props.user;
if (!user.login){
user = {...JSON.parse(localStorage.getItem('user'))};
if (user.count)
user.login = true;
}
if (user.login){
this.setState({
user
});
return;
}
this.setState({
user:{login:false, name:'未登录'}
});
};
infoClick = (e)=>{
this.props.history.push('/updatemine');
};
publishClick = (e)=>{
this.props.history.push('/publish');
};
draftClick = (e)=>{
this.props.history.push('/draft');
};
actionClick = (e)=>{
if (!this.state.user.count){
this.props.history.push('/login');
return;
}
this.props.history.push('/action/'+this.state.user.count);
};
feedbackClick = (e)=>{
this.props.history.push('/feedback');
};
render() {
return (
<div className='mine-box'>
<NavBar
leftContent={<LeftOutlined onClick={() => {this.props.history.goBack();}}/>}
>我的</NavBar>
{
this.state.user&&
<Info
user={this.state.user}
infoClick={(e)=>{this.infoClick(e)}}
/>
}
<Strip
onClick={this.publishClick}
>
我的文章
</Strip>
<Strip
onClick={this.draftClick}
>
我的草稿
</Strip>
<Strip
onClick={this.actionClick}
>
我的动态
</Strip>
<Strip
onClick={this.feedbackClick}
>
意见反馈
</Strip>
<Router/>
</div>
);
}
}
const mapStoreToProps = (store)=>{
return {
user:store.loginReducer
};
};
Mine = connect(mapStoreToProps)(Mine);
export default Mine;
|
import React, { useContext} from 'react';
import ExpenseItem from './ExpenseItem';
import { Context } from '../Context/Context';
const ExpensesList = () => {
const {expenses }= useContext(Context);
return(
<ul>
{expenses.map((expense)=>(
<ExpenseItem
id={expense.id}
name={expense.name}
cost={expense.cost}
/>
))}
</ul>
)
}
export default ExpensesList;
|
// CREATION DE L'OBJET CANVAS
var Canvas = {
// INITIALISATION DU CANVAS
initCanvas: function (canvas) {
context = canvas.getContext("2d");
context.fillText("Signez ici", 20, 20);
painting = false;
},
// FONCTIONS CONCERNANT LA SIGNATURE A LA SOURIS
startDraw: function () {
context.beginPath();
context.moveTo(cursorX, cursorY);
},
draw: function () {
context.lineTo(cursorX, cursorY);
context.strokeStyle = "black";
context.lineWidth = 3;
context.stroke();
},
stopDraw: function () {
painting = false;
},
erase: function () {
context.clearRect(0,0, 350 , 200);
},
// FONCTIONS CONCERNANT LA SIGNATURE AU TOUCHÉ
ongoingTouches: [], // tableau qui regroupe les touch
ongoingTouchIndexById: function (idToFind) {
for (var i=0; i<this.ongoingTouches.length; i++) {
var id = this.ongoingTouches[i].identifier;
if (id == idToFind) {
return i;
}
}
return -1; // not found
},
handleStart: function(e) {
e.preventDefault();
var touches = e.changedTouches;
for (var i=0; i<touches.length; i++) {
this.ongoingTouches.push(touches[i]);
var color = "black";
context.fillStyle = color;
context.fillRect(touches[i].pageX-2-canvas.offsetLeft, touches[i].pageY-2-canvas.offsetTop, 4, 4);
}
},
handleMove:function(e) {
e.preventDefault();
var touches = e.changedTouches;
context.lineWidth = 4;
for (var i=0; i<touches.length; i++) {
var color = "black";
var idx = this.ongoingTouchIndexById(touches[i].identifier);
context.fillStyle = color;
context.beginPath();
context.moveTo(this.ongoingTouches[idx].pageX-canvas.offsetLeft, this.ongoingTouches[idx].pageY-canvas.offsetTop);
context.lineTo(touches[i].pageX-canvas.offsetLeft, touches[i].pageY-canvas.offsetTop);
context.closePath();
context.stroke();
this.ongoingTouches.splice(idx, 1, touches[i]);
}
},
handleEnd: function (e) {
e.preventDefault();
var touches = e.changedTouches;
context.lineWidth = 4;
for (var i=0; i<touches.length; i++) {
var color = "black";
var idx = this.ongoingTouchIndexById(touches[i].identifier);
context.fillStyle = color;
context.beginPath();
context.moveTo(this.ongoingTouches[i].pageX-canvas.offsetLeft, this.ongoingTouches[i].pageY-canvas.offsetTop);
context.lineTo(touches[i].pageX-canvas.offsetLeft, touches[i].pageY-canvas.offsetTop);
this.ongoingTouches.splice(i, 1);
}
},
handleCancel:function (e) {
var touches = e.changedTouches;
for (var i=0; i<touches.length; i++) {
this.ongoingTouches.splice(i, 1);
}
}
};
|
import Confidence from 'confidence'
import path from 'path'
var criteria = {
nodeEnv: process.env.NODE_ENV,
universalEnv: __CLIENT__ ? 'client' : 'server'
};
var config = {
$meta: {
name: 'React Redux Example Development'
},
isProduction: {
$filter: 'nodeEnv',
production: true,
$default: false
},
apiPort: 3030
}
var store = new Confidence.Store(config);
exports.get = (key) => {
return store.get(key, criteria);
};
exports.meta = (key) => {
return store.meta(key, criteria);
};
// module.exports = {
// development: {
// isProduction: false,
// port: 3000,
// apiPort: 3030,
// app: {
// name: 'React Redux Example Development'
// }
// },
// production: {
// isProduction: true,
// port: process.env.PORT,
// apiPort: 3030,
// app: {
// name: 'React Redux Example Production'
// }
// }
// }[process.env.NODE_ENV || 'development'];
|
import callouts from './callouts';
export { callouts };
export * from './theme.css';
export * as header from './Header.css';
export * as benefits from './Benefits.css';
export * as callToAction from './CallToAction.css';
export * as banner from './Banner.css';
export * as captureMessage from './CaptureMessage.css';
|
import * as types from "./types";
// import indexApi from '../api/indexApi'
const state = {
selectMenuUrl: '',
userInfo1: {},
voteMessage: false,
systemMessage: false,
commentMessage: false,
billMessage: false
}
const mutations = {
[types.USER_INFO](state, value) {
state.userInfo1 = value
console.log(state)
console.log(value)
},
}
const actions = {
// getRedMessage({commit}, data) {
// return new Promise((resolve, reject) => {
// indexApi.getMessage({
// userId: data
// }).then(d => {
// if (d.code == "0") {
// if (d.data && d.data.length) {
// d.data.forEach(item => {
// if (item.type == '0' && item.status == '1') {
// commit(types.SYSTEM_MESSAGE, true)
// }
// if (item.type == '1' && item.status == '1') {
// commit(types.COMMENT_MESSAGE, true)
// }
// if (item.type == '2' && item.status == '1') {
// commit(types.VOTE_MESSAGE, true)
// }
// if (item.type == '3' && item.status == '1') {
// commit(types.BILL_MESSAGE, true)
// }
// })
// }
// resolve(d)
// }
// }).catch(err => {
// reject(err)
// })
// })
// },
// getUserInfo({commit}, data){
// }
}
const getters = {}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
|
var assert = require('assert');
module.exports = function(ostore) {
this.transHooks = [];
this.init = function(ctx, className, args) {
return ostore.init(ctx, className, args);
}
this.trans = function(ctx, v1, p) {
var pair = ostore.trans(ctx, v1, p);
if(ctx.error) return pair;
for(var i = 0; i < this.transHooks.length; i++) {
this.transHooks[i].call(this, v1, p, pair[0], pair[1], ctx.conf, ctx);
}
return pair;
}
this.onTrans = function(func) {
this.transHooks.push(func);
}
this.onTrans(checkInvertibility);
this.ostore = ostore;
}
function checkInvertibility(v1, p, v2, r, c, ctx) {
// A conflicting transition is not expected to be invertible.
if(c) return;
var pair = this.ostore.trans(ctx, v2, {_type: 'inv', patch: p});
if(ctx.error) {
return pair;
}
if(JSON.stringify(pair[1]) != JSON.stringify(r)) {
console.error('Result on forward pass:', r);
console.error('Result on backwrads pass:', pair[1]);
console.error('Patch:', p);
console.error('v1:', v1);
console.error('v2:', v2);
throw new Error('Inconsistent result when inverting patch ' + p._type);
}
v1Prime = pair[0];
if(v1Prime.$ == v1.$) return;
var v1Digest = this.ostore.trans(ctx, v1, {_type: 'digest'})[1];
var v1PrimeDigest = this.ostore.trans(ctx, v1Prime, {_type: 'digest'})[1];
if(v1Digest == v1PrimeDigest) return;
var v2Digest = this.ostore.trans(ctx, v2, {_type: 'digest'})[1];
console.error('Non-invertible patch:', p);
console.error('From state:', v2Digest);
console.error('Moved to:', v1PrimeDigest);
console.error('Instead of:', v1Digest);
throw new Error('Patch ' + p._type + ' is not invertible');
}
|
import React from "react";
import useStyles from "../stylesheets/useStyles";
import Todo from "./Todo";
const TodoList = (props) => {
const classes = useStyles();
console.log("Received props from TodoList", props);
console.log(classes);
return (
<div className='d-flex flex-column justify-content-start'>
<div className="d-flex justify-content-start" style={{justifySelf: 'start'}}>
<Todo props={props} />
</div>
);
</div>
);
};
export default TodoList;
|
const db = require('./../database');
const passportHelper = require('./passport-helper');
module.exports = {
setup(app) {
require('./session-setup').setup(app);
passportHelper.setup(app); // log in logic is in here
},
// login and register could maybe possibly idontknow combined :P ?
login(req, res, next) {
if(req.user) req.logout(); // log out if logged in
return passportHelper.authenticate(req, res, next);
},
async register(req, res, next) {
try {
const userExists = await db.User.findOne({
where: { username: req.body.username }
});
if(userExists) {
// todo: should redirect to login function above?
return res.status(401).json({
success: false,
error: {
type: "username",
message: "Username is already taken"
}
});
}
const createdUser = await db.User.createAndHashPassword({
username: req.body.username,
password: req.body.password
});
if(!createdUser) {
return res.status(500).json({
success: false,
error: {
type: "unknown",
message: "Error creating a new user" }
});
}
req.login(createdUser, err => {
if (err) { return next(err); }
console.log("Registeration succesful", "User:", req.body.username);
return res.json({ success: true, payload: { user: createdUser } });
});
}
catch(err) { console.error("Registeration error", err); next(err); };
},
logout(req, res, next) {
req.logout();
res.status(200).send();
},
getLoggedInUser(req, res, next) {
res.json({ user: req.user });
},
requireAuthenticated(req, res, next) {
if (!req.user) return res.status(401).json( { success: false, error: { type: 'auth', message: 'You must be logged in' } });
return next();
}
};
|
module.exports = {
part1: (data) => {
const [card, door] = data.split("\n").map(Number);
let key = 1;
let target = 1;
while (target !== door) {
target = (target * 7) % 20201227;
key = (key * card) % 20201227;
}
return key;
},
part2: () => 0,
};
|
import {
UPDATE_FIELD_ARTICLE_EDITOR,
SUBMIT_ARTICLE,
ASYNC_START,
CLEAN_ERROR,
ARTICLE_EDITOR_PAGE_UNLOADED,
ARTICLE_EDITOR_PAGE_LOADED
} from '../constants'
const defaultState = {
id: null,
title: '',
body: '',
image: ''
}
export default (state=defaultState, action) => {
switch(action.type){
case ARTICLE_EDITOR_PAGE_LOADED:
return {
...state,
id: action.article.id,
title: action.article.title,
body: action.article.body,
image: action.article.image || ''
}
case UPDATE_FIELD_ARTICLE_EDITOR:
return {
...state,
[action.key]: action.value
}
case ASYNC_START:
if(action.subtype === SUBMIT_ARTICLE){
return {
...state,
inProgress: true
}
}
break
case SUBMIT_ARTICLE:
return {
...state,
inProgress: false,
errors: action.error ? action.payload.errors : null
}
case CLEAN_ERROR:
return {
...state,
errors: null
}
case ARTICLE_EDITOR_PAGE_UNLOADED:
return defaultState
default:
}
return state
}
|
var todos = require('./lib/todos')
, fs = require('fs')
var text = '\n'
, todo
for (var category in todos) {
text += '## ' + category + '\n\n'
for (var type in todos[category]) {
todo = todos[category][type]
text += '### ' + type + '\n\n'
text += '- **Title:** ' + todo.title + '\n'
if (todo.help) text += '- **Help:** ' + todo.help + '\n'
if (todo.help_link) text += '- **Help Link:** ' + todo.help_link + '\n'
text += '\n'
}
text += '\n'
}
fs.writeFileSync('docs/todos.md', text)
|
const os = require("os");
const { readFile, existsSync } = require("fs");
// imports
window.xlsToJson = require("convert-excel-to-json");
window.process = require("child_process");
window.fs = require("file-system");
window.path = require("path");
window.electron = require("electron");
window.csvToJson = require("csvjson");
window.qr = require("qr-image");
window.pdf = require("pdfkit");
// constants
window.constants = {
baseDir: path.join(os.homedir(), "Documents", "zonagrad_photos", "photos"),
configDir: path.join(os.homedir(), "Documents", "zonagrad_photos", "config"),
levels: {
PRE: "Pre-escolar",
PRI: "Primaria",
SEC: "Secundaria",
TEC: "Secundaria Técnica",
PRP: "Preparatoria",
UNI: "Universidad",
POS: "Posgrado",
DIP: "Diplomado",
CUR: "Curso",
TAL: "Taller",
CER: "Certificado"
},
shifts: {
M: "Matutino",
I: "Intermedio",
V: "Vespertino"
},
defaultToast: {
message: "[DEFAULT TOAST]",
intent: "primary",
duration: 3000
}
};
const home_config = path.join(
os.homedir(),
"Documents",
"zonagrad_photos",
"config",
"config.json"
);
if (existsSync(home_config))
readFile(home_config, "utf8", (err, data) => {
if (err) return console.error(err);
const { baseDir } = JSON.parse(data);
if (baseDir) window.constants.baseDir = baseDir;
});
else console.info("Fallback to default config");
|
import Taro, { Component } from '@tarojs/taro'
import { Picker,View, Text } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import dayjs from 'dayjs'
import PropTypes from 'prop-types'
import './index.scss';
class DatePicker extends Component {
static propTypes = {
dateStart: PropTypes.string,
dateEnd: PropTypes.string,
onDateChange: PropTypes.func
}
static defaultProps = {
dateStart: dayjs().startOf('month').format('YYYY-MM-DD'),
dateEnd: dayjs().format('YYYY-MM-DD')
}
handleChange = e => {
this.props.onDateChange(e.currentTarget.dataset.name, e.detail.value)
}
render() {
const { dateStart, dateEnd } = this.props
return (
<View className='picker-container'>
<Picker mode='date' data-name='dateStart' onChange={this.handleChange} value={dateStart}>
<View className='picker'>
<Text>{dateStart}</Text>
<AtIcon value='chevron-down' color='#aaa'></AtIcon>
</View>
</Picker>
<Text style='padding: 0 28rpx;'> 至 </Text>
<Picker mode='date' data-name='dateEnd' onChange={this.handleChange} value={dateEnd}>
<View className='picker'>
<Text>{dateEnd}</Text>
<AtIcon value='chevron-down' color='#aaa'></AtIcon>
</View>
</Picker>
</View>
)
}
}
export default DatePicker
|
/* global LOOP_OBJ, define */
window.GATE_INNER_TEMPLATE = new Template("{{TYPE}}<br> < {{IN}}<br> > {{OUT}}");
function Template(html) {
this.html = html;
}
Template.prototype.apply = function(values) {
let html = this.html;
// Apply all values
LOOP_OBJ(values).forEach((k, v) => {
html = html.replace(new RegExp('{{\\s*' + k + '\\s*}}', 'gi'), v);
});
return html;
};
define(() => Template);
|
var SetStateInDepthMixin = {
setStateInDepth: function(updatePath) {
this.setState(React.addons.update(this.state, updatePath));
}
};
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import BaseComponent from '../components/admin/BaseComponent.vue'
import UserTableComponent from '../components/admin/pages/UserTableComponent.vue'
import CreateUser from '../components/admin/pages/CreateUser.vue'
import EditUser from '../components/admin/pages/EditUser.vue'
import ListRole from '../components/admin/pages/ListRole.vue'
import CreateRole from '../components/admin/pages/CreateRole.vue'
import LoginPage from '../components/admin/auth/LoginPage'
import RegisterPage from '../components/admin/auth/RegisterPage'
import NotFoundPage from '../components/admin/error/NotFoundPage'
import widget from '../components/admin/pages/widget.vue'
import Category from '../components/admin/pages/category/ListCategory'
import Main from '../components/user/Main'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: Main,
component: Main,
},
{
path: '/admin',
name: BaseComponent,
component: BaseComponent,
children: [
{
path: 'dashboard',
name: 'widget',
component: widget
},
{
path: 'category',
name: 'Category',
component: Category
},
{
path: 'list-user',
name: 'UserTableComponent',
component: UserTableComponent
},
{
path: 'create-user',
name: 'CreateUser',
component: CreateUser
},
{
path: ':id',
name: 'EditUser',
component: EditUser
},
{
path: 'list-role',
name: 'ListRole',
component: ListRole
},
{
path: 'create-role',
name: 'CreateRole',
component: CreateRole
}
]
},
{
path: '/login',
name: LoginPage,
component: LoginPage,
},
{
path: '/register',
name: RegisterPage,
component: RegisterPage,
},
{
path: '*',
name: NotFoundPage,
component: NotFoundPage,
},
]
})
console.log(router)
export default router
|
const express = require('express');
const bodyParser = require('body-parser');
// MongoDB connect
const connectDB = require('./config/db')
connectDB()
///helpers
const {demoLogger} = require('./helpers');
// active version
const ACTIVE_VERSION = "/api/v1"
//models/
const HttpError = require(`.${ACTIVE_VERSION}/models/error`)
// routes
const authRoutes = require(`.${ACTIVE_VERSION}/routes/auth.routes`)
const usersRoutes = require(`.${ACTIVE_VERSION}/routes/users.routes`)
const journalsRoutes = require(`.${ACTIVE_VERSION}/routes/journals.routes`)
const tasksRoutes = require(`.${ACTIVE_VERSION}/routes/tasks.routes`)
// inititialize app
const app = express()
const PORT = 5000
//body paraser for json
app.use(bodyParser.json())
// logs
app.use(demoLogger)
// assign routes
app.use(`${ACTIVE_VERSION}/auth`, authRoutes);
app.use(`${ACTIVE_VERSION}/users`, usersRoutes);
app.use(`${ACTIVE_VERSION}/journals`, journalsRoutes);
app.use(`${ACTIVE_VERSION}/tasks`, tasksRoutes);
// handle if routes not found
app.use((req, res, next)=>{
const error = new HttpError("404 Not found!",404)
return next(error)
})
// handle errors
app.use((error, req, res, next) => {
if (res.headerSent){
return next(error)
}
console.log("Error : ", req.method, req.originalUrl , error.code, error.message)
res.status(error.code || 500)
res.json({ message: error.message || "Unknown error occured!"});
})
// test
app.use((req,res,next) => {
res.send("Hello")
})
// serve
app.listen(5000, ()=> console.log(`Serving at port ${PORT}`))
|
const axios = require('axios');
const _ = require('lodash');
const sleep = require('./sleep');
const HOUR = 1000 * 60 * 60;
const TIMEOUT = 24 * 6;
const RATE_LIMIT_RESERVE = 5;
const TRY_LIMIT = 3;
const URL_RATE_LIMIT = 'https://api.github.com/rate_limit';
/* eslint-disable prefer-promise-reject-errors, no-throw-literal */
class WorkerManager {
constructor({
workers = 5,
limitReserve = RATE_LIMIT_RESERVE,
timeout = TIMEOUT,
tryLimit = TRY_LIMIT,
authTokens,
...settings
}) {
this.tokens = authTokens;
this.tokenStatus = {};
this.authIndex = 0;
this.authCount = authTokens.length;
const reservedLimit = limitReserve + workers;
Object.assign(this, { ...settings, reservedLimit, tryLimit });
this.createWorkers(workers);
this.repoCursor = 0;
this.repoCount = this.repositories.length;
this.timeout = Date.now() - timeout * HOUR;
}
async run() {
console.log(`start ${this.workers.length} workers`);
const preToken = await this.acquireAuthToken();
console.log(preToken);
return Promise.all(_.map(this.workers, (worker, workerId) => new Promise((resolve) => {
const executor = async (args = {}) => {
try {
await worker(args);
await sleep();
return executor();
} catch (err) {
const { error, rawError = null, ...payload } = err;
switch (error) {
case 'FINISHED': case 'NO_TOKEN': {
return error;
}
case 'FAILED': {
await sleep();
return executor();
}
default: {
console.error(rawError);
await sleep();
return executor(payload);
}
}
}
};
(async () => {
console.log(`Fire worker ${workerId}`);
await executor();
resolve();
})();
})));
}
async acquireNextRepo() {
while (this.repoCursor < this.repoCount) {
const cursor = this.repoCursor;
this.repoCursor = cursor + 1;
const repo = this.repositories[cursor];
const status = this.db.get(`repositories.${repo}`).value();
if (!status) return repo;
const { state, timestamp } = status;
if (timestamp < this.timeout || state !== 'OK') return repo;
}
throw 'FINISHED';
}
async acquireAuthToken(start = null, tried = {}) {
const authId = start === null ? this.authIndex : start;
const token = this.tokens[authId];
let status = this.tokenStatus[token];
if (!status || status.reset < Date.now()) {
await this.fetch(URL_RATE_LIMIT, token);
status = this.tokenStatus[token];
}
if (status.remaining > this.reservedLimit) return token;
if (_.size(tried) >= this.authCount - 1) throw 'NO_TOKEN';
return this.acquireAuthToken(
authId >= this.authCount ? 0 : authId + 1,
{ ...tried, [authId]: 1 },
);
}
async fetch(url, token) {
const { data, headers } = await axios.get(url, {
headers: { Authorization: `token ${token}` },
});
const old = this.tokenStatus[token];
const status = {
remaining: headers['x-ratelimit-remaining'] | 0,
reset: headers['x-ratelimit-reset'] * 1000,
};
if (!old || old.reset < status.reset || status.remaining < old.remaining) {
this.tokenStatus[token] = status;
}
return data;
}
updateRepo({ repo, ...status }) {
this.db.set(`repositories.${repo}`, status).write();
}
createWorkers(workerCount) {
this.workers = _.times(workerCount, workerId => payload => new Promise((resolve, reject) => {
let { tried = 0, repo = null } = payload;
(async () => {
try {
tried += 1;
repo = repo || await this.acquireNextRepo();
const token = await this.acquireAuthToken();
const timestamp = Date.now();
try {
console.log(`[worker ${workerId}] - fetch ${repo}`);
const {
stargazers_count: stars,
subscribers_count: eyes,
forks,
} = await this.fetch(`https://api.github.com/repos/${repo}`, token);
this.updateRepo({
repo,
state: 'OK',
stars,
eyes,
forks,
timestamp,
});
resolve();
} catch (rawError) {
console.log(`[worker ${workerId}] FAILED ${repo}: ${rawError}`);
if (tried < this.tryLimit) {
reject({
error: 'NETWORK',
rawError,
tried,
repo,
});
}
this.updateRepo({
repo,
state: 'ERR.NETWORK',
timestamp,
});
reject({ error: 'FAILED', rawError });
}
} catch (error) {
console.log(`[worker ${workerId}] ERROR ${error}`);
reject({ error });
}
})();
}));
}
}
module.exports = WorkerManager;
|
$(document).ready(function () {
changeFluid();
});
$(window).resize(function () {
changeFluid();
});
$('.collapse').on('show.bs.collapse', function () {
$('.collapse').collapse('hide');
});
$('.btn-left[type="button"]').click(function () {
let has = $(this).hasClass('active');
$('.btn-left').removeClass('active');
if (!has) $(this).addClass('active');
});
function changeFluid() {
if ($(window).width() < 992) {
$('.car-container')
.removeClass('container')
.addClass('container-fluid');
} else {
$('.car-container')
.removeClass('container-fluid')
.addClass('container');
}
}
|
import React from "react";
import Chatkit from "@pusher/chatkit";
import HoverableText from "./HoverableText";
const instanceLocator = "v1:us1:5f6f671c-5638-4ab3-b928-0c0f97c6b872";
const secretKey =
"5b4b74c3-2ebc-480c-94cd-fb5f87e5d4ff:3oKYoWtbJDl8tesyCVqtPt6nGJ7ITnHhUvcIM0uQWuA=";
const testToken =
"https://us1.pusherplatform.io/services/chatkit_token_provider/v1/5f6f671c-5638-4ab3-b928-0c0f97c6b872/token";
const username = "htb-user-01";
// const roomId = 14340058;
const toLang = "en";
// WIP
class ChatWindow extends React.Component {
constructor() {
super();
this.state = {
messages: []
};
this.sendMessage = this.sendMessage.bind(this);
}
componentDidMount() {
const chatManager = new Chatkit.ChatManager({
instanceLocator: instanceLocator,
userId: this.props.userId,
tokenProvider: new Chatkit.TokenProvider({
url: testToken
})
});
chatManager.connect().then(currentUser => {
this.currentUser = currentUser;
this.currentUser.subscribeToRoom({
roomId: this.props.groupId,
hooks: {
onNewMessage: message => {
this.setState({
messages: [...this.state.messages, message]
});
}
}
});
});
}
componentDidUpdate(prevProps) {
if (this.props.groupId !== prevProps.groupId) {
this.setState({ messages: [] });
const chatManager = new Chatkit.ChatManager({
instanceLocator: instanceLocator,
userId: this.props.userId,
tokenProvider: new Chatkit.TokenProvider({
url: testToken
})
});
chatManager.connect().then(currentUser => {
this.currentUser = currentUser;
this.currentUser.subscribeToRoom({
roomId: this.props.groupId,
hooks: {
onNewMessage: message => {
this.setState({
messages: [...this.state.messages, message]
});
}
}
});
});
}
}
sendMessage(text) {
this.currentUser.sendMessage({
text,
roomId: this.props.groupId
});
}
render() {
return (
<div
className="chatWindow"
style={{
height: "100%",
width: "100%"
}}
>
<div
className="messageWindow"
style={{
height: "100%",
width: "100%",
float: "right",
backgroundColor: "none"
}}
>
<div className="chatTitle">
<ChatTitle title={this.props.groupName + " Group Chat"} />
</div>
<div className="messageList">
<MessageList
userId={this.props.userId}
messages={this.state.messages}
/>
</div>
<div className="messageTextBox">
<MessageTextBox sendMessage={this.sendMessage} />
</div>
</div>
</div>
);
}
}
class ChatTitle extends React.Component {
render() {
return (
<div>
<p className="chatTitle">{this.props.title}</p>
</div>
);
}
}
class MessageTextBox extends React.Component {
constructor() {
super();
this.state = {
message: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
message: e.target.value
});
}
handleSubmit(e) {
e.preventDefault();
this.props.sendMessage(this.state.message);
this.setState({
message: ""
});
}
render() {
return (
<form onSubmit={this.handleSubmit} className="send-message-form">
<textarea
className="messageTextBox"
onChange={this.handleChange}
value={this.state.message}
placeholder="Type a message..."
type="text"
style={{
overflow: "auto",
resize: "none"
}}
/>
</form>
);
}
}
class MessageList extends React.Component {
render() {
return (
<div>
<ul className="messageList">
{this.props.messages.map(message => {
const isLeftSided = this.props.userId === message.senderId;
return (
<li className="messageListElement" key={message.id}>
<div
className={
isLeftSided ? "messageHeader-Left" : "messageHeader-Right"
}
>
{message.senderId}
</div>
<div
className={
isLeftSided ? "messageBubble-Left" : "messageBubble-Right"
}
>
<HoverableText
defaultText={message.text}
hoverText={message.senderId}
/>
</div>
<hr />
</li>
);
})}
</ul>
</div>
);
}
}
const DUMMY_DATA = [
{
senderId: "perborgen",
text: "who'll win?"
},
{
senderId: "janedoe",
text: "who'll win?"
}
];
export default ChatWindow;
|
const ERRORS = {
USERS: {
USER_NOT_FOUND: {
text: 'USER_NOT_FOUND_ERROR',
message: 'User not found!'
},
USER_ALREADY_EXISTS: {
text: 'USER_ALREADY_EXISTS_ERROR',
message: 'User already exists!'
},
USER_INPUT_DATA_NOT_VALID: {
text: 'USER_INPUT_DATA_NOT_VALID',
message: 'User input data not valid'
},
USER_STATUS_IS_SAME: {
text: 'USER_STATUS_IS_SAME',
message: 'User status already set to same value!',
}
}
};
export default ERRORS;
|
import React, { Component } from 'react';
import NumKey from './NumKey';
export default class Numpad extends Component {
render() {
return (
<div className="numpad">
<div>
<NumKey name="AC" onClick={name => this.props.onClick(name)} />
<NumKey name="%" onClick={name => this.props.onClick(name)} />
<NumKey name="/" onClick={name => this.props.onClick(name)} />
</div>
<div>
<NumKey name="7" onClick={name => this.props.onClick(name)} />
<NumKey name="8" onClick={name => this.props.onClick(name)} />
<NumKey name="9" onClick={name => this.props.onClick(name)} />
<NumKey name="*" onClick={name => this.props.onClick(name)} />
</div>
<div>
<NumKey name="4" onClick={name => this.props.onClick(name)} />
<NumKey name="5" onClick={name => this.props.onClick(name)} />
<NumKey name="6" onClick={name => this.props.onClick(name)} />
<NumKey name="-" onClick={name => this.props.onClick(name)} />
</div>
<div>
<NumKey name="1" onClick={name => this.props.onClick(name)} />
<NumKey name="2" onClick={name => this.props.onClick(name)} />
<NumKey name="3" onClick={name => this.props.onClick(name)} />
<NumKey name="+" onClick={name => this.props.onClick(name)} />
</div>
<div>
<NumKey name="0" onClick={name => this.props.onClick(name)} />
<NumKey name="=" onClick={name => this.props.onClick(name)} />
</div>
</div>
);
}
}
|
import "../App.css"
import {useState} from "react"
function Field(){
const [title, setTitle] = useState('')
const [title2, setTitle2] = useState('')
function BMI(){
let Bmi= (title2/((title/100)*(title/100)))
let low = Math.floor(18*(title/100)*(title/100));
let high= Math.floor(25*(title/100)*(title/100));
if(Bmi>25 ){
return(` Your BMI is ${Math.floor(Bmi)}, You are in overweight range, prefered weight for healthy range is ${low}-${high}`)
}else if (Bmi<18){
return(` Your BMI is ${Math.floor(Bmi)}, You are in under over underweight range, prefered weight for healthy range is ${low}-${high}`)
}else {
return( `Your BMI is ${Math.floor(Bmi)}, You are in normal weight range, prefered weight for healthy range is ${low}-${high}`)
}
}
return(
<div className="body">
<div>
<label for="weight">Weight in KG:</label>
<input onChange={event => setTitle2(event.target.value)} type="number" name="weight"/>
</div>
<div>
<label for="height">Height in cm:</label>
<input onChange={event => setTitle(event.target.value)} type="number" name="height"/>
</div>
<button onClick={()=>document.querySelector(".Index").style="display:block"} >Submit</button>
<div className="Index">
<h3>{BMI()}</h3>
<h3>Normal BMI ranges between 18-25</h3>
</div>
</div>
)
}
export default Field;
|
import ReactCodeInput from 'react-code-input';
import React from 'react';
class Input2FA extends React.Component {
constructor(props){
super(props);
this.state = {};
}
onChange = (e) => {
if (e.length === 6) {
this.props.confirm({token : e});
}
}
render = () => {
return (
<ReactCodeInput autoFocus={true} type='number' fields={6} onChange={(e) => this.onChange(e)} />
)
}
}
export default Input2FA;
|
/*! Bulma integration for DataTables' Buttons
* © SpryMedia Ltd - datatables.net/license
*/
$.extend(true, DataTable.Buttons.defaults, {
dom: {
container: {
className: 'dt-buttons field is-grouped'
},
button: {
className: 'button is-light',
active: 'is-active',
disabled: 'is-disabled'
},
collection: {
action: {
tag: 'div',
className: 'dropdown-content',
dropHtml: ''
},
button: {
tag: 'a',
className: 'dt-button dropdown-item',
active: 'dt-button-active',
disabled: 'is-disabled',
spacer: {
className: 'dropdown-divider',
tag: 'hr'
}
},
closeButton: false,
container: {
className: 'dt-button-collection dropdown-menu',
content: {
className: 'dropdown-content'
}
}
},
split: {
action: {
tag: 'button',
className: 'dt-button-split-drop-button button is-light',
closeButton: false
},
dropdown: {
tag: 'button',
dropHtml: '<i class="fa fa-angle-down" aria-hidden="true"></i>',
className: 'button is-light',
closeButton: false,
align: 'split-left',
splitAlignClass: 'dt-button-split-left'
},
wrapper: {
tag: 'div',
className: 'dt-button-split dropdown-trigger buttons has-addons',
closeButton: false
}
}
},
buttonCreated: function (config, button) {
// For collections
if (config.buttons) {
// Wrap the dropdown content in a menu element
config._collection = $('<div class="dropdown-menu"/>').append(config._collection);
// And add the collection dropdown icon
$(button).append(
'<span class="icon is-small">' +
'<i class="fa fa-angle-down" aria-hidden="true"></i>' +
'</span>'
);
}
return button;
}
});
|
import Api from '../js/api';
import folders from '../stubs/folders';
import messages from '../stubs/messages';
import palette from '../js/palette';
var _folders = [];
/**
* Init stubs, settings message's folderId, color.
* @param {Array} folders to init
*/
var initStubs = (folders) => {
for (let folder of folders) {
_folders.push(folder);
if (!folder.messages) {
continue;
}
for (let messageId of folder.messages) {
let message = messages.find(message => message.id == messageId);
message.folderId = folder.id;
message.color = palette();
}
if (folder.subfolders) {
initStubs(folder.subfolders);
}
}
}
initStubs(folders);
class MessagesApi extends Api {
getByFolder(folderId) {
return this.get().then(() => {
var folder = _folders.find(folder => folder.id == folderId);
if (!folder) {
return { messages: [], folderId: -1 }
}
var folderMessages = messages.filter(
message => folder.messages.indexOf(message.id) != -1
);
return { messages: folderMessages, folderId: folderId };
});
}
getById(id) {
return this.get().then(() => {
var message = messages.find(message => message.id == id);
return { message: message };
});
}
find(text) {
return this.get().then(() => {
var regExp = new RegExp(text, "i");
var resultMessages = messages.filter(message =>
regExp.test(message.title)
);
return { messages: resultMessages };
});
}
}
export default new MessagesApi();
|
import React, { useState, useEffect } from "react";
//--------------------------------- What was used from material ui core -------------------------------------
import {
TextField,
withStyles,
Grid,
Typography,
Radio,
} from "@material-ui/core";
//-----------------------------------------------------------------------------------------------------------
const ViewTrueFalse = ({ questionData, classes, Index }) => {
// ---------------------------- variables with it's states that we use it in this Page -------------------
const [TFData, setTFData] = useState([]);
const [tfTrue, setTfTrue] = useState(false);
const [tfFalse, setTfFalse] = useState(false);
//---------------------------------------------------------------------------------------------------------
useEffect(() => {
setTFData(questionData);
}, [questionData]);
useEffect(() => {
setTfTrue(TFData.TrueOrFalse);
setTfFalse(!TFData.TrueOrFalse);
}, [TFData]);
return (
<React.Fragment>
<Grid item>
<Grid
style={{
align: "left",
height: "auto",
marginTop: "30px",
marginRight: "9px",
width: "1257px",
}}
>
<Grid
item
style={{
marginLeft: "20px",
minWidth: "300px",
maxWidth: "1130px",
}}
>
<Typography
style={{
fontSize: "35px",
fontWeight: "bold",
}}
>
{` Q ${Index + 1} )`}
</Typography>
<Typography
style={{
fontSize: "35px",
textDecorationLine: "underline",
marginLeft: "80px",
}}
>
{` ${TFData.title}`}
</Typography>
</Grid>
<Grid>
<TextField
label="Question Statement"
value={TFData.QuestionAsString}
defaultValue={TFData.QuestionAsString}
multiline
rows={2}
variant="outlined"
classes={{
root: classes.textFieldRoot,
}}
InputProps={{
classes: {
notchedOutline: classes.notchedOutline,
},
readOnly: true,
style: { fontSize: "30px" },
}}
InputLabelProps={{
classes: {
root: classes.label,
},
shrink: "true",
style: { fontSize: "20px" },
}}
style={{ width: "900px", marginLeft: "160px", marginTop: "40px" }}
/>
</Grid>
<Grid item style={{ marginLeft: "140px" }}>
<Grid item style={{ marginLeft: "180px", paddingBottom: "40px" }}>
<Grid item style={{ marginTop: "5px" }}>
<Typography style={{ fontSize: "20px" }}>[ 1 ]</Typography>
</Grid>
<Grid item style={{ marginTop: "-40px", marginLeft: "70px" }}>
<Typography
style={{
fontSize: "32px",
fontFamily: "Times New Roman",
}}
>
True
</Typography>
</Grid>
<Grid item style={{ marginTop: "-43px", marginLeft: "200px" }}>
<Radio
checked={tfTrue}
disableRipple
inputProps={{ "aria-label": "A" }}
classes={{ root: classes.radio, checked: classes.checked }}
/>
</Grid>
</Grid>
<Grid item style={{ marginLeft: "180px", paddingBottom: "40px" }}>
<Grid item style={{ marginTop: "5px" }}>
<Typography style={{ fontSize: "20px" }}>[ 2 ]</Typography>
</Grid>
<Grid item style={{ marginTop: "-40px", marginLeft: "70px" }}>
<Typography
style={{
fontSize: "32px",
fontFamily: "Times New Roman",
}}
>
False
</Typography>
</Grid>
<Grid item style={{ marginTop: "-43px", marginLeft: "200px" }}>
<Radio
checked={tfFalse}
inputProps={{ "aria-label": "A" }}
disableRipple
classes={{ root: classes.radio, checked: classes.checked }}
/>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</React.Fragment>
);
};
const styles = () => ({
dialog: {
padding: "10px 0px",
},
multilineColor: {
color: "red",
},
titleContainer: {
marginBottom: "18px",
},
textFieldRoot: {
backgroundColor: "white",
borderRadius: "7px",
marginTop: "10px",
marginBottom: "10px",
},
notchedOutline: {
borderWidth: "1px",
borderColor: `black !important`,
fontSize: "21px",
},
label: {
color: "black !important",
fontWeight: "600",
},
dialogPaper: {
minHeight: "50vh",
padding: "20px 0px",
},
createButton: {
height: "40px",
width: "130px",
borderRadius: "16px",
border: "2px black solid",
},
cancelButton: {
height: "40px",
width: "130px",
borderRadius: "16px",
border: "2px red solid",
},
boldText: {
fontWeight: "600",
},
createText: {
color: "silver",
},
radio: {
"&$checked": {
color: "#0e7c61",
},
},
checked: {},
});
export default withStyles(styles)(ViewTrueFalse);
|
$("#target-id").click( function (event) {
output = "User clicked on " + event.pageX + "/" + event.pageY;
$("#display").text(output);
} )
|
const HBORDER = 5
const VBORDER = 5
const TSTEP = 5
const SSTEP = 4
const VSTEP = 3
class Table {
constructor(st) {
this.table = {
'': ['units', 'survived', 'kills'],
red: [101, 101, 101],
blue: [101, 101, 101],
green: [101, 101, 101],
yellow: [101, 101, 101],
}
augment(this, st)
}
adjust() {}
drawInverseTable() {
const tx = this.__
const w = tx.tw - 2*HBORDER
const h = tx.th
const t = this.table
tx
.back(lib.cidx('base'))
.face(lib.cidx('alert'))
function center(txt, x, y) {
txt = '' + txt
const halfWidth = ceil(txt.length/2)
x = max(x - halfWidth, 0)
tx.at(x, y).print(txt)
}
const columns = Object.keys(t)
const clen = columns.length
columns.forEach((c, i) => {
let y = VBORDER
const cw = floor(w/(clen+1))
const xpos = HBORDER + (i+1) * cw
center(c, xpos, y)
y += TSTEP
const ls = t[c]
ls.forEach(e => {
center(e, xpos, y)
y += VSTEP
})
})
}
drawTable() {
const tx = this.__
const w = tx.tw - 2*HBORDER
const h = tx.th
const t = this.table
tx
.back(lib.cidx('base'))
.face(lib.cidx('alert'))
function left(txt, x, y) {
txt = '' + txt
tx.at(x, y).print(txt)
}
function center(txt, x, y) {
txt = '' + txt
const halfWidth = ceil(txt.length/2)
x = max(x - halfWidth, 0)
tx.at(x, y).print(txt)
}
const rows = Object.keys(t)
const clen = rows[0].length + 1
let y = VBORDER
rows.forEach((c, i) => {
const cw = floor(w/(clen + 1))
let x = HBORDER + cw
if (i > 1) left(c, x-4, y)
const ls = t[c]
ls.forEach((e, j) => {
const x = HBORDER + (j+2) * cw
if (i === 0) center(e.toUpperCase(), x+4, y)
else center(e, x+4, y)
})
if (i === 0) y += TSTEP
else y += VSTEP
})
}
draw() {
if (this.inverse) this.drawInverse()
else this.drawTable()
}
setTable(table) {
if (!table) return
this.table = table
}
}
|
var express = require('express');
var router = express.Router();
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
// handler for the /user/:id path, which sends a special response
router.get(['/','/:id([0-9]+)'], function (req, res, next) {
res.json({
name: req.params.name,
surname: req.query.surname,
address: req.query.address,
id: req.params.id,
phone: req.query.phone
});
})
router.get('/create', function(req, res) {
res.sendStatus(404);
});
// define the about route
router.get('/list', function(req, res) {
res.send('Users\'s list');
});
module.exports = router;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.