text
stringlengths 7
3.69M
|
|---|
export const clientId = '2'
export const clientSecret = 'tMDoWOkXlTyqXaBnhAqloDNZMK6zCKDvrgkHskdy'
|
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import FlatListAlarm from '../components/FlatListAlarm'
class AlarmScreen extends Component{
render(){
return(
<View style={{flex:1}}>
<FlatListAlarm></FlatListAlarm>
</View>
)
}
}
export default AlarmScreen;
|
export const authConstant = {
SIGNUP_REQUEST : 'SIGNUP_REQUEST',
SIGNUP_SUCCESS : 'SIGNUP_SUCCESS',
SIGNUP_FAILURE: 'SIGNUP_FAILURE',
LOGIN_REQUEST : 'LOGIN_REQUEST',
LOGIN_SUCCESS : 'LOGIN_SUCCESS',
LOGIN_FAILURE : 'LOGIN_FAILURE',
}
export const postConstant = {
ADD_POST_REQUEST : 'ADD_POST_REQUEST',
ADD_POST_SUCCESS : 'ADD_POST_SUCCESS',
ADD_POST_FAILURE : 'ADD_POST_FAILURE',
GET_POST_REQUEST : 'GET_POST_REQUEST',
GET_POST_SUCCESS : 'GET_POST_SUCCESS',
GET_POST_FAILURE : 'GET_POST_FAILURE',
ADD_COMMENT_REQUEST : 'ADD_COMMENT_REQUEST',
ADD_COMMENT_SUCCESS : 'ADD_COMMENT_SUCCESS',
ADD_COMMENT_FAILURE : 'ADD_COMMENT_FAILURE',
GET_SINGLE_POST_REQUEST : 'GET_SINGLE_POST_REQUEST',
GET_SINGLE_POST_SUCCESS : 'GET_SINGLE_POST_SUCCESS',
GET_SINGLE_POST_FAILURE : 'GET_SINGLE_POST_FAILURE'
}
|
'use strict';
const { request } = require('../utils');
function getAlarmMessage() {
return `* CLI: No data`;
}
exports.getDownloadInfo = async function () {
return getAlarmMessage();
};
|
import {
Card,
CardMedia,
Grid,
Typography,
TextField,
Button,
CardContent,
} from "@material-ui/core";
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
card: {
width: "100vw",
textAlign: "center",
boxShadow: "none",
backgroundColor: "transparent",
},
image: {
width: "90%",
height: "100%",
margin: "0 20px",
borderRadius: "4px",
},
}));
const advertisingBanner = (props) => {
const classes = useStyles();
return (
<Grid container direction="column" justify="center" alignItems="center">
<Grid item style={{ marginTop: "37px" }}>
<Card className={classes.card}>
<CardMedia>
<img
src="https://assets.oyoroomscdn.com/cmsMedia/7700e1f2-3d24-41e8-8c71-f4336c625a88.jpg"
alt="advertising photo"
className={classes.image}
/>
</CardMedia>
</Card>
</Grid>
<Grid item style={{ marginTop: "37px" }}>
<Card className={classes.card}>
<CardMedia>
<img
src="https://assets.oyoroomscdn.com/cmsMedia/b8bad7f9-d052-40c8-8521-bbb4937c5acc.jpg"
alt="advertising photo"
className={classes.image}
/>
</CardMedia>
</Card>
</Grid>
</Grid>
);
};
export default advertisingBanner;
|
const cotizador = new API('9d874bd608813461025de8caa2e89aae1a9630b7d016a9a8f3a9341292d12e97');
const ui = new Interfaz();
const formulario = document.getElementById('formulario');
formulario.addEventListener('submit', (e)=>{
e.preventDefault();
const campoDivisa = document.querySelector('#moneda');
const divisa = campoDivisa.options[campoDivisa.selectedIndex].value;
const campoCripto = document.querySelector('#criptomoneda');
const criptomoneda = campoCripto.options[campoCripto.selectedIndex].value;
if(divisa === "" || criptomoneda === ""){
ui.mostrarMensaje("AMBOS CAMPOS SON OBLIGATRIO", 'alert bg-danger text-center');
}else{
cotizador.obtenerValores(divisa,criptomoneda)
.then(data =>{
ui.imprimirResultadoCotizacion(data.resultado.RAW, divisa, criptomoneda);
});
}
})
|
var express = require('express');
var router = express.Router();
const fs = require('fs');
const path = require('path');
/* GET */
let start_time;
let stop_time;
let radio_op;
router.get('/', function(req, res, next) {
// ここで行えるのは変数を渡すだけ。値を書き換えたりはしない。
res.render('index', { title: 'Express',
start_time: start_time,
stop_time: stop_time,
radio_op: radio_op });
});
/* POST */
router.post('/start', (req, res, next) => {
// ここで行っているのはあくまでもローカル変数にセットしているだけ
stop_time = "";
start_time = Date.now();
radio_op = req.body.options;
res.redirect('/');
});
router.post('/stop', (req, res, next) => {
stop_time = Date.now();
radio_op = req.body.options;
res.redirect('/');
});
router.post('/save', (req, res, next) => {
//基本的にname属性しかとれない?
radio_op = req.body.options;//co(valueが返る)
let obj = {
radio_op: req.body.options,
start_time: req.body.txt_start,
stop_time: req.body.txt_stop,
}
const tmpname = 'result.json';
const newpath = path.join(__dirname, tmpname);
fs.writeFile(newpath, JSON.stringify(obj, undefined, 2), 'utf8', (err) => {
if(err){
return console.log(err);
}
});
//console.log(JSON.stringify(obj, undefined, 2));
res.redirect('/')
});
router.post('/reset', (req, res, next) => {
start_time = "";
stop_time = "";
res.redirect('/')
});
module.exports = router;
|
const express = require('express');
const app = express();
require('dotenv').config();
const mongoose = require('mongoose');
const cors = require('cors');
const PORT = process.env.PORT || 5000;
const authRouter = require('./routes/auth');
const postRouter = require('./routes/post');
const connectDB = async ()=>{
try{
await mongoose.connect(`mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@mern-debut-app.cy8gj.mongodb.net/MERN-Debut-App?retryWrites=true&w=majority`,{
useCreateIndex : true,
useNewUrlParser : true,
useFindAndModify: false,
useUnifiedTopology: true,
})
console.log("Connected!");
}
catch(error)
{
console.log("Connect failed!");
console.log(error);
process.exit(1);
}
}
connectDB();
app.use(cors());
app.use(express.json());
app.get('/',(req,res)=>{
res.send("Hello world");
})
app.use('/api/auth',authRouter);
app.use('/api/posts',postRouter);
app.listen(PORT,()=>console.log("Hello from port 5000"));
|
// Key
// ---------------------------------
$(document).ready(function () {
init();
});
// Global functions ---------------------------------
$.fn.isInViewport = function (offtop) {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + ($(window).height() / offtop);
return elementBottom > viewportTop && elementTop < viewportBottom;
};
function init() {
console.log("asdmfkl");
$('#theme-styles-inline-css').remove();
// Scroll ------------
$('a[href^="#"]').click(function (event) {
event.preventDefault()
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
var target = $(this.hash);
if (this.hash == '#first_section') {
var $next = $(this).closest('.section').next('div');
$($next).attr('id', 'first_section');
$('html,body').animate({
scrollTop: $next.offset().top
}, 300);
}
if (target.length) {
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
$('html,body').animate({
scrollTop: target.offset().top
}, 300);
return false;
}
}
});
// Get url parameter ------------
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
if (
getUrlParameter('careers_submited') ||
getUrlParameter('subscribed') ||
getUrlParameter('footer_subscribe') ||
getUrlParameter('contact')
) {
if ($('#message').length > 0) {
$('html,body').animate({
scrollTop: $('#message').offset().top
}, 300);
}
}
// Chosen ------------
if ( $('.page-oracle-school-bundle-ty').length == 0 ) {
$("select").chosen({
disable_search_threshold: 10
});
}
// ACF ------------
$("input[type=hidden]").trigger('change');
$.each($('.acf-field-image'), function (index, acf_field_image) {
var acf_field_image = $(acf_field_image);
var label1 = acf_field_image.find('.acf-label label');
var input = acf_field_image.find('.acf-image-uploader > input');
label1.clone().prependTo(acf_field_image.find('.acf-image-uploader'));
var label2 = acf_field_image.find('.acf-image-uploader > label');
label2.addClass('file-upload');
label2.wrapInner('<span class="text"></span>');
label2.append('<span class="btn">Choose File</span>');
input.prependTo(label2);
var text = label2.find('.text').text();
input = label2.find('> input');
$(acf_field_image.find('.acf-basic-uploader input')).on('change', function (e) {
var fileName = '';
if ($(this).files && $(this).files.length > 1) {
fileName = ($(this).getAttribute('data-multiple-caption') || '').replace('{count}', $(this).files.length);
} else if (e.target.value) {
fileName = e.target.value.split('\\').pop();
}
console.log(fileName);
(fileName) ? $(this).closest('.acf-field-image').find('.file-upload .text').html(fileName): $(this).closest('.acf-field-image').find('.file-upload .text').html(text);
})
});
$.each($('.acf-field-file'), function (index, acf_field_file) {
var acf_field_file = $(acf_field_file);
var label1 = acf_field_file.find('.acf-label label');
var input = acf_field_file.find('.acf-file-uploader > input');
label1.clone().prependTo(acf_field_file.find('.acf-file-uploader'));
var label2 = acf_field_file.find('.acf-file-uploader > label');
label2.addClass('file-upload');
label2.wrapInner('<span class="text"></span>');
label2.append('<span class="btn">Choose File</span>');
input.prependTo(label2);
var text = label2.find('.text').text();
input = label2.find('> input');
$(acf_field_file.find('.acf-basic-uploader input')).on('change', function (e) {
var fileName = '';
if ($(this).files && $(this).files.length > 1) {
fileName = ($(this).getAttribute('data-multiple-caption') || '').replace('{count}', $(this).files.length);
} else if (e.target.value) {
fileName = e.target.value.split('\\').pop();
}
console.log(fileName);
(fileName) ? $(this).closest('.acf-field-file').find('.file-upload .text').html(fileName): $(this).closest('.acf-field-file').find('.file-upload .text').html(text);
})
});
// hero-slide ------------
$('.testimonials .testimonials-wpr').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
arrows: false,
dots: true,
responsive: [{
breakpoint: 1024,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
$('.slider-wpr .arrow').on('click', function () {
var circles_wpr = $(this).closest('.principles').find('.oval-wpr #circles');
var titles = $(this).closest('.principles').find('.oval-wpr .title');
if ($(this).hasClass('back')) {
$(this).closest('.slider-wpr').find('.principle-text-slider').slick('slickPrev');
$.each(titles, function (index, title) {
var classes = $(title).attr("class");
var new_pos = parseInt(classes.substring(10, 11)) + 1;
if (new_pos == 7) {
new_pos = 1;
}
$(title).attr('class', 'title pos-' + new_pos);
});
var classes = circles_wpr.attr("class");
var new_pos = parseInt(classes.substring(4, 5)) + 1;
if (new_pos == 7) {
new_pos = 1;
}
circles_wpr.attr('class', 'pos-' + new_pos);
} else {
$(this).closest('.slider-wpr').find('.principle-text-slider').slick('slickNext');
$.each(titles, function (index, title) {
var classes = $(title).attr("class");
var new_pos = parseInt(classes.substring(10, 11)) - 1;
if (new_pos == 0) {
new_pos = 6;
}
$(title).attr('class', 'title pos-' + new_pos);
});
var classes = circles_wpr.attr("class");
var new_pos = parseInt(classes.substring(4, 5)) - 1;
if (new_pos == 0) {
new_pos = 6;
}
circles_wpr.attr('class', 'pos-' + new_pos);
}
});
$('.oval-wpr .title').on('click', function () {
var target = $(this).data("target");
var classes = $(this).attr("class");
var current_pos = parseInt(classes.substring(10, 11));
var diff = current_pos - 1;
if (current_pos == 5 || current_pos == 6) {
if (current_pos == 6) {
$('.slider-wpr .arrow.back').trigger('click');
} else {
$('.slider-wpr .arrow.back').trigger('click');
setTimeout(function () {
$('.slider-wpr .arrow.back').trigger('click');
}, 525);
}
} else {
for (var i = 0; i < diff; i++) {
setTimeout(function () {
$('.slider-wpr .arrow.next').trigger('click');
}, (525 * i));
}
}
});
// Animation in ------------
var animation_in = (function () {
animation();
$(window).on('resize scroll', animation);
function animation() {
if ($('.animation-in, .animation-reveal, .animation-reveal-2').length > 0) {
$('.animation-in, .animation-reveal, .animation-reveal-2').each(function () {
var a_trigger = ($(this).data("animation")) ? $(this).data("animation") : 1.1;
($(this).isInViewport(1.1)) ? $(this).addClass('animation-active'): null;
});
}
}
})();
// Core Components - start here
// --------------------------------------------
// Mobile-nav
$('.mobile-nav-wrapper').click(function () {
$(this).toggleClass('active');
$('.menu-main-menu-container').toggleClass('active');
});
// Nav ------------
var nav = (function () {
// var
var mouse_is_inside = false;
// cash
var $header = $('header');
var $nav = $('nav');
var $close = $header.find('.toggle-nav');
var $header_search = $('.header-search-form');
// setup
// events
$close.on('click', toggleDropdown);
$header.find('.right li.search').on('click', function () {
$header_search.addClass('active');
});
$header_search.find('.close').on('click', function () {
$header_search.removeClass('active');
});
$('header nav, header .toggle-nav').hover(function () {
mouse_is_inside = true;
}, function () {
mouse_is_inside = false;
});
$("body").mouseup(function () {
if (!mouse_is_inside && $nav.hasClass('active')) {
toggleDropdown();
}
});
$nav.find('.search form > div > span').on('click', function () {
$nav.find('.search form > div .submit').trigger('click');
});
// function
function toggleDropdown(e) {
if ($nav.hasClass('active')) {
$nav.removeClass('active');
$close.removeClass('active');
$('body').css('height', "");
$('body').css('overflow', "");
} else {
$nav.addClass('active');
$close.addClass('active');
$('body').css('height', '100%');
$('body').css('overflow', 'hidden');
}
}
})();
// breadcrumbs ------------
var breadcrumbs = (function () {
var wpr = $('.breadcrumbs');
if (wpr.length > 0) {
for (var i = 0; i < wpr.find('span').length; i++) {
wpr.html(function () {
return $(this).html().replace("»", "/");
})
}
}
})();
// tiles_image_text ------------
var tiles_image_and_text = (function () {
var wpr = $('.tiles_image_and_text');
if (wpr.length > 0) {
var is_mobile = false;
fixed_image();
$(window).scroll(function () {
fixed_image();
});
function fixed_image() {
is_mobile = wpr.find('.image').css('position') == 'static';
if (is_mobile) {
wpr.find('.image').removeClass('fixed').removeClass('fixed_bottom');
} else {
var scrollTop = $(window).scrollTop();
var scrollBottom = $(window).scrollTop() + $(window).outerHeight();
var rows = wpr.find('.row');
$.each(rows, function (key, value) {
var value_top = $(value).offset().top;
var value_bottom = value_top + $(value).outerHeight();
var value_image = $(value).find('.image');
if (scrollTop <= value_top) {
value_image.removeClass('fixed');
value_image.removeClass('fixed_bottom');
} else if (scrollTop > value_top && scrollBottom <= value_bottom) {
value_image.addClass('fixed');
value_image.removeClass('fixed_bottom');
} else {
value_image.removeClass('fixed');
value_image.addClass('fixed_bottom');
}
});
}
}
}
})();
// FAQ ------------
var faq = (function () {
var wpr = $('.FAQ, .frequently_asked_questions');
if (wpr.length > 0) {
wpr.find('.question-title').on('click', function (e) {
var question = $(e.target).closest('.question');
question.find('.answer').slideToggle();
question.find('.plus-minus-toggle').toggleClass('collapsed');
});
}
})();
// video_thumbnail ------------
var video_thumbnail = (function () {
var wpr = $('.video_thumbnail');
if (wpr.length > 0) {
wpr.find('.play-btn').on('click', function (e) {
$(e.target).closest('.video_thumbnail').find('.video').addClass('active');
});
}
})();
// model ------------
var model = (function () {
var modelLink = $('.model-click');
var model = $('.modal-wpr');
var close = model.find('.close');
var mouse_is_inside = false;
var popups = $('.modal-wpr.popup');
$.each(popups, function (key, value) {
var target = $(value);
if ( target.hasClass('page-exit') ) {
$(document).mouseleave(function () {
if ( ! getCookie('popup_123') ) {
target.addClass('active');
target.addClass('done');
setCookie('popup_123',1,0.1);
}
});
} else if ( target.hasClass('timer') ) {
if ( ! getCookie('popup_123') ) {
var time = target.data("time");
setTimeout(function () {
target.addClass('active');
setCookie('popup_123',1,0.1);
}, time);
}
}
});
$('.model-wpr .model').hover(function () {
mouse_is_inside = true;
}, function () {
mouse_is_inside = false;
});
modelLink.on('click', function () {
var target = $(this).data('target');
$(target).toggleClass('active');
if ($(target).hasClass('video-model')) {
var iframe = $(target).find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.play();
}
});
close.on('click', function () {
console.log('close');
model.removeClass('active');
if (model.hasClass('video-model')) {
var iframe = $(this).closest('.modal-wpr').find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.pause();
}
});
model.mouseup(function () {
if (!mouse_is_inside && model.hasClass('active')) {
model.removeClass('active');
if (model.hasClass('video-model')) {
var iframe = $(this).closest('.modal-wpr').find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.pause();
}
}
});
function setCookie(name,value,hours) {
var expires = "";
if (hours) {
var date = new Date();
date.setTime(date.getTime() + (hours*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
})();
var blog_side_bar = (function () {
scroll();
$(window).on('scroll', scroll);
function scroll() {
var wpr = $('.tve-leads-shortcode');
if (wpr.length > 0) {
if (wpr.find('.add-image').length == 0) {
wpr.find('.thrv_heading').after('<img class="add-image" src="/wp-content/themes/jupiter/images/ebook_mockup_02.png">');
}
}
}
})()
var page_7Energieschallenge = (function () {
var video_thumbnail = $('.top_section .video');
if (video_thumbnail.length > 0) {
var videoplayer = video_thumbnail.find('.video-player');
video_thumbnail.find('.play-btn').on('click', function (e) {
videoplayer.addClass('active');
var iframe = videoplayer.find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.play();
});
videoplayer.find('.close').on('click', function (e) {
videoplayer.removeClass('active');
var iframe = videoplayer.find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.pause();
});
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
var top = video_thumbnail.offset().top;
var bottom = top + video_thumbnail.outerHeight();
if (scrollTop < bottom) {
videoplayer.removeClass('fixed');
} else {
videoplayer.addClass('fixed');
}
});
}
})();
var page_Vision_board_challenge = (function () {
var video_thumbnail = $('.hero_section .video');
if (video_thumbnail.length > 0) {
var videoplayer = video_thumbnail.find('.video-player');
video_thumbnail.find('.play-btn').on('click', function (e) {
videoplayer.addClass('active');
var iframe = videoplayer.find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.play();
});
videoplayer.find('.close').on('click', function (e) {
videoplayer.removeClass('active');
var iframe = videoplayer.find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.pause();
});
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
var top = video_thumbnail.offset().top;
var bottom = top + video_thumbnail.outerHeight();
if (scrollTop < bottom) {
videoplayer.removeClass('fixed');
} else {
videoplayer.addClass('fixed');
}
});
}
})();
var page_oracle_circle_membership = (function () {
var video_thumbnail = $('.video');
if (video_thumbnail.length > 0) {
var videoplayer = video_thumbnail.find('.video-player');
video_thumbnail.find('.play-btn').on('click', function (e) {
var videoplayer = $(this).closest('.video').find('.video-player');
videoplayer.addClass('active');
var iframe = videoplayer.find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.play();
});
// videoplayer.find('.close').on('click', function (e) {
// videoplayer.removeClass('active');
//
// var iframe = videoplayer.find('iframe')[0];
// var player = new Vimeo.Player(iframe);
// player.pause();
// });
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
var top = video_thumbnail.offset().top;
var bottom = top + video_thumbnail.outerHeight();
if (scrollTop < bottom) {
videoplayer.removeClass('fixed');
} else {
videoplayer.addClass('fixed');
}
});
}
})();
// Timer ----------
var timer_section = (function () {
var wpr = $('.timer_section');
if (wpr.length > 0) {
var time = wpr.find('.timer').data("time");
console.log(time);
var newYork = moment(time).tz('America/New_York');
initializeClock(newYork.format());
}
function getTimeRemaining(endtime) {
var currentTime = moment().tz("America/New_York").format('YYYY-MM-DD HH:mm:ss');
var bits = currentTime.split(/\D/);
var currentTime = new Date(bits[0], --bits[1], bits[2], bits[3], bits[4], bits[5]);
var t = Date.parse(endtime) - Date.parse(currentTime);
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
function initializeClock(endtime) {
var clock = wpr.find('.timer');
var daysSpan = clock.find('.days');
var hoursSpan = clock.find('.hours');
var minutesSpan = clock.find('.minutes');
var secondsSpan = clock.find('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
if (t.days >= 1000) {
console.log('not time');
clearInterval(timeinterval);
wpr.css('opacity', 0);
} else if (t.total <= 0) {
clearInterval(timeinterval);
console.log('time done');
wpr.html('CLOSING NOW');
} else {
if (t.days >= 0) {
daysSpan.html(t.days);
}
if (t.hours >= 0) {
hoursSpan.html(t.hours);
}
if (t.minutes >= 0) {
minutesSpan.html(t.minutes);
}
// if ( t.seconds >= 0 ) {
// secondsSpan.html( t.seconds );
// }
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
})();
var solstice_sales = (function () {
var wpr = $('.video_text');
console.log("solstice_sales");
if (wpr.length > 0) {
console.log("1");
wpr.find('.play-btn').on('click', function (e) {
console.log('2');
wpr.find('.video_background').addClass('hide');
wpr.find('.play-btn').addClass('hide');
var iframe = wpr.find('iframe')[0];
var player = new Vimeo.Player(iframe);
player.play();
});
}
})();
}
|
/*
|--------------------------------------------------------------------------
| DR Global Object
|--------------------------------------------------------------------------
|
| Use for states and settings.
*/
(function(win) {
win.define("DR", function() {
var DR = win.DR || {};
var defaults = {
version: "6.0",
autoload: {
lazyLoader: true,
cookiePolicy: true,
topNavigation: true,
footer: true,
drwebstat: true
},
clientInfo: {},
basePath: "",
proxyUrl: null,
addClientInfo: function(name, bool) {
if ((name != null) && (Object.prototype.toString.call(bool) === "[object Boolean]")) {
DR.clientInfo[name] = bool;
}
}
}
// Inherit defaults
for (var key in defaults) {
if (DR[key] == null) {
DR[key] = defaults[key];
} else if (Object.prototype.toString.call(DR[key]) === "[object Object]") {
for (var subkey in defaults[key]) {
if (DR[key][subkey] == null) {
DR[key][subkey] = defaults[key][subkey];
}
}
}
}
win.DR = DR;
return DR;
});
}(window));
|
export function isFunction (obj) {
return typeof obj === 'function';
}
export function preventDefault (event) {
if(event && event.preventDefault){
event.preventDefault();
}
}
export function forEachProperty(obj, func) {
for (let i in obj) {
if(obj.hasOwnProperty(i)){
func(obj[i], i);
}
}
}
export function any(obj, predicate) {
forEachProperty(obj, prop => {if(predicate(prop)){return true;}});
return false;
}
export function isObject (obj) {
return obj !== null && typeof obj === 'object';
}
export function isString (obj) {
return typeof obj === 'string' || Object.prototype.toString.call(obj) === '[object String]';
}
export function getEventValue(event, fieldType){
return isCheckable(fieldType) ? event.target.checked : event.target.value;
}
export function isCheckable(obj){
return obj === 'radio' || obj === 'checkbox'
}
|
/// <reference path="Servicios.js"/>
/// <reference path="jquery-1.10.2-vsdoc.js"/>
/// <reference path="InterfazGrafica.js"/>
|
//with this script you convert all passed courses from student JSON:s to database data
var sqlite3 = require('sqlite3').verbose()
var db = new sqlite3.Database('.././models/database.db')
var moment = require('moment');
var all = require('.././data/all.json');
var mass = require('.././data/massData.json');
var combinedList = {};
combinedList.students = all.students.concat(mass.students);//here we concatenate the lists together
let dates = ['2014-02-11', '2017-02-11', '2016-02-11', '2016-12-21', '2016-06-14', '2015-08-16', '2017-05-1'];
let randomIndex = null;
let randomDate = null;
//format table
db.serialize(function() {
db.run('DROP TABLE IF EXISTS passedCourses');
//db.run('CREATE TABLE if not exists passedCourses (courseId varchar(20) PRIMARY KEY NOT NULL, FOREIGN KEY(studentId) REFERENCES students(studentId))');
db.run('CREATE TABLE if not exists passedCourses (courseId varchar(20), date TEXT, studentId integer, name TEXT);');
});
//insert list data into passedCourses table
for (let student of combinedList.students) {
for (let course of student.passedCourses) {
var id = student.id;
randomIndex = Math.floor((Math.random() * 7) + 0);
var superDate = dates[randomIndex];
console.log('course code: ' + course.courseId);
console.log('course date: ' + superDate);
console.log('course student id: ' + student.id);
db.run('INSERT INTO passedCourses VALUES("'+course.courseId+'","'+superDate+'",'+student.id+', "'+course.name+'");');
//db.run('INSERT OR REPLACE INTO passedCourses VALUES ('+course.code+');');
}
};
|
var nodemailer = require('nodemailer');
const hbs = require("nodemailer-express-handlebars");
let sendMailForJobVerification = (recipitant, categoryName) => {
var transporter = nodemailer.createTransport({
pool: true,
service: 'gmail',
// host: "smtp.example.com",
// port: 465,
// secure: true, // use TLS
// auth: {
// userSelection: process.env.TEAM_EMAIL,
// pass: process.env.TEAM_PASSWORD
// }
auth: {
user: "bilalqmr41@gmail.com",
pass: "BILAL12345"
}
});
var options = {
viewEngine: {
extname: '.handlebars',
layoutsDir: 'views/',
defaultLayout: 'postJob',
},
viewPath: 'views/'
}
transporter.use('compile', hbs(options));
console.log(__dirname)
var mailOptions = {
from: 'bilalqmr41@gmail.com',
to: recipitant,
subject: 'Your ' + categoryName + ' expert is a few clicks away...',
template: 'postJob',
context: {
categoryName
}
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
};
let sendMailForEmailVerification = (recipitant, userName, verificationLink) => {
var transporter = nodemailer.createTransport({
pool: true,
service: 'gmail',
// host: "smtp.example.com",
// port: 465,
// secure: true, // use TLS
auth: {
user: "bilalqmr41@gmail.com",
pass: "BILAL12345"
}
});
var options = {
viewEngine: {
extname: '.handlebars',
layoutsDir: 'views/',
defaultLayout: 'userVerification',
},
viewPath: 'views/'
}
transporter.use('compile', hbs(options));
var mailOptions = {
from: 'bilalqmr41@gmail.com',
to: recipitant,
subject: 'Welcome to TradingSeek...',
template: 'userVerification',
context: {
userName,
verificationLink
}
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
};
let sendMailForPasswordChange = (recipitant, userEmail, updatePasswordLink) => {
var transporter = nodemailer.createTransport({
pool: true,
service: 'gmail',
type: "SMTP",
host: "smtp.gmail.com",
// host: "smtp.example.com",
// port: 465,
// secure: true, // use TLS
auth: {
user: "bilalqmr41@gmail.com",
pass: "BILAL12345"
}
});
var options = {
viewEngine: {
extname: '.handlebars',
layoutsDir: 'views/',
defaultLayout: 'updatePassword',
},
viewPath: 'views/'
}
transporter.use('compile', hbs(options));
var mailOptions = {
from: 'bilalqmr41@gmail.com',
to: recipitant,
subject: 'Reset password instructions...',
template: 'updatePassword',
context: {
userEmail,
updatePasswordLink
}
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
};
let sendMailForNewUserPasswordChange = (recipitant, userEmail, userName, updatePasswordLink) => {
var transporter = nodemailer.createTransport({
pool: true,
service: 'gmail',
type: "SMTP",
host: "smtp.gmail.com",
// host: "smtp.example.com",
// port: 465,
// secure: true, // use TLS
auth: {
user: "bilalqmr41@gmail.com",
pass: "BILAL12345"
}
});
var options = {
viewEngine: {
extname: '.handlebars',
layoutsDir: 'views/',
defaultLayout: 'updateNewUserPassword',
},
viewPath: 'views/'
}
transporter.use('compile', hbs(options));
var mailOptions = {
from: 'bilalqmr41@gmail.com',
to: recipitant,
subject: 'You are now a part of tradingseek, a welcome call is on its way!...',
template: 'updateNewUserPassword',
context: {
userEmail,
userName,
updatePasswordLink
}
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
};
let sendMailForLogin = (recipitant, userEmail, loginLink) => {
var transporter = nodemailer.createTransport({
pool: true,
service: 'gmail',
type: "SMTP",
host: "smtp.gmail.com",
// host: "smtp.example.com",
// port: 465,
// secure: true, // use TLS
auth: {
user: "bilalqmr41@gmail.com",
pass: "BILAL12345"
}
});
var options = {
viewEngine: {
extname: '.handlebars',
layoutsDir: 'views/',
defaultLayout: 'loginUser',
},
viewPath: 'views/'
}
transporter.use('compile', hbs(options));
var mailOptions = {
from: 'bilalqmr41@gmail.com',
to: recipitant,
subject: 'You are now a part of tradingseek, a welcome call is on its way!...',
template: 'loginUser',
context: {
userEmail,
loginLink
}
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
};
module.exports = {
sendMailForJobVerification,
sendMailForEmailVerification,
sendMailForPasswordChange,
sendMailForNewUserPasswordChange,
sendMailForLogin
};
|
import React,{useState} from "react";
import shortid from "shortid";
import './App.css';
import {TodoInputForm} from "./todolist/ToDoInputForm";
import {ToDoList} from "./todolist/ToDoList";
const App = () => {
const [toDoList,setTodoList] = useState([]);
const handleToggle = (id) =>{
setTodoList(toDoList.map(toDo =>{
return toDo.id === Number(id) ?
{...toDo, complete: !toDo.isComplete} :
{...toDo}
}));
}
const addTask = (input) =>{
setTodoList([...toDoList,{
id:shortid.generate(),
todo:input,
isComplete: false
}])
}
return (
<div>
<h1>To Do List</h1>
<TodoInputForm addTodo={addTask}/>
<ToDoList
toDoList={toDoList}
handleToggle={handleToggle}
/>
</div>
);
}
export default App;
|
define([], function () {
'use strict';
return function(){
return {
navigateRepresentation: function(){
var base = '';
if (this._parent && !this.constructor.navigateRoot) {
base = this._parent.navigateRepresentation()+'/'+this._path||'';
}
if (this.collection) {
base = this.collection.navigateRepresentation();
}
if (!base) {
base = this.constructor.getCollectionName();
}
return base +'/'+(this.isNew() ? 'new' : this.id);
}
};
};
});
|
import { mount } from 'enzyme';
import ErrorDialog, { $imports } from '../ErrorDialog';
import mockImportedComponents from '../../../test-util/mock-imported-components';
describe('ErrorDialog', () => {
beforeEach(() => {
$imports.$mock(mockImportedComponents());
});
afterEach(() => {
$imports.$restore();
});
it('displays details of the error', () => {
const err = new Error('Something went wrong');
const wrapper = mount(<ErrorDialog description="Oh no!" error={err} />);
assert.include(wrapper.find('ErrorDisplay').props(), {
description: 'Oh no!',
error: err,
});
});
});
|
(function ($,X) {
X.prototype.controls.widget("Upload",function (controlType) {
var BaseControl = X.prototype.controls.getControlClazz("BaseControl");
//上传图片
function Upload(elem, options){
BaseControl.call(this,elem,options);
this.singleSize = this.options.singleSize;
this.Size = this.options.size;
this.type = this.options.type;
this.maxNum = this.options.maxNum;
this.downloadType = this.options.downloadType;
this.count = 0;
this.upload();
};
X.prototype.controls.extend(Upload,"BaseControl");
Upload.prototype.constructor = Upload;
/**
@method init webuploader初始化设置
*/
Upload.prototype.upload = function () {
var that = this;
var wrapUpload = that.elem.find(".js-wrapUploadData"),
error = that.elem.find('.js-error');
/* if(X.prototype.isFunction(this.options["click"])){
img.on("click",function(event){
this.options["click"](img.attr("src"));
});
}*/
// WebUploader实例
var id = this.options["filePicker"];
var label = this.options["filePickerLabel"] || "选择图片";
var pick;
if(id && label){
pick = {id:id,label:label}
}
// 实例化
this.uploader = WebUploader.create({
pick:pick,
formData: {
fileType: that.type
},
auto:true,
swf: 'js/lib/webuploader/Uploader.swf',
sendAsBinary:true, //指明使用二进制的方式上传文件
duplicate:that.options.duplicate || true,
chunked: true,
thumb: that.options.thumb || false,//上传图片设置缩略图
server: X.prototype.config.PATH_FILE.path.rootImg,
fileNumLimit: 300,
fileSizeLimit: that.Size * 1024 * 1024,
fileSingleSizeLimit:that.singleSize * 1024 * 1024,//验证单个文件大小是否超出限制
accept:that.options.accept || {
/*title: 'Images',*/
extensions: 'jpg,jpeg,png',
mimeTypes: 'image/png,image/jpg,image/jpeg'
}
});
that.duplicate();
this.uploader.on( 'beforeFileQueued', function( file) {
var guid = file._hash;
if(wrapUpload.find(".wrapUpload").length){
that.count = wrapUpload.find(".wrapUpload").length;
}
if(that.options.maxNum){
if (that.count >= that.options.maxNum) {
return false;
}else{
that.count++;
}
}
});
// 文件上传成功
this.uploader.on( 'uploadSuccess', function( file,response) {
if(response.data){
error.html('');
var uploadSuccessInfo;
if(response.data.url){
var imgHost = X.prototype.config.PATH_FILE.path.imageStoreUrl,
imageUrl = response.data.url.indexOf(imgHost) > -1? response.data.url: (imgHost + response.data.url)
uploadSuccessInfo = '<div class="wrapUpload disib"><img src="'+ imageUrl +'"/><span class="cancel">X</span><p class="mt10 tac contract-word-cut">'+response.data.fileName+'</p></div>';
}else{
var uploadUrl = X.prototype.config.PATH_FILE.path.rootUploadUrl;
uploadSuccessInfo = '<div class="wrapUpload">' +
'<a href="'+uploadUrl+'?fileType='+ that.downloadType+'&filePath='+response.data.path+'&fileName='+response.data.fileName+'" class="accessory orange-font">'+response.data.fileName+'</a>' +
'<span class="cancel">X</span></div>';
}
$(wrapUpload).append(uploadSuccessInfo);
if(that.options["cancel"]){
that.cancel();
}
if(that.maxNum){
that.maxNumber();
var wrap = that.elem.find(".wrapUpload");
var input = that.elem.find("input[type=file]");
if (wrap.length >= that.maxNum) {
input.attr("disabled",true);
} else {
input.attr("disabled",false);
}
}
if(X.prototype.isFunction(that.options["uploadSuccess"])){
that.options["uploadSuccess"](response,wrapUpload.find(".wrapUpload").last());
}
that.trigger("uploadSuccess",response);
}
});
this.uploader.on( 'error', function( type ) {
var text;
switch( type ) {
case 'Q_EXCEED_SIZE_LIMIT':
text = '文件大小超出';
break;
case 'Q_EXCEED_NUM_LIMIT':
text = '文件数量超出最大值';
break;
case 'Q_TYPE_DENIED':
text = '文件类型错误';
break;//F_EXCEED_SIZE
case 'F_DUPLICATE':
text = '文件不能重复上传';
break;
case 'F_EXCEED_SIZE':
text = '文件大小超出';
break;
}
that.count--;
error.text(text);
});
};
Upload.prototype.addButton = function (buttons) {
if(!X.prototype.isArray(buttons)){
buttons = [buttons];
}
for(var i = 0; i < buttons.length; i++){
this.uploader.addButton(buttons[i]);
}
};
/**
@method init 重复上传文件
*/
Upload.prototype.duplicate = function(){
var that = this,
_this = that.uploader,
mapping = {};
function hashString( str ) {
var hash = 0,
i = 0,
len = str.length,
_char;
for ( ; i < len; i++ ) {
_char = str.charCodeAt( i );
hash = _char + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
_this.on( 'beforeFileQueued', function( file ) {
var hash = file.__hash || (file.__hash = hashString( file.name +
file.size + file.lastModifiedDate ));
// 已经重复了
if ( mapping[ hash ] ) {
var nameArr = [];
var namewrapArr = that.elem.find(".js-wrapUploadData").find("img").length ? that.elem.find(".js-wrapUploadData").find("img") : that.elem.find(".js-wrapUploadData").find("a");
$.each(namewrapArr,function(i,item){
if(namewrapArr[i].nodeName == "IMG"){
nameArr.push($(namewrapArr[i]).next().next().html());
}else{
nameArr.push($(namewrapArr[i]).html());
}
});
var has = function (){
var hasName;
$.each(nameArr,function(i,item){
if(nameArr[i] == file.name){
hasName = true;
}
});
return hasName;
};
if(has()){
_this.trigger( 'error', 'F_DUPLICATE', file );
return false;
}
}
});
_this.on( 'fileQueued', function( file ) {
var hash = file.__hash;
hash && (mapping[ hash ] = true);
});
_this.on( 'fileDequeued', function( file ) {
var hash = file.__hash;
hash && (delete mapping[ hash ]);
});
_this.on( 'reset', function() {
mapping = {};
});
};
/**
@method init 删除上传文件
*/
Upload.prototype.cancel = function(){
var that = this;
var cancel = that.elem.find(".cancel");
cancel.on('click',function(event){
var fatherDiv = $(event.target).parent();
fatherDiv.remove();
that.count--;
if(that.maxNum){
that.maxNumber();
var wrap = that.elem.find(".wrapUpload");
var input = that.elem.find("input[type=file]");
if (wrap.length >= that.maxNum) {
input.attr("disabled",true);
} else {
input.attr("disabled",false);
}
}
if(X.prototype.isFunction(that.options["cancel"])){
that.options["cancel"]();
}
});
};
/**
@method init 设置上传文件数量
@param value {string} 设置上传文件最大数量
*/
Upload.prototype.maxNumber = function(){
var that = this;
var wrap = that.elem.find(".wrapUpload");
var input = that.elem.find("input[type=file]");
var error = that.elem.find('.js-error');
if (wrap.length > that.maxNum) {
error.text("上传附件不能超过" + that.maxNum + "张");
input.attr("disabled",true);
} else {
input.attr("disabled",false);
error.text("");
}
};
/**
@method init 获取上传图片
@param value {string} 获取上传图片值
*/
Upload.prototype.getValue = function(type){
var that = this;
var arr = [];
if(X.prototype.isFunction(that.options["getValue"])){
arr = that.options["getValue"]();
}else{
var value = that.elem.find(".js-wrapUploadData").find(".wrapUpload");
var arr = [];
if(value.html()){
function getArgStr(value){
var argStr='';
if(value){
argStr = value.split('&')[1].split('=')[1];
}
return argStr;
}
$.each(value,function(i,item){
if($(this).find("a").length){
arr.push({attachmentType:type || that.options.attachmentType,filePath:getArgStr($(this).find("a").attr("href")),filename :$(this).find("a").text()});
}else{
arr.push({attachmentType:type || that.options.attachmentType,url:$(this).find("img").attr("src") || "",filename :$(this).find("p").text()});
}
});
}
}
return arr;
};
/**
@method init 设置上传图片
@param value {string} 设置上传图片值
*/
Upload.prototype.setValue = function(arr){
var that = this;
var wrap = that.elem.find(".js-wrapUploadData");
if(arr){
var uploadUrl = X.prototype.config.PATH_FILE.path.rootUploadUrl;
$.each(arr,function(i,item){
var uploadSuccessInfo;
if(arr[i].url){
var imgHost = X.prototype.config.PATH_FILE.path.imageStoreUrl,
imageUrl = arr[i].url.indexOf(imgHost) > -1? arr[i].url: (imgHost + arr[i].url)
uploadSuccessInfo = '<div class="wrapUpload disib"><img src="'+imageUrl+'"/><span class="cancel">X</span><p class="mt5 contract-word-cut">'+arr[i].filename+'</p></div>';
}else{
uploadSuccessInfo = '<div class="wrapUpload">' +
'<a href="'+uploadUrl+'?fileType='+ that.downloadType+'&filePath='+arr[i].filePath+'&fileName='+arr[i].filename+'" class="accessory orange-font">'+arr[i].filename+'</a>' +
'<span class="cancel">X</span></div>';
}
$(wrap).append(uploadSuccessInfo);
if(arr[i].url){
if(X.prototype.isFunction(that.options["setValue"])){
that.options["setValue"](arr[i],wrap.find(".wrapUpload").last());
}
}
});
that.cancel();
}else{
wrap.html("");
}
};
/**
@method init 重置上传附件展示
*/
Upload.prototype.reset = function () {
this.setValue("");
};
return Upload;
});
})(jQuery,this.Xbn);
|
function Gigasecond(date) {
this.birthday = date;
}
Gigasecond.prototype.date = function () {
var birthSeconds = this.birthday.getTime();
var seconds = birthSeconds + 1000000000000;
var result = new Date(seconds);
result.setHours(0);
result.setMinutes(0);
result.setSeconds(0);
result.setMilliseconds(0);
return result;
}
module.exports = Gigasecond
|
import React from "react";
import { useAuth0 } from "../react-auth0-spa";
import styled from "@emotion/styled";
import tacNyan from "../assets/tacnayn.gif";
import flames from "../assets/fire.gif";
import {
Container,
ResultContainer,
ResultItem,
ImageUsername,
ImageWrapper,
ResultImage,
IsVoiderIcon,
} from "../components/Common";
const KEEPEROFTHEVOID = styled.img`
display:block;
margin: 50px auto;
`;
const Flames = styled.img`
position: absolute;
bottom: 0;
min-width: 225px;
height: 155px;
`;
function VoidCore(props) {
const { user } = useAuth0();
function renderVoiderz() {
if (user) {
if (props.voiderz.length > 0) {
const userVoiderz = props.voiderz.filter(
(voider) => voider.username === user.name
);
if (userVoiderz.length > 0) {
return (
<ResultContainer>
{userVoiderz.map((result) => {
return (
<ResultItem key={result.id}>
{/* the items in the favorites page will always be favorited */}
<IsVoiderIcon
className="fas fa-fire-alt"
onClick={() => props.toggleVoider(result)}
/>
<ImageUsername>{result.user}</ImageUsername>
<ImageWrapper>
<ResultImage
src={result.previewURL}
alt={`${result.username} image`}
/>
<Flames src={flames} />
</ImageWrapper>
</ResultItem>
);
})}
</ResultContainer>
);
} else {
return (
<div>
<p>You not sent anything to the V̵̡̧̡̢̧̧̨̛̛̲͕̳͓̘͍͍̥̙̺͉͕̗̹̣̲̱̘̝̭̙̠͔̖̝͓̱̱̻̖͎̗̖̹̩͔͉͖̗͉̅̓̒̓̈́̅̕͜͝͝Ơ̷̢̢̱̹̱͈̙̹̠͓̈́̇̿̂̔̇̇̉̈́͛̄̀̈̋̄̋͗̑̒͠͝Į̴̨̧̢͚̞̪͓̩̝̬͙͙̰͇̙̰͖̩̲̗̣̰͍̭̬͉̮͕̪͕͍̲̰̜̤͍̠͔̱̲̩̳̘͈̥̼̉̿̿̾͆͐͒̊̅͐͊̈͐̈́̈́̓̏̂̉̎̏̃͒̋̽̓͊̏̇͋́̊͊͊̉͘͘̕̕͜͝͝͝͠͝͝ͅͅD̵̨̢̡̰̮͙̠̯̲̪̖̲̩̮̭̜̫̼͙̦̘̺̤̜̫͉̳̊́̓̌̔̈́̽̀͌́͑̿̄̔͆̀͌̒͑̔̈̃̊͛͌̔̽̿́̉͛̐̉͗̿͗̑̍̌̂͛͗̕͝ͅ {user.nickname} :(</p>
</div>
);
}
} else {
return (
<div>
<p>You not sent anything to the V̵̡̧̡̢̧̧̨̛̛̲͕̳͓̘͍͍̥̙̺͉͕̗̹̣̲̱̘̝̭̙̠͔̖̝͓̱̱̻̖͎̗̖̹̩͔͉͖̗͉̅̓̒̓̈́̅̕͜͝͝Ơ̷̢̢̱̹̱͈̙̹̠͓̈́̇̿̂̔̇̇̉̈́͛̄̀̈̋̄̋͗̑̒͠͝Į̴̨̧̢͚̞̪͓̩̝̬͙͙̰͇̙̰͖̩̲̗̣̰͍̭̬͉̮͕̪͕͍̲̰̜̤͍̠͔̱̲̩̳̘͈̥̼̉̿̿̾͆͐͒̊̅͐͊̈͐̈́̈́̓̏̂̉̎̏̃͒̋̽̓͊̏̇͋́̊͊͊̉͘͘̕̕͜͝͝͝͠͝͝ͅͅD̵̨̢̡̰̮͙̠̯̲̪̖̲̩̮̭̜̫̼͙̦̘̺̤̜̫͉̳̊́̓̌̔̈́̽̀͌́͑̿̄̔͆̀͌̒͑̔̈̃̊͛͌̔̽̿́̉͛̐̉͗̿͗̑̍̌̂͛͗̕͝ͅ {user.nickname} :(</p>
</div>
);
}
} else {
return (
<div>
<p>Log in to save your voiderz!</p>
</div>
);
}
}
return (
<Container>
<KEEPEROFTHEVOID src={tacNyan} />
{renderVoiderz()}
</Container>
);
}
export default VoidCore;
|
var dir_4006cdcac7c2d4e11a50296707493d61 =
[
[ "C1ConnectorRegisterDeviceOptions.h", "_c1_connector_register_device_options_8h_source.html", null ]
];
|
require('../services/rest');
var alertify = require('alertifyjs')
angular.module(MODULE_NAME)
.controller('sqlCtrl', ['$scope', 'restService', '$timeout', function($scope, restService, $timeout) {
var ctrl = this;
$scope.init = init;
$scope.modal = modal;
function init() {
console.log('Archivo build.js iniciado correctamente');
}
function modal(i) {
if (i === 1) {
$('#m1').modal('show');
}else if (i === 2) {
$('#m2').modal('show');
}else if (i === 3) {
$('#m3').modal('show');
}else if (i === 4) {
$('#m4').modal('show');
}else if (i === 5) {
$('#m5').modal('show');
}else if (i === 6) {
$('#m6').modal('show');
}
console.log(i);
}
}]);
angular.module(MODULE_NAME)
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
|
import React, { Component } from 'react';
import { Link } from "react-router-dom";
class App extends Component {
render() {
return (
<div>
<h4>App</h4>
<hr />
<Link to='/'>Home</Link> | <Link to='/product'>Products</Link> | <Link to='/about'>About</Link> | <Link to='/login'>Login</Link>
<div style={{
padding: '5px',
margin: '10px 0',
minHeight: '300px',
border: '1px solid #666'
}}
>
{ this.props.children }
</div>
<footer>footer</footer>
</div>
)
}
}
export default App;
|
/**
* GUESSING GAME:
*
* Created By:Adam Zaimes
* Date:9/17/2013
*
* GUESSING GAME
*/
(function (){
var dom = {
input:document.querySelector("#input"),
output:document.querySelector("#output"),
button:document.querySelector("button")
};
var buttonClicks = 0;
var magicNum = Math.floor(Math.random() * 10 + 1);
console.log(magicNum);
dom.button.onclick = function(e){
//if else statements to determine if the user guesses correctly
if (buttonClicks < 3){
if (dom.input.value < 1 || dom.input.value >10){
document.getElementById("output").innerHTML = ("Your guess needs to be between 1 and 10. Try again.");//validate input number
}
else if (dom.input.value < magicNum){
document.getElementById("output").innerHTML = ("Your guess is too low, please try again");
} else if (dom.input.value > magicNum){
document.getElementById("output").innerHTML = ("Your guess is too high, please try again!");
}else if (dom.input.value == magicNum){
document.getElementById("output").innerHTML = ("You Win!");
outOfGuesses(); // call game over function
} // If statement for clicks
buttonClicks++; // adding to click count
}else{ //else to end display and disable button
outOfGuesses();
}
e.preventDefault(); // prevent to stop function
return false;
};
function outOfGuesses(){ //game over function
//var buttonSelec = document.querySelector("button"); // assigns button
dom.button.addEventListener("click", function(){dom.button.innerHTML = "Please refresh the page to try again."}, false); //stops button from functioning after max tries reached
}
})();
|
import { canvasAddEvents } from './util/canvas.js'
import { motifs } from './util/motif.js'
/**
* canvas part
*/
let canvas = document.getElementById("signature");
let clearSignCanvas = document.getElementById("clear-signature");
clearSignCanvas.addEventListener("click", (e) => {
canvas.getContext("2d").clearRect(0, 0, canvas.clientWidth, canvas.clientHeight)
});
canvasAddEvents(canvas);
let data = {
name: undefined,
residing: undefined,
reason: undefined,
'born-where': undefined,
'born-when': undefined,
'created-where': undefined,
'created-when-date': undefined,
'created-when-time': undefined,
signature: undefined,
};
/**
*
* @param {HTMLElement} element
*/
function toggleDisplayGenerator(element) {
return (display) => {
element.style.display = display ? "" : "none";
}
}
/**
*
* @param {Function} callback
*/
function onChangeTogglerGenerator(callback) {
return (e) => {
callback(e.target.checked);
}
}
/**
*
* @param {Object} data
* @param {Function} format
*/
function onChangeGenerator(data, format = undefined) {
if (format) {
return (e) => {
const { name, value } = e.target;
data[name] = format(value);
console.log(data);
}
}
else {
return (e) => {
const { name, value } = e.target;
data[name] = value;
console.log(data);
}
}
}
/**
*
* @param {*} date an object that can be used by Date
*/
function dateToTimestamp(date) {
const [year, month, day] = date.split('-');
date = new Date(0);
date.setFullYear(parseInt(year), parseInt(month) - 1, parseInt(day));
return date.getTime();
}
/**
*
* @param {String} time
*/
function timeToTimestamp(time) {
const [hours, minutes] = time.split(':');
time = new Date(0)
time.setHours(parseInt(hours));
time.setMinutes(parseInt(minutes));
return time.getTime();
}
let reasonSelector = document.getElementById('reason');
let includeDateToggler = document.getElementById('include-date');
let includeTimeToggler = document.getElementById('include-time');
let includeSignToggler = document.getElementById('include-signature');
let toggleCreationDate = toggleDisplayGenerator(document.getElementById('created-date-box'));
let toggleCreationTime = toggleDisplayGenerator(document.getElementById('created-time-box'));
let toggleSignature = toggleDisplayGenerator(document.getElementById('sign-box'));
let reasonText = document.getElementById('motif-detail');
const createdDateSelector = document.getElementById('created-when-date');
const createdTimeSelector = document.getElementById('created-when-time');
toggleCreationDate(includeDateToggler.checked);
toggleCreationTime(includeTimeToggler.checked);
toggleSignature(includeSignToggler.checked);
document.getElementById('name').addEventListener('change', onChangeGenerator(data));
document.getElementById('born-when').addEventListener('change', onChangeGenerator(data, dateToTimestamp));
document.getElementById('born-where').addEventListener('change', onChangeGenerator(data));
document.getElementById('residing').addEventListener('change', onChangeGenerator(data));
reasonSelector.addEventListener('change', onChangeGenerator(data, (reason) => {
reasonText.textContent = motifs[reason].long;
return reason;
}));
document.getElementById('created-where').addEventListener('change', onChangeGenerator(data));
createdDateSelector.addEventListener('change', onChangeGenerator(data, dateToTimestamp));
createdTimeSelector.addEventListener('change', onChangeGenerator(data, timeToTimestamp));
includeDateToggler.addEventListener('change', onChangeTogglerGenerator(toggleCreationDate));
includeTimeToggler.addEventListener('change', onChangeTogglerGenerator(toggleCreationTime));
includeSignToggler.addEventListener('change', onChangeTogglerGenerator(toggleSignature));
canvas.addEventListener('change', (e) => {
data.signature = canvas.toDataURL();
console.log(canvas.toDataURL());
})
for (let motif in motifs) {
const short = motifs[motif].short;
let opt = document.createElement('option')
opt.value = motif;
opt.textContent = short;
reasonSelector.appendChild(opt);
}
document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault();
data["created-when-time"] = includeTimeToggler.checked && data["created-when-time"];
data["created-when-date"] = includeDateToggler.checked && data["created-when-date"];
data.signature = includeSignToggler.checked && data.signature;
localStorage.data = JSON.stringify(data);
window.location.assign('print.html');
})
const date = new Date();
createdDateSelector.value = date.toISOString('fr-FR').slice(0, 10);
createdTimeSelector.value = date.toTimeString().slice(0, 5);
data["created-when-date"] = dateToTimestamp(createdDateSelector.value);
data["created-when-time"] = timeToTimestamp(createdTimeSelector.value);
|
class Man {
constructor(bl, my, img, x = 0, y = 0) {
this.x = x
this.y = y
this.bl = bl
this.my = my
this.img = img
}
}
class Game {
constructor(type) {
this.type = type
this.canvas = document.getElementById('canvas')
this.ctx = this.canvas.getContext('2d')
this.canvas.width = window.innerWidth - 48
this.canvas.height = this.canvas.width
this.space = this.canvas.width / 8
this.start = this.space / 20
this.onPlay = true
this.count = 0
this.initMap = [
['C0', 'M0', 'T0', 'Q0', 'K0', 'T1', 'M1', 'C1'],
['Z0', 'Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6', 'Z7'],
[, , , , , , , ],
[, , , , , , , ],
[, , , , , , , ],
[, , , , , , , ],
['z0', 'z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7'],
['c0', 'm0', 't0', 'q0', 'k0', 't1', 'm1', 'c1']
]
this.playMap = this.arrClone(this.initMap)
this.mans = new Map()
this.args = new Map()
}
init() {
this.initMans()
this.initEvent()
}
initEvent() {
this.canvas.addEventListener('click',(e) => {
this.getClickPoint(e)
},false)
}
arrClone(arr) {
const newArr = []
for (let item of arr) {
newArr.push(item)
}
return newArr
}
isInArray(arr,point) {
for(let item of arr) {
if(item[0] === point[0] && item[1] === point[1]) {
return true
}
return false
}
}
initMans() {
this.args.set('c', {
img: 'terge',
my: 1,
bl: 'c'
})
.set('m', {
img: 'mori',
my: 1,
bl: 'm'
})
.set('t', {
img: 'temee',
my: 1,
bl: 't'
})
.set('q', {
img: 'bars',
my: 1,
bl: 'q'
})
.set('k', {
img: 'han',
my: 1,
bl: 'k'
})
.set('z', {
img: 'hcni',
my: 1,
bl: 'z'
})
.set('C', {
img: 'terge2',
my: -1,
bl: 'c'
})
.set('M', {
img: 'mori2',
my: -1,
bl: 'm'
})
.set('T', {
img: 'temee2',
my: -1,
bl: 't'
})
.set('Q', {
img: 'bars2',
my: -1,
bl: 'q'
})
.set('K', {
img: 'han2',
my: -1,
bl: 'k'
})
.set('Z', {
img: 'yima2',
my: -1,
bl: 'z'
})
const map = this.playMap
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[i].length; j++) {
const key = map[i][j]
const width = this.space - this.start * 2
if (key) {
const k = key.slice(0, 1)
const bl = k.toLowerCase()
const my = this.args.get(k).my
const img = new Image()
img.onload = () => {
this.ctx.save()
this.ctx.drawImage(img, this.space * j + this.start, this.space * i + this.start, width, width)
}
img.src = `img/${this.args.get(k).img}.png`
this.mans.set(key, new Man(bl, my, img, j, i))
}
}
}
}
getDomXY(dom) {
let left = dom.offsetLeft
let top = dom.offsetTop
let current = dom.offsetParent
while (current != null) {
left += current.offsetLeft
top += current.offsetTop
current = current.offsetParent
}
return {
x: left,
y: top
}
}
getClickPoint(e) {
const domXY = this.getDomXY(this.canvas)
const x = Math.floor((e.pageX - domXY.x) / this.space)
const y = Math.floor((e.pageY - domXY.y) / this.space)
console.log(x,y);
}
}
|
import React from 'react';
import { connect } from 'react-redux';
import PollList from '../components/pollList';
class LatestPolls extends React.Component {
componentDidMount() {
fetch("/api/userPolls",
{
credentials: 'include'
})
.then((res) => res.json())
.then((res) => {
if (res.error) {
return;
}
this.props.setUserPolls(res);
});
}
render() {
return (
this.props.userPolls.length > 0 ?
<PollList polls={this.props.userPolls}
handleClick={this.props.switchToPoll}
/>
:
null
);
}
}
const mapStateToProps = (state) => {
return {
userPolls: state.userPolls
};
};
const mapDispatchToProps = (dispatch) => {
return {
setUserPolls: (polls) => dispatch({type: 'SET_USER_POLLS', polls}),
switchToPoll: (poll) => {
dispatch({type: 'SET_POLL', poll});
dispatch({type: 'CHANGE_VIEW', view: "viewPoll"});
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(LatestPolls);
|
import React, { useState } from "react";
import "./Schedules.css";
import CreateTask2 from "./CreateTask2";
import { Link } from "react-router-dom";
import { withRouter } from "react-router-dom";
import { useMutation, useQuery } from "@apollo/client";
import gql from "graphql-tag";
const INSERT_SCHEDULE = gql`
mutation(
$startHr: Int
$startMin: Int
$startAM: String
$endHr: Int
$endMin: Int
$endAM: String
$title: String!
$day: Int
$month: String
$year: Int
$participants:Int
) {
insert_Schedules_one(
object: {
day: $day
endAM: $endAM
endHr: $endHr
endMin: $endMin
month: $month
startAM: $startAM
startHr: $startHr
startMin: $startMin
title: $title
year: $year
participants:$participants
}
on_conflict: {
constraint: Schedules_pkey
update_columns: participants
where: { title: { _eq: $title } }
}
) {
participants
}
}
`;
const CreateSchedule2 = (props) => {
const [startHr, setStartHr] = useState();
const [startMin, setStartMin] = useState();
const [startAM, setStartAM] = useState();
const [endHr, setEndHr] = useState();
const [endMin, setEndMin] = useState();
const [endAM, setEndAM] = useState();
const [insertSchedule] = useMutation(INSERT_SCHEDULE);
function addTime(input) {
if (input.type === "startHr") setStartHr(input.data);
else if (input.type === "startMin") setStartMin(input.data);
else if (input.type === "startAM") setStartAM(input.data);
else if (input.type === "endHr") setEndHr(input.data);
else if (input.type === "endMin") setEndMin(input.data);
else if (input.type === "endAM") setEndAM(input.data);
}
const submit=()=> {
insertSchedule({
variables: {
title: props.location.state.title,
day: props.location.state.day,
month: props.location.state.month,
year: props.location.state.year,
startHr: startHr,
startMin: startMin,
startAM: startAM,
endHr: endHr,
endMin: endMin,
endAM: endAM,
participants:1
},
});
}
return (
<div className="schedules">
<div className="header">
<h2>New Schedule - Step 2</h2>
</div>
<div className="schedule-container">
<div
onClick={() => {
submit();
}}
style={{
width: "25%",
marginLeft: "50%",
marginTop: "1%",
textAlign: "center",
backgroundColor: "#183e7d",
borderRadius: "5px",
}}
>
<Link
style={{
color: "orange",
textDecoration: "none",
fontWeight: "bolder",
fontSize: "20px",
}}
to="/"
>
Create
</Link>
</div>
<CreateTask2 addData={addTime}></CreateTask2>
</div>
</div>
);
};
export default withRouter(CreateSchedule2);
|
if (document.getElementById('add-post') || document.getElementById('edit-profile')) {
var ImageView = require('imageview');
var iv = new ImageView();
iv.preview();
}
|
//app/models/bear.js
// we'll just create a model and provide our bears
// with a name field
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name:String
});
module.exports = mongoose.model('Bear',BearSchema);
|
var el = document.querySelector(".swiper-wrapper");
var ticking = false;
var timer;
var evt;
var mc = new Hammer.Manager(el);
mc.add(new Hammer.Swipe());
mc.get('swipe').set({ direction: Hammer.DIRECTION_VERTICAL });
mc.on("swipe", onSwipe);
function updateElementTransform() {
var direction = evt.direction;
var distance = evt.distance;
if (viewVideo.total <= 1) {
return
}
if (direction == 8 && distance > 177){
if (viewVideo.showNumber >= viewVideo.total -1) {
return
}
viewVideo.showNumber -= -1;
viewVideo.mousewheel();
} else if (direction == 16 && distance > 177) {
if (viewVideo.showNumber <= 0) {
return
}
viewVideo.showNumber -= 1;
viewVideo.mousewheel();
}
$(".play").hide();
$(".play").addClass("hidden");
$(".video")[0].autoplay = "autoplay";
}
function requestElementUpdate() {
if(!ticking) {
ticking = true;
setTimeout(function () {
updateElementTransform();
}, 111);
setTimeout(function () {
ticking = false;
}, 111);
}
}
function onSwipe(ev) {
// console.log(ev.direction, ev.distance);
evt = ev;
clearTimeout(timer);
timer = setTimeout(function () {
requestElementUpdate();
}, 444);
}
|
const Team = require("../models/Team");
const User = require("../models/User");
const ServerError = require("../Class/ServerError");
const unknownErrorCode = "UNKNOWN_ERROR";
const unknownErrorMessage = "Unknown Error has occurred";
const fetchTeam = async (req, res) => {
try {
if (!req.query.teamId)
throw new ServerError("Missing parameter teamId", 422, "INVALID_ENTRY");
var team = await Team.findById(req.query.teamId);
if (!team)
throw new ServerError("Could not find team", 404, "NO_ENTRY_IN_DB");
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ message: err.message, code: err.code });
} else {
res
.status(404)
.send({ message: "Could not find team", code: "NO_ENTRY_IN_DB" });
}
return;
}
try {
let response;
if (
team.memberIds.includes(req.user._id) ||
team.leadIds.includes(req.user._id)
) {
response = await constructDetailTeamResponse(team, true);
} else {
response = await constructDetailTeamResponse(team, false);
}
res.send(response);
} catch (err) {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
};
const searchTeams = async (req, res) => {
const { teamName, email } = req.query;
if (teamName) var teamSearchable = teamName.toLowerCase().split(" ").join("");
try {
let response;
if (teamName && !email) {
const teams = await Team.find({
searchableName: { $regex: teamSearchable, $options: "i" }
});
response = await constructTeamsResponse(teams);
}
if (!teamName && email) {
const user = await User.findOne({ email });
const teams = await Team.find({ _id: { $in: user.teamIds } });
response = await constructTeamsResponse(teams);
}
if (teamName && email) {
const user = await User.findOne({ email });
const teams = await Team.find({ _id: { $in: user.teamIds } });
const matchingTeams = teams.filter(
(team) => team.searchableName.indexOf(teamSearchable) !== -1
);
response = await constructTeamsResponse(matchingTeams);
}
if (!teamName && !email) {
throw new ServerError("Need valid entry to search.", 422, "INVALID_REQUEST");
}
res.send(response);
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ code: err.code, message: err.message });
} else {
res.status(400).send({ code: unknownErrorCode, message: unknownErrorMessage });
}
}
};
const createTeam = async (req, res) => {
try {
if (!req.body.name)
throw new ServerError(
"Missing required parameter: name",
422,
"INVALID_REQUEST"
);
const existingTeam = await Team.findOne({ name: req.body.name });
if (existingTeam) {
throw new ServerError(
"The same team name already exists",
409,
"ENTRY_CONFLICT"
);
}
let team = new Team({
name: req.body.name,
searchableName: req.body.name.toLowerCase().split(" ").join(""),
});
team.leadIds.push(req.user._id);
team.founderId = req.user._id;
team = await team.save();
const user = await User.findById(req.user._id);
user.teamIds.push(team._id);
const newUser = await user.save();
res.send({ team, user: newUser });
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ code: err.code, message: err.message });
} else {
res.status(400).send({
code: unknownErrorCode,
message: unknownErrorMessage,
});
}
}
};
const deleteTeam = async (req, res) => {
const team = req.team;
try {
var members = [...team.leadIds, ...team.memberIds];
await Team.deleteOne({ _id: team._id });
} catch (e) {
res.status(404).send("Team could not be found.");
}
try {
const users = await User.find().where("_id").all(members);
for (let i = 0; i < users.length; i++) {
const user = users[i];
user.teamIds.pull(team._id);
await user.save();
}
res.status(200).send({});
} catch (err) {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
};
// available to team leads
const editTeam = async (req, res) => {
const { teamId } = req.body;
try {
const team = await Team.findById(teamId);
const existingTeam = await Team.find({ name: req.body.name });
if (existingTeam.length > 0) {
throw new ServerError("Existing team name.", 409, "ENTRY_CONFLICT");
}
if (req.body.name) {
team.name = req.body.name;
team.searchableName = req.body.name.split(" ").join("").toLowerCase();
}
const newTeam = await team.save();
res.send(newTeam);
} catch (e) {
if (e.code) {
res.status(e.statusCode).send({ message: e.message, code: e.code });
} else {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
}
};
// available to team leads
const addTeamMembers = async (req, res) => {
const team = req.team;
const { members } = req.body;
try {
if (!members)
throw new ServerError(
"Missing members parameter",
422,
"INVALID_PARAMETER"
);
const emails = members.map((member) => member.email);
const users = await User.find({ email: { $in: emails } });
if (users.length === 0) {
throw new ServerError(
"Please enter correct email address(es)",
422,
"INVALID_PARAMETER"
);
}
for (let i = 0; i < members.length; i++) {
const member = members[i];
const user = users.filter((user) => user.email === member.email)[0];
if (user._id == req.user._id)
throw new ServerError(
"You cannot invite yourself",
422,
"INVALID_REQUEST"
);
if (member.isLead && team.leadIds.indexOf(user._id) === -1) {
team.leadIds.push(user._id);
}
if (!member.isLead && team.memberIds.indexOf(user._id) === -1) {
team.memberIds.push(user._id);
}
if (user.teamIds.indexOf(team._id) === -1) {
user.teamIds.push(team._id);
}
await user.save();
}
await team.save();
res.send(team);
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ message: err.message, code: err.code });
} else {
res.status(400).send({
message: unknownErrorMessage,
code: unknownErrorCode,
});
}
}
};
const fetchTeamMembers = async (req, res) => {
try {
const response = {};
const founderInfo = await getUsersInfo([req.team.founderId]);
response.founder = founderInfo[0];
response.leads = await getUsersInfo(req.team.leadIds);
response.members = await getUsersInfo(req.team.memberIds);
res.send(response);
} catch (err) {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
};
const fetchTeamProjects = async (req, res) => {};
// available to team leads
const removeTeamMember = async (req, res) => {
const { userId } = req.body;
const { team, user } = req;
try {
if (userId == team.founderId) {
throw new ServerError(
"A founder cannot be removed from team",
422,
"INVALID_REQUEST"
);
}
if (
team.leadIds.includes(userId) &&
team.founderId != userId &&
userId != user._id &&
user._id != team.founderId
) {
throw new ServerError(
"A team lead cannot remove another lead",
422,
"UNAUTHORIZED_REQUEST"
);
}
if (
team.memberIds.includes(userId) &&
userId != user._id &&
team.memberIds.includes(user._id)
) {
throw new ServerError(
"A member cannot remove another member from the team",
422,
"UNAUTHORIZED_REQUEST"
);
}
if (team.memberIds.includes(user) && team.leadIds.includes(userId)) {
throw new ServerError(
"A team member cannot remove a lead",
422,
"UNAUTHORIZED_REQUEST"
);
}
if (!team.leadIds.includes(userId) && !team.memberIds.includes(userId)) {
throw new ServerError("User is not in team", 404, "NO_MATCHING_ENTITY");
}
if (team.leadIds.includes(userId)) {
team.leadIds.pull(userId);
} else {
team.memberIds.pull(userId);
}
const removedUser = await User.findById(userId);
removedUser.teamIds.pull(team._id);
removedUser.save();
const newTeam = await team.save();
res.send(newTeam);
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ message: err.message, code: err.code });
} else {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
return;
}
try {
const user = await User.findById(userId);
user.teamIds.pull(team._id);
await user.save();
} catch (err) {
throw "There was an error updating the user";
}
};
// available to team leads
const promoteMemberToLead = async (req, res) => {
const { userId } = req.body;
const { team } = req;
try {
if (team.leadIds.includes(userId)) {
throw new ServerError("Cannot promote lead", 422, "INVALID_OPERATION");
}
if (!team.memberIds.includes(userId)) {
throw new ServerError("User is not a member", 422, "INVALID_ENTITY");
}
team.memberIds.pull(userId);
team.leadIds.push(userId);
const newTeam = await team.save();
res.send(newTeam);
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ message: err.message, code: err.code });
} else {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
}
};
const demoteLeadToMember = async (req, res) => {
const { team } = req;
const { userId } = req.body;
try {
if (team.leadIds.length === 1 && team.leadIds[0] == req.user._id) {
throw new ServerError(
"You cannot demote yourself to team member when you are the only team lead.",
422,
"INVALID_REQUEST"
);
}
if (userId == team.founderId)
throw new ServerError(
"Founder cannot be demoted",
403,
"INVALID_OPERATION"
);
if (!team.leadIds.includes(userId)) {
throw new ServerError("User is not a lead", 422, "INVALID_ENTITY");
}
team.leadIds.pull(userId);
team.memberIds.push(userId);
const newTeam = await team.save();
res.send(newTeam);
} catch (err) {
if (err.code) {
res.status(err.statusCode).send({ message: err.message, code: err.code });
} else {
res
.status(400)
.send({ message: unknownErrorMessage, code: unknownErrorCode });
}
}
};
//helpers
const getUsersInfo = async (ids) => {
const users = await User.find({ _id: { $in: ids } });
return users.map((user) => {
const { _id, email, name } = user;
return { _id, email, name };
});
};
const constructDetailTeamResponse = async (team, isTeamMember) => {
const {
_id,
name,
founderId,
leadIds,
memberIds,
projectIds,
requests,
} = team;
const founderInfo = await getUsersInfo([founderId]);
const response = {
_id,
name,
founder: founderInfo[0],
projects: [],
requests: [],
};
if (isTeamMember) {
const leads = await getUsersInfo(leadIds);
response.leads = leads;
const members = await getUsersInfo(memberIds);
response.members = members;
}
return response;
};
const constructTeamsResponse = async (teams) => {
const newTeams = [];
for (let i = 0; i < teams.length; i++) {
const team = teams[i];
const { name, founderId, _id } = team;
const founderInfo = await getUsersInfo([founderId]);
newTeams.push({ _id, name, founder: founderInfo[0] });
}
return newTeams;
};
module.exports = {
fetchTeam,
searchTeams,
createTeam,
deleteTeam,
editTeam,
addTeamMembers,
fetchTeamMembers,
promoteMemberToLead,
demoteLeadToMember,
removeTeamMember,
};
|
class Droplet{
constructor(){
this.x = random(-width/2, width*1.5);
this.y = -20;
this.z = random();
let a = PI/2 + random(0, .1) + .1;
this.dx = cos(a)*(this.z*5 + 1);
this.dy = sin(a)*(this.z*5 + 1);
this.splash = false;
this.dead = false;
this.amt = 0;
}
update(){
if (!this.splash){
this.prevX = this.x;
this.prevY = this.y;
this.x += this.dx;
this.y += this.dy;
}
else {
this.amt += .01;
if (this.amt > 1) this.dead = true;
}
if (this.y > height*(1 - (1-this.z)/4)) this.splash = true;
}
render(){
if (this.splash){
buffer.stroke(1, (1-this.amt)/3);
buffer.noFill();
let w = this.amt*(this.z + .05)*100;
buffer.ellipse(this.x, this.y, w, w/3);
} else {
buffer.stroke(1);
buffer.line(this.prevX, this.prevY, this.x, this.y);
}
}
}
class Lightning{
constructor(){
this.x = random(width);
this.y = 0;
this.amt = 1;
this.hue = random(.5, .8);
this.seed = frameCount;
let sound = random(thunder);
sound.setVolume(.5);
sound.play();
let points = [createVector(this.x, height*.7)];
let n = random(30, 50);
let w = random(200, 300);
for (let i = 0; i < n; i++){
let amt = random();
let y = amt*height*.7;
let x = this.x + random(-w, w)*(1 - abs(amt*2 - 1));
points.push(createVector(x, y));
}
let fill = [createVector(this.x, this.y)];
this.lines = [];
while(points.length > 0){
let d = 1e6;
let fIdx = 0;
let pIdx = 0;
fill.forEach((p1, i) => {
points.forEach((p2, j) => {
let d2 = p1.dist(p2);
let a = p1.angleBetween(p2);
if (d2 < d && a > 0){
d = d2;
fIdx = i;
pIdx = j;
}
});
});
let p1 = fill[fIdx];
let p2 = points[pIdx];
this.lines.push({p1, p2})
fill.push(points[pIdx]);
points.splice(pIdx, 1);
};
this.points = fill;
}
update(){
this.amt -= .01;
this.light = noise(this.seed + pow(this.amt, .1)*100)*this.amt*3;
}
render(buffer){
buffer.stroke(this.hue, .3, this.light);
buffer.strokeWeight(2);
this.lines.forEach(l => {
let {p1, p2} = l;
buffer.line(p1.x, p1.y, p2.x, p2.y);
});
}
}
let soundsLoaded = false;
let thunder = [{play:() => {}, setVolume:() => {}}];
function loadSounds(){
soundsLoaded = true;
thunder = [];
let path = "https://www.cs.unm.edu/~bmatthews1/hosted/sounds/sounds/";
soundFormats('wav');
let rain = loadSound(path + "rain", () => {
rain.setVolume(3);
rain.play();
});
for (let i = 1; i < 9; i++) thunder.push(loadSound(path + "thunder" + i, ));
}
function setup (){
pixelDensity(1);
createCanvas();
colorMode(HSB, 1, 1, 1);
windowResized();
}
let drops, buffer, lightning;
let init = () => {
drops = [];
lightning = [];
buffer = createGraphics(width, height);
buffer.colorMode(HSB, 1, 1, 1);
}
function draw(){
background(0);
if (!soundsLoaded && frameCount > 150){
loadSounds();
}
for (let y = floor(height*.7); y < height; y++){
let amt = (y-height*.7)/(height*.3);
stroke(.6, 1, amt);
line(0, y, width, y);
}
buffer.blendMode(BLEND);
buffer.background(0, .2);
buffer.blendMode(ADD);
for (let i = 0; i < 2*width/1000; i++) drops.push(new Droplet());
drops.forEach(d => {
d.update();
d.render();
})
drops = drops.filter(d => !d.dead);
if (random() < .005 && lightning.length < 3) lightning.push(new Lightning());
lightning.forEach(l => {
l.render(this);
l.update();
});
lightning = lightning.filter(l => l.amt > 0);
blendMode(ADD);
image(buffer, 0, 0);
lightning.forEach(l => {
background(l.hue, .3, l.light, .2);
});
blendMode(BLEND);
}
function windowResized(){
resizeCanvas(windowWidth, windowHeight);
init();
}
|
import React, { Component } from 'react';
import Monitor from "./Monitor"
class Platforms extends Component {
render() {
let platforms;
if (this.props.platforms) {
platforms = this.props.platforms.map(platform => {
return ( <Monitor key={platform.name} platform={platform} />) ;
});
}
return (
<div className="Platforms" >
<ul>
{platforms}
</ul>
</div>
);
}
}
export default Platforms;
|
"use strict";
dinnerApp.controller('RestaurantCtrl',
[
'$scope',
'SharedService',
'LoadingService',
'$compile',
function($scope,
$sharedService,
$loadingService,
$compile
) {
var reservation = $sharedService.get().reservations.selected;
$scope.restaurant = reservation.restaurant;
var location = reservation.restaurant.address || "Madrid, Spain";
function initializeWithAddress(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
initialize(results[0].geometry.location);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize(location) {
var myLatlng = location || new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>" + reservation.restaurant.name + "</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
initializeWithAddress(location);
}]);
|
import React from 'react';
import '../ui-toolkit/css/nm-cx/main.css';
import { OldSchoolMenuLink } from './activeLinks';
export const NavigationBar = (props) => {
return (
<ul className="heading-nav padding-bottom-medium">
<OldSchoolMenuLink activeOnlyWhenExact={true} to="/" label="Home"/>
<OldSchoolMenuLink activeOnlyWhenExact={true} to="/products" label="Product List"/>
<OldSchoolMenuLink to="/products/new" label="Product Creation"/>
</ul>
);
}
|
import axios from "axios";
import {
GET_NOW_PLAYING_MOVIES,
GET_POPULAR_MOVIES,
GET_TOP_RATED_MOVIES,
GET_UPCOMING_MOVIES,
GET_MOVIE_DETAIL,
GET_MOVIE_VIDEO,
ADD_FAVORITE_MOVIE,
DELETE_FAVORITE_MOVIE,
} from "./types";
let APIKey = "2c2295ea8b7a115e319ed2ddd08aa9a3";
let config = { Authorization: "2c2295ea8b7a115e319ed2ddd08aa9a3" };
export const getNowPlayingMovies = () => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/now_playing?api_key=${APIKey}&language=es-ES&page=1`,
{ headers: config }
)
.then((res) => {
dispatch({
type: GET_NOW_PLAYING_MOVIES,
payload: res.data.results,
});
})
.catch((err) => console.log(err));
};
export const getPopularMovies = () => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/popular?api_key=${APIKey}&language=es-ES&page=1`,
{ headers: config }
)
.then((res) => {
dispatch({
type: GET_POPULAR_MOVIES,
payload: res.data.results,
});
})
.catch((err) => console.log(err));
};
export const getTopRatedMovies = () => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/top_rated?api_key=${APIKey}&language=es-ES&page=1`,
{ headers: config }
)
.then((res) => {
dispatch({
type: GET_TOP_RATED_MOVIES,
payload: res.data.results,
});
})
.catch((err) => console.log(err));
};
export const getUpcomingMovies = () => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/upcoming?api_key=${APIKey}&language=es-ES&page=1`,
{ headers: config }
)
.then((res) => {
dispatch({
type: GET_UPCOMING_MOVIES,
payload: res.data.results,
});
})
.catch((err) => console.log(err));
};
export const getMovieDetail = (id) => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/${id}?api_key=${APIKey}&language=es-ES&page=1`,
{ headers: config }
)
.then((res) => {
dispatch({
type: GET_MOVIE_DETAIL,
payload: res.data,
});
})
.catch((err) => console.log(err));
};
export const getMovieVideos = (id) => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/${id}/videos?api_key=${APIKey}&language=es-ES&page=1`,
{ headers: config }
)
.then((res) => {
dispatch({
type: GET_MOVIE_VIDEO,
payload: res.data.results,
});
})
.catch((err) => console.log(err));
};
export const addFavoriteMovie = movie => (dispatch, getState) => {
const favorite_movies = getState().movies.favorite_movies;
const newFavorites = [...favorite_movies, movie];
dispatch({
type: ADD_FAVORITE_MOVIE,
favorite_movies: newFavorites
})
};
export const deleteFavoriteMovie = (id) => (dispatch, getState) => {
const favorite_movies = getState().movies.favorite_movies;
const newFavorites = favorite_movies.filter(item => item.id !== id)
dispatch({
type: DELETE_FAVORITE_MOVIE,
favorite_movies: newFavorites
});
};
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import {require, define} from 'requirejs';
import packageJson from '../../package.json';
window.require = require;
window.requirejs = require;
window.define = define;
/* jshint camelcase: false */
const moduleName = packageJson.com_infiniteautomation.moduleName;
const modulePath = `/modules/${moduleName}/web`;
const configuration = {
moduleVersions: {},
defaultVersion: packageJson.version
};
const exposedVendorModules = {
'angular': () => import(/* webpackMode: "eager" */ 'angular'),
'angular-ui-router': () => import(/* webpackMode: "eager" */ 'angular-ui-router'),
'angular-loading-bar': () => import(/* webpackMode: "eager" */ 'angular-loading-bar'),
'angular-ui-ace': () => import(/* webpackMode: "lazy", webpackChunkName: "ace" */ 'angular-ui-ace'),
'angular-material': () => import(/* webpackMode: "eager" */ 'angular-material'),
'angular-animate': () => import(/* webpackMode: "eager" */ 'angular-animate'),
'angular-messages': () => import(/* webpackMode: "eager" */ 'angular-messages'),
'angular-aria': () => import(/* webpackMode: "eager" */ 'angular-aria'),
'angular-resource': () => import(/* webpackMode: "eager" */ 'angular-resource'),
'angular-sanitize': () => import(/* webpackMode: "eager" */ 'angular-sanitize'),
'angular-cookies': () => import(/* webpackMode: "eager" */ 'angular-cookies'),
'moment': () => import(/* webpackMode: "eager" */ 'moment'),
'moment-timezone': () => import(/* webpackMode: "eager" */ 'moment-timezone'),
'mdPickers': () => import(/* webpackMode: "eager" */ 'md-pickers'),
'angular-material-data-table': () => import(/* webpackMode: "eager" */ 'angular-material-data-table'),
'amcharts/amcharts': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/amcharts'),
'amcharts/funnel': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/funnel'),
'amcharts/gantt': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/gantt'),
'amcharts/gauge': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/gauge'),
'amcharts/pie': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/pie'),
'amcharts/radar': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/radar'),
'amcharts/serial': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/serial'),
'amcharts/xy': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/xy'),
'amcharts/plugins/export/export': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/plugins/export/export'),
'amcharts/plugins/responsive/responsive': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/plugins/responsive/responsive'),
'amcharts/plugins/dataloader/dataloader': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/plugins/dataloader/dataloader'),
'amcharts/plugins/animate/animate': () => import(/* webpackMode: "lazy", webpackChunkName: "amcharts" */ 'amcharts/plugins/animate/animate'),
'rql/query': () => import(/* webpackMode: "eager" */ 'rql/query'),
'rql/parser': () => import(/* webpackMode: "eager" */ 'rql/parser'),
'tinycolor': () => import(/* webpackMode: "eager" */ 'tinycolor2'),
'md-color-picker': () => import(/* webpackMode: "eager" */ 'md-color-picker'),
'sha512': () => import(/* webpackMode: "eager" */ 'js-sha512'),
'papaparse': () => import(/* webpackMode: "eager" */ 'papaparse'),
'globalize': () => import(/* webpackMode: "eager" */ 'globalize'),
'cldr': () => import(/* webpackMode: "eager" */ 'cldrjs'),
// 'cldr-data': () => import(/* webpackMode: "eager" */ 'cldr-data'),
'ipaddr': () => import(/* webpackMode: "eager" */ 'ipaddr.js'),
'mathjs': () => import(/* webpackMode: "eager" */ 'mathjs'),
'simplify-js': () => import(/* webpackMode: "eager" */ 'simplify-js'),
'jszip': () => import(/* webpackMode: "eager" */ 'jszip'),
'stacktrace': () => import(/* webpackMode: "eager" */ 'stacktrace-js'),
'd3': () => import(/* webpackMode: "lazy", webpackChunkName: "d3" */ 'd3')
};
// maps a defined AMD name to the import plugin which loads the resource using ES6/webpack async import()
const mapToImportPlugin = Object.keys(exposedVendorModules).reduce((map, name) => {
map[name] = 'webpackImport!' + name;
return map;
}, {});
require.config({
//baseUrl: modulePath + '/vendors',
urlArgs: function(id, url) {
if (url.indexOf('?v=') > 0 || url.indexOf('&v=') > 0 || url.match(/^(https?:)?\/\//i)) {
return '';
}
let version = configuration.defaultVersion;
const moduleMatches = id.match(/^modules\/(.+?)\//);
if (moduleMatches) {
const moduleVersion = configuration.moduleVersions[moduleMatches[1]];
if (moduleVersion) {
version = moduleVersion;
}
}
return (url.indexOf('?') > 0 ? '&' : '?') + 'v=' + version;
},
paths : {
'modules': '/modules',
'mangoUIModule': modulePath
},
map: {
'*': mapToImportPlugin
}
});
// defines an RequireJS plugin that uses ES6/webpack async import() to load a resource
define('webpackImport', [], () => {
return {
load(name, req, onload, config) {
const importFn = exposedVendorModules[name];
if (typeof importFn !== 'function') {
// fall back to require()
req([name], value => {
onload(value);
}, error => {
onload.error(error);
});
return;
}
importFn().then(module => {
onload(module.default != null ? module.default : module);
}, error => {
onload.error(error);
});
}
};
});
export default configuration;
|
const server = require('../../server')
module.exports = async (on, config) => {
await server.start()
let db = server.getDb()
await db.dropDatabase()
on('task', {
async resetDb() {
return db.dropDatabase()
},
})
require('../../../plugin')(on, config, db)
}
|
var Properties = require ("../build/properties");
new Properties ()
.set ("p1", "v1", "Property 1")
.set ("p2", null, "Property 2, empty")
.set ("p3", "v3")
.set ("p4", null)
.store ("example.properties", "Example .properties file", function (error){
new Properties ().load ("example.properties", function (error){
var me = this;
var keys = this.keys ();
console.log ("keys: " + keys);
keys.forEach (function (key){
console.log (key + ":" + me.get (key));
});
});
});
|
const cloudinary = require('cloudinary');
const init = () =>
cloudinary.config({
cloud_name: 'dtruzsecs',
api_key: '149518964655596',
api_secret: 'MDtZHbsXY2TU2yBcMuNO3of8FwM'
});
module.exports = { init, cloudinary };
|
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
var userSchema = mongoose.Schema({
nombre:{
type: String,
required: true,
default: ""
},
apellidos:{
type: String
},
correo:{
type: String,
required: true,
default: ''
},
fechaNacimiento:{
type: Date
},
genero:{
type: String
},
foto:{
type: String
},
password:{
type: String,
default: ''
},
tipo:{
type: String,
default: 'user'
},
rutinas:[{
type: mongoose.Schema.Types.ObjectId,
ref: "Routine"
}]
});
// Middleware to encrypt the incoming password
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
if (!user.password) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
var User = module.exports = mongoose.model('User', userSchema);
//Get All
module.exports.getAll = function(callback){
User.find(callback)
.populate({
path: 'rutinas',
populate:{
path: 'actividades'
}
})
};
//Get by ID
module.exports.getById = function(id, callback){
User.findById(id, callback)
.populate({
path: 'rutinas',
populate:{
path: 'actividades'
}
});
};
//Get by Email
module.exports.getByEmail = function(email, callback){
User.findOne({correo: email}, callback)
.populate({
path: 'rutinas',
populate:{
path: 'actividades'
}
});
};
// //Add Object
module.exports.createObject = function(newObject, next, callback){
newObject.save((error, newObj)=>{
if(error){
return next(new Error(error))
}
User.findById(newObj.id, callback)
.populate({
path: 'rutinas',
populate:{
path: 'actividades'
}
});
});
};
//Remove Object
module.exports.removeObject = function(id, callback){
User.find({_id: id}).remove(callback);
};
//Update Object
module.exports.updateObject = function(id, data, next, callback){
User.findById(id, function(err, obj){
if(!obj){
return next(new Error("Could not load User to update"))
}else{
obj.nombre = data.nombre;
obj.apellidos = data.apellidos;
obj.correo = data.correo;
obj.tipo = data.tipo;
obj.fechaNacimiento = data.fechaNacimiento;
obj.genero = data.genero;
obj.foto = data.foto;
obj.rutinas = data.rutinas;
obj.save((error, newObj)=>{
if(error){return next(err);}
User.findById(newObj.id, callback)
.populate({
path: 'rutinas',
populate:{
path: 'actividades'
}
});
});
}
});
};
module.exports.updatePassword = function(id, data, next, callback){
User.findById(id, function(err, obj){
if(!obj){
return next(new Error("Could not load User to update"))
}else{
obj.password = data.password;
obj.save((error, newObj)=>{
if(error){return next(err);}
User.findById(newObj.id, callback)
.populate({
path: 'rutinas',
populate:{
path: 'actividades'
}
});
});
}
});
};
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.ui.visualization.TimeDomainScale');
goog.require('audioCat.ui.visualization.TimeUnit');
goog.require('goog.asserts');
/**
* Provides the scale at which to visualize audio.
* @param {number} majorTickWidth The width in pixels of a single major tick.
* @param {number} majorTickTime The number of time units the major tick
* represents.
* @param {!audioCat.ui.visualization.TimeUnit} timeUnit The time unit to use
* for display.
* @param {number} decimalPlaces The number of decimal places to round to.
* @param {number} minorTickCount The number of minor ticks per major tick to
* draw.
* @constructor
*/
audioCat.ui.visualization.TimeDomainScale = function(
majorTickWidth,
majorTickTime,
timeUnit,
decimalPlaces,
minorTickCount) {
/**
* Integer. The major tick width in pixels.
* @private {number}
*/
this.majorTickWidth_ = majorTickWidth;
/**
* The number of time units the major tick represents.
* @private {number}
*/
this.majorTickTime_ = majorTickTime;
/**
* The time unit to use for display.
* @private {!audioCat.ui.visualization.TimeUnit}
*/
this.timeUnit_ = timeUnit;
/**
* The number of decimal places to round to.
* @private {number}
*/
this.numberOfDecimalPlaces_ = decimalPlaces;
/**
* The number of minor ticks per major tick to draw.
* @private {number}
*/
this.minorTicksPerMajorTick_ = minorTickCount;
var unitsPerSecond = 0;
switch (timeUnit) {
case audioCat.ui.visualization.TimeUnit.S:
unitsPerSecond = 1;
break;
case audioCat.ui.visualization.TimeUnit.MS:
unitsPerSecond = 1000;
break;
default:
// We are missing a unit.
throw 1;
}
/**
* The ratio of pixels to seconds.
* @private {number}
*/
this.pixelsPerSecond_ =
this.majorTickWidth_ / this.majorTickTime_ * unitsPerSecond;
};
/**
* @return {number} The major tick width in pixels.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.getMajorTickWidth =
function() {
return this.majorTickWidth_;
};
/**
* @return {number} The time in the time units that each major tick represents.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.getMajorTickTime =
function() {
return this.majorTickTime_;
};
/**
* @return {!audioCat.ui.visualization.TimeUnit} The time unit to display.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.getTimeUnit =
function() {
return this.timeUnit_;
};
/**
* @return {number} The number of decimal places to round major tick values.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.getDecimalPlaces =
function() {
return this.numberOfDecimalPlaces_;
};
/**
* @return {number} The number of minor ticks to draw per major tick.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.getMinorTicksPerMajorTick =
function() {
return this.minorTicksPerMajorTick_;
};
/**
* Converts from pixels to seconds based on the current scale.
* @param {number} pixels The number of pixels.
* @return {number} The time in seconds based on the current scale.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.convertToSeconds =
function(pixels) {
return this.getSecondsFromTimeUnits(
pixels * this.majorTickTime_ / this.majorTickWidth_);
};
/**
* Converts time units for this scale - it could be seconds or milliseconds for
* instance into seconds.
* @param {number} timeUnits The number of time units (that are used for this
* scale).
* @return {number} The equivalent number of seconds.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.getSecondsFromTimeUnits =
function(timeUnits) {
var unitsPerSecond;
switch (this.timeUnit_) {
case audioCat.ui.visualization.TimeUnit.S:
unitsPerSecond = 1;
break;
case audioCat.ui.visualization.TimeUnit.MS:
unitsPerSecond = 1000;
break;
}
goog.asserts.assert(unitsPerSecond);
return timeUnits / unitsPerSecond;
};
/**
* Converts from seconds to pixels based on the current scale.
* @param {number} seconds The time in seconds to convert to pixels.
* @return {number} The number of pixels tantamount to the seconds.
*/
audioCat.ui.visualization.TimeDomainScale.prototype.convertToPixels =
function(seconds) {
return seconds * this.pixelsPerSecond_;
};
|
const addressesTableName = 'addresses';
exports.up = function(knex) {
return knex.schema.createTable(addressesTableName, table => {
table.string('id', 16).notNullable().primary();
table.string('user_id').notNullable().references('users.id');
table.string('address').notNullable();
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('updated_at').defaultTo(null);
})
};
exports.down = function(knex) {
return knex.schema.dropTable(addressesTableName);
};
|
module.exports = class Logger {
constructor(name, options) {
this.clazzName = name
this.logging = options.logging
this.io = options.io || console
}
_writeMsg(io, msg, data) {
msg = `[${this.clazzName}] ${msg}`
data ? io(msg, data) : io(msg)
}
_log(msg, data) {
if (this.logging) {
let io = this.io.log
this._writeMsg(io, `INFO: ${msg}`, data)
}
}
_warn(msg, data) {
if (this.logging) {
let io = this.io.log
this._writeMsg(io, `WARNING: ${msg}`, data)
}
}
_error(msg, data) {
if (this.logging) {
let io = this.io.error || this.io.log
this._writeMsg(io, `ERROR: ${msg}`, data)
throw new Error(msg)
}
}
}
|
var request = require('request');
var cheerio = require('cheerio');
var moment = require('moment');
var assert = require('assert');
var Converter = require("csvtojson").Converter;
var Q = require('q')
exports.getArrayOfAllSymbols = function(db, collectionName) {
return new Promise(function(resolve){
var cursor = db.collection(collectionName)
.find({},{_id:0, symbol:1})
.toArray(function(err, documents){
// db.close();
var symbolArray = documents.map(function(elm){
return elm.symbol;
});
resolve(symbolArray);
});
});
};
exports.downloadHistoricalPrices = function(ticker){
return new Promise(function(resolve, reject){
var urlFront = "http://real-chart.finance.yahoo.com/table.csv?s="
var urlBack = "&d=1&e=27&f=2016&g=d&a=7&b=1&c=2000&ignore=.csv"
var url = urlFront + ticker + urlBack;
var converter = new Converter({});
request(url, function(error, response, data){
assert.equal(error, null);
console.log('historical prices loaded for ' + ticker);
converter.fromString(data, function(err,result){
resolve(result);
});
})
}); // promise function
}
exports.downloadKeyStats = function(ticker){
var keyStatsUrl = 'https://sg.finance.yahoo.com/q/ks?s=';
return new Promise(function(resolve,reject){
var url = keyStatsUrl + ticker;
request(url, function(error, response, html){
if(error){
console.log(error);
} else {
console.log('key stats html loaded for ' + ticker);
var $ = cheerio.load(html);
// intialize json doc
var tempDoc = {};
// set date of retrieval
tempDoc.date = new Date();
//collect period headings
$('td.yfnc_tablehead1')
.each(function(i, elm){
tempDoc[$(this).text().replace(/\s/g, "_")]=$(this).siblings().first().text();
});
resolve(tempDoc);
}
})
})
}
exports.downloadCashFlow = function(ticker, annualBool){
var cashFlowUrl = 'https://sg.finance.yahoo.com/q/cf?s=';
return new Promise(function(resolve,reject){
var url = ''
// concatenate url and ticker depending on annual parameter
if(annualBool) {
var url = cashFlowUrl + ticker + '&annual';
} else {
var url = cashFlowUrl + ticker;
}
request(url, function(error, response, html){
if(error){
console.log(error);
} else {
console.log('CF html loaded for ' + ticker);
var $ = cheerio.load(html);
// intialize data arrays
var statArray = [];
var periodarray = [];
//collect period headings
$('td.yfnc_modtitle1').each(function(i, elm){
periodarray.push($(this).text().trim());
});
// push period ending headings as first item of each inc statement document
for (var i = 1; i < 5; i++) {
var docObj = {};
docObj[periodarray[0]] = moment(periodarray[i], 'DD MMM, YYYY').toDate();
statArray.push(docObj);
}
$('td.yfnc_modtitle1').parent().siblings()
.each(function(i,elm){
var textArray = [];
// push table row data into a text array
$(this).children().each(function(i, elm){
var text = $(this).text().trim();
//only if not empty string
if (text != '') {
textArray.push(text);
}
});
// push line item onto each income statement document
if (textArray.length != 0) {
for (var i = 0; i< 4; i++) {
statArray[i][textArray[0]]= textArray[i+1];
}
}
});
resolve(statArray);
}
})
})
}
exports.downloadBalSheet = function(ticker, annualBool){
var balSheetUrl = 'https://sg.finance.yahoo.com/q/bs?s=';
return new Promise(function(resolve,reject){
var url = ''
// concatenate url and ticker depending on annual parameter
if(annualBool) {
var url = balSheetUrl + ticker + '&annual';
} else {
var url = balSheetUrl + ticker;
}
request(url, function(error, response, html){
if(error){
console.log(error);
} else {
console.log('BS html loaded for ' + ticker);
var $ = cheerio.load(html);
// intialize data arrays
var statArray = [];
var periodarray = [];
//collect period headings
$('td.yfnc_modtitle1').each(function(i, elm){
periodarray.push($(this).text().trim());
});
// push period ending headings as first item of each inc statement document
for (var i = 1; i < 5; i++) {
var docObj = {};
docObj[periodarray[0]] = moment(periodarray[i], 'DD MMM, YYYY').toDate();
statArray.push(docObj);
} // for
$('td.yfnc_modtitle1').parent().siblings()
.each(function(i,elm){
var textArray = [];
// push table row data into a text array
$(this).children().each(function(i, elm){
var text = $(this).text().trim();
//only if not empty string
if (text != '') {
textArray.push(text);
}
}); //children.each
// push line item onto each income statement document
if (textArray.length != 0) {
for (var i = 0; i< 4; i++) {
statArray[i][textArray[0]]= textArray[i+1];
}
}
}); //siblings.each
resolve(statArray);
} // else
}) //request
})
}
exports.downloadIncStatement = function(ticker, annualBool) {
return new Promise(function(resolve,reject){
var incStUrl = 'https://sg.finance.yahoo.com/q/is?s=';
var url = '';
// concatenate url and ticker depending on annual parameter
if(annualBool) {
var url = incStatUrl + ticker + '&annual';
} else {
var url = incStatUrl + ticker;
}
request(url, function(error, response, html){
if(error){
console.log(error);
} else {
console.log('html loaded for ' + ticker);
var $ = cheerio.load(html);
// intialize data arrays
var statArray = [];
var periodarray = [];
//yfnc_modtitle is class of table header row
$('tr.yfnc_modtitle1').children().each(function(i, elm){
periodarray.push($(this).text().trim());
});
// push period ending headings as first item of each inc statement document
for (var i = 1; i < 5; i++) {
var docObj = {};
docObj[periodarray[0]] = moment(periodarray[i], 'DD MMM, YYYY').toDate();
statArray.push(docObj);
}
// siblings are the financial statement line items
// in each line item row
$('tr.yfnc_modtitle1').siblings()
.each(function(i, elm){
var textArray = [];
// push table row data into a text array
$(this).children().each(function(i, elm){
var text = $(this).text().trim();
if (text != '') {
textArray.push(text);
}
});
// push line item onto each income statement document
if (textArray.length != 0) {
for (var i = 0; i< 4; i++) {
statArray[i][textArray[0]]= textArray[i+1];
}
}
});
resolve(statArray);
}
});
}); //promise function
};
|
import React, { Component } from 'react'
import Link from "../../components/Link/index"
class WithErrorHandler extends Component {
constructor (props) {
super(props)
this.state = { hasError: false }
}
componentDidCatch (error, info) {
this.setState(state => ({ ...state, hasError: true,info:info,error:error }))
}
render () {
if (this.state.hasError) {
return (
<div className="content-wrap">
<div className="container">
<div className="notfound">
<div className="row verticalcntr">
<div className="col-md-12 text-center">
{
this.state.error && this.state.error.message && this.props.pageInfoData.environment == "dev" ?
<h2>{this.state.error.message}</h2>
: <h2>{this.props.t("Whoops! Something went wrong here. Please try again later.")}</h2>
}
{
this.state.info && this.props.pageInfoData.environment == "dev" ?
<React.Fragment>
<p><code>{this.state.info.componentStack}</code></p><br />
</React.Fragment>
: null
}
<Link href="/">
<a><i className="fas fa-angle-left"></i> {this.props.t("Go Back to the homepage")}</a>
</Link>
</div>
</div>
</div>
</div>
</div>
)
}
return this.props.children
}
}
export default WithErrorHandler
|
import React from 'react';
import styled from 'styled-components'
function NavBar() {
return (
<Container>
<Tab><Link href="#contact_section">Contact</Link></Tab>
<Tab><Link href="https://kevinpark-61806.medium.com/">Blog</Link></Tab>
<Tab><Link href="#projects_section">Projects</Link></Tab>
<Tab><Link href="#about_section">About</Link></Tab>
</Container>
)
}
export default NavBar;
const Container = styled.div`
width: 100%;
height: 75px;
top: 0%;
`
const Link = styled.a`
color: white;
text-shadow: 2px 2px black;
text-decoration: none;
font-size: 23pt;
`
const Tab = styled.h2`
float: right;
display: inline-block;
margin-right: 8%;
font-family: American Typewriter;
opacity: 1.0;
`
// background-color: #0B4F95;
|
var express = require('express');
var router = express.Router();
var middle = require('../module/middleware');
///////////////////////////////////////////
//middleware USE function --- 1
///////////////////////////////////////////
router.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
///////////////////////////////////////////
//middleware USE function --- 2
///////////////////////////////////////////
router.use('/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
}, function (req, res, next) {
console.log('Request finished router.use . . .. . ..');
next();
});
///////////////////////////////////////////
//middleware USE function --- 3
///////////////////////////////////////////
router.get('/:id',middle.getId,middle.isIdEquZero, function (req, res, next) {
// if the user ID is 0, skip to the next router
if (req.params.id == 0) next('route');
// otherwise pass control to the next middleware function in this stack
else next(); //
}, function (req, res, next) {
// render a regular page
res.render('index', { title: "regular"});
});
// handler for the /user/:id path, which renders a special page
router.get('/:id', function (req, res, next) {
console.log(req.params.id);
res.render('index', { title: "special"});
});
router.get('/', function(req, res, next) {
res.render('index', { title: "Middleware"});
});
module.exports = router;
|
import nr from 'newrelic';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import templateFn from './template';
import Sidebar from '../client/src/components/Sidebar.jsx';
import path from 'path';
const app = express();
const DIST_DIR = path.join(__dirname, '../client/dist');
const port = process.env.PORT || 3001;
const db = require('../database/indexPostGres');
db.connect();
app.use(express.static(DIST_DIR));
app.get('/restaurants/:id', (req, res) => {
res.header('Access-Control-Allow-Origin', '*');
db.any(`select * from zagnar where id = ${req.params.id}`).then((data) => {
const body = renderToString(<Sidebar data={data} />);
const title = 'Zaget';
res.send(templateFn(
title,
body,
data[0],
));
});
});
app.listen(port);
|
var codebreak = require("./codebreak");
/*var prompt = require('prompt');
codebreak.start();
console.log("\nWelcome to Code Breakers!");
console.log("=========================\n");
//console.log(codebreak.code);
ask();
function ask() {
prompt.start();
prompt.get(['guess'], function (err, result) {
if (result.guess == "ans") {
console.log(codebreak.code);
return;
}
var res = codebreak.evaluate(result.guess);
if (res.join() == "4,0") {
console.log("CORRECT! You did it in " + codebreak.guesses() + " guesses.");
} else {
console.log(res);
ask();
}
});
}*/
var express = require('express');
var app = require('express')();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
var io = require('socket.io')(server, {'heartbeat timeout': 60});
var path = require('path');
codebreak.start();
console.log("=== Welcome to Code Breakers ===");
console.log(codebreak.code);
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function(req, res){
res.sendFile('index.html');
});
io.on('connection', function (socket) {
console.log('Client ' + socket.id + ' connected');
socket.on('start', function(val){
socket.username = val;
socket.attempts = 0;
socket.broadcast.emit('join', socket.username);
console.log(socket.username + " has joined the game");
});
socket.on('guess', function(val){
var res = codebreak.evaluate(val);
socket.emit('reply', res);
socket.attempts++;
socket.broadcast.emit('opponent-guess', res, socket.username, socket.attempts);
console.log(socket.username + " guessed " + val);
if (res.join() == "4,0") {
io.emit('win', {
name: socket.username,
code: codebreak.code.join(""),
attempts: socket.attempts
});
console.log(socket.username + " wins!");
console.log("=== new game ===");
codebreak.generate();
console.log(codebreak.code);
}
});
socket.on('lose', function(loser) {
socket.emit('lose', {
name: loser,
code: codebreak.code.join("")
});
console.log(socket.username + " loses.");
});
socket.on('disconnect', function () {
console.log('Client ' + socket.id + ' disconnected');
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
|
import React, { Component } from 'react';
class BookForm extends Component {
captureInput(e){
e.preventDefault();
const entry = {
text: this.text.value,
name: this.name.value
};
if(this.text.value || this.name.value){
this.props.handleBookFormSubmits(entry);
this.entryForm.reset();
}
}
render(){
return (
<form className="guestbook-form__container" ref={(input) => this.entryForm = input} onSubmit={(e) => {this.captureInput(e)}}>
<fieldset>
<legend>New guestbook entry</legend>
<label htmlFor="text">Text</label>
<textarea name="" className="form-control" ref={(input) => this.text = input} cols="30" rows="10">
</textarea>
<label htmlFor="name">Name</label>
<input type="text" className="form-control" ref={(input) => this.name = input} />
<button className="submit btn btn-success" type="submit">Send</button>
</fieldset>
</form>
)
}
}
export default BookForm;
|
let vm = new Vue({
el: "#app",
data: {
idCard: "",
flag: 0
},
methods: {
//验证身份证号
idCardChk: function (str) {
if (str.length !== 18) {
return false;
}
str = str.toUpperCase();//字符全部转大写
let newStr = str.substr(0, 17);//取字符前17位
let wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
let codeArr = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
let sigma = 0;
for (let i = 0; i < 17; i++) {
sigma += parseInt(newStr[i]) * wi[i];
}
let code = codeArr[(sigma % 11)];
newStr = newStr + "" + code;
return (newStr == str);
}
},
computed: {
birthday: function () {
let num = this.idCard;
let birthday = "未知";
if (num !== "") {
if (this.idCardChk(num)) {
this.flag = 1;
let year = num.substr(6, 4);
let month = num.substr(10, 2);
let date = num.substr(12, 2);
birthday = year + "-" + month + "-" + date;
return birthday;
} else {
this.flag = 2;
return birthday;
}
} else {
this.flag = 0;
return birthday;
}
},
gender: function () {
let garder = "未知";
let num = this.idCard;
if (this.idCardChk(num)) {
gender = num.substr(16, 1);
return (gender % 2) ? "男" : "女";
} else {
return garder;
}
},
areaInfo: function () {
let area = "未知";
let num = this.idCard;
if (this.idCardChk(num)) {
let areaCode = num.substr(0, 6);
if (areaCode != "undefined") {
for (x in areaCodeArr) {
if (areaCode == areaCodeArr[x].areaCode) {
area = areaCodeArr[x].detail;
break;
}
}
}
}
return area;
},
age: function () {
let age = "未知";
let num = this.idCard;
if (this.idCardChk(num)) {
now = new Date();
let nowyear = now.getFullYear();
let nowmonth = now.getMonth();
let nowdate = now.getDate();
let year = num.substr(6, 4);
let month = num.substr(10, 2);
let date = num.substr(12, 2);
if (parseInt(nowmonth + "" + nowdate) < parseInt(month + date)) {
age = nowyear - year - 1;
} else {
age = nowyear - year;
}
}
return age;
},
constellation: function () {
let num = this.idCard;
let cst = "未知";
if (this.idCardChk(num)) {
let month = num.substr(10, 2);
let date = num.substr(12, 2);
let md = month + "" + date;
if (md != "undefined") {
for (x in constellations) {
if (parseInt(md) <= parseInt(constellations[x].End) && parseInt(md) >= parseInt(constellations[x].Start)) {
cst = constellations[x].Name;
break;
}
}
}
}
return cst;
}
},
});
|
const VerkeersinformatieRoadworks = require("../model/verkeersinformatieRoadworks");
module.exports = function updateAndInsertAnwbJsonDataRoadworks() {
anwbJsonData.roads.map(roads =>
roads.segments
.filter(segments => typeof segments.roadworks !== "undefined")
.map(segments =>
VerkeersinformatieRoadworks.bulkWrite(
segments.roadworks.map(roadworks => ({
updateOne: {
filter: {
"segments.roadworks.id": roadworks.id
},
update: {
$set: {
segments: {
start: segments.start,
end: segments.end,
roadworks: {
id: roadworks.id,
road: roadworks.road,
type: roadworks.type,
category: roadworks.category,
label: roadworks.label,
incidentType: roadworks.incidentType,
from: roadworks.from,
to: roadworks.to,
fromLoc: roadworks.fromLoc,
toLoc: roadworks.toLoc,
polyline: roadworks.polyline,
bounds: roadworks.bounds,
events: roadworks.events,
start: roadworks.start,
stop: roadworks.stop,
reason: roadworks.reason
}
}
}
},
upsert: true
}
})),
function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
}
)
)
);
};
|
import select from 'd3-selection/src/select';
import mouse from 'd3-selection/src/mouse';
import pie from 'd3-shape/src/pie';
import arc from 'd3-shape/src/arc';
import Tooltip from './components/Tooltip';
import addLegend from './utils/addLegend';
import addLabels from './utils/addLabels';
import addFont from './utils/addFont';
import addFilter from './utils/addFilter';
import colors from './utils/colors';
import config from './config';
const margin = 50;
class Pie {
constructor(svg, {
title, data: { labels, datasets }, options,
}) {
this.options = {
unxkcdify: false,
innerRadius: 0.5,
legendPosition: config.positionType.upLeft,
dataColors: colors,
fontFamily: 'xkcd',
strokeColor: 'black',
backgroundColor: 'white',
showLegend: true,
...options,
};
this.title = title;
this.data = {
labels,
datasets,
};
this.filter = 'url(#xkcdify-pie)';
this.fontFamily = this.options.fontFamily || 'xkcd';
if (this.options.unxkcdify) {
this.filter = null;
this.fontFamily = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
}
this.svgEl = select(svg)
.style('stroke-width', '3')
.style('font-family', this.fontFamily)
.style('background', this.options.backgroundColor)
.attr('width', svg.parentElement.clientWidth)
.attr('height', Math.min((svg.parentElement.clientWidth * 2) / 3, window.innerHeight));
this.svgEl.selectAll('*').remove();
this.width = this.svgEl.attr('width');
this.height = this.svgEl.attr('height');
this.chart = this.svgEl.append('g')
.attr('transform',
`translate(${this.width / 2},${this.height / 2})`);
addFont(this.svgEl);
addFilter(this.svgEl);
this.render();
}
render() {
if (this.title) {
addLabels.title(this.svgEl, this.title, this.options.strokeColor);
}
const tooltip = new Tooltip({
parent: this.svgEl,
title: 'tooltip',
items: [{ color: 'red', text: 'weweyang: 12' }, { color: 'blue', text: 'timqian: 13' }],
position: { x: 30, y: 30, type: config.positionType.upRight },
unxkcdify: this.options.unxkcdify,
strokeColor: this.options.strokeColor,
backgroundColor: this.options.backgroundColor,
});
const radius = Math.min(this.width, this.height) / 2 - margin;
const thePie = pie();
const dataReady = thePie(this.data.datasets[0].data);
const theArc = arc()
.innerRadius(radius
* (this.options.innerRadius === undefined ? 0.5 : this.options.innerRadius))
.outerRadius(radius);
this.chart.selectAll('.xkcd-chart-arc')
.data(dataReady)
.enter()
.append('path')
.attr('class', '.xkcd-chart-arc')
.attr('d', theArc)
.attr('fill', 'none')
.attr('stroke', this.options.strokeColor)
.attr('stroke-width', 2)
.attr('fill', (d, i) => this.options.dataColors[i])
.attr('filter', this.filter)
// .attr("fill-opacity", 0.6)
.on('mouseover', (d, i, nodes) => {
select(nodes[i]).attr('fill-opacity', 0.6);
tooltip.show();
})
.on('mouseout', (d, i, nodes) => {
select(nodes[i]).attr('fill-opacity', 1);
tooltip.hide();
})
.on('mousemove', (d, i, nodes) => {
const tipX = mouse(nodes[i])[0] + (this.width / 2) + 10;
const tipY = mouse(nodes[i])[1] + (this.height / 2) + 10;
tooltip.update({
title: this.data.labels[i],
items: [{
color: this.options.dataColors[i],
text: `${this.data.datasets[0].label || ''}: ${d.data}`,
}],
position: {
x: tipX,
y: tipY,
type: config.positionType.downRight,
},
});
});
// Legend
const legendItems = this.data.datasets[0].data
.map((data, i) => ({ color: this.options.dataColors[i], text: this.data.labels[i] }));
// move legend down to prevent overlaping with title
const legendG = this.svgEl.append('g')
.attr('transform', 'translate(0, 30)');
if (this.options.showLegend) {
addLegend(legendG, {
items: legendItems,
position: this.options.legendPosition,
unxkcdify: this.options.unxkcdify,
parentWidth: this.width,
parentHeight: this.height,
strokeColor: this.options.strokeColor,
backgroundColor: this.options.backgroundColor,
});
}
}
// TODO: update chart
update() {
}
}
export default Pie;
|
//npm init
//npm install express --s
//inisialisasi express
const express = require("express")
const app = express()
var statuslampu = 0;
var statuslampu2 = 0;
app.listen(3000, function(){
console.log("Server is running")
})
app.get("/:lampu",function(req,res){
statuslampu = req.params.lampu
res.redirect("/")
})
app.get("/",function(req,res){
res.send({
lampu:statuslampu
})
})
|
import express from 'express';
import * as contactCtrl from '../controllers/contact.controller';
import isAuthenticated from '../middlewares/authenticate';
import validate from '../config/joi.validate';
import schema from '../utils/validator';
const router = express.Router();
/**
* @swagger
* tags:
* - name: contact us
* description: Cotact US operations
*/
router.route('/modify')
/**
* @swagger
* /contact/modify:
* put:
* tags:
* - contact us
* summary: "Modify Contact Us By Id"
* security:
* - Bearer: []
* operationId: modify
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: body
* in: body
* description: Updated Contact Us object
* required: true
* schema:
* $ref: "#/definitions/ContactUs"
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/ContactUs"
* 400:
* description: Invalid ContactUs
*/
.put(validate(schema.ContactUs), (req, res) => {
contactCtrl.ModifyContact(req, res);
});
router.route('/upload_image/:id')
.post(validate(schema.CheckId), (req, res) => {
contactCtrl.UploadContactImage(req, res);
});
router.route('/download_image/:id')
.get(validate(schema.CheckId), (req, res) => {
contactCtrl.UploadContactImage(req, res);
});
router.route('/get')
/**
* @swagger
* /contact/get:
* get:
* tags:
* - contact us
* summary: Get Contact Us
* operationId: getById
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: id
* in: path
* description: id of contact us that needs to be fetched
* required: true
* type: integer
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/ContactUs"
* 404:
* description: ContactUs not found
* schema:
* $ref: '#/definitions/Error'
*/
.get((req, res) => {
contactCtrl.GetContactById(req, res);
});
export default router;
|
'use strict';
define(['./BaseTask', 'jquery', 'jquery.hotkeys', 'base'], function (BaseTask) {
/**
* Rate item task
* - User is shown a series of items and asked to rate how good they are
*/
function RateItemTask(params) {
BaseTask.call(this, params);
// Number of rating choices
this.nChoices = params.conf['nChoices'];
this.choices = params.conf['choices'];
// Whether the label of the choice will be saved
this.saveChoiceLabel = params.conf['saveChoiceLabel'];
// Hook up UI behavior
this.descriptionElem = $(params.descriptionElem || '#description');
this.itemElem = $(params.itemElem || '#itemImage');
this.ratingGroup = $(params.ratingGroup || '#ratingBtnGroup');
// Set rating button click
var taskState = this;
this.ratingGroup.find('input[name=rating]').click(function() {
//$(this).addClass('active').prop('checked', true).siblings().removeClass('active');
var rating = $(this).val();
taskState.select(rating, true);
});
// Also hook up rating keys to keyboard numbers
for (var i = 1; i <= this.nChoices; i++) {
$(document).bind('keydown', i.toString(), function(rating) {
console.log(rating);
taskState.select(rating, true);
}.bind(this, i.toString()));
}
}
RateItemTask.prototype = Object.create(BaseTask.prototype);
RateItemTask.prototype.constructor = RateItemTask;
RateItemTask.prototype.check = function() {
// TODO: Check if the description is acceptable...
var ok = (this.rating >= 1 && this.rating <= this.nChoices);
if (ok){
var currentEntry = this.entries[this.entryIndex];
var label = this.choices? this.choices[this.rating] : undefined;
var results = {
rating: this.rating,
entry: currentEntry
};
var summary = {
entryId: currentEntry.id,
rating: this.rating
};
if (label != undefined && this.saveChoiceLabel) {
results['ratingLabel'] = label;
summary['ratingLabel'] = label;
}
return {
results: results,
summary: summary
}
} else{
return {
error: "Please select a rating!"
};
}
};
RateItemTask.prototype.select = function (rating, save) {
this.rating = rating;
if (save) {
this.save();
}
};
RateItemTask.prototype.updateEntry = function(entry) {
this.descriptionElem.text(entry['description'] || '');
if (entry.url) {
this.itemElem.attr('src', entry.url);
}
this.select(-1);
// Reset radio selection
$('input[name=rating]:checked').prop('checked', false);
this.ratingGroup.find('label').removeClass('active');
};
// Exports
return RateItemTask;
});
|
// This module helps the user sign in for the first time to the app
/*
Revisions:
- We are no longer using a database. All information will be stored in key value storage.
*/
class signUp {
signup(email, password, confirmPassword, name) {
/*
initially show sign up screen
save user's email/username/password and userID in key value storage
- documentation for key value storage: https://reactnative.dev/docs/asyncstorage
if password equals confirmPassword, navigate to home screen of app
- a previous tutorial I used for login with React Native: https://aboutreact.com/react-native-login-and-signup/
@param email: string of user's email
@param name: string of user's name
@param password: string of user's password
@param confirmPassword: string of user's confirmed password
NOTE: email, name, and password will be stored in database
*/
}
}
|
export default {
black : '#000000',
white : '#ffffff',
whiteShade: '#fffbff',
whitePurple : '#f7f7f7',
whiteGray : '#E5E2DD',
gray : '#dddddd',
darkGrayTxt: '#949494',
gold: '#deaf1b',
green: '#38d39f',
red: '#d63031',
errorRed: '#FF6E6A',
darkSilver: '#bdc3c7',
text_color: '#002E0D',
background_color : '#F6F0F6',
button_border: '#0E802E',
mediumseagreen: '#3CB371',
green_background : '#0F959A',
orange : '#F7933A',
textInput_border: '#BCBCBC',
text: '#BBBBBB',
field_color: '#F1E7F0',
textInuputColor : '#495057',
iconColor: '#0F959A',
blackShade : '#4b4b4b',
darkGray : '#444444',
divider : '#e2e2e2',
blue : '#137ff2',
card : '#1262A1',
sliderCard : '#F4F5F4',
purple : '#2D002B',
}
|
import React from 'react'
import { Route, Switch } from 'react-router-dom'
import Home from './Home.js'
import MoviesRoutes from '../movies/Routes'
import GenresRoutes from '../categories/Routes.js'
import AdminRoutes from '../admin/Routes'
import Login from './Login.jsx'
export default function Routes() {
return (
<Switch>
<Route path="/admin" component={AdminRoutes} />
<Route path="/movies" component={MoviesRoutes} />
<Route path="/genres" component={GenresRoutes} />
<Route path="/login" component={Login} />
<Route path="/" component={Home} exact />
</Switch>
)
}
|
module.exports = {
'@tags': ['service'],
beforeEach: browser => {
browser.page.servicePage()
.navigate()
.waitForElementVisible('body', 3000)
},
afterEach: browser => {
browser.end();
},
'Test message from service': browser => {
const serviceMessageText = 'Service Message: Hello World!'
browser.page.servicePage()
.waitForElementVisible('@serviceMessage', 'Message from service is visible')
.assert.containsText('@serviceMessage', serviceMessageText, 'Service message contains correct text')
}
};
|
/*
* allParentPanelComponent.js
*
* Copyright (c) 2018 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* Custom Hierarchy -> Children panel component.
*
* @author l730832
* @since 2.16.0
*/
(function () {
angular.module('productMaintenanceUiApp').component('childrenPanel', {
// isolated scope binding
bindings: {
currentLevel: '<'
},
scope: {},
// Inline template which is binded to message variable in the component controller
templateUrl: 'src/customHierarchy/childrenPanel.html',
// The controller that handles our component logic
controller: childrenPanelController
});
childrenPanelController.$inject = ['customHierarchyService', 'CustomHierarchyApi', 'PermissionsService', '$scope'];
/**
* Case Pack Import component's controller definition.
* @constructor
* @param customHierarchyService
* @param customHierarchyApi
* @param permissionsService
* @param $scope
*/
function childrenPanelController(customHierarchyService, customHierarchyApi, permissionsService, $scope) {
var self = this;
self.pathList = null;
// Mass update for unassign products.
self.massUpdateType = "UNASSIGN_PRODUCTS";
self.unassignProductsDescriptionBooleanValue = "true";
self.unassignProductsDescriptionStringValue = "";
self.unassignProductsDescription = null;
self.selectedProducts = [];
self.unassignProductsTransactionMessage = null;
self.hasPathChangeCompleted = false;
self.levelToBeRemoved = null;
/**
* Search criteria used during Add Products to Task.
*/
self.searchCriteria = "";
/**
* This method converts a string to a date
* @type {*|function}
*/
var convertDate = $scope.$parent.convertDate;
var PRODUCT_GROUP_ENTITY_TYPE = "PGRP";
var ACTION_CODE_ADDING = 'Y';
var ADD_HIERARCHY_PRODUCT_GROUP = "ADD_HIERARCHY_PRODUCT_GROUP";
var REMOVE_LEVEL_CONFIRMATION_MESSAGE = "Do you want to remove all paths to the children, or only the current path to the children?";
self.$onChanges = function () {
self.originalCurrentLevel = self.currentLevel;
getImmediateNonProductChildren();
// reset the remove button when clicking on another level
self.levelToBeRemoved = null;
};
function getImmediateNonProductChildren(){
// relationship selected
if(typeof self.originalCurrentLevel['id'] === 'undefined'){
customHierarchyApi.getImmediateNonProductChildren(
{
parentEntityId: self.originalCurrentLevel.key.childEntityId,
hierarchyContextId: self.originalCurrentLevel.key.hierarchyContext
},
function(results){
self.originalCurrentLevel.childRelationships = results;
self.currentLeve = angular.copy(self.originalCurrentLevel);
},
fetchError
);
}
// hierarchy context selected
else {
customHierarchyApi.getImmediateNonProductChildren(
{
parentEntityId: self.originalCurrentLevel.parentEntityId,
hierarchyContextId: self.originalCurrentLevel.id
},
function(results){
self.originalCurrentLevel.childRelationships = results;
self.currentLeve = angular.copy(self.originalCurrentLevel);
},
fetchError
);
}
}
/**
* Callback for when the backend returns an error.
*
* @param error The error from the backend.
*/
function fetchError(error) {
self.isWaiting = false;
self.isWaitingForData = false;
self.data = null;
customHierarchyService.setErrorMessage(getError(error), true);
}
/**
* Gets the error given an api error message.
*
* @param error Error message from api.
* @returns {string}
*/
function getError(error){
if (error && error.data) {
if(error.data.message) {
return error.data.message;
} else {
return error.data.error;
}
}
else {
return "An unknown error occurred.";
}
}
/**
* Helper method to determine if a level in the product hierarchy should be collapsed or not.
*
* @param relationship
* @returns {boolean}
*/
self.isLowestBranchOrHasNoRelationships = function(relationship){
if(relationship.lowestBranch){
return true;
}else if(relationship.childRelationships === null || relationship.childRelationships.length === 0) {
return true;
}
return false;
};
self.selectChildRelationship = function(childRelationship){
self.childData = [];
customHierarchyApi.getCurrentLevel(
childRelationship.key,
loadChildData,
fetchError);
};
function loadChildData(results){
results.isCollapsed = false;
if(typeof results['childRelationships'] !== 'undefined'){
expandAllCustomHierarchyRelationships(results.childRelationships);
}
self.childData.push(results);
}
/**
* This function sets the collapsed variable to false for all current levels of the product hierarchy.
*/
function expandAllCustomHierarchyRelationships(relationships){
angular.forEach(relationships, function (relationship) {
relationship.isCollapsed = false;
if(typeof relationship['childRelationships'] !== 'undefined'){
expandAllCustomHierarchyRelationships(relationship.childRelationships);
}
});
}
/**
* This method clears our all of the previous values for the add level modal
*/
self.clearAddLevelModal = function () {
self.addLevelDescription = null;
self.currentEffectiveDate = new Date(Date.now());
self.currentEndDate = new Date('December 31, 9999');
self.addLevelActiveSwitch = true;
};
/**
* Method that calls api to add a new level to selected Level and Hierarchy context.
*
* @param effectiveDate
* @param endDate
* @param description
* @param activeSwitch
*/
self.addCustomHierarchy = function (effectiveDate, endDate, description, activeSwitch) {
customHierarchyService.setWaitingForUpdate(true, true);
// self.currentLevel.key = {parentEntityId: self.currentLevel.parentEntityId};
if(angular.isUndefined(activeSwitch)) {
activeSwitch = false;
}
var currentLevel = angular.copy(self.currentLevel);
currentLevel.effectiveDate = convertDate(currentLevel.effectiveDate);
currentLevel.expirationDate = convertDate(currentLevel.expirationDate);
var hierarchyValues = {
newEffectiveDate : convertDate(effectiveDate),
newEndDate : convertDate(endDate),
newDescription: description,
newActiveSwitch: activeSwitch,
currentLevel: currentLevel,
parentEntityId: self.currentLevel.parentEntityId,
hierarchyContext: customHierarchyService.getHierarchyContextSelected()
};
customHierarchyApi.addCustomHierarchy(hierarchyValues,
function(results){
customHierarchyService.setSuccessMessage(results.message, true);
var tempSelectedArray = customHierarchyService.getHierarchyToSelectedLevel();
tempSelectedArray.push(results.data);
customHierarchyService.setHierarchyToSelectedLevelAndUpdate(tempSelectedArray);
},
fetchError)
};
/**
* Open the FreightConfirmed picker to select a new date.
*/
self.openEffectiveDatePicker = function () {
self.effectiveDatePickerOpened = true;
self.options = {
minDate: new Date()
};
};
/**
* Open the FreightConfirmed picker to select a new date.
*/
self.openEndDatePicker = function () {
self.endDatePickerOpened = true;
self.options = {
minDate: new Date()
};
};
/**
* This method will attempt to remove a level from the hierarchy
*/
self.removeHierarchyLevel = function () {
customHierarchyService.setWaitingForUpdate(true, true);
customHierarchyApi.saveRemoveLevel(
self.levelToBeRemoved,
function(results){
customHierarchyService.setSuccessMessage(results.message, true);
customHierarchyService.updateSelectedHierarchy();
},
fetchError)
};
/**
* This method will update the level to remove and remove the previously selected level
* @param childRelationships the new level to remove
*/
self.setToRemove = function (childRelationships) {
if(self.levelToBeRemoved !==null){
self.levelToBeRemoved.removeSelected=false;
}
childRelationships.removeSelected = true;
self.levelToBeRemoved = childRelationships;
};
/**
* This method will verify there a a level to remove
* @returns {boolean}
*/
self.isRemoveValid = function () {
return self.levelToBeRemoved === null;
};
/**
* Call api to mass update add product groups.
*/
self.addCustomerProductGroups = function(){
var addedProductGroupIds = [];
angular.forEach(self.allCustomerProductGroups, function(customerProductGroup){
if(customerProductGroup.isChecked){
addedProductGroupIds.push(customerProductGroup.custProductGroupId);
}
});
self.productIds = addedProductGroupIds;
self.massUpdateType = ADD_HIERARCHY_PRODUCT_GROUP;
self.totalUpdates = addedProductGroupIds.length;
};
/**
* Gets all customer product groups to be able to add them to a hierarchy relationship. This call sends the
* current hierarchy level information, so the currently attached product groups are not included in the
* return.
*/
self.getAllCustomerProductGroups = function(){
self.isWaitingForAllProductGroups = true;
self.allCustomerProductGroups = [];
self.customerProductGroupsError = null;
self.allCustomProductGroupsChecked = false;
customHierarchyApi.findAllCustomerProductGroupsNotOnParentEntity(
{
hierarchyContext: self.currentLevel.key.hierarchyContext,
parentEntityId: self.currentLevel.key.childEntityId
},
loadCustomerProductGroups,
function(error){
self.isWaitingForAllProductGroups = false;
customHierarchyService.setErrorMessage(getError(error), true);
}
)
};
/**
* Callback for load customer product groups.
*
* @param results
*/
function loadCustomerProductGroups(results){
self.allCustomerProductGroups = results;
self.isWaitingForAllProductGroups = false;
}
/**
* Mass updates product groups by assigning the product search criteria and mass update parameters, then
* calling the api to mass update the selected body of product groups.
*/
self.massUpdateProductGroups = function(){
customHierarchyService.setWaitingForUpdate(true, true);
var productSearchCriteria = {
lowestCustomerHierarchyNode: self.currentLevel.key,
entityType: PRODUCT_GROUP_ENTITY_TYPE
};
var massUpdateParameters = {
attribute: self.massUpdateType,
stringValue: self.descriptionStringValue,
description: self.description,
entityRelationship: {
key: self.currentLevel.key
}
};
productSearchCriteria.productGroupIds = self.productIds.toString();
massUpdateParameters.entityRelationship.actionCode = ACTION_CODE_ADDING;
var massUpdateRequest = {
parameters: massUpdateParameters,
productSearchCriteria: productSearchCriteria
};
customHierarchyApi.massUpdate(
massUpdateRequest,
function(results){
customHierarchyService.setSuccessMessage(results.message, true);
},
fetchError);
};
/**
* Set all product groups selected value to 'all selected' value.
*/
self.setAllCustomProductGroups = function(){
angular.forEach(self.allCustomerProductGroups, function(customerProductGroup){
customerProductGroup.isChecked = self.allCustomProductGroupsChecked;
});
};
/**
* Callback for a successful start of a mass update job.
*
* @param data The data sent from the back end.
*/
self.massUpdateSuccess = function(data) {
customHierarchyService.setSuccessMessage(data.message, true);
};
/**
* This method will tell the api to only delete a single layer of children after failing to remove a level from the hierarchy
*/
self.deleteSingleRemoveLevel = function () {
customHierarchyService.setWaitingForUpdate(true, true);
customHierarchyApi.deleteSingleRemoveLevel(self.levelToBeRemoved, self.successfulHierarchyChange, fetchError)
};
/**
* This method will tell the api to delete all children after failing to remove a level from the hierarchy
*/
self.deleteAllRemoveLevel = function () {
customHierarchyService.setWaitingForUpdate(true, true);
customHierarchyApi.deleteAllRemoveLevel(self.levelToBeRemoved, self.successfulHierarchyChange, fetchError)
};
/**
* Upon successful removing a level from the hierarchy this method will reset the view
* @param results
*/
self.successfulHierarchyChange = function(results){
customHierarchyService.setSuccessMessage(results.message, true);
customHierarchyService.updateSelectedHierarchy();
};
}
}());
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import debounce from "lodash/debounce";
import NavigationItem from "../navigationItem/NavigationItem";
import "./NavigationBar.css";
class NavigationBar extends Component {
constructor(props) {
super(props);
this.timer = null;
this.state = {
slidePosition: {
left: 0,
width: 0,
},
selectedItem: null,
selectedCity: "",
resizing: false,
};
this.enableTransition = debounce(() => {
this.setState({
resizing: false,
});
}, 200);
}
componentDidMount() {
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
setSlidePosition = (slideBar) => {
this.setState({
slidePosition: {
left: slideBar.offsetLeft,
width: slideBar.offsetWidth,
},
});
};
handleClick = (span, section) => {
this.setSlidePosition(span);
this.setState({
selectedItem: span,
selectedCity: section,
});
};
handleResize = () => {
if (!this.state.resizing) {
this.setState({
resizing: true,
});
}
const slideBar = this.state.selectedItem;
slideBar && this.setSlidePosition(slideBar);
this.enableTransition();
};
getMenuClass = (section) => {
const { selectedCity } = this.state;
return selectedCity === section ? "selected" : "";
};
render() {
const { navigationData } = this.props;
const resizeClass = this.state.resizing ? "resizing" : "";
return (
navigationData && (
<nav className="App-navbar">
<ul className={`App-navbar-container`}>
{navigationData.map(({ label, section }) => (
<NavigationItem
label={label}
key={section}
section={section}
className={this.getMenuClass(section)}
handleClick={this.handleClick}
/>
))}
</ul>
<SlideBar
className={resizeClass}
slidePosition={this.state.slidePosition}
/>
</nav>
)
);
}
}
NavigationBar.propTypes = {
navigationData: PropTypes.array.isRequired,
};
const SlideBar = ({ slidePosition, className }) => (
<div className="App-navbar-underline-container">
<span
className={`App-navbar-underline ${className}`}
style={slidePosition}
></span>
</div>
);
export default NavigationBar;
|
import * as PropTypes from 'prop-types';
import React from 'react';
import {Text} from 'react-native-elements';
import {View} from 'react-native';
import i18n from 'i18n-js';
import Chart from 'react-apexcharts';
export default function VictoryChartPerformance({st}) {
if ((st && st.perf_hist && st.perf_hist.length === 0) || !st) {
return (
<Text style={{textAlign: 'left', fontFamily: 'Rubik_300Light'}}>
{i18n.t('player_chart_not_available')}
</Text>
);
}
const options = {
stroke: {
curve: 'straight',
width: st.perf_hist && st.perf_hist.length > 30 ? 1 : 2,
},
markers: {
size: 0,
},
chart: {
zoom: false,
toolbar: {
show: false,
},
},
annotations: {
yaxis: [
{
y: 0,
borderColor: '#00E396',
label: {
borderColor: '#00E396',
style: {
color: '#fff',
background: '#00E396',
},
text: 'ranking line',
},
},
],
},
yaxis: {
labels: {
formatter: (value) => {
return value + '';
},
},
},
xaxis: {
labels: {
show: false,
},
},
};
const series = [
{
name: 'Performance',
data: st.perf_hist.map((p) => p + ''),
},
];
return (
<View>
<Chart options={options} series={series} type="line" height={320} />
</View>
);
}
VictoryChartPerformance.propTypes = {st: PropTypes.any};
|
import React from "react"
import {
View,
Image,
ImageBackground,
TouchableOpacity,
Text,
Button,
Switch,
TextInput,
StyleSheet,
ScrollView
} from "react-native"
import Icon from "react-native-vector-icons/FontAwesome"
import { CheckBox } from "react-native-elements"
import { connect } from "react-redux"
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp
} from "react-native-responsive-screen"
import { getNavigationScreen } from "@screens"
export class Blank extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render = () => (
<ScrollView
contentContainerStyle={{ flexGrow: 1 }}
style={styles.ScrollView_1}
>
<View style={styles.View_2} />
<View style={styles.View_1242_6240} />
<View style={styles.View_1242_6241}>
<Text style={styles.Text_1242_6241}>This Month</Text>
</View>
<View style={styles.View_1242_6242}>
<View style={styles.View_1242_6243}>
<Text style={styles.Text_1242_6243}>You Earned 💰</Text>
</View>
<View style={styles.View_1242_6244}>
<View style={styles.View_1242_6245}>
<Text style={styles.Text_1242_6245}>$6000</Text>
</View>
</View>
</View>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/f774/da29/abf1fa475dab9ca75c81788aa5b0dd0a"
}}
style={styles.ImageBackground_1242_6246}
/>
<View style={styles.View_1242_6251}>
<View style={styles.View_1242_6252}>
<View style={styles.View_1242_6253}>
<Text style={styles.Text_1242_6253}>
your biggest Income is from
</Text>
</View>
<View style={styles.View_1242_6254}>
<View style={styles.View_1242_6255}>
<View style={styles.View_1242_6256}>
<View style={styles.View_1242_6257}>
<View style={styles.View_1242_6258}>
<View style={styles.View_1242_6259}>
<View style={styles.View_I1242_6259_280_6325}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/8abd/bc3a/ac5e631d7892e670c023854b52653de1"
}}
style={styles.ImageBackground_I1242_6259_280_6326}
/>
</View>
</View>
</View>
<View style={styles.View_1242_6260}>
<View style={styles.View_1242_6261}>
<Text style={styles.Text_1242_6261}>Salary</Text>
</View>
</View>
</View>
</View>
<View style={styles.View_1242_6262}>
<Text style={styles.Text_1242_6262}>$ 5000</Text>
</View>
</View>
</View>
</View>
</View>
<View style={styles.View_1242_6264}>
<View style={styles.View_I1242_6264_217_6979}>
<View style={styles.View_I1242_6264_217_6979_108_2809} />
</View>
</View>
<View style={styles.View_1242_6265}>
<View style={styles.View_I1242_6265_816_117}>
<View style={styles.View_I1242_6265_816_118}>
<Text style={styles.Text_I1242_6265_816_118}>9:41</Text>
</View>
</View>
<View style={styles.View_I1242_6265_816_119}>
<View style={styles.View_I1242_6265_816_120}>
<View style={styles.View_I1242_6265_816_121}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/42fe/75df/eee86effef9007e53d20453d65f0d730"
}}
style={styles.ImageBackground_I1242_6265_816_122}
/>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/323b/7a56/3bd8d761d4d553ed17394f5c34643bfe"
}}
style={styles.ImageBackground_I1242_6265_816_125}
/>
</View>
<View style={styles.View_I1242_6265_816_126} />
</View>
<View style={styles.View_I1242_6265_816_127}>
<View style={styles.View_I1242_6265_816_128} />
<View style={styles.View_I1242_6265_816_129} />
<View style={styles.View_I1242_6265_816_130} />
<View style={styles.View_I1242_6265_816_131} />
</View>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/2e76/21a5/ca49045f4b39546b3cfd31fde18b9385"
}}
style={styles.ImageBackground_I1242_6265_816_132}
/>
</View>
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
ScrollView_1: { backgroundColor: "rgba(255, 255, 255, 1)" },
View_2: { height: hp("111%") },
View_1242_6240: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("111%"),
minHeight: hp("111%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 168, 107, 1)"
},
View_1242_6241: {
width: wp("35%"),
minWidth: wp("35%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("33%"),
top: hp("14%"),
justifyContent: "center"
},
Text_1242_6241: {
color: "rgba(255, 255, 255, 1)",
fontSize: 19,
fontWeight: "400",
textAlign: "left",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6242: {
width: wp("91%"),
minWidth: wp("91%"),
height: hp("19%"),
minHeight: hp("19%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("37%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6243: {
width: wp("91%"),
minWidth: wp("91%"),
minHeight: hp("5%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "center"
},
Text_1242_6243: {
color: "rgba(255, 255, 255, 1)",
fontSize: 26,
fontWeight: "700",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6244: {
width: wp("91%"),
minWidth: wp("91%"),
height: hp("10%"),
minHeight: hp("10%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("9%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6245: {
width: wp("58%"),
minWidth: wp("58%"),
minHeight: hp("11%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("17%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_1242_6245: {
color: "rgba(255, 255, 255, 1)",
fontSize: 51,
fontWeight: "700",
textAlign: "left",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
ImageBackground_1242_6246: {
width: wp("93%"),
minWidth: wp("93%"),
height: hp("0%"),
minHeight: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("3%"),
top: hp("9%")
},
View_1242_6251: {
width: wp("91%"),
minWidth: wp("91%"),
height: hp("32%"),
minHeight: hp("32%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("73%"),
backgroundColor: "rgba(255, 255, 255, 1)",
overflow: "hidden"
},
View_1242_6252: {
width: wp("91%"),
minWidth: wp("91%"),
height: hp("27%"),
minHeight: hp("27%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6253: {
width: wp("61%"),
minWidth: wp("61%"),
minHeight: hp("8%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("15%"),
top: hp("0%"),
justifyContent: "center"
},
Text_1242_6253: {
color: "rgba(13, 14, 15, 1)",
fontSize: 19,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6254: {
width: wp("91%"),
minWidth: wp("91%"),
height: hp("17%"),
minHeight: hp("17%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("10%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6255: {
width: wp("91%"),
minWidth: wp("91%"),
height: hp("17%"),
minHeight: hp("17%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6256: {
width: wp("34%"),
minWidth: wp("34%"),
height: hp("9%"),
minHeight: hp("9%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("29%"),
top: hp("0%"),
backgroundColor: "rgba(252, 252, 252, 1)"
},
View_1242_6257: {
width: wp("25%"),
minWidth: wp("25%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6258: {
width: wp("9%"),
minWidth: wp("9%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(207, 250, 234, 1)"
},
View_1242_6259: {
width: wp("6%"),
minWidth: wp("6%"),
height: hp("3%"),
minHeight: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%"),
backgroundColor: "rgba(0, 0, 0, 0)",
overflow: "hidden"
},
View_I1242_6259_280_6325: {
flexGrow: 1,
width: wp("4%"),
height: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("0%")
},
ImageBackground_I1242_6259_280_6326: {
width: wp("4%"),
height: hp("3%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
View_1242_6260: {
width: wp("15%"),
minWidth: wp("15%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6261: {
width: wp("15%"),
minWidth: wp("15%"),
minHeight: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("1%"),
justifyContent: "flex-start"
},
Text_1242_6261: {
color: "rgba(13, 14, 15, 1)",
fontSize: 14,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6262: {
width: wp("33%"),
minWidth: wp("33%"),
minHeight: hp("6%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("29%"),
top: hp("10%"),
justifyContent: "flex-start"
},
Text_1242_6262: {
color: "rgba(13, 14, 15, 1)",
fontSize: 29,
fontWeight: "500",
textAlign: "right",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6264: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("5%"),
minHeight: hp("5%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("106%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I1242_6264_217_6979: {
flexGrow: 1,
width: wp("100%"),
height: hp("5%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I1242_6264_217_6979_108_2809: {
flexGrow: 1,
width: wp("36%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("32%"),
top: hp("3%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_1242_6265: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("6%"),
minHeight: hp("6%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I1242_6265_816_117: {
flexGrow: 1,
width: wp("14%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("5%"),
top: hp("2%")
},
View_I1242_6265_816_118: {
width: wp("14%"),
minWidth: wp("14%"),
minHeight: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_I1242_6265_816_118: {
color: "rgba(255, 255, 255, 1)",
fontSize: 12,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: -0.16500000655651093,
textTransform: "none"
},
View_I1242_6265_816_119: {
flexGrow: 1,
width: wp("18%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("78%"),
top: hp("2%")
},
View_I1242_6265_816_120: {
width: wp("7%"),
minWidth: wp("7%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("0%")
},
View_I1242_6265_816_121: {
width: wp("7%"),
height: hp("2%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
ImageBackground_I1242_6265_816_122: {
width: wp("6%"),
minWidth: wp("6%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%")
},
ImageBackground_I1242_6265_816_125: {
width: wp("0%"),
minWidth: wp("0%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("6%"),
top: hp("1%")
},
View_I1242_6265_816_126: {
width: wp("5%"),
minWidth: wp("5%"),
height: hp("1%"),
minHeight: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)",
borderColor: "rgba(76, 217, 100, 1)",
borderWidth: 1
},
View_I1242_6265_816_127: {
width: wp("5%"),
height: hp("1%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
View_I1242_6265_816_128: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("1%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I1242_6265_816_129: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I1242_6265_816_130: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("3%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I1242_6265_816_131: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
ImageBackground_I1242_6265_816_132: {
width: wp("4%"),
minWidth: wp("4%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("6%"),
top: hp("0%")
}
})
const mapStateToProps = state => {
return {}
}
const mapDispatchToProps = () => {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Blank)
|
/**
* @Author:hgq
* @Describe:
*/
import React, { useState, useEffect } from 'react';
import * as utils from '@/utils/utils';
const CHESS_COUNT = 20;
const initChessBox = () => {
let chessBoardInfo = [];
for (let i = 0; i < CHESS_COUNT; i++) {
chessBoardInfo[i] = [];
for (let j = 0; j < CHESS_COUNT; j++) {
chessBoardInfo[i][j] = 0;
}
}
console.log('chessBoardInfo--->', chessBoardInfo);
return chessBoardInfo;
// setChessBoardInfo(chessBoardInfo);
};
function About() {
const [chessBoard, setChessBoard] = useState(null);
const [chessBoardInfo, setChessBoardInfo] = useState(initChessBox());
const [isBlack, setIsBlack] = useState(true);
const drawChessBoard = () => {
let canvas = document.getElementById('myCanvas');
let context = canvas.getContext('2d');
context.fillRect(15, 585, 15, 585);
for (let i = 0; i < CHESS_COUNT; i++) {
context.moveTo(15 + i * 30, 15);
context.lineTo(15 + i * 30, 585);
//垂直方向画15根,相距30px
context.stroke();
context.moveTo(15, 15 + i * 30);
context.lineTo(585, 15 + i * 30);
//水平方向画15根,相距30px
context.stroke();
}
setChessBoard(context);
canvas.addEventListener('click', (e) => canvasClick(e));
};
const canvasClick = (e) => {
let x = e.offsetX;//相对于棋盘左上角的x坐标
let y = e.offsetY;//相对于棋盘左上角的y坐标
let i = Math.floor(x / 30);
let j = Math.floor(y / 30);
console.log('click', i, j, chessBoardInfo);
if (chessBoardInfo[i][j] === 0) {
drawChess(i, j, isBlack);
if (isBlack) {
chessBoardInfo[i][j] = 1;
} else {
chessBoardInfo[i][j] = 2;
}
setIsBlack(!isBlack);
}
};
// 绘制黑棋或白棋
const drawChess = (x, y, isBlack) => {
// const context = this.chessboard.getContext('2d');
console.log('chessBoard--->', chessBoard);
// let gradient = chessBoard.createRadialGradient(x, y, 10, x - 5, y - 5, 0);
// chessBoard.beginPath();
// chessBoard.arc(x, y, 10, 0, 2 * Math.PI);
// chessBoard.closePath();
// if (isBlack) {
// gradient.addColorStop(0, '#0a0a0a');
// gradient.addColorStop(1, '#636766');
// } else {
// gradient.addColorStop(0, '#d1d1d1');
// gradient.addColorStop(1, '#f9f9f9');
// }
// chessBoard.fillStyle = gradient;
// chessBoard.fill();
};
useEffect(() => {
initChessBox();
drawChessBoard();
}, []);
return (
<div>
<canvas id="myCanvas" width="600px" height="600px"/>
</div>
);
}
export default About;
|
"use strict";
let assert = require("assert");
let fixture = require("z-fixture-loader");
describe ("When get business from business api", function(){
before(function(done){
fixture.loadFixturesToElasticsearch(function(error){
if(error) done(error);
done()
});
});
it("should return 1 business ",function(){
assert(true);
});
});
|
const { Router } = require('express');
const PartnerModel = require('../db/models/partnerModel');
const router = Router();
router.get('/', async (req, res) => {
const partners = await PartnerModel.find();
res.render('partners', { partners });
});
module.exports = router;
|
import {
EVENT_NAME,
EVENT_IMAGE,
EVENT_PRICE,
EVENT_QUANTITY,
EVENT_PAYMENT,
EVENT_PRODUCT_TYPE,
EVENT_AVAILIBLE_CITY,
EVENT_NEW_CITY,
EVENT_PRODUCT_LIST
} from "./action";
import { initialState} from "./store";
export function reducer(state = initialState, action) {
switch (action.type) {
case EVENT_NAME:
return {
...state,
name: action.payload
};
case EVENT_IMAGE:
return {
...state,
image: action.payload
};
case EVENT_PRICE:
return {
...state,
price: action.payload
};
case EVENT_QUANTITY:
return {
...state,
quantity: action.payload
};
case EVENT_PAYMENT:
return {
...state,
payment: action.payload
};
case EVENT_PRODUCT_TYPE:
return {
...state,
productType: action.payload
};
case EVENT_AVAILIBLE_CITY:
return {
...state,
available: action.payload
};
case EVENT_NEW_CITY:
return {
...state,
city: action.payload
};
case EVENT_PRODUCT_LIST:
return {
...state,
data: action.payload
};
default:
return state;
}
}
|
import React from 'react'
import { Divider } from 'react-native-elements'
import { MaterialCommunityIcons } from '@expo/vector-icons'
import { Text, View, SafeAreaView, TouchableOpacity, ScrollView, StyleSheet, Image, Linking } from 'react-native'
import CustomHeader from '../CustomHeader'
let laCpasule =
<Text
style={{color: '#9400d3'}}
onPress={() => Linking.openURL('https://www.lacapsule.academy/')}>
La Capsule
</Text>
let galLaf =
<Text
style={{color: '#9400d3'}}
onPress={() => Linking.openURL('https://www.groupegalerieslafayette.fr/')}>
Galeries Lafayette
</Text>
let sap =
<Text
style={{color: '#9400d3'}}
onPress={() => Linking.openURL('https://www.servicesalapersonne.gouv.fr/')}>
Services à la personne
</Text>
let matmut =
<Text
style={{color: '#9400d3'}}
onPress={() => Linking.openURL('https://www.matmut.fr/')}>
Matmut
</Text>
let starbx =
<Text
style={{color: '#9400d3'}}
onPress={() => Linking.openURL('https://www.starbucks.fr/')}>
Starbucks Coffee
</Text>
let sodistrel =
<Text
style={{color: '#9400d3'}}
onPress={() => Linking.openURL('http://sodistrel.com/')}>
Sodistrel
</Text>
const goToTop = () => {
scroll.scrollTo({x: 0, y: 0, animated: true});
}
function JobsScreenDetail({navigation}) {
const br = `\n`
return (
<SafeAreaView style={{ flex: 1, marginTop: 10 }}>
<CustomHeader title='Jobs Detail' navigation={navigation}/>
<View style={styles.container}>
<View style={styles.must}>
<View style={{alignSelf: 'center', marginBottom: 10}}>
<Text style={{fontWeight: 'bold', fontStyle: 'italic', fontSize: 20, textDecorationLine: 'underline'}}>LES ENTREPRISES</Text>
</View>
<ScrollView ref={(c) => {scroll = c}}>
<Text style={styles.vert}>
<Image
style={{width: 60, height: 60}}
source={require('../assets/images/lacapsule.png')}
/>
{br}
{br}
{br}
<Text>
La Capsule est une école de code pour les entrepreneurs et les Digital Makers qui souhaitent apprendre à coder une appli Web ou Mobile.
{br}
{br}
En 10 semaines, l’objectif est de donner aux gens les briques techniques nécessaires pour prototyper, coder et piloter une appli Web ou Mobile et les rendre autonomes techniquement. A La Capsule, nous avons à cœur d’offrir à nos élèves une parenthèse de vie, une expérience pédagogique et humaine unique et riche!
{br}
{br}
L’école est née en 2016, cofondée par Marlene ANTOINAT et Noel PAGANELLI portés par la conviction qu’un virage digital majeur est en route et par l’envie de faire grandir les gens grâce à l’apprentissage du code.
L’école possède aujourd’hui 2 campus à Paris et à Lyon.
{br}
{br}
<Text>Site internet : {laCpasule}</Text>
</Text>
{br}
{br}
<Divider style={{ backgroundColor: 'black', width: 330, height: 1 }} />
<Image
style={{width: 60, height: 60}}
source={require('../assets/images/rqz.png')}
/>
{br}
{br}
{br}
<Text>
Spécialiste de la mode implanté au cœur des villes, le groupe Galeries Lafayette se développe comme une référence du commerce omnicanal. Il contribue, en France et dans le monde, à faire rayonner un certain Art de Vivre à la française à travers toutes ses marques.
{br}
{br}
Fort de son patrimoine architectural et d’une solide culture de l’innovation, le groupe Galeries Lafayette accueille chaque année plus de 60 millions de visiteurs dans 290 magasins et sur ses sites e-commerce. Il entretient un lien historique et affectif avec ses clients qui continue à vivre sur tous ses points de rencontre, physiques ou digitaux, pour leur offrir le meilleur du commerce et de la création.
{br}
{br}
Le Groupe bénéficie aujourd’hui d’une reconnaissance internationale reposant sur des marques emblématiques : Galeries Lafayette, BHV MARAIS, La Redoute, Eataly Paris Marais, Galeries Lafayette-Royal Quartz Paris, Louis Pion, Mauboussin et BazarChic. Il accompagne la transformation patrimoniale, digitale et créative de celles-ci avec le concours de Citynove, Lafayette Plug and Play et Lafayette Anticipations - Fondation d’entreprise Galeries Lafayette.
{br}
{br}
<Text>Site internet : {galLaf}</Text>
</Text>
{br}
{br}
<Divider style={{ backgroundColor: 'black', width: 330, height: 1 }} />
<Image
style={{width: 60, height: 60}}
source={require('../assets/images/sap.png')}
/>
{br}
{br}
{br}
<Text>
Les services à la personne englobent diverses prestations fournies à domicile et répondant à un besoin à caractère social.
{br}
{br}
Les activités de services à la personne peuvent être exercées librement, à l’exception des activités destinées aux publics fragiles (jeunes enfants, personnes âgées ou handicapées) qui nécessitent parfois un agrément.
{br}
{br}
Pour bénéficier des avantages sociaux et fiscaux, les organismes de services à la personne, qu’ils soient ou non agréés, doivent faire l’objet d’une déclaration d’activité, les contraignant à respecter certaines règles. Une décision de retrait de déclaration peut être prononcée en cas de non-respect de celles-ci, entraînant la radiation de l’organisme, notamment de l’annuaire des organismes de services à la personne.
{br}
{br}
<Text>Site internet : {sap}</Text>
</Text>
{br}
{br}
<Divider style={{ backgroundColor: 'black', width: 330, height: 1 }} />
<Image
style={{width: 60, height: 60}}
source={require('../assets/images/matmut.png')}
/>
{br}
{br}
{br}
<Text>
La Matmut est une société d'assurance mutuelle, chargée de la stratégie du Groupe et des fonctions centrales. Elle possède toutes les filiales opérationnelles d'assurance et apporte également aux assurés des prestations en matière de protection juridique vie privée et d'assistance. Enfin elle conçoit, gère et distribue les contrats d'assurance « dommages » pour les particuliers.
{br}
{br}
Créée en 1961, la Matmut est au service de ses sociétaires. Acteur majeur sur le marché français, le Groupe Matmut assure aujourd'hui près de 3,8 millions de sociétaires et plus de 7,2 millions de contrats.
{br}
{br}
Il offre à tous - particuliers, professionnels, entreprises, associations - une gamme complète de produits d'assurance des biens et des personnes (auto, moto, habitation, bateau, chasse, responsabilités, protection de la famille, santé, prévoyance, protection juridique, assistance) et de services financiers et d'épargne (crédits auto, crédit consommation, livret d'épargne, assurance-vie, assurance emprunteur...).
{br}
{br}
<Text>Site internet : {matmut}</Text>
</Text>
{br}
{br}
<Divider style={{ backgroundColor: 'black', width: 330, height: 1 }} />
<Image
style={{width: 60, height: 60}}
source={require('../assets/images/star.png')}
/>
{br}
{br}
{br}
<Text>
Starbucks Corporation est une chaîne de cafés américaine fondée en 1971. En partie en franchise[réf. nécessaire], il s'agit de la plus grande chaîne de ce genre dans le monde, avec 310 256 établissements implantés dans 78 pays, dont 12 000 aux États-Unis.
{br}
{br}
Les établissements Starbucks vendent exclusivement leur propre marque de café (moulu ou en grains), du thé, des boissons, des pâtisseries, des ustensiles et des machines à café, mais l'entreprise vise principalement à « offrir une expérience-consommateur » (deliver consumer experience en anglais), c’est-à-dire de proposer à sa clientèle un service unique qu’elle ne retrouvera pas dans les cafés d’une autre enseigne (confort, calme,…).
{br}
{br}
Starbucks Coffee Company est à l'origine un commerce spécialisé dans le café en grains. L'entreprise est officiellement devenue Starbucks Corporation en 1987 après son acquisition par Howard Schultz2, tout en continuant à communiquer sous le nom de Starbucks Coffee Company.
{br}
{br}
<Text>Site internet : {starbx}</Text>
</Text>
{br}
{br}
<Divider style={{ backgroundColor: 'black', width: 330, height: 1 }} />
<Image
style={{width: 60, height: 60}}
source={require('../assets/images/sodi.png')}
/>
{br}
{br}
{br}
<Text>
Sodistrel est une PME spécialisée dans l’identification et la traçabilité dans les activités industrielles. Pour l’impression des étiquettes, le transfert thermique est la solution optimale pour résister aux contraintes pointues des clients (UV, solvants, normes aéronautiques, températures, humidité…). Notre expertise dans le domaine de l’étiquette technique nous permet de répondre aux cahiers des charges les plus exigeants.
{br}
{br}
Depuis 40 ans, Sodistrel distribue et innove dans l'impression d'étiquettes techniques et solutions d'impressions pour l'industrie
{br}
{br}
Sodistrel est fort de sa présence sur des marchés diversifiés : aéronautique (civil et militaire), spatial, défense & sécurité, ferroviaire, médical, pétrochimie, électrique et Datacom, Telecom.
{br}
{br}
<Text>Site internet : {sodistrel}</Text>
</Text>
</Text>
<Divider style={{ backgroundColor: 'black', width: 330, height: 1 }} />
<Text>{br}</Text>
<Text onPress={goToTop}>
<MaterialCommunityIcons name='chevron-up-circle' color='#9400d3' size={18} /> Retour vers le haut de la page
</Text>
<View style={{marginBottom: 50, alignItems: 'center'}}>
<TouchableOpacity
style={{
marginTop: 15,
paddingTop: 15,
paddingBottom: 15,
marginLeft: 30,
marginRight: 30,
backgroundColor: '#ffff ',
borderRadius: 50,
borderWidth: 2,
borderColor: '#9400d3',
width: 170,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
}}
onPress={goToTop}
>
<MaterialCommunityIcons name='chevron-up' color='#9400d3' size={23} />
<Text style={{ color: '#9400d3', fontWeight: 'bold' }}> RETOUR EN HAUT</Text>
</TouchableOpacity>
</View>
</ScrollView>
</View>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#0000'
},
must: {
marginHorizontal: 20,
},
vert: {
textAlign: 'justify'
}
})
export default JobsScreenDetail
|
(function() {
'use strict';
// Feature detect
if (!(window.customElements && document.body.attachShadow)) {
document.querySelector('tl-etherlynk').innerHTML = "<b>Your browser doesn't support Shadow DOM and Custom Elements v1.</b>";
return;
}
customElements.define('tl-etherlynk', class extends HTMLElement {
constructor() {
super(); // always call super() first in the ctor.
// Create shadow DOM for the component.
let shadowRoot = this.attachShadow({mode: 'open'});
//The following array is like this ... [midinumber,color,buttontitle]
this.buttonmap=[
[null],
[56,null],[57,null],[58,null],[59,null],[60,null],[61,null],[62,null],[63,null], [82,null],
[48,null],[49,null],[50,null],[51,null],[52,null],[53,null],[54,null],[55,null], [83,null],
[40,null],[41,null],[42,null],[43,null],[44,null],[45,null],[46,null],[47,null], [84,null],
[32,null],[33,null],[34,null],[35,null],[36,null],[37,null],[38,null],[39,null], [85,null],
[24,null],[25,null],[26,null],[27,null],[28,null],[29,null],[30,null],[31,null], [86,null],
[16,null],[17,null],[18,null],[19,null],[20,null],[21,null],[22,null],[23,null], [87,null],
[8,null] ,[9,null] ,[10,null],[11,null],[12,null],[13,null],[14,null],[15,null], [88,null],
[0,null] ,[1,null] ,[2,null] ,[3,null] ,[4,null] ,[5,null] ,[6,null] ,[7,null] , [89,null],
[64,null],[65,null],[66,null],[67,null],[68,null],[69,null],[70,null],[71,null], [98,null]
]
this.slidermap = {48:0,49:1,50:2,51:3,52:4,53:5,54:6,55:7,56:8}
this.timeout={}
this.timeoutval = 500;
this.midienabled = true;
this.defaultbuttonmap = this.buttonmap.slice(0);
this.buttonSlot;
shadowRoot.innerHTML = `
<style>
:host {
display: block;
width: 780px;
height:580px;
overflow:hidden;
font-family: 'helvetica';
contain: content;
background-color: #656565;
padding:10px;
border-radius:10px;
background-repeat: no-repeat;
background-position: 762px 567px;
background-size: 33px 27px;
}
.but{
height:40px;
width:75px;
float:left;
border-radius:5px;
margin:4px;
position:relative;
font-family: 'helvetica';
// font-weight:bold;
font-size: 14px;
box-sizing: border-box;
// overflow:hidden;
// white-space: nowrap;
// text-overflow: ellipsis;
}
.round{
position:relative;
height:40px;
width:40px;
border-radius:50%;
margin-left:15px;
margin-right:40px;
overflow:visible;
}
.round label{
display:block;
position:absolute;
top:9px;
left:40px;
// white-space: nowrap;
width:70px;
text-align:left;
color:#fff;
}
.bot{
margin:15px 18px 14px 25px;
}
.bot label{
display:block;
position:absolute;
top:40px;
left:-13px;
text-align:center;
white-space: normal;
color:#fff;
}
.square{
border-radius:5px;
margin: 15px 0 0 16px;
}
.red{
background-color:red;
color:#fff;
}
.green{
background-color:green;
color:#fff;
}
.yellow{
background-color:orange;
// color:#fff;
}
.greenflash{
background-color: green;
color: #fff;
animation: backgroundblinker .5s step-end infinite alternate;
-webkit-animation: backgroundblinker .5s step-end infinite alternate;
}
.redflash{
background-color: red;
color: black;
animation: backgroundblinker .5s step-end infinite alternate;
-webkit-animation: backgroundblinker .5s step-end infinite alternate;
}
.yellowflash{
background-color: orange;
color: black;
animation: backgroundblinker .5s step-end infinite alternate;
-webkit-animation: backgroundblinker .5s step-end infinite alternate;
}
@-webkit-keyframes backgroundblinker {
// 50% { background-color: transparent; }
50% { background-color: #DDD; color:black;}
}
@keyframes backgroundblinker {
// 50% { background-color: transparent; }
50% { background-color: #DDD; color:black;}
}
#sliders{
// border:solid red 1px;
width:800px;
margin-top:475px;
margin-left:10px;
}
input[type=range].vertical
{
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
width: 72px;
height: 100px;
padding: 0px;
margin:0 6px 0 0;
}
.notifyindicator{
position:absolute;
width:13px;
height:13px;
color:#ffffff;
font-size:10px;
overflow:hidden;
padding:2px;
line-height:11px;
top:-7px;
right:-7px;
border:solid 1px #c00606;
border-radius:50%;
background-color:red;
}
.hidden{
display:none;
}
</style>
<div id="buttonSlot"></div>
<div id="sliders">
<label for="slider1"></label><input id="slider1" mid="48" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider2"></label><input id="slider2" mid="49" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider3"></label><input id="slider3" mid="50" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider4"></label><input id="slider4" mid="51" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider5"></label><input id="slider5" mid="52" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider6"></label><input id="slider6" mid="53" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider7"></label><input id="slider7" mid="54" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider8"></label><input id="slider8" mid="55" type="range" min="0" max="128" value="0" class="vertical">
<label for="slider9"></label><input id="slider8" mid="56" type="range" min="0" max="128" value="0" class="vertical">
</div>
`;
}
set data(data){
this.buttonmap=data
this._updateshaddowdom()
}
get data(){
return this.buttonmap;
}
setbutton(data){
var index = this.buttonmap.findIndex(x => x[0]==data[0]);
this.buttonmap[index]=data
this._updateshaddowdom()
}
connectedCallback() {
if(this.midienabled==true){
Tletherlynk.Midi.init()
}
this.buttonSlot = this.shadowRoot.querySelector('#buttonSlot');
this.sliders = this.shadowRoot.querySelector('#sliders').getElementsByTagName("input")
this.test = this.getAttribute('name');
this.buttonSlot.addEventListener("mousedown", this._onclickbuttondown.bind(this), true);
this.buttonSlot.addEventListener("mouseup", this._onclickbuttonup.bind(this), true);
for (var i = 0; i < this.sliders.length; i++) {
this.sliders[i].addEventListener("input", function(e){
_this._broadcastevent(176,e.path[0].getAttribute("mid"),e.path[0].value)
});
this.sliders[i].addEventListener("wheel", function(e){
console.log("wheel",e.deltaY)
if(e.deltaY>0){
this.value-=10;
}else{
this.value-=-10;
}
_this._broadcastevent(176,e.path[0].getAttribute("mid"),e.path[0].value)
},{
capture: true,
passive: true
});
};
var _this=this;
document.body.addEventListener('webmidievent', function (e) {
if(_this.midienabled==true){
// console.info('webmidievent recieved',e.detail)
_this._broadcastevent(e.detail.data1,e.detail.data2,e.detail.data3)
switch (e.detail.data1 & 0xf0) {
case 144:
//Note On
if (e.detail.data2!=0) { // if velocity != 0, this is a note-on message
// console.log("midi call back button= ",midiassignmentmap.pads[e.detail.data2])
return;
}
case 128:
//Note off
//console.log("note off = ",e.detail.data2)
return;
case 176:
//cc value
// console.log("midi knob= ",e.detail.data2)
_this.sliders[_this.slidermap[e.detail.data2]].value=e.detail.data3;
return;
}
}
}, false);
setTimeout(function(){
_this._updateshaddowdom()
},100);
}
_updateshaddowdom(){
this.buttonSlot.innerHTML=""
for (var i = 1; i < 82; i++) {
var contactbut = document.createElement('button');
var label = document.createElement('label');
var notify = document.createElement('div');
if(i==81){
contactbut.className = "but round square"
}
else if(i>72){
contactbut.className = "but round bot"
if(this.buttonmap[i][1]=="redflash"){
colorcode="00";
}
}
else{
if(i % 9===0){
contactbut.className = "but round"
}
else{
contactbut.className = "but"
}
}
if(this.buttonmap[i][2]!=undefined){
contactbut.className = contactbut.className+" "+ this.buttonmap[i][1]
}
contactbut.id = "but"+i;
if(this.buttonmap[i][2]!=undefined){
label.innerHTML = this.buttonmap[i][2]
}
else{
//show numbers
// label.innerHTML = this.buttonmap[i][0]
}
if(this.buttonmap[i][3]!=undefined){
notify.className="notifyindicator"
notify.innerHTML = this.buttonmap[i][3]
}else{
notify.className="notifyindicator hidden"
notify.innerHTML=" "
}
label.setAttribute('uid', this.buttonmap[i][0]);
contactbut.setAttribute('uid', this.buttonmap[i][0]);
this.buttonSlot.appendChild(contactbut)
contactbut.appendChild(label)
contactbut.appendChild(notify)
//set midilights here
if(this.buttonmap[i][1]!=undefined){
var colorcode;
switch(this.buttonmap[i][1]) {
case "red":
colorcode="03";
break;
case "green":
colorcode="01";
break;
case "yellow":
colorcode="05";
break;
case "redflash":
colorcode="04";
break;
case "greenflash":
colorcode="02";
break;
case "yellowflash":
colorcode="06";
break;
default:
//off
colorcode="00";
}
//overide for round red buts
if(i>72){
if(this.buttonmap[i][1]=="redflash"){
colorcode="02";
}
}
if(this.midienabled==true){
Tletherlynk.Midi.sendlight("144",this.buttonmap[i][0],colorcode)
}
}else{
if(this.midienabled==true){
if(i==1){
console.log("1")
Tletherlynk.Midi.sendlight("144","56","00")
}
Tletherlynk.Midi.sendlight("144",this.buttonmap[i][0],"00")
}
}
}
// this.buttonSlot.addEventListener("mousedown", this._onclickbuttondown.bind(this), true);
// this.buttonSlot.addEventListener("mouseup", this._onclickbuttonup.bind(this), true);
}
_onclickbuttondown(e){
var userclicked = e.path[0].getAttribute("uid")
console.info("Clicked > ",userclicked,e)
this._broadcastevent(144,userclicked,127)
}
_onclickbuttonup(e){
var userclicked = e.path[0].getAttribute("uid")
console.info("Clicked > ",userclicked)
this._broadcastevent(128,userclicked,127)
}
resetlights(){
// reset midi lights
for (var i = 1; i < 82; i++) {
if(this.midienabled==true){
Tletherlynk.Midi.sendlight("144",this.buttonmap[i][0],"00");
}
}
}
loaddefaults(){
this.buttonmap = this.defaultbuttonmap.slice(0)
this._updateshaddowdom()
}
_broadcastevent(data1,data2,data3){
var etherlynkuievent = new CustomEvent('etherlynk.ui.event', { 'detail': {'data1':parseInt(data1), 'data2':parseInt(data2), 'data3':parseInt(data3)} });
document.body.dispatchEvent(etherlynkuievent);
//test for key held
if(parseInt(data1)==144){
var etherlynkeventbuttondown = new CustomEvent('etherlynk.event.buttondown', { 'detail': {'button':parseInt(data2)} });
document.body.dispatchEvent(etherlynkeventbuttondown);
this.timeout[parseInt(data2)] = setTimeout(function(){
// console.log("Button held",parseInt(data2))
var etherlynkeventheld = new CustomEvent('etherlynk.event.held', { 'detail': {'button':parseInt(data2)} });
document.body.dispatchEvent(etherlynkeventheld);
}, this.timeoutval);
}
if(parseInt(data1)==128){
clearTimeout(this.timeout[parseInt(data2)])
var etherlynkeventbuttonup = new CustomEvent('etherlynk.event.buttonup', { 'detail': {'button':parseInt(data2)} });
document.body.dispatchEvent(etherlynkeventbuttonup);
};
}
});
})();
|
app.constant('API_URL', 'http://localhost:3000/');
app.constant('BASE_URL', 'http://localhost:5000/');
|
'use strict';
var watchMenu = function($timeout, $ionicSideMenuDelegate) {
function link(scope) {
$timeout(function() {
scope.$watch(function() {
return $ionicSideMenuDelegate.getOpenRatio();
}, function(ratio) {
scope.data = ratio;
scope.ratio = (ratio >= 0.5);
});
});
}
var directive = {
link: link,
restrict: 'A'
};
return directive;
};
angular.module('arcanine.directives').directive('watchMenu', watchMenu);
|
define([
// Defaults
"jquery",
"angular",
"angularSanitize",
"jqueryUI",
"blueimpUpload"
], function($){
"use strict";
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
// ------------------------------------------------------------------------
var App = {
MainApp : void 0,
init: function(MainApp) {
this.MainApp = MainApp;
// ------------------------------------------------------------------------
// Module
// ------------------------------------------------------------------------
MainApp.keepoApp.controller('signupModule', ['$scope', '$element', '$http', 'accessToken',
function($scope, $element, $http, accessToken) {
$scope.message = {
text: void 0,
note: void 0
};
$scope.step = void 0;
$scope.previous = false;
$scope.validating = false;
$scope.data = {
username: void 0,
email: void 0,
password: void 0,
confirmed: void 0,
dob: void 0,
photo: void 0
};
$scope.imageFilename = void 0;
$scope.imageDataURI = void 0;
$scope.processing = {
preComplete: false,
complete: false,
postComplete: false
};
$scope.typeDateSupported = Modernizr.inputtypes.date ? 'date' : 'text';
var messages = {
'username': {
text: 'Adek mau daftar pake username apa?',
note: 'Min 5 karakter, max 15 karakter, tanpa spasi dan ngga boleh pakai tanda baca (@#!:") ya!'
},
'email': {
text: 'Emailnya dik?',
note: ''
},
'password': {
text: 'Masukin passwordnya dik!',
note: 'no spasi ya! minimal 6 karakter, max 11 karakter'
},
'confirm-password': {
text: 'Coba ulangi lagi passwordnya!',
note: ''
},
'birthday': {
text: 'Tanggal lahir adek?',
note: ''
},
'photo': {
text: 'Senyum, lihat kamera dulu ya dik! Bapak mau ambil potonya!',
note: ''
},
'almost-there': {
text: 'Bentar ya dik. Bapak buatkan dokumennya dulu',
note: ''
}
};
// ------------------------------------------------------------------------
$scope.runStep = function() {
// Check current step to determine next step (simplest way...to lazy to make it advanced one ¯\_(ツ)_/¯)
switch ($scope.step) {
case 'username':
$scope.step = 'email';
$scope.previous = true;
break;
case 'email':
$scope.step = 'password';
break;
case 'password':
$scope.step = 'confirm-password';
break;
case 'confirm-password':
$scope.step = 'birthday';
break;
case 'birthday':
$scope.step = 'photo';
break;
case 'photo':
var nDate, nMonth, tmpDate;
if (Modernizr.inputtypes.date)
{ tmpDate = $scope.data.dob; }
else {
tmpDate = $scope.data.dob.split('/');
tmpDate = new Date(tmpDate[2], (tmpDate[1] - 1), tmpDate[0]);
}
nDate = ((tmpDate.getDate() < 10) ? '0' : '') + tmpDate.getDate(),
nMonth = (((tmpDate.getMonth() + 1) < 10) ? '0' : '') + (tmpDate.getMonth() + 1);
// set dob and temp pass (masked it with *)
$scope.tempDOB = nDate + '/' + nMonth + '/' + tmpDate.getFullYear();
$scope.tempPass = $scope.data.password.replace(/./g, '*');
$scope.processing.complete = true;
$scope.step = 'almost-there';
break;
default:
$scope.step = 'username';
$scope.processing = {
preComplete: false,
complete: false,
postComplete: false
};
break;
};
// Set message
$scope.message = messages[$scope.step];
};
$scope.nextStep = function($event, button) {
var button = button || false;
if ($scope.validating) { return false; }
// reset message warning
$scope.message.warning = void 0;
// Key Enter?
if (!button && $event.keyCode == 13) {
this._validate();
return;
}
// Button?
if (button) {
this._validate();
return;
}
};
$scope.prevStep = function($event) {
// Check current step to determine prev step (simplest way...to lazy to make it advanced one ¯\_(ツ)_/¯)
switch ($scope.step) {
case 'email':
$scope.step = 'username';
$scope.previous = false;
$scope.processing = {
preComplete: false,
complete: false,
postComplete: false
};
break;
case 'password':
$scope.step = 'email';
break;
case 'confirm-password':
$scope.step = 'password';
break;
case 'birthday':
$scope.step = 'confirm-password';
break;
case 'photo':
$scope.step = 'birthday';
break;
case 'almost-there':
$scope.processing = {
preComplete: false,
complete: false,
postComplete: false
};
$scope.step = 'photo';
break;
default:
break;
};
// Set message
$scope.message = messages[$scope.step];
};
$scope.process = function() {
$scope.processing = {
preComplete: false,
complete: false,
postComplete: true
};
// ------------------------------------------------------------------------
// Start upload file
if ($scope.imageFilename)
{ $('#upload').trigger('click'); }
else { $scope.completing(); }
};
$scope.completing = function(uploadResult) {
var prepData = angular.copy($scope.data),
tmpDate;
// Set DOB to Y-m-d format
if (! Modernizr.inputtypes.date) {
tmpDate = $scope.data.dob.split('/');
prepData.dob = new Date(tmpDate[2], (tmpDate[1] - 1), tmpDate[0]);
}
prepData.birthday = prepData.dob.getFromFormat('yyyy-mm-dd');
// Set to server
$.post(MainApp.baseURL + 'api/v1/auth/register', prepData).
done(function(response) {
console.log('Great!!! Let\'s redirect the page shall we :)');
window.location.href = MainApp.baseURL;
}).
fail(function(response) {
$scope.processing = {
preComplete: false,
complete: true,
postComplete: false
};
$scope.popuperror = 1;
$scope.errormsg = 'Maaf dek, proses registrasi gagal karena ada problem di server. Coba registrasi ulang dong!';
$scope.$apply();
});
};
// ------------------------------------------------------------------------
$scope._validate = function() {
$scope.validating = true;
// Username validation
if ($scope.step == 'username') {
if (! $scope.data.username) {
$scope.message = {
text: 'Ngantuk ya dik, usernamenya salah atuh?',
note: void 0,
warning: true
}
$scope.validating = false;
return;
}
if(! (/^(([a-zA-Z0-9]){5,15})$/g).test($scope.data.username)) {
$scope.message = {
text: 'yee... kan sudah dibilangin ngga boleh pake tanda baca dan tanpa spasi.',
note: void 0,
warning: true
};
$scope.validating = false;
return;
}
// Check if username already exists?
this._isAvailable(
// Success
function() {
$scope.validating = false;
$scope.runStep();
},
// Failed
function() {
$scope.message = {
text: 'Username ini sudah terpakai dik. Coba cari yang lain deh.',
note: void 0,
warning: true
};
$scope.validating = false;
}
);
return false;
}
// Email validation
if ($scope.step == 'email') {
if (! (/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i).test($scope.data.email)) {
$scope.message = {
text: 'Ngantuk ya dik, emailnya salah atuh?',
note: void 0,
warning: true
}
$scope.validating = false;
return;
}
// Check if username already exists?
this._isAvailable(
// Success
function() {
$scope.validating = false;
$scope.runStep();
},
// Failed
function() {
$scope.message = {
text: 'Emailnya sudah pernah kedaftar. Coba ganti yang lain deh!',
note: void 0,
warning: true
};
$scope.validating = false;
}
);
return false;
}
// Password validation
if ($scope.step == 'password') {
if (! $scope.data.password) {
$scope.message = {
text: 'Ngantuk ya dik, usernamenya salah atuh?',
note: void 0,
warning: true
}
$scope.validating = false;
return;
}
if (! (/^([^\s]){6,11}$/g).test($scope.data.password)) {
$scope.message = {
text: 'Minimal 6 karakter, max 11 karakter dan ngga boleh pake spasi!',
note: void 0,
warning: true
};
$scope.validating = false;
return;
}
$scope.validating = false;
$scope.runStep();
return false;
}
// Confirm Password validation
if ($scope.step == 'confirm-password') {
if ($scope.data.confirm != $scope.data.password) {
$scope.message = {
text: 'Lah kok ngga sama? Ulangi lagi deh',
note: void 0,
warning: true
};
$scope.validating = false;
return;
}
$scope.validating = false;
$scope.runStep();
return false;
}
// DOB Validation
if ($scope.step == 'birthday') {
var errorMessage = {
text: 'Ngawur tanggalnya!',
note: void 0,
warning: true
}, nDate, today = new Date();
if (Modernizr.inputtypes.date) {
nDate = $scope.data.dob || new Date('invalid date');
} else {
if (! (/^([0-9]{2}\/[0-9]{2}\/[0-9]{4})$/g).test($scope.data.dob)) {
$scope.message = errorMessage;
$scope.validating = false;
return;
}
nDate = $scope.data.dob.split('/');
nDate = new Date(nDate[2], nDate[1], nDate[0]);
}
if (nDate == 'Invalid Date') {
$scope.message = errorMessage;
$scope.validating = false;
return;
}
// Check the year, seriously check the year...sometimes user is really dump ಠ_ಠ
if (nDate.getFullYear() > today.getFullYear()) {
$scope.message = errorMessage;
$scope.validating = false;
return;
}
$scope.validating = false;
$scope.runStep();
return false;
}
// Photo Validation
if ($scope.step == 'photo') {
$scope.validating = false;
$scope.runStep();
return false;
}
};
$scope._isAvailable = function(success, failed) {
var url = MainApp.baseURL + 'api/v1/is-available?check=' + $scope.step + '&value=' + $scope.data[$scope.step];
// Set message
$scope.message = {
text: 'Bentar ya dik, Bapak periksa dulu',
note: void 0
}
return accessToken.get().then(
function (token) {
// token received, now get the data
return $http.get(url, token).then(
function (response) {
success();
},
function (response) {
failed();
}
);
}
);
};
$scope._setTodayDate = function() {
var today = new Date(),
date = today.getDate(),
month = today.getMonth() + 1,
year = today.getFullYear();
if (date < 10) { date = '0' + date; }
if (month < 10) { month = '0' + month; }
};
$scope._initFileUpload = function($element, options) {
var self = this,
options = options || {},
fileUploadOptions;
if (! $element.length) { return false; }
// ------------------------------------------------------------------------
fileUploadOptions = {
url: MainApp.baseURL + 'api/v1/asset/img',
autoUpload: false,
dropZone: void 0,
add: function(e, data) {
var that = $(this).data('blueimpUIFileupload'),
options = that.options,
files = data.files;
// Validation
// ------------------------------------------------------------------------
that._adjustMaxNumberOfFiles(-files.length);
data.isAdjusted = true;
data.files.valid = data.isValidated = that._validate(files);
if (! data.files.valid){
that._showError(data.files);
return false;
}
// DOM manipulation
// ------------------------------------------------------------------------
var reader = new FileReader();
reader.onload = function() {
$scope.imageDataURI = reader.result;
$scope.$apply();
};
$scope.imageFilename = files[0].name;
reader.readAsDataURL(files[0]);
$('#upload').one('click', function(e) {
e.preventDefault();
data.submit();
});
},
done: function(e, data) {
// On result
// ------------------------------------------------------------------------
if (data.result.error) {
data.errorThrown = data.result.error;
that._trigger('fail', e, data);
} else {
$scope.data.photo = data.result.id;
$scope.$apply();
$scope.completing();
}
},
fail: function(e, data) {
// Back to step photo
$scope.step = 'photo';
$scope.message = {
text: data.errorThrown,
note: void 0,
warning: true
};
$scope.processing = {
preComplete: false,
complete: false,
postComplete: false
};
$scope.$apply();
},
progress: function(e, data) {
return;
}
};
fileUploadOptions = $.extend(fileUploadOptions, options);
$element.fileupload(fileUploadOptions);
};
// ------------------------------------------------------------------------
var initialize = function (token) {
// Set AJAX globally
$.ajaxSetup({
//headers: { 'Authorization': token.token_type + ' ' + token.access_token }
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', token.token_type + ' ' + token.access_token);
}
});
}
// Check access token
if (window.localStorage.token == undefined) {
$.post(self.MainApp.baseURL + 'oauth/access_token', {
'grant_type': 'client_credentials',
'client_id': 'vkw86HQQ43Qhlf4NQRJLuzd',
'client_secret': 'md6qdfnQoXFg7fIlqWWJBqAxdnjFdFx'
}).then(function (response) {
window.localStorage.token = JSON.stringify(response);
initialize(response);
});
} else {
initialize(JSON.parse(window.localStorage.token));
}
// Init fileupload
$scope._initFileUpload($('#upload-images'));
// Start step
$scope.runStep();
}]);
// ------------------------------------------------------------------------
this.MainApp.keepoApp.config([
'$compileProvider', '$interpolateProvider', '$sceProvider', '$httpProvider',
function ($compileProvider, $interpolateProvider, $sceProvider, $httpProvider) {
// whitelist href content
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|javascript):/);
// disable debug info
$compileProvider.debugInfoEnabled(true);
// change binding notation
$interpolateProvider.startSymbol('<@');
$interpolateProvider.endSymbol('@>');
// disable SCE
$sceProvider.enabled(false);
// Set Authorization
if (window.localStorage.token) {
var temp = JSON.parse(window.localStorage.token);
$httpProvider.defaults.headers.common = {
'Authorization': temp.token_type + ' ' + temp.access_token
};
}
}
]);
MainApp.keepoApp.run();
angular.bootstrap(document.querySelector("html"), ["keepoApp"]);
}
};
return App;
});
|
const busMariposasController={};
busMariposasController.list = (req,res) =>{
res.render("busMariposas")
}
module.exports =busMariposasController;
|
var http = require('http'),
express = require('express'),
schools = require('./data/schools.json'),
departments = require('./data/departments.json'),
courses = require('./data/courses.json'),
course = require('./data/course.json'),
port = 8000;
var app = express();
app.use(express.json({limit: '20mb'}));
app.use(app.router);
app.all('*', function (req, res, next) { setTimeout(next, 500); });
app.get('/api/login', function (req, res) { res.send(200); });
app.get('/api/school', function (req, res) { res.send(schools); });
app.get('/api/school/:id', function (req, res) { res.send(departments); });
app.get('/api/department/:id', function (req, res) { res.send(courses); });
app.get('/api/course/:id', function (red, res) { res.send(course); });
app.get('/dist/build.js', function (req, res) { res.sendfile('dist/build.js'); });
app.get('/dist/ga.js', function (req, res) { res.sendfile('dist/ga.js'); });
app.get('/dist/build.css', function (req, res) { res.sendfile('dist/build.css'); });
app.get('/dist/phone@2x.png', function (req, res) { res.sendfile('dist/phone@2x.png'); });
app.get('/dist/logo@2x.png', function (req, res) { res.sendfile('dist/logo@2x.png'); });
app.get('/dist/radar-tail.png', function (req, res) { res.sendfile('dist/radar-tail.png'); });
app.get('*', function (req, res) { res.sendfile('index.html'); });
var httpServer = http.createServer(app).listen(port, function () {
console.log('Fakepi listening on port ' + port);
});
|
const fs = require('fs');
const args = process.argv.slice(2);
if (args.length != 1) {
console.error("usage: extractlinks inputfile");
process.exit(1);
}
const filename = args[0];
// !!!! IMPLEMENT ME
// Read file
let file = fs.readFileSync(filename, 'utf8');
// Set up regex
const regex = /https?:\/\/\w?.[^"'\)\s]+/g
// Find matches
const links = file.match(regex);
// Print all matches
links.forEach(link => {
console.log(link);
})
|
var _ = require('underscore');
var getLastVideo = require('cloud/lastVideoId.js');
Parse.Cloud.job('dailymotion', function(request, status) {
Parse.Cloud.httpRequest({
url: 'https://api.dailymotion.com/user/djalbertolive/videos?fields=id,title,views_total,&sort=recent&limit=100',
success: function(httpResponse) {
var Dailymotion = Parse.Object.extend("dailymotion");
var prom = _.map(httpResponse.data.list, function(singleItem) {
var query = new Parse.Query("dailymotion");
query.equalTo('externalId', singleItem.id)
return query.first().then(function(foundedDailymotion) {
if (foundedDailymotion) {
if (foundedDailymotion.get('plays') !== parseInt(singleItem.views_total)) {
return foundedDailymotion.save();
} else {
console.log('Dailymotion - no more plays with ' + foundedDailymotion.get('title'));
}
} else {
return Parse.Promise.when(getLastVideo.calculate()).then(function(newVideoId){
var dailymotionObject = new Dailymotion();
dailymotionObject.set('externalId', singleItem.id);
dailymotionObject.set('dailymotionId', newVideoId);
dailymotionObject.set('plays', 0);
return dailymotionObject.save();
});
}
});
});
Parse.Promise.when(prom).then(function() {
status.success('success');
});
},
error: function(httpResponse) {
status.error(httpResponse);
console.error('Request first call failed with response code ' + httpResponse.status);
}
});
});
Parse.Cloud.afterSave("dailymotion", function(request) {
var query = new Parse.Query("dailymotion");
query.get(request.object.id).then(function(dailymotionObject) {
Parse.Cloud.httpRequest({
url: 'https://api.dailymotion.com/user/djalbertolive/videos?fields=id,title,views_total,&sort=recent&limit=100',
success: function(httpResponse) {
_.map(httpResponse.data.list, function(singleItem) {
if (dailymotionObject.get('externalId') == singleItem.id) {
if(dailymotionObject.get('title') === undefined){
dailymotionObject.set('title', singleItem.title);
dailymotionObject.save();
}
var lastPlays = parseInt(singleItem.views_total) - parseInt(dailymotionObject.get('plays'));
if (lastPlays !== 0) {
console.log('Dailymotion - ' + lastPlays + ' plays in ' + singleItem.title);
}
dailymotionObject.set('plays', parseInt(singleItem.views_total));
dailymotionObject.save();
}
});
},
error: function(httpResponse) {
console.error('Request second call failed with response code ' + httpResponse.status);
}
});
});
});
|
import React from 'react';
import { connect } from 'react-redux';
import EncounterContainer from '../containers/EncounterContainer';
const mapStateToProps = state => {
return {
encounter: state.encounter,
user: state.user
};
};
const Encounter = connect(
mapStateToProps
)(EncounterContainer)
export default Encounter;
|
module.exports = {
rules: {
// http://eslint.org/docs/rules/no-param-reassign
'no-param-reassign': [
'off',
],
// http://eslint.org/docs/rules/no-return-assign
'no-return-assign': [
'error',
'except-parens',
],
// http://eslint.org/docs/rules/wrap-iife
'wrap-iife': [
'error',
'inside',
],
// http://eslint.org/docs/rules/no-prototype-builtins
'no-prototype-builtins': [
'off',
],
// http://eslint.org/docs/rules/consistent-return
'consistent-return': 'warn',
},
};
|
import React, { Component } from "react";
import "../Style/works.css";
class Works extends Component {
state = {
works: []
};
componentDidMount = () => {
fetch("/api/fetch", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: {
name: "ricky"
}
})
.then(response =>
response.json().then(data => {
this.setState({ works: data });
console.log(this.state.works);
})
)
.catch(err => console.log(err));
};
render() {
return (
<React.Fragment>
{this.state.works.map(work => (
<div class="works-item-container">
<figure>
<img
src={require("../Images/thumbnails/" +
work.pr_thumbnail.replace("png", "PNG"))}
alt={work.pr_name}
/>
</figure>
<div class="works-text-wrapper">
<div class="animation" />
<h3>{work.pr_name}</h3>
<p>{work.pr_desc}</p>
</div>
</div>
))}
</React.Fragment>
);
}
}
export default Works;
|
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('#new-item-form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const newList = document.createElement('ul');
const l1 = document.createElement('li');
const l2 = document.createElement('li');
const l3 = document.createElement('li');
l1.textContent = event.target.title.value;
l2.textContent = event.target.author.value;
l3.textContent = event.target.category.value;
l1.classList = 'titleClass';
l2.classList = 'authorClass';
l3.classList = 'categoryClass';
newList.appendChild(l1);
newList.appendChild(l2);
newList.appendChild(l3);
const readingList = document.querySelector('#reading-list');
readingList.appendChild(newList);
form.reset();
});
const button = document.querySelector('#delete-all');
button.addEventListener('click', () => {
const readingList = document.querySelector('#reading-list');
const children = document.querySelectorAll('ul');
for(child of children){
readingList.removeChild(child);
};
});
});
|
class Scene3 extends Phaser.Scene {
constructor() {
super("winGame");
}
create() {
var highScore = localStorage.getItem('scScore') || 9999;
if (highScore > gameSettings.gameTime) {
localStorage.setItem('scScore', gameSettings.gameTime.toString())
}
this.background = this.add.tileSprite(0, 0, config.width, config.height, "background");
this.background.setOrigin(0, 0);
var style = { font: "bold 32px Arial", width: "1000", align: "center" };
this.add.text(500, 300, ["You Saved Space Chicken!", " ", " Press Space to Save Him Again"], style).setOrigin(0.5, 0.5)
this.cursorKeys = this.input.keyboard.createCursorKeys();
}
update() {
if (this.cursorKeys.space.isDown) {
this.resetGame()
}
this.background.tilePositionX -= 0.5;
}
resetGame() {
gameSettings.gameTime = 0;
gameSettings.isGameDone = false;
this.scene.start("playGame");
}
}
|
'use strict';
var fs = require('fs');
const execFile = require('child_process').execFile;
const child = execFile('./start_read.sh', (error, stdout, stderr) => {
if (error) {
console.error('stderr', stderr);
} else {
var arr= stdout.split("\n\n");
var result_weight=NaN;
for ( var i=0; i< arr.length; i++){
var ves = arr[i].split("=");
var weight1="";
var sovp=0;
for (var ii=0; ii<ves.length; ii++){
if ((ves[ii].length==7) && (+ves[ii]) ) {
var weight= ves[ii].split("").reverse().join("");
console.log(weight);
if ( weight1.indexOf(weight) == -1 ) {
weight1 += " " +weight;
} else {
sovp++;
if ( sovp > 5 ) {
sovp=0;
result_weight = weight;
console.log("stable: "+(+weight)+" same "+10 + " i: "+i);
}
}
}
}
//console.log("stabel: " +weight1+ " sovp: " + sovp);
}
console.log('pages/add_ves', {set_weight: result_weight} );
}
});
console.log("test");
|
import React from 'react';
import { Link } from 'react-router-dom';
import AuthTemplate from '../components/auth/AuthTemplate';
import LoginForm from '../containers/auth/LoginForm';
import qs from 'query-string';
const Division = () => {
return (
<>
<Link to="/register/company">
기업으로 회원가입
</Link>
<br />
<Link to="/register/person">
개인으로 회원가입
</Link>
</>
);
};
export default Division;
|
import React from "react";
const Checkbox = ({ name, value, error }) => {
return (
<div className="form-check">
<input
type="checkbox"
className="form-check-input"
name={name}
id={name}
/>
<label
className="form-check-label"
htmlFor="checkbox"
aria-describedby="help"
>
<small id="help" className="form-text text-muted">
I CONFIRM THAT I UNDERSTAND THE PRIVACY POLICY AND CONSENT TO THE
COLLECTION OF MY INFORMATION.
</small>
</label>
{error && <div className="alert alert-danger">{error}</div>}
</div>
);
};
export default Checkbox;
|
/*
Copyright (c) 2009 Mike Desjardins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This has so much in common w/ onetweet-browser that the two files
// really ought to be merged.
Components.utils.import("resource://app/chrome/content/js/global.js");
function Browser() {}
Browser.prototype=BrowserBase;
// View a conversations between two users
//
Browser.prototype.viewConversation = function(tweetId) {
jsdump('viewing conversation ' + tweetId);
getMainWindow().arguments[0].out = {'action':'oneTweet', 'tweetId':tweetId};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Reply
//
Browser.prototype.replyTo = function(id) {
jsdump('replying to ' + id);
var replyTo = document.getElementById("screenname-" + id).innerHTML;
getMainWindow().arguments[0].out = {'action':'reply', 'tweetId':id, 'replyTo':replyTo};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Show User
//
Browser.prototype.showUser = function(userId) {
getMainWindow().arguments[0].out = {'action':'user', 'userId':userId};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Send DM
//
Browser.prototype.sendDirect = function(id) {
jsdump('direct to ' + id);
var directTo = document.getElementById("screenname-" + id).innerHTML;
getMainWindow().arguments[0].out = {'action':'directTo', 'tweetId':id, 'directTo':directTo};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Retweet
//
Browser.prototype.retweet = function(id) {
jsdump('retweet ' + id);
getMainWindow().arguments[0].out = {'action':'retweet', 'tweetId':id};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Quote
//
Browser.prototype.quote = function(id) {
jsdump('quote ' + id);
//var raw = document.getElementById("raw-" + id).innerHTML;
var raw = Global.rawTweets[id];
var screenName = document.getElementById("screenname-" + id).innerHTML;
getMainWindow().arguments[0].out = {'action':'quoteText', 'screenName':screenName, 'text':raw};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Stop Following
//
Browser.prototype.stopFollowing = function(id) {
jsdump('unfollow ' + id);
getMainWindow().arguments[0].out = {'action':'unfollow', 'userId':id};
getMainWindow().document.getElementById('user-dialog').acceptDialog();
}
// Called onload of the browser. Dispatches up to the main window for now.
//
function start() {
try {
var ev = document.createEvent("Events");
ev.initEvent("start", true, false);
getMainWindow().document.dispatchEvent(ev);
} catch (e) {
jsdump("Exception sending start event: "+ e);
}
}
// Just dispatches.
//
function firstCycleFetch() {
jsdump('sending event up.');
try {
var ev = document.createEvent("Events");
ev.initEvent("firstCycleFetch", true, false);
getMainWindow().document.dispatchEvent(ev);
} catch (e) {
jsdump("Exception sending firstCycleFetch event: "+ e);
}
}
// General Event Dispatcher
//
function dispatch(eventName) {
try {
var ev = document.createEvent("Events");
ev.initEvent(eventName, true, false);
getMainWindow().document.dispatchEvent(ev);
} catch (e) {
jsdump("Exception sending '" + eventName + "' event: " + e);
}
}
browser = new Browser();
|
import React, { Fragment } from "react";
import { Container, Row, Col, Button, Form } from "reactstrap";
import {
FaFacebookF,
FaLinkedinIn,
FaTwitter,
FaInstagram,
} from "react-icons/fa";
/* import "../assets/styles/style.css"; */
class Footer extends React.Component {
render() {
return (
<Fragment>
<div className='footer bg-f'>
<Container className='unique-color-dark'>
<Row>
<Col className='col-md-3 col-sm-8'>
<div className='footer-info'>
<h2 className='wow fadeInUp' data-wow-delay='0.2s'>
Adresa
</h2>
</div>
<address className='wow fadeInUp' data-wow-delay='0.4s'>
<p>
Parcul Tineretului
<br />
Aleea Trandafirilor <br /> Nr. 123
</p>
</address>
</Col>
<Col className='col-md-3 col-sm-8'>
<div className='footer-info section-title'>
<h2 className='wow fadeInUp' data-wow-delay='0.2s'>
Rezervari
</h2>
<address className='wow fadeInUp' data-wow-delay='0.4s'>
<p>072 999 0033 | 072 123 6661</p>
<p>
<a
href='mailto:food4fun@company.com'
target='_blank'
rel='noreferrer'
>
food4fun@company.com
</a>
</p>
</address>
</div>
</Col>
<Col className='col-md-3 col-sm-8'>
<div className='footer-info footer-open-hour'>
<h2 className='wow fadeInUp' data-wow-delay='0.2s'>
Orar
</h2>
<div className='wow fadeInUp' data-wow-delay='0.4s'>
<p>Luni: Îmchis</p>
<div>
<strong>Marți - Vineri</strong>
<p>7:00 AM - 9:00 PM</p>
</div>
<div>
<strong>Sâmbătă & Duminică</strong>
<p>11:00 AM - 10:00 PM</p>
</div>
</div>
</div>
</Col>
<Col className='col-md-3 col-sm-8'>
<h2 className='wow fadeInUp' data-wow-delay='0.2s'>
Subscriptie
</h2>
<div className='subscribe_form'>
<Form className='subscribe_form'>
<input
name='EMAIL'
id='subs-email'
className='form_input'
placeholder='Adresa de email...'
type='email'
/>
<Button type='submit' className='submit'>
SUBSCRIBE
</Button>
<ul className='list-inline f-social'>
<li className='list-inline-item'>
<a
href='https://www.facebook.com/'
target='_blank'
without
rel='noreferrer'
>
<FaFacebookF />
{/* <i className='fab fa-facebook' aria-hidden='true'></i> */}
</a>
</li>
<li className='list-inline-item'>
<a
href='https://twitter.com/'
target='_blank'
without
rel='noreferrer'
>
<FaTwitter />
{/* <i className='fab fa-twitter' aria-hidden='true'></i> */}
</a>
</li>
<li className='list-inline-item'>
<a
href='https://www.linkedin.com/'
target='_blank'
without
rel='noreferrer'
>
<FaLinkedinIn />
{/* <i className='fab fa-linkedin' aria-hidden='true'></i> */}
</a>
</li>
<li className='list-inline-item'>
<a
href='https://www.instagram.com/goo'
target='_blank'
without
rel='noreferrer'
>
<FaInstagram />
{/* <i className='fab fa-instagram' aria-hidden='true'></i> */}
</a>
</li>
</ul>
</Form>
</div>
</Col>
</Row>
</Container>
{/* <div className='text-right p-3'>
<p className='text-white'>
Licenta Informatica 2021 ID Muresanu Catalin
</p>
</div> */}
</div>
</Fragment>
);
}
}
export default Footer;
|
const grid = require('./grid'),
{ Untouched, Touched, Start, Finish, Wall } = require('./cell-type').full;
// Takes a valid config object and creates a game object
function game(config) {
let state = Object.assign({},
getConfiguredGridState(config),
getConfiguredPlayerState(config)
);
return _game(state);
}
function _game(state) {
// return (function() {
return Object.assign(function() {
return state;
}, {
moveUp: () => _game(movePlayer(state, 'up')),
moveDown: () => _game(movePlayer(state, 'down')),
moveLeft: () => _game(movePlayer(state, 'left')),
moveRight: () => _game(movePlayer(state, 'right'))
});
// })();
}
function getConfiguredGridState(config) {
// initialize new grid
const _grid = grid({
width: config.width,
height: config.height,
seedValue: Untouched
}).setCell(config.start).to(Start)
.setCell(config.finish).to(Finish)
.setCells(config.walls).to(Wall);
return { grid: _grid };
}
// Returns what the player
function getConfiguredPlayerState(config) {
return { player: config.start.slice() };
}
// Moves the player position if the player can legally make the move. If not, no update
// @returns a new game state with the updated (or not, if move failed) player position
function movePlayer(state, dir) {
if (typeof dir !== 'string') throw new Error('Direction must be a string.');
const direction = {
up: [0,1],
down: [0,-1],
left: [-1, 0],
right: [1, 0]
};
// get the new position
dir = direction[dir.toLowerCase()];
let newPos = translatePosition(state.player, dir);
// depending on type of cell at newPos:
switch(state.grid.getCell(newPos)) {
case Untouched:
// move player
state = setPlayerPosition(state, newPos);
break;
case Finish:
// test end game
break;
case Touched:
case Wall:
case Start:
default:
// do nothing
break;
}
return state;
}
// Sets the player's position
function setPlayerPosition(state, position) {
return Object.assign({}, state, { player: position });
}
// @param { number[2] } pos - position to apply the delta to
// @param { number[2] } delta - difference to add to the position [0] + [0], [1] + [1]
// @returns { number[2] } - first index is new x coord, second is new y coord
function translatePosition(pos, delta) {
return [
pos[0] + delta[0],
pos[1] + delta[1]
];
}
module.exports = game;
|
let amqplib = require('amqplib/callback_api');
const DbManager = require("./db-manager");
const CONNECT_URL = "amqp://guest:guest@localhost:5672/test";
const QUEUE_NAME = "products";
class Consumer {
constructor() {
this.db = new DbManager();
}
pullMessages() {
amqplib.connect(CONNECT_URL, (err, connection) => {
if (err) throw err;
connection.createChannel((err, channel) => {
if (err) throw err;
channel.assertQueue(QUEUE_NAME, {
durable: true
});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", QUEUE_NAME);
channel.consume(QUEUE_NAME, message => {
this.db.insert(message.content.toString()).then(response => {
console.log(" [x] Record saved on database");
channel.ack(message);
}).catch(err => {
channel.nack(message);
});
}, {
noAck: false
});
});
});
}
}
module.exports = Consumer;
|
angular.module('app.controllers')
.controller('HomeCtrl',function($scope, $user) {
})
|
import server from './src/config/server';
import * as schedule from 'node-schedule-tz'
import UserRepository from './src/repository/UserRepository';
import Roles from "./src/model/Roles";
import ProcessExecuterService from './src/service/ProcessExecuterService';
import Axios from 'axios';
import UserService from './src/service/UserService';
import CourseService from './src/service/CourseService';
import ForumService from './src/service/ForumService';
import SlackService from './src/service/SlackService';
import EmailService from "./src/service/EmailService";
import TopicRecommendator from "./src/recommendator/TopicRecommendator";
import MessageService from './src/service/MessageService';
server.listen(process.env.APP_PORT, () => {
console.log(`Server is up on ${process.env.APP_PORT}`)
});
setTimeout(() => {
// Axios.post('https://discord.com/api/channels/760559085242023946/messages',
// {
// content: 'Ola Mundo!'
// },
// {
// headers: {
// 'Authorization': 'Bot bfaf9f1643632f6ba8d793ee7c5c319c31e9d5a710c59eb7f6352483c0eff727',
// 'Content-Type': 'application/json'
// }
// }
// )
// .then(console.log)
// .catch(console.error);
// UserRepository.findAll().then(users => {
// console.log(users.filter(u => u.id == 62).pop().roles.includes(Roles[1]));
// })
// new ProcessExecuterService()
// .next(new UserService(UserRepository))
// .next(new CourseService(Axios))
// .next(new ForumService(Axios))
// .next(new TopicRecommendator())
// .next(new MessageService(Axios))
// // .next(new EmailService())
// // .next(new SlackService(Axios))
// .next({ execute: function(result) { console.log(result) } })
// .execute();
// var rule = new schedule.RecurrenceRule();
// rule.dayOfWeek = [new schedule.Range(1, 5)];
// rule.hour = 9;
// rule.minute = 0;
// rule.tz = 'America/Sao_Paulo';
// var j = schedule.scheduleJob(rule, function(){
// console.log('Today is recognized by Rebecca Black!');
// });
}, 2000)
|
let items = [];
var modalCount = 0;
var total_bill = 0;
var cart_count = 0;
function updateCartCount() {
$('#cart-count').attr('data-count', cart_count);
}
$('#cart-count').attr('data-count', cart_count);
// $('#total-bill').text('$' + total_bill);
checkItemsInCart();
if (window.localStorage.getItem('row')) {
items = JSON.parse(window.localStorage.getItem('row'));
}
if (items.length != 0) {
items.forEach(e => {
let temp = $('<div class="col-md-6 col-xl-4">\
<a data-target="#modal-' + modalCount + '" data-toggle="modal">\
<img class=" pb-4" src=' + e.url + ' alt="" />\
</a >\
<div class="overlay">\
<div class="row">\
<div class="col-9">\
<p class="lead ml-2 mb-0">' + e.name + '</p>\
<p class="ml-2">$' + e.price + '</p>\
</div>\
<div class="col-3">\
<button id="add-to-cart-from-view-' + modalCount + '" type="button" class="mt-2 btn btn-outline-success add-to-cart-from-view"><i class="mr-auto fas fa-cart-plus fa-lg "></i></button>\
</div>\
</div>\
</div>\
</div>');
$('#list').append(temp);
let temp2 = $('<div class="modal" id="modal-' + modalCount + '">\
<div class= "modal-dialog view-modal-dialog">\
<div class="modal-content view-modal-content">\
<div class="modal-header">\
<div class="row">\
<h5 class="modal-title ml-3 pr-3">' + e.name + '</h5>\
</div>\
<div class="row">\
<p class="modal-title muted pl-4 ml-2">In Stock</p>\
</div>\
<button class="close" data-dismiss="modal">×</button>\
</div>\
<div class="modal-body">\
<div class="row">\
<div class="col-5">\
<img class="modal-img img-fluid" src=' + e.url + ' alt="">\
</div>\
<div class="col-7">\
<div class="col">\
<p class="modal-description lead">' + e.description + '</p>\
</div>\
<div class="col">\
<button class="btn btn-outline-success px-4" type="button">$' + e.price + '</button>\
</div>\
<div class="col">\
<button id="add-to-cart-from-modal-view-' + modalCount + '" class="mt-3 btn btn-outline-success add-to-cart-from-modal-view" type="button">\
<i class="mr-auto fas fa-cart-plus fa-2x"></i>\
</button>\
</div>\
</div>\
</div>\
</div>\
<div class="modal-footer bg-white">\
<button class="btn btn-secondary" data-dismiss="modal">Close</button>\
</div>\
</div>\
</div>\
</div >');
$('#modal-list').append(temp2);
modalCount++;
});
}
if (window.localStorage.getItem('count')) {
modalCount = JSON.parse(window.localStorage.getItem('count'));
}
$(document).on('click', '.remove', function() {
// console.log($(this));
var btn_number = $(this).attr('id');
btn_number = btn_number[btn_number.length - 1];
// console.log(btn_number);
$('#add-to-cart-from-modal-view-' + btn_number).attr('disabled', false);
$('#add-to-cart-from-view-' + btn_number).attr('disabled', false);
var x = $(this)
.parent()
.parent()
.next('.spacer')
.remove();
// console.log(x);
$(this)
.parent()
.parent()
.remove();
updateTotalBill();
checkItemsInCart();
cart_count--;
updateCartCount();
});
$(document).on('click', '.add-to-cart-from-view', function() {
// console.log('clicked from view');
$(this).attr('disabled', true);
var parent_of_title = $(this)
.parent()
.siblings('.col-9');
// var title = parent_of_title.children('.lead').text();
var str = parent_of_title.children('.ml-2').text();
str = str.split('$');
// console.log(parent_of_title);
title = str[0];
price = parseFloat(str[1]);
var img_src = $(this)
.parent()
.parent()
.parent()
.siblings('a')
.children('img')
.attr('src');
// console.log(img_src);
// console.log(title);
// console.log(price);
var btn_number = $(this).attr('id');
btn_number = btn_number.replace(/\D/g, '');
$('#add-to-cart-from-modal-view-' + btn_number).attr('disabled', true);
let temp = $('<div class="row">\
<div id="cart-item-image" class="col-5">\
<img class="cart-item-image " src=' + img_src + ' alt="" />\
</div>\
<div id="cart-item-description" class="col-7">\
<h4>' + title + '</h4>\
<p class="text-muted mb-1 cart-item-price d-inline" >$' + price + '</p>\
<p class="text-muted mb-1 ml-3 total-cart-item-price d-inline p-1" >Total: $' + price + '</p>\
<form class="mt-3 form-inline quantity-form">\
<label for="cart-quantity" class="quantity-label">Quantity: </label>\
<input type="number" class="cart-quantity ml-2 form-control quantity" value="1" min="1" />\
</form>\
<button id="btn-remove-' + btn_number + '" type="button" class="remove btn btn-outline-danger btn-sm ml-0 quantity align-content-endcenter pb-4">X Remove</button>\
</div>\
</div>\
<div class="spacer"><hr /></div>');
$('#cart-item').append(temp);
// $('#add-to-cart-from-modal-view-' + 0).attr('disabled', true);
// console.log(btn_number);
total_bill += price;
$('#total-bill').text('$' + total_bill);
updateTotalBill();
checkItemsInCart();
cart_count++;
updateCartCount();
});
$(document).on('click', '.add-to-cart-from-modal-view', function() {
// console.log('clicked from modal');
$(this).attr('disabled', true);
var price = $(this)
.parent()
.parent()
.children('.col')
.children('button', 0)
.text();
price = parseFloat(price.slice(1));
console.log(price);
var img_src = $(this)
.parent()
.parent()
.parent()
.parent()
.children('.row', 0)
.children('.col-5', 0)
.children('img')
.attr('src');
// console.log(img_src);
var title = $(this)
.parent()
.parent()
.parent()
.parent()
.parent()
.children('.modal-header', 0)
.children('.row', 0)
.children('h5', 0)
.text();
// console.log(title);
var btn_number = $(this).attr('id');
btn_number = btn_number.replace(/\D/g, '');
$('#add-to-cart-from-view-' + btn_number).attr('disabled', true);
let temp = $('<div class="row">\
<div id="cart-item-image" class="col-5">\
<img class="cart-item-image " src=' + img_src + ' alt="" />\
</div>\
<div id="cart-item-description" class="col-7">\
<h4>' + title + '</h4>\
<p class="text-muted mb-1 cart-item-price d-inline" >$' + price + '</p>\
<p class="text-muted mb-1 ml-3 total-cart-item-price d-inline p-1" >Total: $' + price + '</p>\
<form class="mt-3 form-inline quantity-form">\
<label for="cart-quantity" class="quantity-label">Quantity: </label>\
<input type="number" class="cart-quantity ml-2 form-control quantity" value="1" min="1" />\
</form>\
<button id="btn-remove-' + btn_number + '" type="button" class="remove btn btn-outline-danger btn-sm ml-0 quantity align-content-endcenter pb-4">X Remove</button>\
</div>\
</div>\
<div class="spacer"><hr /></div>');
$('#cart-item').append(temp);
total_bill += price;
$('#total-bill').text('$' + total_bill);
updateTotalBill();
checkItemsInCart();
cart_count++;
updateCartCount();
});
$(document).on('input', '.cart-quantity', function() {
var item_count = $(this).val();
var item_price = parseFloat(
$(this)
.parent()
.parent()
.children('p', 0)
.text()
.substr(1)
);
var total_item_price = parseFloat(item_count) * item_price;
$(this)
.parent()
.parent()
.children('p')
.eq(1)
.text('Total: $' + total_item_price);
// console.log(item_count);
// console.log(total_item_price);
// console.log(item_price);
// total_bill += total_item_price;
// $('#total-bill').text('$' + total_bill);
// total_bill = 0;
updateTotalBill();
checkItemsInCart();
});
$(document).on('click', '#add', function() {
var name = $('#name').val();
var description = $('#description').val();
var url = $('#url').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
if (name && description && url && quantity && price) {
// let item = $('<li>').text(title + ' - ' + author);
// $('#list').append(item);
// let temp = $('<div>', { class: 'col-md-6 col-xl-4' }).append();
let temp = $('<div class="col-md-6 col-xl-4">\
<a data-target="#modal-' + modalCount + '" data-toggle="modal">\
<img class=" pb-4" src=' + url + ' alt="" />\
</a >\
<div class="overlay">\
<div class="row">\
<div class="col-9">\
<p class="lead ml-2 mb-0">' + name + '</p>\
<p class="ml-2">$' + price + '</p>\
</div>\
<div class="col-3">\
<button id="add-to-cart-from-view-' + modalCount + '" type="button" class="mt-2 btn btn-outline-success add-to-cart-from-view"><i class="mr-auto fas fa-cart-plus fa-lg "></i></button>\
</div>\
</div>\
</div>\
</div>');
$('#list').append(temp);
items.push({ name: name, description: description, url: url, quantity: quantity, price: price });
window.localStorage.setItem('row', JSON.stringify(items));
$('#form')[0].reset();
let temp2 = $('<div class="modal" id="modal-' + modalCount + '">\
<div class= "modal-dialog view-modal-dialog">\
<div class="modal-content view-modal-content">\
<div class="modal-header">\
<div class="row">\
<h5 class="modal-title ml-3 pr-3">' + name + '</h5>\
</div>\
<div class="row">\
<p class="modal-title muted pl-4 ml-2">In Stock</p>\
</div>\
<button class="close" data-dismiss="modal">×</button>\
</div>\
<div class="modal-body">\
<div class="row">\
<div class="col-5">\
<img class="modal-img img-fluid" src=' + url + ' alt="">\
</div>\
<div class="col-7">\
<div class="col">\
<p class="modal-description lead">' + description + '</p>\
</div>\
<div class="col">\
<button class="btn btn-outline-success px-4" type="button">$' + price + '</button>\
</div>\
<div class="col">\
<button id="add-to-cart-from-modal-view-' + modalCount + '" class="mt-3 btn btn-outline-success add-to-cart-from-modal-view" type="button">\
<i class="mr-auto fas fa-cart-plus fa-2x"></i>\
</button>\
</div>\
</div>\
</div>\
</div>\
<div class="modal-footer bg-white">\
<button class="btn btn-secondary" data-dismiss="modal">Close</button>\
</div>\
</div>\
</div>\
</div >');
$('#modal-list').append(temp2);
modalCount++;
window.localStorage.setItem('count', JSON.stringify(modalCount));
} else {
alert('Fields Empty!!');
console.log('Fields Empty!!');
}
});
function updateTotalBill() {
var cart_item = $('#cart-item').children('.row');
var total = 0;
// console.log(cart_item.length);
for (var i = 1; i < cart_item.length; i++) {
var item = cart_item.eq(i);
var price = item
.children('#cart-item-description')
.children('p')
.eq(0)
.text();
price = parseFloat(price.replace('$', ' '));
// console.log(price);
var quantity = item
.children('#cart-item-description')
.children('form')
.eq(0)
.children('input')
.eq(0)
.val();
// console.log(quantity);
total += price * quantity;
}
$('#total-bill').text('$' + total);
}
function checkItemsInCart() {
var bill = $('#total-bill').text();
if (bill !== '$0') {
$('#cart-empty').hide();
} else {
$('#cart-empty').show();
}
}
|
import keyMirror from 'key-mirror';
const types = keyMirror({
FLUSH: null,
INITIALIZE: null,
LOGIN_EMAIL: null,
SET_USER: null,
TOGGLE_NAV: null,
SET_NAV: null,
});
export default types;
|
var mongoose = require('mongoose');
var Prezenta = mongoose.model('Prezenta', {
nume: {
type:String,
required: true,
minlength: 1,
trim: true
},
prenume: {
type:String,
required: true,
minlength: 1,
trim:true
},
grupa:{
type:String,
required:true,
minlength:1,
trim:true
},
_creator:{
type: mongoose.Schema.Types.ObjectId,
required: true
}
});
module.exports = {Prezenta};
|
window.RotateRay2 = (function(){
var IE = navigator.appName == 'Microsoft Internet Explorer' || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv 11/)) || window.navigator.userAgent.indexOf("MSIE")>0;
var _rayWidth = IE ? 600 : 4000;
var _rayHeight = 0;
var _animationTime = 100;
function RotateRay2(){
this.init = this.init.bind(this);
this.firstTime = true;
this.supportTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
this.default = {
color : "#F0CB3A",
speed : 4,
rayNumber : 13,
};
this.options = {};
this.sunburst = null;
}
RotateRay2.prototype.init = function(BannerFlow) {
if (this.firstTime) {
this.container = document.querySelector(".container");
this.sunburst = document.querySelector(".sunburst");
if (IE) this.container.style.transform = "scale(4)";
this.firstTime = false;
}
for (var attr in this.default){
this.options[attr] = this.default[attr];
}
if (BannerFlow) {
for (var attr in this.default){
this.options[attr] = BannerFlow.settings[attr] || this.default[attr];
}
this.options["rayNumber"] = Math.max(this.options["rayNumber"],2);
}
this.container.style.opacity= 0;
this.sunburst.innerHTML = "";
var corner = Math.PI / this.options.rayNumber ;
_rayHeight = _rayWidth*Math.tan(corner/2);
var settingStyle = "";
var animation = "rotateBackground "+_animationTime/this.options.speed+"s linear infinite";
settingStyle += getStyle(".sunburst",{
"color" : this.options.color,
//"animation-duration" : _animationTime/this.options.speed+"s"
"-webkit-animation" : animation,
"-moz-animation" : animation,
"-o-animation" : animation,
"animation" : animation,
});
settingStyle += getStyle(".sunburst b",{
"border-width" : _rayHeight + "px " + _rayWidth + "px",
"top" : "calc(50% - "+_rayHeight+"px)",
"left" : "calc(50% - "+_rayWidth+"px)",
});
for (var i = 0;i<this.options.rayNumber;i++) {
var b = document.createElement("b");
this.sunburst.appendChild(b);
setStyleCss3(b,"transform","rotate("+i*2*corner+"rad)");
}
document.querySelector("#settings").innerHTML = settingStyle;
this.container.style.opacity = 1;
};
return RotateRay2;
})();
/*-----------------
Utils
-----------------*/
//get style from object style
var getStyle = function(selector,styleObj){
var isAttribute = false;
var newStyle = selector+"{";
for(var attr in styleObj) {
if (styleObj[attr]) {
isAttribute = true;
newStyle += attr+" : "+styleObj[attr]+";";
}
}
newStyle+="}";
return isAttribute ? newStyle : "";
}
//get CSS3 style
var setStyleCss3 = function (object, key, value) {
object.style['-webkit-'+ key] = value;
object.style['-moz-'+key] = value;
object.style['-ms-'+key] = value;
object.style[key] = value;
}
/*-----------------
Main function
-----------------*/
var timer,widget=new RotateRay2(); ;
if (typeof BannerFlow != 'undefined') {
BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function() {
clearTimeout(timer);
timer = setTimeout(function(){
widget.init(BannerFlow);
},500);
});
} else {
window.addEventListener("load",function(){
widget.init();
});
}
|
module.exports = {
parser: 'babel-eslint',
parserOptions: {
allowImportExportEverywhere: true,
},
plugins: [
'jest',
'security',
'jsx-a11y',
'simple-import-sort',
],
extends: [
'airbnb',
'plugin:security/recommended',
'plugin:react/recommended',
],
rules: {
semi: ['error', 'never'],
'simple-import-sort/sort': 'error',
'react/jsx-filename-extension': 0,
'import/prefer-default-export': 0,
'max-len': [
2,
{
code: 135,
},
],
'jsx-a11y/aria-role': [2, {
ignoreNonDOM: true,
}],
'react/jsx-props-no-spreading': 'off',
'import/no-extraneous-dependencies': ['error', { devDependencies: ['**/setupTests.js', '**/*.spec.jsx', '*.config.js'] }],
'import/named': 'off',
'linebreak-style': 'off',
},
env: {
'jest/globals': true,
browser: true,
node: true,
es6: true,
},
settings: {
'import/resolver': 'webpack',
'import/extensions': [
'.js',
'.jsx',
],
},
}
|
function doianh1() {
if (document.getElementById("image1").src == "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part1x1.jpg")
{
document.getElementById("image1").src = "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part1x1.jpg";
}
else if(document.getElementById("image1").src == "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part1x1.jpg")
{
document.getElementById("image1").src = "https://demo.codegym.vn/8/puzzlegame/img/monkey_part1x1.jpg";
}
else{
document.getElementById("image1").src = "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part1x1.jpg";
}
}
function doianh2() {
if (document.getElementById("image2").src == "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part2x1.jpg")
{
document.getElementById("image2").src = "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part2x1.jpg";
}
else if(document.getElementById("image2").src == "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part2x1.jpg")
{
document.getElementById("image2").src = "https://demo.codegym.vn/8/puzzlegame/img/monkey_part2x1.jpg";
}
else{
document.getElementById("image2").src = "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part2x1.jpg";
}
}
function doianh3() {
if (document.getElementById("image3").src == "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part3x1.jpg")
{
document.getElementById("image3").src = "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part3x1.jpg";
}
else if(document.getElementById("image3").src == "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part3x1.jpg")
{
document.getElementById("image3").src = "https://demo.codegym.vn/8/puzzlegame/img/monkey_part3x1.jpg";
}
else{
document.getElementById("image3").src = "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part3x1.jpg";
}
}
function doianh4() {
if (document.getElementById("image4").src == "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part4x1.jpg")
{
document.getElementById("image4").src = "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part4x1.jpg";
}
else if(document.getElementById("image4").src == "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part4x1.jpg")
{
document.getElementById("image4").src = "https://demo.codegym.vn/8/puzzlegame/img/monkey_part4x1.jpg";
}
else{
document.getElementById("image4").src = "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part4x1.jpg";
}
}
function doianh5() {
if (document.getElementById("image5").src == "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part5x1.jpg")
{
document.getElementById("image5").src = "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part5x1.jpg";
}
else if(document.getElementById("image5").src == "https://demo.codegym.vn/8/puzzlegame/img/funny-cat1_part5x1.jpg")
{
document.getElementById("image5").src = "https://demo.codegym.vn/8/puzzlegame/img/monkey_part5x1.jpg";
}
else{
document.getElementById("image5").src = "https://demo.codegym.vn/8/puzzlegame/img/panda_swap_part5x1.jpg";
}
}
|
$(document).ready(function () {
$(function () {
$.scrollify({
section: '.section',
before: function (index, section) {
$('.sidebarNavigation .nav-item').on('click', function () {
$('.sidebarNavigation .nav-item').removeClass('active');
$(this).addClass('active');
});
},
after: function (index, section) {
$('.sidebarNavigation .nav-item').each(function (i, navItem) {
i == index
? $(navItem).addClass('active')
: $(navItem).removeClass('active');
});
},
});
});
$('.sidebarNavigation a').on('click', $.scrollify.move);
$('.progressBar').each(function (index, progressBar) {
let value = $(progressBar).attr('data-percentage');
$(progressBar)
.find('.progress')
.css('width', value + '%');
$(progressBar)
.find('.progress .percentage')
.text(value + '%');
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.