text
stringlengths 7
3.69M
|
|---|
import { extend } from '../../core/utils/extend';
import { Component } from '../../core/component';
import DataHelperMixin from '../../data_helper';
var ItemsOptionBase = Component.inherit({}).include(DataHelperMixin);
class ItemsOption extends ItemsOptionBase {
constructor(diagramWidget) {
super();
this._diagramWidget = diagramWidget;
this._resetCache();
}
_dataSourceChangedHandler(newItems, e) {
this._resetCache();
this._items = newItems.map(item => extend(true, {}, item));
this._dataSourceItems = newItems.slice();
if (e && e.changes) {
var internalChanges = e.changes.filter(change => change.internalChange);
var externalChanges = e.changes.filter(change => !change.internalChange);
if (internalChanges.length) {
this._reloadContentByChanges(internalChanges, false);
}
if (externalChanges.length) {
this._reloadContentByChanges(externalChanges, true);
}
} else {
this._diagramWidget._onDataSourceChanged();
}
}
_dataSourceLoadingChangedHandler(isLoading) {
if (isLoading && !this._dataSource.isLoaded()) {
this._diagramWidget._showLoadingIndicator();
} else {
this._diagramWidget._hideLoadingIndicator();
}
}
_prepareData(dataObj) {
for (var key in dataObj) {
if (!Object.prototype.hasOwnProperty.call(dataObj, key)) continue;
if (dataObj[key] === undefined) {
dataObj[key] = null;
}
}
return dataObj;
}
insert(data, callback, errorCallback) {
this._resetCache();
var store = this._getStore();
store.insert(this._prepareData(data)).done((data, key) => {
store.push([{
type: 'insert',
key,
data,
internalChange: true
}]);
if (callback) {
callback(data);
}
this._resetCache();
}).fail(error => {
if (errorCallback) {
errorCallback(error);
}
this._resetCache();
});
}
update(key, data, callback, errorCallback) {
var store = this._getStore();
var storeKey = this._getStoreKey(store, key, data);
store.update(storeKey, this._prepareData(data)).done((data, key) => {
store.push([{
type: 'update',
key,
data,
internalChange: true
}]);
if (callback) {
callback(key, data);
}
}).fail(error => {
if (errorCallback) {
errorCallback(error);
}
});
}
remove(key, data, callback, errorCallback) {
this._resetCache();
var store = this._getStore();
var storeKey = this._getStoreKey(store, key, data);
store.remove(storeKey).done(key => {
store.push([{
type: 'remove',
key,
internalChange: true
}]);
if (callback) {
callback(key);
}
this._resetCache();
}).fail(error => {
if (errorCallback) {
errorCallback(error);
}
this._resetCache();
});
}
findItem(itemKey) {
if (!this._items) {
return null;
}
return this._getItemByKey(itemKey);
}
getItems() {
return this._items;
}
hasItems() {
return !!this._items;
}
_reloadContentByChanges(changes, isExternalChanges) {
changes = changes.map(change => extend(change, {
internalKey: this._getInternalKey(change.key)
}));
this._diagramWidget._reloadContentByChanges(changes, isExternalChanges);
}
_getItemByKey(key) {
this._ensureCache();
var cache = this._cache;
var index = this._getIndexByKey(key);
return cache.items[index];
}
_getIndexByKey(key) {
this._ensureCache();
var cache = this._cache;
if (typeof key === 'object') {
for (var i = 0, length = cache.keys.length; i < length; i++) {
if (cache.keys[i] === key) return i;
}
} else {
var keySet = cache.keySet || cache.keys.reduce((accumulator, key, index) => {
accumulator[key] = index;
return accumulator;
}, {});
if (!cache.keySet) {
cache.keySet = keySet;
}
return keySet[key];
}
return -1;
}
_ensureCache() {
var cache = this._cache;
if (!cache.keys) {
cache.keys = [];
cache.items = [];
this._fillCache(cache, this._items);
}
}
_fillCache(cache, items) {
if (!items || !items.length) return;
var keyExpr = this._getKeyExpr();
if (keyExpr) {
items.forEach(item => {
cache.keys.push(keyExpr(item));
cache.items.push(item);
});
}
var itemsExpr = this._getItemsExpr();
if (itemsExpr) {
items.forEach(item => this._fillCache(cache, itemsExpr(item)));
}
var containerChildrenExpr = this._getContainerChildrenExpr();
if (containerChildrenExpr) {
items.forEach(item => this._fillCache(cache, containerChildrenExpr(item)));
}
}
_getKeyExpr() {
throw 'Not Implemented';
}
_getItemsExpr() {}
_getContainerChildrenExpr() {}
_initDataSource() {
super._initDataSource();
this._dataSource && this._dataSource.paginate(false);
}
_dataSourceOptions() {
return {
paginate: false
};
}
_getStore() {
return this._dataSource && this._dataSource.store();
}
_getStoreKey(store, internalKey, data) {
var storeKey = store.keyOf(data);
if (storeKey === data) {
var keyExpr = this._getKeyExpr();
this._dataSourceItems.forEach(item => {
if (keyExpr(item) === internalKey) storeKey = item;
});
}
return storeKey;
}
_getInternalKey(storeKey) {
if (typeof storeKey === 'object') {
var keyExpr = this._getKeyExpr();
return keyExpr(storeKey);
}
return storeKey;
}
_resetCache() {
this._cache = {};
}
}
export default ItemsOption;
|
/**
* This is a basic gulpfile showing a configuration for creating a build process
* that copies assets to a build folder, converts html templates into js, and
* places them in the template cache of a module. In this example, we tell
* gulp-ng-html2js to use a module with the same name as our main module which
* means we are adding the templates into the template cache of the main module.
*/
var gulp = require('gulp');
var ngHtml2Js = require('gulp-ng-html2js');
var del = require('del');
var inject = require('gulp-inject');
var debug = require('gulp-debug');
/**
* This task will run when you enter gulp at the command line without a task
* name.
*/
gulp.task('default',['inject']);
/**
* We set things up so everything will be run in the correct order using this
* one task
*/
gulp.task('inject', ['html2js'], function() {
return gulp.src('./build/index.html')
.pipe(inject(gulp.src('./build/*.view.js'), {ignorePath: 'build'}))
//.pipe(inject(gulp.src(tpl_src), {ignorePath: 'build'}))
.pipe(gulp.dest('./build/'));
});
/**
* Convert html templates to js Module name should be the same as main app
* module.
*/
gulp.task('html2js', ['copy-assets'], function() {
return gulp.src('*.view.html')
.pipe(ngHtml2Js({
moduleName: 'main',
prefix: ''
}))
.pipe(gulp.dest('build/'));
});
/**
* Copy-assets will only run after copy-js and copy-html are finished.
*/
gulp.task('copy-assets', ['copy-js', 'copy-html'], function() {
});
/**
* Copy js files to build folder
*/
gulp.task('copy-js', ['clean'], function() {
gulp.src(['./*.js', '!./gulpfile.js'])
.pipe(gulp.dest('build/'));
});
/**
* Copy html files to build folder. Exclude .view.html files (which are
* templates) and will be handled later in the build process by gulp-ng-html2js
*/
gulp.task('copy-html', ['clean'], function() {
gulp.src(['./*.html', '!*.view.html'])
.pipe(gulp.dest('build/'));
});
/**
* Clean out the build folder before a new build process. Just in case. Even
* though both copy-js and copy-html depend on this task completing it will only
* be run once.
*/
gulp.task('clean', function(cb) {
del(['./build/*'], cb);
});
|
import React, {useState, useEffect} from 'react'
import { Table } from 'react-bootstrap'
import { formatNearAmount } from "near-api-js/lib/utils/format";
import tokenIcon from './tokenIcon'
import { coinList } from './Dash'
const Account = ({contract, accountId, ausdContract}) => {
const _coinList = coinList.filter((coin) => coin !== 'art')
const [assetB, setAssetB] = useState({'aNEAR':'0', 'aBTC':'0', 'aGOLD':'0', 'aSPY':'0', 'aEUR':'0'})
const loadAssetBalance = async (a) => {
return await contract.get_asset_balance({account_id: accountId, asset: a})
}
const [aUSDBalnce, setAusdBalance] = useState('')
const loadAUSDBalance = () => {
ausdContract.get_balance({owner_id: accountId})
.then((ausd) => setAusdBalance(ausd))
}
useEffect(() => {
async function loadBalance() {
let asset = {aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null}
for(const p in asset){
let ass = await loadAssetBalance(p)
console.log(ass)
asset[p] = ass
}
setAssetB(asset)
}
loadAUSDBalance()
loadBalance()
}, [])
const Tr = ({asset, index}) =>
<tr>
<th>{index + 1}</th>
<td><img src={tokenIcon[asset]} alt='icon' className="icon"/>{asset}</td>
<td>{formatNearAmount(assetB[asset], 5)}</td>
</tr>
return <div className="trade-card">
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Token</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td><img src={tokenIcon.aUSD} alt='icon' className="icon"/>aUSD</td>
<td>{formatNearAmount(aUSDBalnce,5)}</td>
</tr>
{_coinList.map((coin,index) => <Tr asset={coin} index={index} />)}
</tbody>
</Table>
</div>
}
export default Account
|
const Header = ({ header }) => {
return (
<div className="container">
<h1 className="display-4 fst-italic">{header}</h1>
<hr />
</div>
);
};
export default Header;
|
import React, { useEffect, useState } from 'react'
import DoneOutlineIcon from '@material-ui/icons/DoneOutline';
import { Avatar } from '@material-ui/core'
import CancelIcon from '@material-ui/icons/Cancel';
import db from "../../Firebase"
import { useStateValue } from "../../StateReducer/StateProvider"
import firebase from "firebase"
function Request({ idd, docId }) {
const [{ id, user },] = useStateValue();
const [name, setName] = useState('');
const [fri, setFri] = useState('');
const [mi, setMi] = useState('');
const [photo, setPhoto] = useState('');
useEffect(() => {
db.collection("users").doc(idd).get().then((doc) => {
setName(doc.data().name);
setPhoto(doc.data().photoUrl);
})
}, [idd])
useEffect(() => {
if (fri !== '') {
db.collection("users").doc(id).collection("chats").doc(mi).update({
friendRoomId: fri,
})
db.collection("users").doc(idd).collection("chats").doc(fri).update({
friendRoomId: mi,
})
alert("Friend added");
db.collection("users").doc(id).collection("requests").doc(docId).delete();
}
}, [fri,mi,idd])
const accept = () => {
db.collection("users").doc(id).collection("friends").add({
friend: idd,
name: name,
photo: photo,
});
db.collection("users").doc(id).collection("chats").add({
friend: idd,
name: name,
photo: photo,
friendRoomId: null,
lastMessage: firebase.firestore.FieldValue.serverTimestamp(),
}).then(docRef => {
setMi(docRef.id);
});
db.collection("users").doc(idd).collection("friends").add({
friend: id,
name: user.displayName,
photo: user.photoURL,
});
db.collection("users").doc(idd).collection("chats").add({
friend: id,
name: user.displayName,
photo: user.photoURL,
friendRoomId: null,
lastMessage: firebase.firestore.FieldValue.serverTimestamp(),
}).then(docRef => {
setFri(docRef.id);
});
}
const reject = () => {
db.collection("users").doc(id).collection("requests").doc(docId).delete()
}
return (
<div className="request">
<div className="Names">
<Avatar src={photo} style={{ height: "60px", width: "60px" }} />
<h3 className="name">{name}</h3>
</div>
<div className="req-icons">
<div className="icon">
<DoneOutlineIcon onClick={accept} />
</div>
<div className="icon">
<CancelIcon onClick={reject} />
</div>
</div>
</div>
)
}
export default Request
|
module.exports.RikkiTikkiAPI = module.parent.exports.RikkiTikkiAPI || module.parent.exports;
module.exports = require('./lib');
|
const devConfig = {
API_URL: 'API_URL'
}
const prodConfig = {
API_URL: 'API_URL'
}
export default __DEV__ ? devConfig : prodConfig
|
const fs = require("fs");
const util = require("util");
const axios = require("axios");
const inquirer = require("inquirer");
const generateMarkdown = require('./generateMarkdown');
const questions = [
"Project title",
"Project Description"
];
function writeToFile(fileName, data) {
const markdown = generateMarkdown(data);
fs.writeFile(fileName, markdown, function (error) {
console.log('Error writing:', error);
});
}
async function askQuestions() {
const answers = [];
let index = 0;
while (index < questions.length) {
let { answer } = await inquirer
.prompt({
message: questions[index],
name: 'answer'
});
answers.push(answer);
index++;
}
return answers;
}
async function getGithubInfo() {
let { username } = await inquirer
.prompt({
message: "What is Your GitHub Username?",
name: "username"
});
const queryUrl = `https://api.github.com/users/${username}/repos?per_page=10`;
let res = await axios.get(queryUrl);
const login = res.data[0].owner.login;
const avatar = res.data[0].owner.avatar_url;
return { login, avatar };
}
|
import './side_nav.html';
import { Meteor } from 'meteor/meteor';
import { ReactiveDict } from 'meteor/reactive-dict'
import { Template } from 'meteor/templating';
import { FlowRouter } from 'meteor/kadira:flow-router';
Template.side_nav.onCreated(function () {
this.state = new ReactiveDict;
const current = FlowRouter.current();
const currentPath = current.path;
if (currentPath.indexOf('recipe') >= 0) {
this.state.set('selected', 'recipes');
} else if (currentPath.indexOf('ingredient') >= 0) {
this.state.set('selected', 'ingredients');
} else {
this.state.set('selected', 'home');
}
});
Template.side_nav.helpers({
selected(el) {
return el.hash.className == Template.instance().state.get('selected') ? '': '';
},
selectedColor(el) {
// return el.hash.className == Template.instance().state.get('selected') ? 'rgb(255, 0, 78)': 'rgb(63,63,63)';
return el.hash.className == Template.instance().state.get('selected') ? 'cornflowerblue': 'rgb(63,63,63)';
}
});
Template.side_nav.events({
'click #header-recipes': function(event) {
Template.instance().state.set('selected', 'recipes');
},
'click #header-ingredients': function(event) {
Template.instance().state.set('selected', 'ingredients');
},
'click #header-home': function(event) {
Template.instance().state.set('selected', 'home');
}
});
|
document.getElementById('startGame').onclick = function() {
var iframe = document.createElement('iframe');
var container = document.getElementById('gameContainer');
iframe.id = "gameBox";
iframe.src = 'game.html';
container.appendChild(iframe);
this.style.display = "none";
};
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
var iframe = document.getElementById("gameBox");
if (iframe != null) {
iframe.parentNode.removeChild(iframe);
var playButton = document.getElementById("startGame");
playButton.style.display = "inline";
}
}
};
|
import * as React from "react";
export default class EditProjectForm extends React.Component {
render() {
// const { project, loading } = this.props;
return(
<form action="/">
<div className="edit-group">
<div className="form-input-flex edit edit-form">
<div className="form-input-name">Campaign:</div>
<div className="form-input-value">Dr Choy social</div>
<div className="edit-icon js-edit"></div>
<div className="editable-input">
<input type="text" defaultValue="Dr Choy social" />
<div className="save-icon js-save"></div>
</div>
</div>
<div className="form-input-flex edit edit-form">
<div className="form-input-name">Campaign:</div>
<div className="form-input-value">Facebook post</div>
<div className="edit-icon js-edit"></div>
<div className="editable-input">
<input type="text" defaultValue="Facebook post"/>
<div className="save-icon js-save"></div>
</div>
</div>
<div className="form-input-flex edit edit-form">
<div className="form-input-name">Tags:</div>
<div className="form-input-value">Awareness, SMB</div>
<div className="edit-icon js-edit"></div>
<div className="editable-input">
<input type="text" defaultValue="Awareness, SMB"/>
<div className="save-icon js-save"></div>
</div>
</div>
<div className="form-input-flex edit">
<div className="form-input-name">Created by:</div>
<div className="form-input-value value-img">Andy Z <img src="img/user.png" alt="user"/></div>
</div>
<div className="form-input-flex edit">
<div className="form-input-name">Writer:</div>
<div className="form-input-value value-img">Brenna C <img src="img/user.png" alt="user"/></div>
</div>
<div className="form-input-flex edit">
<div className="form-input-name">Status:</div>
<div className="form-input-value value-status">Draft</div>
</div>
</div>
<div className="edit-date-group">
<div className="form-input-flex edit-date">
<div className="form-input-name">Current step due:</div>
<div className="form-input-value">18/07/2018 4:00PM</div>
<div className="edit-icon js-date"></div>
</div>
<div className="form-input-flex edit-date">
<div className="form-input-name">Planed publish:</div>
<div className="form-input-value">28/07/2018 4:00PM</div>
<div className="edit-icon js-date"></div>
</div>
</div>
<div className="form-input-flex form-input-submit">
<input type="submit" defaultValue="Order" className="button_filter"/>
<button type="submit" name="Order">Edit</button>
</div>
</form>
)
}
}
|
var DeviceModel = Backbone.Model.extend({
defaults: {
tag: "ๅ
จ้จๆฑๆป"
},
render :function(attributes){
var temp = "";
if(this.attributes[attributes.tag + "_low_ratio"]){
temp += "<td style='background:" + attributes.colors + "'>"
temp += "<span>{{" + attributes.tag +" }}</span>"
temp += "<span data-tag='"+attributes.tag+"' hour-num='"+this.attributes['hour_num']+"' class = 'glyphicon glyphicon-arrow-down icon-small low-notice'>{{ percentage(" + attributes.tag +'_low_ratio'+") }}</span></td>";
}else{
temp += "<td class= '"+attributes.add_td_class+"' style='word-wrap:break-word;background:" + attributes.colors + ";color:"+attributes.td_color+"'>{{ " + attributes.tag + " }}</td>";
}
return temp;
},
add_ratio: function () {
var me = this;
_.each(["2","3","7","15","30"],function(item){
current_ratio = parseFloat(me.attributes['ratio_alive'+item].replace('%',''))/100;
me.attributes["background_alive"+item] = me.gradient_color(current_ratio);
});
},
gradient_color: function (radio) {
if (radio == "") {
return "";
} else {
var r = (-2 * parseInt(radio * 100)) + 182;
var g = (-1 * parseInt(radio * 100)) + 242;
var b = (-1 * parseInt(radio * 100)) + 243;
return "rgb(" + r + "," + g + "," + b + ")";
}
}
});
var DeviceList = Backbone.Collection.extend({
Model: DeviceModel
});
var list = new DeviceList;
var footList = new DeviceList;
var DeviceItemView = Backbone.View.extend({
tagName: "tr",
initialize: function () {
this.template = _.template(template(this.model));
},
render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
},
events: {
"click .td_click_field" : "set_input_val"
},
set_input_val : function(){
arr = []
key = this.model.attributes.input_events.attr("tag");
ids = this.model.attributes.input_events.attr("input_events").split('|');
value = this.model.attributes[key];
index = value.lastIndexOf('_');
arr.push(value.substring(0,index))
arr.push(value.substring(index+1));
_.each(ids,function(item,index){
if(ids.length == 1){
$("#"+item).val(value);
return false;
}
$("#"+item).val(arr[index]);
})
}
});
var DeviceListView = Backbone.View.extend({
initialize: function (obj) {
var me = this;
window.FakeLoader.showOverlay();
postSend(obj.url, obj.params,function (data) {
if (data.foot) {
me.load_foot_data(data.foot,obj);
}
if (data.other_foot) {
me.load_foot_data(data.other_foot,obj.other_model);
}
if (data.body) {
me.load_body_data(data.body,obj);
}
if (data.hourly_comparison){
_.each(data.hourly_comparison,function(item,index){
if(item){
_.each(item,function(value,key){
data.other_body[index][key+"_low_ratio"] = value;
})
}
})
}
if (data.other_body) {
me.load_body_data(data.other_body,obj.other_model);
}
window.FakeLoader.hideOverlay();
if (obj.overflow_hidden)
setOverflowHidden(obj.overflow_hidden)
$("tfoot td").css({"word-wrap":"break-word"});
if(obj.set_ellipsis)
setEllipsis()
}, "json", "get");
},
load_body_data : function(data,model){
var me = this;
if (data.length == 0) $("#" + model.tb_id + " tfoot").hide();
loadData(data,model);
//list.each(me.add_one);
_.each(list.models, function (item, index) {
me.add_one(item, model)
});
init_dataTables(model.tb_id, model.attributes);
// if(!$("[data-layout='sidebar-collapse']").is(":checked"))
// $("[data-layout='sidebar-collapse']").click();
// setTimeout(function(){
// init_dataTables(model.tb_id, model.attributes);
// },500);
},
load_foot_data : function(data,model){
var me = this;
$("#" + model.tb_id + " tfoot").show();
_.each(data, function (singleFoot, index) {
if (singleFoot) {
footData = singleFoot.table ? singleFoot.table : singleFoot; //OpenStruct resultๅ
ๅซtableๅฑๆง
_.each(footData, function (item, key) {
me.add_foot(item, key, model, index);
})
}
})
},
add_one: function (item, obj) {
var itemView = new DeviceItemView({model: item.set({"tb_id": obj.tb_id})});
var el = itemView.render().el;
obj.set_class(el, item);
$("#" + obj.tb_id + " tbody").append(el);
},
add_foot: function (item, key, obj, index) {
_.each($("#" + obj.tb_id + " tfoot tr[index='" + index + "'] td[tag='" + key + "']"), function (ele) {
$(ele).attr("type","foot");
tmp_obj = {}
tmp_obj[key] = item;
data_transfer(tmp_obj,ele);
})
}
});
//็ๆๆฐๆฎๆจกๆฟ
function template(model) {
var tb_id = model.attributes.tb_id;
thIndex = $("#" + tb_id).attr("th-index") ? $("#" + tb_id).attr("th-index") : 0;
var temp = "";
_.each($("#" + tb_id + " thead").find("tr").eq(thIndex).find("th"), function (ele, index) {
tagAttr = {}
tagAttr.tag = $(ele).attr("tag")
if($(ele).attr("color") == model.attributes.color) {
tagAttr.td_color = model.attributes.color;
}
if($(ele).attr("input_events")){
tagAttr.add_td_class = 'td_click_field';
model.attributes.input_events = $(ele)
}
tagAttr = add_td_backgroud(tagAttr, model.attributes);
temp += model.render(tagAttr);
});
return temp;
}
function add_td_backgroud(tagAttr, model) {
var tag = tagAttr.tag.replace("stay_", "").replace("ratio_", "");
_.each(["2", "3", "7", "15", "30"], function (item) {
if (("alive" + item) == tag) {
tagAttr.colors = model["background_alive" + item];
}
});
return tagAttr;
}
function data_transfer(item,ele){
var method_group = '';
tag = $(ele).attr("tag");
type = $(ele).attr("type");
fieldExec = $(ele).attr("field_exec");
if(fieldExec) method_group = fieldExec.split(',');
color = $(ele).attr("color");
if(color && item[tag] < 0.5) item.color = color;
if (typeof(item) != "undefined" && item) {
if(method_group) {
_.each(method_group,function(func){
tmp_function = func == "roundToInt" ? func+"('"+item[tag]+"')" : func+"("+item[tag]+")";
item[tag] = eval(tmp_function)
if(type == "foot") $(ele).html(item[tag]);
})
}
}
}
//ๅฐๆๅก็ซฏjsonๆฐๆฎaddๅฐBackbone้ๅไธญ
function loadData(data,m) {
list.reset();
thIndex = $("#" + m["tb_id"]).attr("th-index") ? $("#" + m["tb_id"]).attr("th-index") : 0;
_.each(data, function (item) {
_.each($("#" + m["tb_id"] + " thead").find("tr").eq(thIndex).find("th"), function (ele, index) {
$(ele).attr("type","body");
data_transfer(item,ele);
});
var model = new DeviceModel(item);
if(m.is_ratio) model.add_ratio();
if(m.input_events) model.attributes.input_events = m.input_events;
list.add(model);
});
}
//้่table็ๆปๅจๆก
function setOverflowHidden(pos){
overflowStr = "overflow-"+pos;
obj = {}
obj[overflowStr] = "hidden"
$(".dataTables_scrollBody").css(obj);
}
|
let blog="Azul web"
let nombre="Isabel"
console.log("Hola "+nombre+" bienvenida a: "+blog)
|
/*
* Write a function that generates every sequence of throws a single
* player could throw over a n-round game of rock-paper-scissors.
*/
var rockPaperScissors = function(n, combos){
combos = combos || [[]];
if(n < 1) { return combos; }
var choices = [['rock'], ['paper'], ['scissors']];
var current = [];
for(var i = 0; i < combos.length; i++){
for(var j = 0; j < choices.length; j++){
current.push(combos[i].concat(choices[j]));
}
}
return rockPaperScissors(n-1, current);
};
console.log(rockPaperScissors(0))
console.log(rockPaperScissors(2))
console.log(rockPaperScissors(4))
|
var firebaseConfig = {
apiKey: "AIzaSyC_Dzph-_yI-iTTMz4SYz6Xnoe9ZcKcJ3E",
authDomain: "project-name-d329b.firebaseapp.com",
databaseURL: "https://project-name-d329b.firebaseio.com",
projectId: "project-name-d329b",
storageBucket: "project-name-d329b.appspot.com",
messagingSenderId: "804094921804",
appId: "1:804094921804:web:4d39a9d8b6ca68651c78e9",
measurementId: "G-BMLF23YLY8"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
//VARIABLES
var database = firebase.database();
var ref = database.ref('Player');
ref.on('value',gotData, errData);
var Player;
var keys;
var k;
var Name;
var Password;
var ID;
var possibleID=0;
//FUNCTION
function gotData(data){
Player = data.val();
keys = Object.keys(Player);
for( var a = 0; a < keys.length; a++){
k = keys[a];
Name = Player[k].Name;
Password = Player[k].Password;
ID = Player[k].ID;
console.log(ID,Name,Password);
//Wrong way of checking ID (may masmaganda at sure na walang pareho) pero try lang
while(possibleID ==Player[k].ID){
possibleID = possibleID +1;
}
}
}
function errData(err){
console.log("Error");
}
function SignIn(){
var name = document.getElementById('name').value;
var pass = document.getElementById('pass').value;
data = {
ID: possibleID,
Name:name,
Password:pass
}
if(data.Name.length > 0){
if(ref.push(data)){
document.write("SUCCESS");
}
else{
document.write("FAILED")
}
}
else{
console.log("ERROR");
}
}
|
function conquer(x,y){
if (waiting)
return;
socket.emit("conquer", {x: x, y:y});
document.getElementById("status").innerHTML = "Recovering...";
document.getElementById("status").style.color = "red";
waiting = true;
setTimeout(function(){
document.getElementById("status").innerHTML = "Ready";
document.getElementById("status").style.color = "green";
waiting = false;
}, 1000);
}
|
import React, { createContext, useState, useMemo } from "react";
import * as Space from "react-spaces";
import { Switch, Route, Redirect, Link } from "react-router-dom";
import { ReportDashboard } from "./ReportDashboard";
import { ReportCapability } from "./ReportCapability";
import { ReportDepartment } from "./ReportDepartment";
const reportRoutes = [
{ name: "Dashboard", path: "/reports/dashboard" },
{ name: "Department", path: "/reports/department" },
{ name: "Capability", path: "/reports/capability" }
];
const reportNavStyles = {
backgroundColor: "#eee",
display: "flex",
flexDirection: "column",
justifyContent: "flex-start"
};
export const ReportsContext = createContext();
export const Reports = ({ match }) => {
const [dashboardData, setDashboardData] = useState(null);
const [departmentData, setDepartmentData] = useState(null);
const [capabilityData, setCapabilityData] = useState(null);
const reportsContextValue = useMemo(() => {
return {
dashboardData,
setDashboardData,
departmentData,
setDepartmentData,
capabilityData,
setCapabilityData
};
}, [
dashboardData,
setDashboardData,
departmentData,
setDepartmentData,
capabilityData,
setCapabilityData
]);
return (
<ReportsContext.Provider value={reportsContextValue}>
<Space.Fill>
<Space.Left size={"25%"} style={reportNavStyles} as="aside">
{reportRoutes.map(route => (
<Link key={route.name} to={route.path}>
{route.name}
</Link>
))}
</Space.Left>
<Space.Fill>
<Switch>
<Route
exact
path={match.url + "/dashboard"}
component={ReportDashboard}
/>
<Route
exact
path={match.url + "/department"}
component={ReportDepartment}
/>
<Route
exact
path={match.url + "/capability"}
component={ReportCapability}
/>
<Redirect from="/" to="/reports/dashboard" />
</Switch>
</Space.Fill>
</Space.Fill>
</ReportsContext.Provider>
);
};
|
#!/usr/bin/env node
'use strict';
var readline = require('readline');
var async = require('async');
var gumyen = require('gumyen');
var writeUTF16 = require('./util').writeUTF16;
function main(args) {
var fs = require('fs-extra');
var path = require('path');
var config = require(path.join(process.cwd(), 'plgconfig'));
var directory;
var pluginFilename;
if (args.length === 0) {
directory = config.srcDir;
pluginFilename = config.pluginFilename;
} else if (args.length === 1 && args[0] === 'test') {
directory = config.testDir;
pluginFilename = 'Test' + config.pluginFilename;
} else {
directory = args[0];
pluginFilename = args[1];
}
if (!directory || !pluginFilename) {
console.log("Usage: buildPlg [directory plg-filename | test]" );
console.log("No args - builds configured plugin" );
console.log("Arg is 'test' - builds configured test plugin" );
console.log("Plugin file is written to configured build directory");
process.exit(1);
}
var dirParts = directory.split('/');
var fullPathDirPfxLength = dirParts.length;
if (dirParts[0] === '' || dirParts[0] === '.') {
fullPathDirPfxLength = fullPathDirPfxLength - 1;
}
var output = '{\n';
try {
var globals = path.join(directory, 'GLOBALS.mss');
addFileToOutput(globals);
} catch (e) {
// NOP
}
try {
var dialogDirectory = path.join(directory, 'dialog');
var dialogsDir = fs.readdirSync(dialogDirectory);
dialogsDir
.filter(function(name) { return name.match(/.+\.msd$/)})
.forEach(function(name) { addFileToOutput(path.join(dialogDirectory, name))});
} catch (e) {
// NOP
}
buildFromDir(directory, end);
function buildFromDir(directory, cb) {
var dir = fs.readdirSync(directory);
var fullPaths = dir.map(function(name) {
return path.join(directory, name)
});
var mssFiles = fullPaths.filter(function(path) { return path.match(/.+\.mss$/)});
async.each(mssFiles, function(path, cb) { addMethodFileToOutput(path, cb)}, doSubdirs);
function doSubdirs(err) {
var subdirs = fullPaths.filter(function(path) {
var stat = fs.statSync(path);
return stat.isDirectory();
});
async.each(subdirs, buildFromDir, cb);
}
}
function addFileToOutput(mssFilename) {
var data = gumyen.readFileWithDetectedEncodingSync(mssFilename);
if (data.length) {
output += data;
output += '\n';
}
}
function end() {
output += '}\n';
writeUTF16(path.join(config.buildDir, pluginFilename), output);
console.log('written plugin code to ' + pluginFilename);
}
var funcRegex = /function\s*([_a-zA-Z][_a-zA-Z0-9$]*)\s*(\(.*\))\s*\{/;
var moduleLineRegex = /\s*\/\/\$module\(([\w/]+\.mss)\)/;
function proposedFromPath(mssFilename) {
var parts = mssFilename.split('/');
return parts.slice(fullPathDirPfxLength).join('/');
}
function addMethodFileToOutput(mssFilename, cb) {
var proposedModuleName = proposedFromPath(mssFilename);
var encoding = gumyen.encodingSync(mssFilename);
var head = '';
var moduleName = '';
var module = '';
var body = '';
var rd = readline.createInterface({
input: fs.createReadStream(mssFilename, {encoding: encoding}),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
var func = funcRegex.exec(line);
if (func) {
var mssFuncLine = '\t' + func[1] + ' "' + func[2] + ' {\n';
console.log('function: ' + func[1]);
head = mssFuncLine;
if (func[1] !== proposedModuleName) {
module = '//$module(' + proposedModuleName + ')\n'
}
} else if (line.match(/^}\s*\/\/\$end/)) {
body = body + '}"\n';
output += head;
if (module.length) output += module;
output += body;
output += '\n';
head = module = body = '';
} else if (moduleName = moduleLineRegex.exec(line)) {
module = '//$module(' + moduleName[1] + ')\n'
} else {
body += line;
body += '\n';
}
});
rd.on('close', function() {
cb(false);
});
}
}
main(process.argv.slice(2));
|
OC.L10N.register(
"lib",
{
"today" : "แแฆแแก",
"yesterday" : "แแฃแจแแ",
"last month" : "แแแกแฃแ แแแแจแ",
"last year" : "แแแแ แฌแแแก",
"seconds ago" : "แฌแแแแก แฌแแ",
"None" : "แแ แ",
"Username" : "แแแแฎแแแ แแแแแก แกแแฎแแแ",
"Password" : "แแแ แแแ",
"__language_name__" : "__language_name__",
"Apps" : "แแแแแแแชแแแแ",
"General" : "แแแแแแ",
"Storage" : "แกแแชแแแ",
"Security" : "แฃแกแแคแ แแฎแแแแ",
"Encryption" : "แแแแ แแแชแแ",
"Sharing" : "แแแแแแ แแแ",
"Search" : "แซแแแแ",
"%s enter the database username." : "%s แจแแแงแแแแแ แแแแแก แแฃแแแ แแแแแ.",
"%s enter the database name." : "%s แจแแแงแแแแแ แแแแแก แกแแฎแแแ.",
"Oracle username and/or password not valid" : "Oracle แแฃแแแ แแแแแ แแ/แแ แแแ แแแ แแ แแ แแก แกแฌแแ แ",
"DB Error: \"%s\"" : "DB แจแแชแแแแ: \"%s\"",
"Offending command was: \"%s\"" : "Offending แแ แซแแแแแ แแงแ: \"%s\"",
"You need to enter either an existing account or the administrator." : "แแฅแแแ แฃแแแ แจแแแงแแแแแ แแ แกแแแฃแแ แแแแฎแแแ แแแแแแก แกแแฎแแแ แแ แแแแแแแกแขแ แแขแแ แ.",
"Offending command was: \"%s\", name: %s, password: %s" : "Offending แแ แซแแแแแ แแงแ: \"%s\", แกแแฎแแแ: %s, แแแ แแแ: %s",
"PostgreSQL username and/or password not valid" : "PostgreSQL แแฃแแแ แแแแแ แแ/แแ แแแ แแแ แแ แแ แแก แกแฌแแ แ",
"Set an admin username." : "แแแแงแแแแ แแแแแแแกแขแ แแขแแ แแก แกแแฎแแแ.",
"Set an admin password." : "แแแแงแแแแ แแแแแแแกแขแ แแขแแ แแก แแแ แแแ.",
"Could not find category \"%s\"" : "\"%s\" แแแขแแแแ แแแก แแแซแแแแ แแแ แแแฎแแ แฎแแ",
"A valid username must be provided" : "แฃแแแ แแแฃแแแแแ แแ แกแแแฃแแ แแแแฎแแแ แแแแแก แกแแฎแแแ",
"A valid password must be provided" : "แฃแแแ แแแฃแแแแแ แแ แกแแแฃแแ แแแ แแแ",
"Settings" : "แแแ แแแแขแ แแแ",
"Users" : "แแแแฎแแแ แแแแแ",
"Imprint" : "แแแญแแแ",
"Application is not enabled" : "แแแแแแแชแแ แแ แแ แแก แแฅแขแแฃแ แ",
"Authentication error" : "แแแแแแขแแคแแแแชแแแก แจแแชแแแแ",
"Token expired. Please reload page." : "Tokenโแก แแแแ แแแฃแแแแ. แแแฎแแแ แแแแแแฎแแแ แแแแ แแ."
},
"nplurals=2; plural=(n!=1);");
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
angular.module('appMain').controller('listParcController',function($scope,$http){
//get parceiros from DB
listaParceiros();
//Edit User
$scope.editUser = function(u){
$scope.edit = u;
};
//Remove User
$scope.removeUser = function(u){
if(u !== undefined && u !== {}){
$http({
url:'php/admin/editarParceiro.php',
method:'POST',
data:JSON.stringify({'parceiro':u,'op':'D'})
}).then(function(answer){
if(answer.data){
alert(answer.data);
}
$scope.edit = {};
listaParceiros();
});
}
};
//Save or update parceiro
$scope.saveUser = function(u){
$http({
url:'php/admin/editarParceiro.php',
method:'POST',
data:JSON.stringify({'parceiro':u,'op':'IU'})
}).then(function(answer){
$scope.edit = {};
listaParceiros();
});
};
//Clear form
$scope.clear = function(){
$scope.edit = {};
};
function listaParceiros(){
$http({
url:'php/getData.php',
method:'POST',
data:'cad_parceiros'
}).then(function(answer){
$scope.parceiros= answer.data;
});
}
});
|
/**
* Created by Happy Life on 2017/2/11.
*/
// ๅๅปบไธไธชๆๅกๆจกๅ
angular.module("movieApp.service",[])
.service("$movieServ",function () {
});
|
describe("testing BowlingGame HTML page",function(){
beforeEach(function() {
// browser().reload();
browser().navigateTo('Bowling.html');
// add player 1
input('Name').enter('Player1');
element('#add_user_btn',"Add Player Button").click();
input('Name').enter('Player2');
element('#add_user_btn',"Add Player Button").click();
});
it("should update score when user plays",function(){
input('pin').enter('4');
element('#play-btn:button',"Play Button").click();
expect(element('div#scorePlayer1').text()).toBe("4");
input('pin').enter('6');
element('#play-btn:button',"Play Button").click();
expect(element('div#scorePlayer1').text()).toBe("10");
input('pin').enter('2');
element('#play-btn:button',"Play Button").click();
expect(element('div#scorePlayer2').text()).toBe("2");
});
afterEach(function(){
// alert("done");
});
});
|
const readBooks = require('./callback.js')
const books = [
{ name: 'LOTR', timeSpent: 3000 },
{ name: 'Fidas', timeSpent: 2000 },
{ name: 'Kalkulus', timeSpent: 4000 },
{ name: 'komik', timeSpent: 1000 }
]
// Tulis code untuk memanggil function readBooks di sini
let waktu = 10000
const getPosts = (waktu) => {
setTimeout(() => {
readBooks(waktu, books[1], getPosts1)
}, books[1].timeSpent)
}
const getPosts1 = (waktu) => {
setTimeout(() => {
readBooks(waktu, books[2], getPosts2)
}, books[2].timeSpent)
}
const getPosts2 = (waktu) => {
setTimeout(() => {
readBooks(waktu, books[3], getPost)
}, books[3].timeSpent)
}
const getPost = () => {
setTimeout(() => {
books.forEach(books => {
console.log(books)
})
}, 1000)
}
readBooks(waktu, books[0], getPosts)
|
/**
* Created by StarkX on 08-Mar-18.
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
let mongooseHidden = require('mongoose-hidden')();
let langList = [ 'en-us' ];
const UserSchema = new Schema({
handle : { type : String, trim : true, required : true },
email : { type : String, trim : true, required : true, unique : true, sparse : true, lowercase : true },
password : { type : String, required : true, hideJSON : true },
role : { type : String, enum : [ 'user', 'admin' ], default : 'user', hideJSON : true },
profile : {
name : { type : String, trim : true, required : true },
lang : { type : String, default : 'en-us', enum : langList },
}
});
UserSchema.plugin(mongooseHidden);
module.exports = UserSchema;
|
import { connect } from 'react-redux';
import { Redirect } from 'react-router';
function RedirectToFirstPage(props) {
const { userInfo, location } = props;
const { pathname } = location;
return (<div>
{ userInfo ? ( pathname === '/' ? <Redirect to='/userCenter'/> : <Redirect to={pathname}/>) : '' }
</div>);
}
function mapStateProps(state) {
return {
userInfo: state.userInfo
};
}
export default connect(mapStateProps)(RedirectToFirstPage);
|
/**
* Created by kanak on 1/6/16.
*/
var datepicker1 = $('#datepicker1');
var datepicker4 = $('#datepicker4');
datepicker4.on('change', function () {
var date_from = datepicker1.val();
var new_date_from = new Date(date_from);
var date_to = datepicker4.val();
var new_date_to = new Date(date_to);
if (date_from > date_to) {
alert('To Date cannot be smaller than From Date');
datepicker4.val('');
}
else {
var timeDiff = Math.abs(new_date_to.getTime() - new_date_from.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays == 1) {
diffDays = 2;
}
if (diffDays == 0) {
var time_from = date_from + ' ' + $('#timepicker1').val() + ':00';
var time_to = date_to + ' ' + $('#timepicker4').val() + ':00';
var diff = moment.duration(moment(time_to).diff(moment(time_from)));
diff = diff / 3600 / 1000;
if (diff <= 4) {
$('#total_days').val('Half day leave');
}
else if (diff > 4) {
$('#total_days').val('Full day leave');
}
}
else {
if (diffDays > 1) {
$('#total_days').val(toWords(diffDays) + 'days leave');
}
else {
$('#total_days').val(toWords(diffDays) + 'day leave');
}
}
}
});
datepicker1.on('change', function () {
var date_from = datepicker1.val();
var new_date_from = new Date(date_from);
var date_to = datepicker4.val();
var new_date_to = new Date(date_to);
var timeDiff = Math.abs(new_date_to.getTime() - new_date_from.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays == 1) {
diffDays = 2;
}
if (diffDays == 0) {
var time_from = date_from + ' ' + $('#timepicker1').val() + ':00';
var time_to = date_to + ' ' + $('#timepicker4').val() + ':00';
var diff = moment.duration(moment(time_to).diff(moment(time_from)));
diff = diff / 3600 / 1000;
if (diff <= 5) {
$('#total_days').val('Half day leave');
}
else if (diff > 5) {
$('#total_days').val('Full day leave');
}
}
else {
if (diffDays > 1) {
$('#total_days').val(toWords(diffDays) + 'days leave');
}
else {
$('#total_days').val(toWords(diffDays) + 'day leave');
}
}
//}
});
$('#timepicker4').on('change', function () {
var date_from = datepicker1.val();
var new_date_from = new Date(date_from);
var date_to = datepicker4.val();
var new_date_to = new Date(date_to);
var timeDiff = Math.abs(new_date_to.getTime() - new_date_from.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays == 1) {
diffDays = 2;
}
if (diffDays == 0) {
var time_from = date_from + ' ' + $('#timepicker1').val() + ':00';
var time_to = date_to + ' ' + $('#timepicker4').val() + ':00';
var diff = moment.duration(moment(time_to).diff(moment(time_from)));
diff = diff / 3600 / 1000;
if (diff <= 3.5) {
$('#total_days').val('First half leave');
}
else if (diff > 3.5 && diff < 5) {
$('#total_days').val('Second half leave');
}
else if (diff > 5) {
$('#total_days').val('Full day leave');
}
}
else {
if (diffDays > 1) {
$('#total_days').val(toWords(diffDays) + 'days leave');
}
else {
$('#total_days').val(toWords(diffDays) + 'day leave');
}
}
});
// Convert numbers to words
// copyright 25th July 2006, by Stephen Chapman http://javascript.about.com
// permission to use this Javascript on your web page is granted
// provided that all of the code (including this copyright notice) is
// used exactly as shown (you can change the numbering system if you wish)
// American Numbering System
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'Please select both days ';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
}
$(document).on('change', '.leave_type', function () {
var showLeaveCount = $('#show-leave-count');
var leaveTypeId = $('.leave_type').val();
var token = $('#token').val();
var userId = $('#user_id').val();
$.post('/get-leave-count', {'leaveTypeId': leaveTypeId, '_token': token, 'userId': userId}, function (data) {
parsed = JSON.parse(data);
showLeaveCount.empty();
var html = "<div class=' col-md-5 alert alert-dark center-block '>Leaves   Remaining : " + parsed + "</div>";
showLeaveCount.append(html);
});
});
$('.approveClick').click(function () {
var leaveId = $(this).data('id');
var type = $(this).data('name');
var token = $('#token').val();
$('#leave_id').val(leaveId);
$('#type').val(type);
$('#remarkModal').modal('show');
});
$('#proceed-button').click(function () {
$('#loader').removeClass('hidden');
console.log('please wait processing...');
var remarks = $('#remark-text').val();
var type = $('#type').val();
console.log('remarks ' + remarks);
var leave_id = $('#leave_id').val();
var token = $('#token').val();
var message = '';
var divClass = 'alert-success';
var url = '/approve-leave';
var buttonText = 'Approved';
var buttonClass = 'btn-success';
var buttonIcon = 'fa-check';
if (type == 'approve') {
message = 'Successfully Approved';
}
else {
message = 'Leave Rejected';
divClass = 'alert-danger';
url = '/disapprove-leave';
buttonText = 'Disapproved';
buttonClass = 'btn-danger';
buttonIcon = 'fa-times';
}
$.post(url, {'leaveId': leave_id, 'remarks': remarks, '_token': token}, function (data) {
var parsed = JSON.parse(data);
if (parsed === 'success') {
$('#loader').addClass('hidden');
var statusmessage = $('#status-message');
statusmessage.append("<div class='alert " + divClass + "'>" + message + "</div>");
statusmessage.removeClass('hidden');
var remarks_div = $('#remark-' + leave_id);
remarks_div.append(remarks);
var leavebutton = $('#button-' + leave_id);
leavebutton.empty();
leavebutton.append("<button type='button' class='btn " + buttonClass + " br2 btn-xs fs12' aria-expanded='false'><i class='fa " + buttonIcon + "'>" + buttonText + "</i> </button>");
setTimeout(function () {
$('#remarkModal').modal('hide');
}, 4000);
}
});
});
$('.disapproveClick').click(function () {
var leaveId = $(this).data('id');
var token = $('#token').val();
$('#leave_id').val(leaveId);
$('#remarkModal').modal('show');
});
/*$('#proceed-button').click(function(){
$('#loader').removeClass('hidden');
console.log('please wait processing...');
var remarks = $('#remark-text').val();
console.log('remarks ' + remarks);
var leave_id = $('#leave_id').val();
var token = $('#token').val();
console.log('leave id ' + leave_id);
$.post('/disapprove-leave', {'leaveId': leave_id, 'remarks' : remarks, '_token' : token}, function(data)
{
var parsed = JSON.parse(data);
if(parsed === 'success')
{
$('#loader').addClass('hidden');
$('#status-message2').removeClass('hidden');
var remarks_div = $('#remark-'+leave_id);
remarks_div.append(remarks);
var leave_button = $('#button-'+leave_id);
leave_button.empty();
leave_button.append("<button type='button' class='btn btn-success br2 btn-xs fs12' aria-expanded='false'><i class='fa fa-check'> Disapproved </i> </button>");
setTimeout(function() {
$('#remarkModal2').modal('hide');
},4000);
}
});
});*/
$('#passwordForm').submit(function (event) {
event.preventDefault();
var old_password = $('#old_password').val();
var new_password = $('#new_password').val();
var confirm_password = $('#confirm_password').val();
if (new_password != confirm_password) {
alert('New password and confirm password does not match');
return false;
}
document.getElementById("passwordForm").submit();
});
$('#create-event').click(function () {
$('#status-section').removeClass('hidden');
var name = $('#event_name').val();
var coordinator = $('#event_cordinater').val();
var attendees = $('#event_attendees').val();
var date = $('#date_time').val();
var message = $('#event_description').val();
var token = $('#token').val();
$.post('create-event', {
'name': name,
'coordinator': coordinator,
'attendees': attendees,
'date': date,
'message': message,
'_token': token
}, function (data) {
$('#status-section').addClass('hidden');
$('#message-section').removeClass('hidden');
var parsed = JSON.parse(data);
if (parsed === 'success') {
alert(parsed);
}
});
});
$('#create-meeting').click(function () {
$('#status-section').removeClass('hidden');
var name = $('#meeting_name').val();
var coordinator = $('#meeting_cordinater').val();
var attendees = $('#meeting_attendees').val();
var date = $('#date_time').val();
var message = $('#meeting_description').val();
var token = $('#token').val();
$.post('create-meeting', {
'name': name,
'coordinator': coordinator,
'attendees': attendees,
'date': date,
'message': message,
'_token': token
}, function (data) {
$('#status-section').addClass('hidden');
$('#message-section').removeClass('hidden');
var parsed = JSON.parse(data);
if (parsed === 'success') {
alert(parsed);
}
});
});
$(document).on('change', '#qualification', function () {
var value = $('.qualification_select').val();
if (value == 'Other') {
$('.qualification_text').removeClass('hidden');
}
else if (value != 'Other') {
$('.qualification_text').addClass('hidden');
}
});
$(document).on('change', '#probation_period', function () {
var value = $('.probation_select').val();
if (value == 'Other') {
$('.probation_text').removeClass('hidden');
}
else if (value != 'Other') {
$('.probation_text').addClass('hidden');
}
});
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["qualification_text"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["qualification"];
var oDDL = oForm.elements["qualification_list"];
var oTextbox = oForm.elements["qualification_text"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
/*
var number = 10;
function doStuff() {
number = number +10;
$('.progress-bar').attr('aria-valuenow', number).css('width',number);
}*/
$('.showModal').click(function () {
var info = $(this).data('info');
var employee_id = info[0];
var employee_name = info[1];
var bank_name = info[2];
var account_number = info[3];
var ifsc_code = info[4];
var pf_account_number = info[5];
$('#employee_name').val(employee_name);
$('#bank_name').val(bank_name);
$('#account_number').val(account_number);
$('#ifsc_code').val(ifsc_code);
$('#pf_account_number').val(pf_account_number);
$('#emp_id').val(employee_id);
$('#bankModal').modal('show');
});
$('#update-bank-account-details').click(function () {
swal(
"Please wait while we process your request"
);
var employee_id = $('#emp_id').val();
var employee_name = $('#employee_name').val();
var bank_name = $('#bank_name').val();
var account_number = $('#account_number').val();
var ifsc_code = $('#ifsc_code').val();
var pf_account_number = $('#pf_account_number').val();
var token = $('#token').val();
console.log(account_number)
$.post('/update-account-details', {
'employee_id': employee_id,
'employee_name': employee_name,
'bank_name': bank_name,
'account_number': account_number,
'ifsc_code': ifsc_code,
'pf_account_number': pf_account_number,
'_token': token
}, function (data) {
var parsed = JSON.parse(data);
if (parsed == 'success') {
swal({
title: "Success!",
text: "Bank Details Successfully updated!",
type: "success",
confirmButtonText: "OK",
allowEscapeKey: true,
allowOutsideClick: true
},
function () {
location.reload(true);
});
}
else {
swal({
title: "Error!",
text: "Sorry, details not update!",
type: "error",
confirmButtonText: "OK",
allowEscapeKey: true,
allowOutsideClick: true
},
function () {
location.reload(true);
});
}
});
});
$(document).on('change', '#promotion_emp_id', function () {
var oldDesignation = $('#old_designation');
var oldSalary = $('#old_salary');
var emp_id = $('#promotion_emp_id').val();
var token = $('#token').val();
$.post('/get-promotion-data', {'employee_id': emp_id, '_token': token}, function (data) {
var parsed = JSON.parse(data);
if (parsed.status == 'success') {
oldDesignation.val('');
oldDesignation.val(parsed.data.designation);
oldSalary.val('');
oldSalary.val(parsed.data.salary);
}
else {
}
});
});
$('#post-update').click(function()
{
var postUpdate = $('#post-update');
$('#post-button').css('padding-left', '80%');
postUpdate.val('Posting...');
var status = $('#status').val();
var token = $('meta[name=csrf_token]').attr("content");
$.post('/status-update', {'status': status, '_token' : token}, function(data)
{
var parsed = JSON.parse(data);
if(parsed.status)
{
$('.append-post').prepend(parsed.html);
}
$('#post-button').css('padding-left', '90%');
postUpdate.val('Post');
});
});
$('.post-reply').click(function()
{
var postId = $(this).data('post_id');
var postUpdate = $('.post-reply');
$('.reply-button').css('padding-left', '75%');
postUpdate.val('Replying...');
var reply = $('.reply');
var token = $('meta[name=csrf_token]').attr("content");
$.post('/post-reply', {'reply': reply.val(), 'post_id' : postId, '_token' : token}, function(data)
{
var parsed = JSON.parse(data);
if(parsed.status)
{
$('.container-for-reply-'+postId).append(parsed.html);
}
reply.val('');
$('.reply-button').css('padding-left', '80%');
postUpdate.val('Reply');
});
});
$('#code').blur(function(){
var code = $(this).val();
var codeGroup = $('.code-group');
$.get('/validate-code/'+code, function(data)
{
var parsed = JSON.parse(data);
if(parsed.status)
{
$('.btn-info').removeAttr('disabled');
codeGroup.removeClass('has-error');
codeGroup.addClass('has-success');
}
else
{
$('.save-client').attr('disabled','disabled');
codeGroup.removeClass('has-success');
codeGroup.addClass('has-error');
}
});
});
|
import React, {Component} from 'react';
import {Text, TouchableOpacity} from 'react-native';
import { connect } from 'react-redux';
import { employeeCreateAction, employeeCreateWith } from '../actions';
import { Card, CardSection} from './common/';
import EmployeeForm from './EmployeeForm';
class EmployeeCreate extends Component{
onButtonPress(){
const {name, phone, shift} = this.props;
this.props.employeeCreateWith({name, phone, shift: shift || 'Monday'})
}
render(){
return(
<Card>
<EmployeeForm {...this.props} />
<CardSection>
<TouchableOpacity style = {styles.buttonStyle} onPress={this.onButtonPress.bind(this)}>
<Text style={styles.textStyle}>Create</Text>
</TouchableOpacity>
</CardSection>
</Card>
);
}
}
const styles = {
buttonStyle: {
flex: 1,
alignSelf: 'stretch',
borderRadius: 5,
borderWidth: 1,
borderColor: '#007aff',
marginLeft: 5,
marginRight: 5
},
textStyle: {
color: '#007aff',
fontSize: 16,
fontWeight: '600',
alignSelf: 'center',
paddingTop: 10,
paddingBottom: 10
}
}
const mapStateToProps = (state) => {
const {name, phone, shift} = state.employeeForm;
return{ name, phone, shift };
}
export default connect(mapStateToProps, {employeeCreateAction, employeeCreateWith})(EmployeeCreate);
|
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const bourbon = require('node-bourbon').includePaths;
const config = require('./webpack.config.js');
config.devtool = 'cheap-module-eval-source-map';
config.entry = {
'sanji-ui': [
'webpack/hot/dev-server',
'webpack-dev-server/client?http://0.0.0.0:8080',
'./app.js'
]
};
config.module.loaders = [
{test: /\.js$/, loader: 'ng-annotate-loader', exclude: /(node_modules)/, enforce: 'post'},
{test: /\.scss/, loader: 'style-loader!css-loader!postcss-loader!sass-loader?includePaths[]=' + bourbon},
{test: /\.css$/, loader: 'style-loader!css-loader!postcss-loader?browsers=last 2 versions'}
].concat(config.module.loaders);
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.LoaderOptionsPlugin({
debug: true,
options: {
postcss: [
autoprefixer({ browsers: ['last 2 versions'] })
]
}
}),
new HtmlWebpackPlugin({
template: 'index.html',
hash: true
})
);
module.exports = config;
|
import React, { Component } from 'react';
import 'datatables.net-dt/css/jquery.dataTables.css'
import 'datatables-bulma/css/dataTables.bulma.css'
// import 'jquery/dist/jquery.min'
// import 'datatables.net-dt/js/dataTables.dataTables'
// import 'datatables-bulma/js/dataTables.bulma'
const $ = require('jquery')
$.DataTable = require('datatables-bulma')
export default class Table extends Component {
componentDidMount() {
console.log(this.el)
this.$el = $(this.el)
this.$el.DataTable(
{
data: this.props.data,
columns: [
{title: 'Name'},
{title: 'Position'},
{title: 'Office'},
{title: 'Extn.'},
{title: 'Start date'},
{title: 'Salary'}
]
}
)
}
render() {
return (
<div>
<div className="card">
<header className="card-header">
<p className="card-header-title"> Title</p>
</header>
<div className="card-content">
<table className="table is-bordered is-hoverable is-narrow " ref={ el => this.el = el }></table>
</div>
</div>
</div>
);
}
}
|
/******************************************************************************************************************************
COMMING SOON PAGE
*******************************************************************************************************************************/
(function($) {
/**
* Set your date here (YEAR, MONTH (0 for January/11 for December), DAY, HOUR, MINUTE, SECOND)
* according to the GMT+0 Timezone
**/
var launch = new Date(2017, 04, 24, 04, 00);
/**
* The script
**/
var message = $('#message');
var days = $('#days');
var hours = $('#hours');
var minutes = $('#minutes');
var seconds = $('#seconds');
var daysM = $('#daysM');
var hoursM = $('#hoursM');
var minutesM = $('#minutesM');
var secondsM = $('#secondsM');
setDate();
function setDate(){
var now = new Date();
if( launch < now ){
days.html('<h1>0</H1><p>Dias</p>');
hours.html('<h1>0</h1><p>Horas</p>');
minutes.html('<h1>0</h1><p>Minutos</p>');
seconds.html('<h1>0</h1><p>Segundos</p>');
//message.html('OUR SITE IS NOT READY YET...');
message.html('0 Dรญas 0 Horas 0 Minutos 0 Segundos<br>');
}
else{
var s = -now.getTimezoneOffset()*60 + (launch.getTime() - now.getTime())/1000;
var d = Math.floor(s/86400);
days.html('<h1>'+d+'</h1><p>Dรญa'+(d>1?'s':''),'</p>');
s -= d*86400;
var h = Math.floor(s/3600);
hours.html('<h1>'+h+'</h1><p>Hora'+(h>1?'s':''),'</p>');
s -= h*3600;
var m = Math.floor(s/60);
minutes.html('<h1>'+m+'</h1><p>Minuto'+(m>1?'s':''),'</p>');
s = Math.floor(s-m*60);
seconds.html('<h1>'+s+'</h1><p>Segundo'+(m>1?'s':'')+'</p>');
message.html(d+' Dรญa'+(d>1?'s ':' ')+h+' Hora'+(h>1?'s ':' ')+m+' Minuto'+(m>1?'s ':' ')+s+' Segundo'+(m>1?'s':'')+'<br>');
setTimeout(setDate, 1000);
}
}
})(jQuery);
|
class FSM {
/**
* Creates new FSM instance.
* @param config
*/
constructor(config) {
if (!config) {
throw new Error('config is\'not passed');
}
this.config = config;
this.initialState = config.initial;
this.state = config.initial;
this.history = [config.initial];
this.undoHistory = [];
this.triggerDisabler = false;
}
/**
* Returns active state.
* @returns {String}
*/
getState() {
return this.state;
}
/**
* Goes to specified state.
* @param state
*/
changeState(state) {
if (!this.config.states.hasOwnProperty(state)) {
throw new Error('There is no such state!');
}
for(var _state in this.config.states){
if (_state == state) {
this.state = state;
this.history.push(this.state);
this.triggerDisabler = true;
}
}
}
/**
* Changes state according to event transition rules.
* @param event
*/
trigger(event) {
for (var _stateCheck in this.config.states) {
if (_stateCheck == this.state) {
if (!this.config.states[_stateCheck].transitions.hasOwnProperty(event)) {
throw new Error('No such event in this state!');
}
}
}
for (var _state in this.config.states) {
if(_state == this.state){
for (var transition in this.config.states[_state].transitions) {
if(transition == event){
this.state = this.config.states[_state].transitions[transition];
this.history.push(this.state);
this.triggerDisabler = true;
return true;
}
}
}
}
}
/**
* Resets FSM state to initial.
*/
reset() {
this.state = this.initialState;
this.history.push(this.state);
}
/**
* Returns an array of states for which there are specified event transition rules.
* Returns all states if argument is undefined.
* @param event
* @returns {Array}
*/
getStates(event) {
var inStates = [];
if (!event) {
for (var _state in this.config.states) {
inStates.push(_state);
}
}else {
for (var _state in this.config.states) {
if (this.config.states[_state].transitions.hasOwnProperty(event)) {
inStates.push(_state);
}
}
}
return inStates;
}
/**
* Goes back to previous state.
* Returns false if undo is not available.
* @returns {Boolean}
*/
undo() {
if (this.history.length == 1) {
return false;
}
else{
this.undoHistory.push(this.history.pop());
//this.changeState(this.history[this.history.length - 1]);
this.state = this.history[this.history.length - 1];
this.triggerDisabler = false;
return true;
}
}
/**
* Goes redo to state.
* Returns false if redo is not available.
* @returns {Boolean}
*/
redo() {
if (this.undoHistory.length == 0) {
return false;
} else if (this.triggerDisabler == true){
return false;
}
else{
this.state = this.undoHistory[this.undoHistory.length - 1];
this.history.push(this.undoHistory.pop());
return true;
}
}
/**
* Clears transition history
*/
clearHistory() {
this.history = [this.initialState];
this.undoHistory = [];
}
}
module.exports = FSM;
/** @Created by Uladzimir Halushka **/
|
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint @typescript-eslint/no-var-requires: "off" */
const { join } = require('path');
module.exports = {
rootDir: join(__dirname, '..'),
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.ts'],
};
|
function init() {
var divBiaoQian = document.getElementById('agou')
divBiaoQian.innerHTML=''
divBiaoQian.setAttribute('style','height:200px;width:280px;background-color:pink;margin-left:400px;margin-top:400px')
}
window.onload = init;
|
// >>> Section: Key state class
// The key state class contains detailed information about a keys state
function KeyState()
{
var pressed_time = 0.0; // Time the key has been pressed or 0.0 if currently not pressed
var pressedframe_time = 0.0; // Time the key has been pressed in this frame or 0.0 if currently not pressed
var pressedframe_duration = 0.0; // Total duration the key had been pressed during this frame (even if currently not pressed)
this.onKeyDown = function(t)
{
pressed_time = t;
pressedframe_time = t;
}
this.onKeyUp = function(t)
{
pressed_time = 0.0;
pressedframe_duration += (pressedframe_time != 0.0) * (t - pressedframe_time);
pressedframe_time = 0.0;
}
this.onFrame = function(t)
{
if(pressedframe_time)
pressedframe_time = t;
pressedframe_duration = 0.0;
}
this.reset = function()
{
pressed_time = 0.0;
pressedframe_time = 0.0;
pressedframe_duration = 0.0;
}
this.isPressed = function()
{
return pressed_time != 0.0;
}
this.pressedDuration = function(t) // Duration since the key was pressed or 0.0 if not currently pressed
{
return pressed_time == 0.0 ? 0.0 : t - pressed_time;
}
this.pressedFrameDuration = function(t) // See pressedframe_duration
{
return pressedframe_duration + (pressedframe_time != 0.0) * (t - pressedframe_time);
}
}
/*// >>> Section: Keyboard input handler
var pressedkeys = [];
for(i = 0; i < 255; i++) pressedkeys[i] = false;
function handleKeyDown(event)
{
event.preventDefault();
if(pressedkeys[event.keyCode] == false)
{
var t = new Date().getTime() / 1000.0 - starttime;
pressedkeys[event.keyCode] = true;
var statekeymap = keymap[statemachine.getState()];
if(statekeymap)
{
// Perform any-key action
var anykeyaction = statekeymap[-1];
if(anykeyaction && anykeyaction[0])
anykeyaction[0](t, event.keyCode);
// Perform key specific action
var keyaction = statekeymap[event.keyCode];
if(keyaction && keyaction[0])
keyaction[0](t, event.keyCode);
}
}
}
function handleKeyUp(event)
{
event.preventDefault();
if(pressedkeys[event.keyCode] == true)
{
var t = new Date().getTime() / 1000.0 - starttime;
pressedkeys[event.keyCode] = false;
var statekeymap = keymap[statemachine.getState()];
if(statekeymap)
{
// Perform any-key action
var anykeyaction = statekeymap[-1];
if(anykeyaction && anykeyaction[1])
anykeyaction[1](t, event.keyCode);
// Perform key specific action
var keyaction = statekeymap[event.keyCode];
if(keyaction && keyaction[1])
keyaction[1](t, event.keyCode);
}
}
}*/
// >>> Section: Mouse input handler
var mouseHandlers = [], mouseHandlerCanvasList = [];
var pressedmousebuttons = [];
function RegisterMouseHandler(cls, canvas)
{
pressedmousebuttons[mouseHandlers.length] = [false, false, false, false];
mouseHandlers.push(cls);
mouseHandlerCanvasList.push(canvas);
}
function handleMouseDown(event)
{
var canvas = event.target;
var idx = mouseHandlerCanvasList.indexOf(event.target);
var mouseHandler = mouseHandlers[idx];
event.preventDefault();
pressedmousebuttons[idx][event.which] = true;
if(typeof(mouseHandler.onMouseDown) == 'function')
{
var canvasBounds = canvas.getBoundingClientRect();
mouseHandler.onMouseDown(canvas, event.clientX - canvasBounds.left, event.clientY - canvasBounds.top, event.which);
}
}
function handleMouseUp(event)
{
for(var i = 0; i < mouseHandlers.length; ++i)
{
var canvas = mouseHandlerCanvasList[i];
var mouseHandler = mouseHandlers[i];
if(pressedmousebuttons[i][event.which] == true)
{
event.preventDefault();
pressedmousebuttons[i][event.which] = false;
if(typeof(mouseHandler.onMouseUp) == 'function')
{
var canvasBounds = canvas.getBoundingClientRect();
mouseHandler.onMouseUp(canvas, event.clientX - canvasBounds.left, event.clientY - canvasBounds.top, event.which, event.target);
}
}
}
}
function handleMouseMove(event)
{
// Fire event for canvas with mouse down
for(var i = 0; i < mouseHandlers.length; ++i)
{
var canvas = mouseHandlerCanvasList[i];
var mouseHandler = mouseHandlers[i];
if(pressedmousebuttons[i].some(function(button) { return button; }))
{
event.preventDefault();
if(typeof(mouseHandler.onMouseMove) == 'function')
{
var canvasBounds = canvas.getBoundingClientRect();
mouseHandler.onMouseMove(canvas, event.clientX - canvasBounds.left, event.clientY - canvasBounds.top, pressedmousebuttons[i]);
return;
}
}
}
// If no canvas had mouse down, fire event for target (canvas under mouse cursor)
var idx = mouseHandlerCanvasList.indexOf(event.target);
if(idx != -1)
{
var canvas = event.target;
var mouseHandler = mouseHandlers[idx];
if(typeof(mouseHandler.onMouseMove) == 'function')
{
canvas = mouseHandler.canvas;
event.preventDefault();
var canvasBounds = canvas.getBoundingClientRect();
mouseHandler.onMouseMove(event.target, event.clientX - canvasBounds.left, event.clientY - canvasBounds.top, pressedmousebuttons[idx]);
}
}
}
function handleMouseLeave(event)
{
var canvas = event.target;
var idx = mouseHandlerCanvasList.indexOf(event.target);
var mouseHandler = mouseHandlers[idx];
event.preventDefault();
if(typeof(mouseHandler.onMouseLeave) == 'function')
{
var canvasBounds = canvas.getBoundingClientRect();
mouseHandler.onMouseLeave(canvas, event.clientX - canvasBounds.left, event.clientY - canvasBounds.top, pressedmousebuttons[idx]);
}
}
function handleMouseWheel(event)
{
var canvas = event.target;
var idx = mouseHandlerCanvasList.indexOf(event.target);
var mouseHandler = mouseHandlers[idx];
if(mouseHandler != null && typeof(mouseHandler.onMouseWheel) == 'function')
{
var deltaZ = event.wheelDelta == null ? event.detail : -event.wheelDelta / 20.0;
event.preventDefault();
var canvasBounds = canvas.getBoundingClientRect();
mouseHandler.onMouseWheel(canvas, event.clientX - canvasBounds.left, event.clientY - canvasBounds.top, deltaZ, pressedmousebuttons[idx]);
}
}
|
var exp = '';
var res = '';
$("#clear").click(function (){
$(".result-text").text('0');
$(".type-text").text('');
exp = '';
res = '';
this.blur();
});
$("#equal").click(function() {
this.blur()
})
$(".btn").css('outline','none');
$("#clear, #equal").click(function(){
this.focus();
this.blur();
}
)
$(".type").click(function(){
this.blur();
exp += $(this).text();
res += $(this).text();
$(".btn").css('outline','none');
$(".type-text").text(exp);
if(res.match(/\/|\*|\+|\-/g)!=null){
res = $(this).text();
$(".result-text").text(res);
res = '';
} else {
$(".result-text").text(res);
}
if(res.length>13||exp.length>25){
$(".result-text").text('Limit Reached');
$('.type-text').text('');
res = '';
exp = '';
}
});
$("#equal").click( function() {
if(exp.match(/\/{2}|\+{2}|\-{2}|\*{2}|\/\*|\*\//g)){
$(".result-text").text('Syntax Error');
$(".type-text").text('');
res = '';
exp = '';
}
try {
var result = eval(exp);
exp = result.toString();
if (result.toString().length>9){
result = parseInt(result).toExponential()
if(result.toString().length>13){
$(".result-text").text('Limit Reached')
$('.type-text').text('');
} else {
$(".result-text").text(result);
$(".type-text").text(result);
}
} else{
$(".result-text").text(result);
$(".type-text").text(result);
}
}
catch(err){
console.log();
if($(".result-text").text()=="0"){
$(".result-text").text('0');
} else {
$(".result-text").text('Syntax Error');
$(".type-text").text('');
}
}
})
$(".btn-none").click(function (e) {
$(".ripple").remove();
var posX = $(this).offset().left,
posY = $(this).offset().top,
buttonWidth = $(this).width(),
buttonHeight = $(this).height();
$(this).prepend("<span class='ripple'></span>");
if(buttonWidth >= buttonHeight) {
buttonHeight = buttonWidth;
} else {
buttonWidth = buttonHeight;
}
var x = e.pageX - posX - buttonWidth / 2;
var y = e.pageY - posY - buttonHeight / 2;
$(".ripple").css({
width: buttonWidth,
height: buttonHeight,
top: y + 'px',
left: x + 'px'
}).addClass("rippleEffect");
});
$('html').keydown(function(e){
switch(e.keyCode){
case 8: //backspace
exp = exp.substr(0, exp.length-1);
res = res.substr(0, res.length-1);
$('.type-text').text(exp);
if(res.length>0){
$('.result-text').text(res);
} else {
$('.result-text').text('0');
}
break;
case 13: //enter
$("#equal").click().focus();
setTimeout(function() {$("#equal").blur()}
, 200);
break;
case 96: //num 0
case 48: //0
$("button[val='0']").click().focus();
setTimeout(function() {$("button[val='0']").blur()}
, 200);
break;
case 49: //1
case 97: //num1
$("button[val='1']").click().focus();
setTimeout(function() {$("button[val='1']").blur()}
, 200);
break;
case 50: //2
case 98://num 2
$("button[val='2']").click().focus();
setTimeout(function() {$("button[val='2']").blur()}
, 200);
break;
case 51: //3
case 99://num 3
$("button[val='3']").click().focus();
setTimeout(function() {$("button[val='3']").blur()}
, 200);
break;
case 52: //4
case 100://num 4
$("button[val='4']").click().focus();
setTimeout(function() {$("button[val='4']").blur()}
, 200);
break;
case 53: //5
case 101: //num 5
$("button[val='5']").click().focus();
setTimeout(function() {$("button[val='5']").blur()}
, 200);
break;
case 54://6
case 102: //num 6
$("button[val='6']").click().focus();
setTimeout(function() {$("button[val='6']").blur()}
, 200);
break;
case 55://7
case 103://num 7
$("button[val='7']").click().focus();
setTimeout(function() {$("button[val='7']").blur()}
, 200);
break;
case 56: //8
case 104: //num 8
$("button[val='8']").click().focus();
setTimeout(function() {$("button[val='8']").blur()}
, 200);
break;
case 57://9
case 105://num 9
$("button[val='9']").click().focus();
setTimeout(function() {$("button[val='9']").blur()}
, 200);
break;
case 106: //multiply
$("button[val='*']").click().focus();
setTimeout(function() {$("button[val='*']").blur()}
, 200);
break;
case 111: //divide
$("button[val='/']").click().focus();
setTimeout(function() {$("button[val='/']").blur()}
, 200);
break;
case 107: // add
$("button[val='+']").click().focus();
setTimeout(function(){$("button[val='+']").blur()}
, 200);
break;
case 109://subtract
$("button[val='-']").click().focus();
setTimeout(function() {$("button[val='-']").blur()}
, 200);
break;
case 110: //decimal point
$("button[val='.']").click().focus();
setTimeout(function() {$("button[val='.']").blur()}
, 200);
break;
case 46: //'delete'
$("#clear").click().focus();
setTimeout(function() {$("#clear").blur()}
, 200);
break;
};
})
|
const SilverFocusable = require('silver-focusable')
/**
* <%= projectName %>
* @class
*/
export class <%= projectName %> extends SilverFocusable {
constructor(opt) {
super(opt)
}
/**
* initView ๆจกๆฟๆนๆณ
* @memberOf <%= projectName %>.prototype
* @method initView
* @param {Object} style ๆ ทๅผๅๆฐ
* @param {Object} data ๆฐๆฎๅๆฐ
* @return {Node} domๅฏน่ฑก
*/
initView(style, data) {
const node = document.createElement('div')
node.setAttribute('fe-role', 'Widget')
return node
}
/**
* renderView ้็ปๆนๆณ
* @memberOf <%= projectName %>.prototype
* @method render
* @param {Node} node initViewๆนๆณ่ฟๅ็domๅฏน่ฑก
* @param {Object} style ๆ ทๅผๅๆฐ
* @param {Object} data ๆฐๆฎๅๆฐ
*/
renderView(node, style, data) {
node.innerHTML = ''
}
/**
* makeStyle ๆ นๆฎoptๅๆฐ่ฟๅstyleๅฏน่ฑก
* @memberOf <%= projectName %>.prototype
* @method makeStyle
* @param {Object} opt constructorๅๆฐ
* @return {Object} ๆ ทๅผๅฏน่ฑก
*/
makeStyle(opt) {
return {}
}
/**
* getName ่ทๅ็ปไปถๅ็งฐ
* @memberOf <%= projectName %>.prototype
* @method getName
* @return {String}
*/
getName() {
return '<%= projectName %>'
}
}
|
/***
* Em um parque de diversรตes nos pedem
* um programa para verificar se os passageiros da montanha-russa podem entrar no brinquedo.
*
* Crie uma funรงรฃo podeSubir() que receba dois parรขmetros:
* altura da pessoa;
* se estรก acompanhada.
*
* Deve retornar um valor booleano (TRUE, FALSE) que indique se a pessoa pode subir ou nรฃo,
* baseado nas seguintes condiรงรตes:
* A pessoa deve medir mais de 1.40m e menos de 2 metros.
* Se a pessoa medir menos de 1.40m, deverรก ir acompanhada.
* Se a pessoa medir menos de 1.20m, nรฃo poderรก subir, nem acompanhada.
*/
/**
*
* @param {*} altura
* @param {*} vemAcompanhado
* @returns podeSubir
*/
function podeSubir(altura, vemAcompanhado){ // parametros
let podeSubir = false; // estado da resposta
if (altura <= 2.0 && altura >= 1.20){ // se pessoa medir entre 1.20m e 2m, ela pode subir SOZINHA
podeSubir = true // estado da resposta: pode subir SOZINHA
}
if(altura >= 1.20 && vemAcompanhado){ // se a pessoa medir mais que 1.20m E vier acompanhada
podeSubir = true // estado da resposta: pode subir ACOMPANHADA
}
return podeSubir;
}
/**
* Funcao alterada
*/
function mensagemPodeSubir(altura,vemAcompanhado){
if((altura <= 2.0 && altura >= 1.20) || (altura >= 1.20 && vemAcompanhado)){
// return true
return console.log("Acesso autorizado");
}
else{
// return false
return console.log("Acesso autorizado somente com acompanhante");
}
}
function podeSubirUnica(altura,vemAcompanhado){
return (altura <= 2.0 && altura >= 1.20) || (altura >= 1.20 && vemAcompanhado)
}
function liberaAcesso(altura,vemAcompanhado){
if(podeSubirUnica(altura, vemAcompanhado)){
return console.log("Acesso autorizado");
}
else{
return console.log("Acesso autorizado somente com acompanhante");
}
}
podeSubir(1.74, false);
mensagemPodeSubir(1.74, false);
liberaAcesso(1.20, true);
|
var mysql = require("mysql");
var inquirer = require("inquirer");
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "Priyansh0518",
database: "bamazon"
});
connection.connect(function(err) {
if (err) throw err;
managerView();
});
function managerView() {
inquirer
.prompt([
{
name: "option",
type: "list",
message: "What would you like to do?",
choices: [
"View Products for Sale",
"View Low Inventory",
"Add to Inventory",
"Add New Product",
"Exit"
]
}
])
.then(function(prompt_res) {
switch (prompt_res.option) {
case "View Products for Sale": {
productForSale();
break;
}
case "View Low Inventory": {
lowInventory();
break;
}
case "Add to Inventory": {
addInventory();
break;
}
case "Add New Product": {
addNewProduct();
break;
}
case "Exit": {
connection.end();
break;
}
default: {
connection.end();
break;
}
}
});
}
function productForSale() {
connection.query("select * from products", function(err, res) {
if (err) throw err;
console.table(res);
console.log(
"---------------------------------------------------------------------"
);
managerView();
});
}
function lowInventory() {
connection.query("select * from products where stock_quantity < 5", function(
err,
res
) {
if (err) throw err;
console.table(res);
console.log(
"---------------------------------------------------------------------"
);
managerView();
});
}
function addInventory() {
inquirer
.prompt([
{
name: "id",
type: "number",
message: "Please enter item_id?"
},
{
name: "quantity",
type: "number",
message: "Quantity to add in stock?"
}
])
.then(function(prompt_res) {
connection.query(
"update products set stock_quantity = stock_quantity + ? where ?",
[
prompt_res.quantity,
{
item_id: prompt_res.id
}
],
function(err) {
if (err) {
console.log("Id not Found.");
console.log(err);
}
console.log("\nQuantity Added");
console.log(
"---------------------------------------------------------------------"
);
managerView();
}
);
});
}
function addNewProduct() {
inquirer
.prompt([
{
name: "name",
type: "input",
message: "Name of product?"
},
{
name: "department",
type: "input",
message: "Name of department?"
},
{
name: "price",
type: "input",
message: "Price of product?"
},
{
name: "quantity",
type: "number",
message: "Intial quantity of product?"
}
])
.then(function(prompt_res) {
connection.query(
"insert into products set ?",
{
product_name: prompt_res.name,
department_name: prompt_res.department,
price: prompt_res.price,
stock_quantity: prompt_res.quantity
},
function(err) {
if (err) throw err;
console.log("\nEntry Added");
console.log(
"---------------------------------------------------------------------"
);
managerView();
}
);
});
}
|
import {
identifier,
validation,
stringHandler,
} from '../util'
export default {
install: function(Vue, options){
Vue.prototype.$identifier = identifier;
Vue.prototype.$validation = validation;
Vue.prototype.$stringHandler = stringHandler;
}
}
|
$(document).ready(function() {
$('#usernameLoading').hide();
$('#username').blur(function(){
alert("IT DID SOMETHING?");
$('#usernameLoading').show();
$.post("../functions/checkuser.php", {
username: $('#username').val()
}, function(response){
$('#usernameResult').fadeOut();
setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) {
$('#usernameLoading').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
} //finishAjax
|
/**
* Authors: Diego Ceresuela, Raรบl Piracรฉs and Luis Jesรบs Pellicer.
* Date: 16-05-2016
* Name file: auth.controller.js
* Description: Controller for provide twitter authentication, necessary jwt.
*/
(function() {
'use strict';
var passport = require('passport');
var mongoose = require('mongoose');
var Twitter = mongoose.model('twitter');
var request = require('request');
var atob = require('atob');
module.exports = function(app) {
// Session with Twitter
app.get('/auth/twitter',
passport.authenticate('twitter'));
// Callback received from twitter
app.get('/auth/twitter/callback',
passport.authenticate('twitter', { failureRedirect: '/login' }),
function(req, res) {
if(req.session.jwt) {
// Gets jwt from authorization header
var payload = req.session.jwt.split('.')[1];
payload = atob(payload);
payload = JSON.parse(payload);
var mainContent = req.user.profile._json;
var newTwitter = new Twitter({
"user": payload.email,
"in_use": false,
"token": req.user.token,
"secret": req.user.tokenSecret,
"description": mainContent.description,
"screen_name": mainContent.screen_name,
"name": mainContent.name,
"id_str": mainContent.id_str,
"location": mainContent.location,
"url": mainContent.url,
"followers_count": mainContent.followers_count,
"friends_count": mainContent.friends_count,
"favourites_count": mainContent.favourites_count,
"statuses_count": mainContent.statuses_count,
"profile_image_url": mainContent.profile_image_url,
"tweet_app": 0
});
// Update user.
newTwitter.save(function (err) {
if (err) {
// Error updating user
res.redirect(process.env.CURRENT_DOMAIN + '/#/errors');
} else {
// Successful authentication
// Now setting as active account (using)
request({
url: process.env.CURRENT_DOMAIN + '/twitter/' + mainContent.id_str + '/use',
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + req.session.jwt
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
res.redirect(process.env.CURRENT_DOMAIN + "/#/twitterAccounts");
} else {
res.redirect(process.env.CURRENT_DOMAIN + '/#/errors');
}
});
}
});
} else {
// If not have jwt -> error.
res.redirect(process.env.CURRENT_DOMAIN + '/#/errors');
}
});
// Return middleware.
return function(req, res, next) {
next();
};
};
})();
|
import { Link } from 'react-router-dom';
import { BulletList } from 'react-content-loader';
import useProfiles from '../../../hooks/useProfiles';
import useFollowUser from '../../../hooks/useFollowUser';
import Button from '../../Button';
import * as S from './styles';
const Suggestions = () => {
const { status, data } = useProfiles();
const { mutate: followUser } = useFollowUser();
return (
<S.Container>
<strong>Suggestions For You</strong>
{status === 'loading' && <BulletList />}
{status === 'error' && <span>Something wrong happenned.</span>}
<S.List>
{data?.length === 0 && <p>There are no more users to follow.</p>}
{data?.map((user) => (
<li key={user.id}>
<Link to={`/${user.username}`}>
<img
src={
user.image
? user.image
: `https://eu.ui-avatars.com/api/?name=${user.username}`
}
alt={user.username}
/>
<strong>{user.username.toLowerCase()}</strong>
</Link>
<Button
type="button"
variant="secondary"
onClick={() => followUser(user)}
>
Follow
</Button>
</li>
))}
</S.List>
</S.Container>
);
};
export default Suggestions;
|
const Product = require('models/Product');
exports.write = async (ctx) => {
const { name, description, price, discountRate, imageUrl } = ctx.request.body;
const product = new Product({
name: name,
description: description,
price: price,
discountRate: discountRate,
imageUrl: imageUrl
});
try {
await product.save();
ctx.body = product;
} catch (e) {
ctx.throw(e, 500);
}
}
exports.list = async (ctx) => {
try {
const products = await Product.find().exec();
ctx.body = products;
} catch (e) {
ctx.throw(e, 500);
}
}
exports.read = async (ctx) => {
const { id } = ctx.params;
try {
const product = await Product.findById(id).exec();
if (!product) {
ctx.status = 404;
return;
}
ctx.body = product;
} catch (e) {
ctx.throw(e, 500);
}
}
|
////////////// Express settings... /////////////
const express = require('express');
const app = express();
const PORT = process.env.PORT || '3000';
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`)
});
////// Google Trends API .../////////////
const googleTrends = require('google-trends-api');
app.get('/interestOverTime/:keyword/:startDate/:endDate', (req, res) => {
return googleTrends.interestOverTime({
keyword: req.params.keyword,
startTime: new Date(req.params.startDate),
endTime: new Date(req.params.endDate)
})
.then(data => {
res.json(JSON.parse(data));
})
.catch(err => {
console.log(err);
res.sendStatus(500);
})
});
//////////// Twitter API /////////////////////
const Twit = require('twit')
const T = new Twit({
consumer_key: 'ABsisdF8CgLaBs8Phw6jJHkTC',
consumer_secret: 'vPwh3knd8y6DkN7sJ1RXKguNlL0KNAUIKBTjuwPBT4KLrmhrdt',
access_token: '939883399333871616-wqNnaZvXtBMDz38EoaJwCMSHxETzPGp',
access_token_secret: 'GI3aDKMoFyPl7l2cWpd0VK7Lyjvapmwv6HbVThQZaTTF8',
timeout: 60*1000
})
// app.get('/twitter', (req, res) => {
// return T.get('search/tweets', {q: 'crypto since:2018-01-01', count: 30}, (err, data, response) => {
// try {
// res.json(data)
// }
// catch(err) {
// console.log('server error: ', err)
// }
// })
// });
app.get('/twitter/:userId', (req, res) => {
return T.get('statuses/user_timeline', {screen_name: req.params.userId, count: 30}, (err, data, response) => {
try {
res.json(data)
}
catch(err) {
console.log('server error: ', err)
}
})
});
|
import DashView from "@/components/Dash.vue";
import NotFoundView from "@/components/404.vue";
// Import Views - Dash
import Links from "@/components/views/Links.vue";
const routes = [{
path: "/",
component: DashView,
children: [{
path: "links",
alias: "",
component: Links,
name: "Links",
meta: {
description: "่้ๅ็จฎ้ฃ็ต",
showname: "้ฃ็ต",
breadcrumb: [{
name: "้ฆ้ ",
link: "/"
}, {
name: "้ฃ็ต"
}]
// }, {
// path: 'tables',
// component: TablesView,
// name: 'Tables',
// meta: {description: 'Simple and advance table in CoPilot'}
// }, {
// path: 'tasks',
// component: TasksView,
// name: 'Tasks',
// meta: {description: 'Tasks page in the form of a timeline'}
// }, {
// path: 'setting',
// component: SettingView,
// name: 'Settings',
// meta: {description: 'User settings page'}
// }, {
// path: 'access',
// component: AccessView,
// name: 'Access',
// meta: {description: 'Example of using maps'}
// }, {
// path: 'server',
// component: ServerView,
// name: 'Servers',
// meta: {description: 'List of our servers', requiresAuth: true}
// }, {
// path: 'repos',
// component: ReposView,
// name: 'Repository',
// meta: {description: 'List of popular javascript repos'}
} }]
}, {
path: "*",
component: NotFoundView
}];
export default routes;
|
import React from 'react';
import {Button} from 'antd';
import './AboutUs.css';
function AboutUs() {
return (
<>
<section id='about-us'>
<div className='about-wrapper'>
<h3 className='about-h3'>Welcome</h3>
<h2 className='about-h2'>About Vegetables</h2>
<p className='about-p'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
<Button className='about-btn' href='#product'>Get Direction</Button>
</div>
</section>
</>
)
}
export default AboutUs;
|
var addItemModel = function () {
this.submitEvent = new Event(this);
this.getCategoriesEvent = new Event(this);
this.editEvent = new Event(this);
}
addItemModel.prototype.submit = function (data) {
$.ajax({
url: '/register',
type: 'POST',
data: { data: data },
dataType: 'json',
success: (result) => {
this.submitEvent.notify(result);
}
});
};
addItemModel.prototype.getCategories = function () {
$.ajax({
url: '/getCategories',
type: 'GET',
dataType: 'json',
success: (result) => {
this.getCategoriesEvent.notify(result);
}
});
};
addItemModel.prototype.saveImages = function (data) {
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
var flag = data[0];
data = data.filter(function (item) {
return item !== 'edit';
});
data = data.filter(function (item) {
return item !== 'add';
});
$.ajax({
url: '/saveImages',
type: 'POST',
dataType: 'json',
data: {
displayImage: data[0],
images: data[1]
},
success: (result) => {
if (flag == 'edit') {
$.ajax({
url: '/updateItem?id=' + id,
type: 'POST',
dataType: 'json',
data: {
image: result.displayName,
other_images: result.imagesNames.toString(),
name: data[2],
first_bid: data[3],
buy_price: data[4],
category: data[5].toString(),
started: data[6],
ends: data[7],
description: data[8],
location: data[9]
},
success: (res) => {
window.location.assign('/main/myitems');
}
});
} else {
$.ajax({
url: '/main/myitems/addItem',
type: 'POST',
dataType: 'json',
data: {
image: result.displayName,
other_images: result.imagesNames.toString(),
name: data[2],
first_bid: data[3],
buy_price: data[4],
category: data[5].toString(),
started: data[6],
ends: data[7],
description: data[8],
location: data[9]
},
success: (res) => {
window.location.assign('/main/myitems');
}
});
}
}
});
};
addItemModel.prototype.edit = function (id) {
$.ajax({
url: '/itemInfo',
type: 'POST',
dataType: 'json',
data: { id: id },
success: (result) => {
this.editEvent.notify(result);
}
});
};
|
const UserResolver = require('./users/index');
const CourseResolver = require('./courses/index');
const ForumQuestionResolver = require('./forumQuestions/index');
const { globalAutocomplete } = require('./global/globalAutocomplete');
const RootResolver = {
...UserResolver,
...CourseResolver,
...ForumQuestionResolver,
globalAutocomplete
};
module.exports = RootResolver;
|
// Example: snowpack.config.mjs
// The added "@type" comment will enable TypeScript type information via VSCode, etc.
/** @type {import("snowpack").SnowpackUserConfig } */
export default {
plugins: [
// https://www.npmjs.com/package/@snowpack/plugin-typescript
[
"@snowpack/plugin-typescript",
{
args: "./src/**",
},
],
[
// https://www.npmjs.com/package/@snowpack/plugin-sass
"@snowpack/plugin-sass",
{
loadPath: "./src/**",
sourceMap: true,
},
],
],
};
|
function solve(arr) {
return Math.max.apply('', arr);
}
|
import { createFile, updateFile, deleteFile, findFile, fetchFiles, paginateFiles} from '../../services/FileService'
import {AuthenticationError, ForbiddenError} from "apollo-server-express";
import {
FILE_SHOW,
FILE_UPDATE,
FILE_CREATE,
FILE_DELETE
} from "../../permissions/File";
export default {
Query: {
fileFind: (_, {id}, {user,rbac}) => {
if (!user) throw new AuthenticationError("Unauthenticated")
if(!rbac.isAllowed(user.id, FILE_SHOW)) throw new ForbiddenError("Not Authorized")
return findFile(id)
},
fileFetch: (_, {}, {user,rbac}) => {
if (!user) throw new AuthenticationError("Unauthenticated")
if(!rbac.isAllowed(user.id, FILE_SHOW)) throw new ForbiddenError("Not Authorized")
return fetchFiles()
},
filePaginate: (_, {pageNumber, itemsPerPage, search, orderBy, orderDesc}, {user,rbac}) => {
if (!user) throw new AuthenticationError("Unauthenticated")
if(!rbac.isAllowed(user.id, FILE_SHOW)) throw new ForbiddenError("Not Authorized")
return paginateFiles(pageNumber, itemsPerPage, search, orderBy, orderDesc)
},
},
Mutation: {
fileUpdate: (_, {id, input}, {user,rbac}) => {
if (!user) throw new AuthenticationError("Unauthenticated")
if(!rbac.isAllowed(user.id, FILE_UPDATE)) throw new ForbiddenError("Not Authorized")
return updateFile(user, id, input)
},
fileDelete: (_, {id}, {user,rbac}) => {
if (!user) throw new AuthenticationError("Unauthenticated")
if(!rbac.isAllowed(user.id, FILE_DELETE)) throw new ForbiddenError("Not Authorized")
return deleteFile(id)
},
}
}
|
// leanModal v1.0 by Ray Stone - http://finelysliced.com.au
(function($) {
$.fn.extend({
leanModal : function(options) {
var defautOptions = {
top : 100,
overlay : 0.5
};
options = $.extend(defautOptions, options);
return this.each(function() {
var o = options;
$(this).click(function(e) {
var maskDiv = $("<div id='lean_overlay'></div>");
var box = $(this).attr("href");
$("body").append(maskDiv);
$("#lean_overlay").click(function() {
show(box);
});
var boxHeight = $(box).outerHeight();
var boxWidth = $(box).outerWidth();
$("#lean_overlay").css({
"display" : "block",
opacity : 0
});
$("#lean_overlay").fadeTo(200, o.overlay);
$(box).css({
"display" : "block",
"position" : "fixed",
opacity : 0,
"z-index" : 11000,
"left" : 50 + "%",
"margin-left" : -(boxWidth / 2) + "px",
"top" : o.top + "px"
});
$(box).fadeTo(200, 1);
e.preventDefault();
});
});
function show(box) {
$("#lean_overlay").fadeOut(200);
$(box).css({
"display" : "none"
});
};
}
});
})(jQuery);
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', "firebase", 'starter.controllers', 'starter.directives', 'chart.js', 'ionic-material', 'ionMdInput'])
.value('report', {})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($sceDelegateProvider)
{
$sceDelegateProvider.resourceUrlWhitelist(['self', new RegExp('^(http[s]?):\/\/(w{3}.)?youtube\.com/.+$')]);
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
// Turn off caching for demo simplicity's sake
$ionicConfigProvider.views.maxCache(0);
/*
// Turn off back button text
$ionicConfigProvider.backButton.previousTitleText(false);
*/
$stateProvider.state('main', {
url: '/main',
templateUrl: 'templates/main.html',
controller: 'AppCtrl'
})
.state('activity', {
url: '/activity',
templateUrl: 'templates/activity.html',
controller: 'ActivityCtrl'
})
.state('profile', {
url: '/profile',
templateUrl: 'templates/profile.html',
controller: 'ProfileCtrl'
})
.state('map', {
url: '/map',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
})
.state('status', {
url: '/status',
templateUrl: 'templates/status.html',
controller: 'StatusCtrl'
})
.state('symptom', {
url: '/symptom',
templateUrl: 'templates/symptom.html',
controller: 'SymptomCtrl'
})
.state('ListSymptom', {
url: '/ListSymptom',
templateUrl: 'templates/KnowSymptom.html',
controller: 'ListSymptomCtrl'
})
.state('disease', {
url: '/disease',
templateUrl: 'templates/disease.html',
controller: 'DiseaseCtrl'
})
.state('reportMap', {
url: '/reportMap',
templateUrl: 'templates/reportMap.html',
controller: 'ReportMapCtrl'
})
.state('report', {
url: '/report',
templateUrl: 'templates/report.html',
controller: 'ReportCtrl'
})
;
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/main');
});
|
angular.module('myfavor', []);
|
angular
.module("empresa.service", [])
.factory('empresa', ['$http', 'auth', function($http, auth) {
// Might use a resource here that returns a JSON array
var headers = {};
headers[API.token_name] = auth.getToken();
var dataEmpresa = {};
dataEmpresa.getSucursal = function() {
return ($http({
url: API.base_url + 'public/sucobtener/4',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}));
};
dataEmpresa.getHorarios = function() {
return ($http({
url: API.base_url + 'public/dhlistar/4',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}))
};
dataEmpresa.getTelefonos = function() {
return ($http({
url: API.base_url + 'public/dclistartelsuc/4',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}))
};
dataEmpresa.getDatosContacto = function() {
return ($http({
url: API.base_url + 'public/dcobtenersuc/4',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}))
};
dataEmpresa.getParametros = function() {
return ($http({
url: API.base_url + 'public/parobtener/4',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}))
};
dataEmpresa.getAderezos = function() {
return ($http({
url: API.base_url + 'public/adelistar1',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data;
return datos;
}).error(function(err) {
error = err;
}))
};
return dataEmpresa;
}]);
|
const { rword } = require('rword')
const wd = require('word-definition')
const ON_DEATH = require('death')
const log = require('single-line-log').stdout
const fs = require('fs')
let totalWordsToDownload = null
let wordsDownloaded = 0
let avgResponseTime = null
//todo timeout
let getTimeElapsedMs = start => {
let diff = process.hrtime(start)
let diffNs = diff[0] * 1e9 + diff[1]
let diffMs = diffNs / 1e6
return diffMs
}
let printStats = ({ currentWord, diffMs }) => {
percentage = Math.floor(
((wordsDownloaded + 1) / totalWordsToDownload) * 100
)
if (avgResponseTime === null) {
avgResponseTime = diffMs
} else {
avgResponseTime = (diffMs + avgResponseTime) / 2
}
let displayTime = Math.floor(avgResponseTime)
log(
`Current word: ${currentWord}\nAverage response time: ${displayTime} ms\nWord ${wordsDownloaded +
1} out of ${totalWordsToDownload}\n[${percentage}%]`
)
wordsDownloaded += 1
}
let doStop = false
let finish = () => {
console.log('Ended.')
process.exit(0)
}
const fetchDef = word => {
return new Promise((resolve, reject) => {
wd.getDef(word, 'en', { hyperlinks: 'none' }, def => {
resolve(def)
//handle errors
})
if (doStop) {
reject(new Error('Download canceled.'))
}
})
}
let tasks = []
let getWords = amount => {
let totalTimerStart = process.hrtime()
return new Promise((resolve, reject) => {
let randomWords = rword.generate(amount, {
length: '4-10',
contains: /^[^-]+$/
})
totalWordsToDownload = amount
randomWords.forEach(word => {
currentWord = word
tasks.push(
new Promise((resolve, reject) => {
let start = process.hrtime()
fetchDef(word)
.then(def => {
resolve(def)
printStats({
currentWord: word,
diffMs: getTimeElapsedMs(start)
})
})
.catch(err => {
reject(err)
})
})
)
})
Promise.all(tasks).then(results => {
resolve({ results, timeElapsed: getTimeElapsedMs(totalTimerStart) })
})
})
}
//* probably not needed because we already provide regex in the random word generator
let filterWords = words => {
let regex = new RegExp('^[a-z]+$', 'gi')
let withDefinitions = words.filter(w => {
return !w.hasOwnProperty('err')
})
console.log(withDefinitions)
let englishLettersOnly = withDefinitions.filter(w => {
return regex.test(w.word)
})
console.log(englishLettersOnly)
return englishLettersOnly
}
let saveWordsToFile = data => {
let currentTime = new Date().toISOString()
let filename = currentTime
.replace(/T/, '_')
.replace(/\..+/, '')
.replace(/\:/g, '-')
let filteredWords = filterWords(data)
let toSave = JSON.stringify({ words: filteredWords })
fs.writeFile(`./download/${filename}.json`, toSave, err => {
if (err) throw err
console.log('Saved to file.')
})
}
getWords(1723).then(result => {
let json = result.results
let timeElapsed = Math.floor(result.timeElapsed / 1000)
log.clear()
log(
`Finished. Downloading ${
json.length
} words took ${timeElapsed} seconds.`
)
saveWordsToFile(json)
})
ON_DEATH((signal, err) => {
doStop = true
// log.clear()
// log('Stopping...')
})
|
import {updateSession} from "../services/SessionService";
const sessionMiddleware = (req, res, next) => {
if (req.user) updateSession(req.user)
next()
}
export default sessionMiddleware
|
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { getDetails } from '../services/movieApis';
import styles from './MovieDetail.css';
const MovieDetail = ({ match }) => {
const [details, setDetails] = useState({});
useEffect(() => {
getDetails(match.params.movie_id)
.then(details => setDetails(details));
}, []);
return (
<>
<div className={styles.movieItem}>
<img className={styles.moviePoster} src={`http://image.tmdb.org/t/p/w780/${details.poster_path}`} onError={(e)=>{e.target.onerror = null; e.target.src = 'https://lh3.googleusercontent.com/proxy/GOuPCAzhMBl60T5N9_oNmDUCRRh8kdI0QukUzA4YvACAlP9i0CniYBeh0FuKlNvXBI_0QA6l-GlvgpczcEZ2n0yN3Dpf_xzqsT39iXs3pw4njq15g34_aQAv-Pt5DsgG03Wg';}} />
<div className={styles.movieDetails}>
<p className={styles.movieTitle}>{details.title}</p>
<p className={styles.movieDate}>{details.release_date?.slice(0, 4)}</p>
<p className={styles.movieTime}>{details.runtime} minutes</p>
<p className={styles.movieOverview}>{details.overview}</p>
</div>
</div>
</>
);
};
MovieDetail.propTypes = {
match: PropTypes.object.isRequired
};
export default MovieDetail;
|
function buildFunctions() {
var arr = [];
for (var i = 0; i < 3; i++) {
//console.log("in loop: " + i);
arr.push(function() {
console.log(i);
});
}
//console.log("after loop: " + i);
return arr;
}
var functions = buildFunctions();
functions[0]();
functions[1]();
functions[2]();
function buildFunctions2() {
var arr = [];
for (var i = 0; i < 3; i++) {
//console.log("in loop: " + i);
arr.push(
(function(j) {
return function() {
console.log(j);
}
})(i)
);
}
//console.log("after loop: " + i);
return arr;
}
var functions2 = buildFunctions2();
functions2[0]();
functions2[1]();
functions2[2]();
|
import highlights from './highlights';
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
highlights,
});
export default rootReducer;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TextRendererEditor {
constructor(tbody, config, projectClient, editConfig) {
this.fields = {};
this.pendingModification = 0;
this.tbody = tbody;
this.editConfig = editConfig;
this.projectClient = projectClient;
this.fontAssetId = config.fontAssetId;
this.color = config.color;
this.size = config.size;
this.overrideOpacity = config.overrideOpacity;
this.opacity = config.opacity;
const fontRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.font"));
this.fontFieldSubscriber = SupClient.table.appendAssetField(fontRow.valueCell, this.fontAssetId, "font", projectClient);
this.fontFieldSubscriber.on("select", (assetId) => {
this.editConfig("setProperty", "fontAssetId", assetId);
});
const textRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.text"));
this.fields["text"] = SupClient.table.appendTextAreaField(textRow.valueCell, config.text);
this.fields["text"].addEventListener("input", (event) => {
this.pendingModification += 1;
this.editConfig("setProperty", "text", event.target.value, (err) => {
this.pendingModification -= 1;
if (err != null) {
new SupClient.Dialogs.InfoDialog(err);
return;
}
});
});
const alignmentRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.align.title"));
const alignmentOptions = {
"left": SupClient.i18n.t("componentEditors:TextRenderer.align.left"),
"center": SupClient.i18n.t("componentEditors:TextRenderer.align.center"),
"right": SupClient.i18n.t("componentEditors:TextRenderer.align.right")
};
this.fields["alignment"] = SupClient.table.appendSelectBox(alignmentRow.valueCell, alignmentOptions, config.alignment);
this.fields["alignment"].addEventListener("change", (event) => { this.editConfig("setProperty", "alignment", event.target.value); });
const verticalAlignmentRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.verticalAlign.title"));
const verticalAlignmentOptions = {
"top": SupClient.i18n.t("componentEditors:TextRenderer.verticalAlign.top"),
"center": SupClient.i18n.t("componentEditors:TextRenderer.verticalAlign.center"),
"bottom": SupClient.i18n.t("componentEditors:TextRenderer.verticalAlign.bottom")
};
this.fields["verticalAlignment"] = SupClient.table.appendSelectBox(verticalAlignmentRow.valueCell, verticalAlignmentOptions, config.verticalAlignment);
this.fields["verticalAlignment"].addEventListener("change", (event) => { this.editConfig("setProperty", "verticalAlignment", event.target.value); });
const colorRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.color"), { checkbox: true });
this.colorCheckbox = colorRow.checkbox;
this.colorCheckbox.addEventListener("change", (event) => {
const color = this.colorCheckbox.checked ? (this.fontAsset != null ? this.fontAsset.pub.color : "ffffff") : null;
this.editConfig("setProperty", "color", color);
});
const colorField = this.fields["color"] = SupClient.table.appendColorField(colorRow.valueCell, null);
colorField.addListener("change", (color) => {
this.editConfig("setProperty", "color", color);
});
this.updateColorField();
const sizeRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.size"), { checkbox: true });
this.sizeRow = sizeRow.row;
this.sizeCheckbox = sizeRow.checkbox;
this.sizeCheckbox.addEventListener("change", (event) => {
const size = this.sizeCheckbox.checked ? (this.fontAsset != null ? this.fontAsset.pub.size : 16) : null;
this.editConfig("setProperty", "size", size);
});
this.fields["size"] = SupClient.table.appendNumberField(sizeRow.valueCell, "", { min: 0 });
this.fields["size"].addEventListener("input", (event) => {
if (event.target.value === "")
return;
this.editConfig("setProperty", "size", parseInt(event.target.value, 10));
});
this.updateSizeField();
const opacityRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:TextRenderer.opacity"), { checkbox: true });
this.overrideOpacityField = opacityRow.checkbox;
this.overrideOpacityField.addEventListener("change", (event) => {
this.editConfig("setProperty", "opacity", this.fontAsset != null ? this.fontAsset.pub.opacity : null);
this.editConfig("setProperty", "overrideOpacity", event.target.checked);
});
const opacityParent = document.createElement("div");
opacityRow.valueCell.appendChild(opacityParent);
const transparentOptions = {
empty: "",
opaque: SupClient.i18n.t("componentEditors:TextRenderer.opaque"),
transparent: SupClient.i18n.t("componentEditors:TextRenderer.transparent"),
};
this.transparentField = SupClient.table.appendSelectBox(opacityParent, transparentOptions);
this.transparentField.children[0].hidden = true;
this.transparentField.addEventListener("change", (event) => {
const opacity = this.transparentField.value === "transparent" ? 1 : null;
this.editConfig("setProperty", "opacity", opacity);
});
this.opacityFields = SupClient.table.appendSliderField(opacityParent, "", { min: 0, max: 1, step: 0.1, sliderStep: 0.01 });
this.opacityFields.numberField.parentElement.addEventListener("input", (event) => {
this.editConfig("setProperty", "opacity", parseFloat(event.target.value));
});
this.updateOpacityField();
}
destroy() { this.fontFieldSubscriber.destroy(); }
config_setProperty(path, value) {
if (path === "fontAssetId") {
if (this.fontAssetId != null) {
this.projectClient.unsubAsset(this.fontAssetId, this);
this.fontAsset = null;
}
this.fontAssetId = value;
this.updateColorField();
if (this.fontAssetId != null)
this.projectClient.subAsset(this.fontAssetId, "font", this);
this.fontFieldSubscriber.onChangeAssetId(this.fontAssetId);
}
else if (path === "color") {
this.color = value;
this.updateColorField();
}
else if (path === "size") {
this.size = value;
this.updateSizeField();
}
else if (path === "text") {
if (this.pendingModification === 0)
this.fields["text"].value = value;
}
else if (path === "overrideOpacity") {
this.overrideOpacity = value;
this.updateOpacityField();
}
else if (path === "opacity") {
this.opacity = value;
this.updateOpacityField();
}
else
this.fields[path].value = value;
}
updateColorField() {
const color = this.color != null ? this.color : (this.fontAsset != null ? this.fontAsset.pub.color : null);
this.fields["color"].setValue(color);
this.colorCheckbox.checked = this.color != null;
this.fields["color"].setDisabled(this.color == null);
}
updateSizeField() {
if (this.fontAsset != null && this.fontAsset.pub.isBitmap) {
this.sizeRow.hidden = true;
return;
}
else
this.sizeRow.hidden = false;
const size = this.size != null ? this.size : (this.fontAsset != null ? this.fontAsset.pub.size : "");
this.fields["size"].value = size;
this.sizeCheckbox.checked = this.size != null;
this.fields["size"].disabled = this.size == null;
}
updateOpacityField() {
this.overrideOpacityField.checked = this.overrideOpacity;
this.transparentField.disabled = !this.overrideOpacity;
this.opacityFields.sliderField.disabled = !this.overrideOpacity;
this.opacityFields.numberField.disabled = !this.overrideOpacity;
if (!this.overrideOpacity && this.fontAsset == null) {
this.transparentField.value = "empty";
this.opacityFields.numberField.parentElement.hidden = true;
}
else {
const opacity = this.overrideOpacity ? this.opacity : this.fontAsset.pub.opacity;
if (opacity != null) {
this.transparentField.value = "transparent";
this.opacityFields.numberField.parentElement.hidden = false;
this.opacityFields.sliderField.value = opacity.toString();
this.opacityFields.numberField.value = opacity.toString();
}
else {
this.transparentField.value = "opaque";
this.opacityFields.numberField.parentElement.hidden = true;
}
}
}
// Network callbacks
onAssetReceived(assetId, asset) {
this.fontAsset = asset;
this.updateColorField();
this.updateSizeField();
this.updateOpacityField();
}
onAssetEdited(assetId, command, ...args) {
if (command !== "setProperty")
return;
if (command === "setProperty" && args[0] === "color")
this.updateColorField();
if (command === "setProperty" && (args[0] === "size" || args[0] === "isBitmap"))
this.updateSizeField();
if (command === "setProperty" && args[0] === "opacity")
this.updateOpacityField();
}
onAssetTrashed(assetId) {
this.fontAsset = null;
this.updateColorField();
this.updateSizeField();
this.updateOpacityField();
}
}
exports.default = TextRendererEditor;
|
'use strict'
module.exports = (sequelize, Sequelize) => {
const Game = sequelize.define('Game', {
home_team: {
type: Sequelize.INTEGER,
allowNull: false
},
away_team: {
type: Sequelize.INTEGER,
allowNull: false
},
score_home: {
type: Sequelize.INTEGER
},
score_away: {
type: Sequelize.INTEGER
}
},
{
freezeTableName: true,
timestamps: false,
paranoid: true,
underscored: true,
classMethods: {
associate: (models) => {
Game.hasMany(models.Performance, {
foreignKey: 'game_id',
as: 'performances'
}),
Game.belongsTo(models.Round, {
onDelete: 'CASCADE',
foreignKey: 'id'
})
}
}
});
return Game;
};
|
var N = Number(2400);
var n = 3500;
console.log(typeof(N));
console.log(typeof(n));
console.log(N.toFixed(2));
console.log(n.toFixed(2));
console.log(5 .toFixed(2));
console.log("");
console.log(n.toExponential(3));
console.log(n.toPrecision(5));
console.log("");
var i = 10;
console.log(i);
console.log(-i);
console.log(++i);
console.log(i);
console.log(i++);
console.log(i);
console.log(5 + 3);
console.log(5 - 3);
console.log(5 * 3);
console.log(5 / 3);
console.log(5 % 3);
console.log("");
n = 20;
n = n + 10;
console.log(n);
n += 10;
console.log(n);
console.log("");
console.log(10 < 5);
console.log(10 <= 10);
console.log(10 == 10);
console.log(10 === 10);
console.log(10 == "10");
console.log(10 === "10");
console.log("");
//Math
console.log(Math.PI);
console.log(Math.E);
console.log(Math.sqrt(25));
console.log(Math.pow(5, 3));
console.log(1e308);
console.log(1e309);//Infinity
console.log(typeof(Infinity));//Number
console.log("");
console.log(1e-323);
console.log(1e-324);//0
console.log(5 / 0);//Infinity
console.log(-5 / 0);//-Infinity
console.log(0 / 0);//NaN
console.log(Infinity / Infinity);//NaN
console.log(Math.sqrt(-25));//NaN
console.log(NaN === NaN);//false NaN - ะธะดะตะฝัะธัะธะบะฐัะพั (ะฟะฐััะตั)
console.log("");
console.log(0.2 + 0.1);//ัะพัะฝะพััั ะฒััะต ั ัะตะปัั
console.log(1072 .toString(2));
|
const router = require('express').Router();
const { dbToRes, reqToDb } = require('../../../utils');
const { Projects, Jobsheets, Components } = require('../../../data/models');
const { getUserInfo, getUserOrganizations } = require('../../middleware/users');
router.get('/:id/jobsheets', getUserOrganizations, async (req, res) => {
const { id } = req.params;
let project
try {
project = await Projects.findBy({ id }).first();
if (!project) {
return res.status(404).json({ error: 'project with this id does not exists' });
}
if (!req.userOrganizations.includes(project.client_id)) {
return res.status(403).json({ error: 'project is not associated with a client that belongs to the user' });
}
} catch (error) {
return res.status(500).json({ error: error.message, step: '/:id/jobsheets' });
}
let jobsheets;
try {
jobsheets = await Jobsheets.findBy({ project_id: id });
return res.status(200).json(jobsheets);
} catch (error) {
return res.status(500).json({ error: error.message, step: '/:id/jobsheets' });
}
});
module.exports = router;
|
const router = require('koa-router')()
var NeihanModel = require('../model/Neihan');
var ad = require('../conf/ad.json')
router.prefix('/neihan');
router.get('/', async(ctx, next) => {
let page = ctx.request.query.page || 1
let id = ctx.request.query.id
let type = ctx.request.query.type || ""
let arr = [];
let soureArr = ["neihan","gaoxiaogif","jiefu"]
if (id && type && type == "share") {
var share_message = await NeihanModel.find({_id: id, source: "neihan"});
let res = JSON.parse(JSON.stringify(share_message));
res[0].page = page
arr.push(res[0])
}
var messages = await NeihanModel.find({source: {$in:soureArr}}).skip((page - 1) * 20).limit(20).sort({createAt: 1});
if(messages.length>=20){
for (var message of messages) {
let res = JSON.parse(JSON.stringify(message));
res.page = page
arr.push(res)
}
arr.splice(4,0,ad.ad1)
arr.splice(11,0,ad.ad2)
arr.splice(18,0,ad.ad3)
}else{
for (var message of messages) {
let res = JSON.parse(JSON.stringify(message));
res.page = page
arr.push(res)
}
arr.code = "end"
}
ctx.body = {messages: arr,code:arr.code, version: "1.0.2"}
})
router.get('/test', async(ctx, next) => {
let page = ctx.request.query.page || 1
let id = ctx.request.query.id
let type = ctx.request.query.type || ""
let arr = [];
let soureArr = ["neihan","gaoxiaogif","jiefu"]
if (id && type && type == "share") {
var share_message = await NeihanModel.find({_id: id, source: "neihan"});
let res = JSON.parse(JSON.stringify(share_message));
res[0].page = page
arr.push(res[0])
}
var messages = await NeihanModel.find({source: {$in:soureArr}}).skip((page - 1) * 20).limit(20).sort({createAt: 1});
if(messages.length>=20){
for (var message of messages) {
let res = JSON.parse(JSON.stringify(message));
res.page = page
arr.push(res)
}
arr.splice(4,0,ad.ad1)
arr.splice(11,0,ad.ad2)
arr.splice(18,0,ad.ad3)
}else{
for (var message of messages) {
let res = JSON.parse(JSON.stringify(message));
res.page = page
arr.push(res)
}
arr.code = "end"
}
ctx.body = {messages: arr,code:arr.code, version: "1.0.2"}
})
module.exports = router
|
$(function (){
$("fnameErrorMsg").hide();
var error_fname = false;
var error_lname = false;
var error_email = false;
var error_pass = false;
var error_repass = false;
var error_addr = false;
var error_mob = false;
var error_dob = false;
var name_regex = /^[a-zA-Z]+$/;
var email_regex = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/;
var addr_regex = /^(\w*\s*[\#\-\,\/\.\(\)\&]*)+$/;
/*
Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
*/
var mob_regex = /^[0-9]{3}-[0-9]{4}-[0-9]{3}$/;
$("#fname").focusout(function(){
check_fname();
});
$("#lname").focusout(function(){
check_lname();
});
$("#email").focusout(function(){
check_email();
});
$("#pass").focusout(function(){
check_pass();
});
$("#repass").focusout(function(){
check_repass();
});
$("#address").focusout(function(){
check_address();
});
$("#mobile").focusout(function(){
check_mobile();
});
$("#datepicker").focusout(function(){
check_dob();
});
function check_fname(){
var fname_length = $("#fname").val().length;
if(fname_length < 3 || fname_length > 20){
$("#fnameErrorMsg").html("Should be 3 to 20 characters").css("color", "red");
}
else if(!$("#fname").val().match(name_regex)){
$("#fnameErrorMsg").html("Should be alphabets").css("color", "red");
}
else{
$("#fnameErrorMsg").html("*First name Accepted").css("color", "green");;
}
error_fname = true;
}
function check_lname(){
var fname_length = $("#lname").val().length;
if(fname_length < 3 || fname_length > 20){
$("#lnameErrorMsg").html("Should be 3 to 20 characters").css("color", "red");
}
else if(!$("#lname").val().match(name_regex)){
$("#lnameErrorMsg").html("Should be alphabets").css("color", "red");
}
else{
$("#lnameErrorMsg").html("*Last name Accepted").css("color", "green");;
}
error_lname = true;
}
function check_email(){
if(!$("#email").val().match(email_regex)){
$("#emailErrorMsg").html("Invalid Email Address!").css("color", "red");
}
else{
$("#emailErrorMsg").html("*Email Accepted").css("color", "green");;
}
error_email = true;
}
function check_pass(){
var pass_val = $("#pass").val();
var repass_val= $("#repass").val();
if(pass_val.length < 3 ){
$("#passErrorMsg").html("Password should be 3 characters minimum!").css("color", "red");
if(pass_val != repass_val){
$("#repassErrorMsg").html("*Password doesn't match").css("color","red");
}
}else{
$("#passErrorMsg").html("*Password accepted!").css("color", "green");
}
error_pass = true;
}
function check_repass(){
var pass_val = $("#pass").val();
var repass_val = $("#repass").val();
if((pass_val == null || pass_val == "") && (repass_val == null || repass_val == "")){
$("#passErrorMsg").html("Password should be 3 characters minimum!").css("color", "red");
}
else if(pass_val != repass_val){
$("#repassErrorMsg").html("*Password doesn't match").css("color","red");
}
else{
$("#repassErrorMsg").html("*Password matched!").css("color", "green");
}
error_repass = true;
}
function check_address(){
var addr = $("#address").val();
if((addr == "" || addr == null)){
$("#addressErrorMsg").html("*Address is required!").css("color", "red");
}
else if((!addr.match(addr_regex)) || (addr.length < 3)){
$("#addressErrorMsg").html("Minimum 3 characters required!").css("color", "red");
}
else{
$("#addressErrorMsg").html("*Address Accepted").css("color", "green");;
}
error_addr = true;
}
function check_mobile(){
var mob = $("#mobile").val();
if(mob == "" || mob == null){
$("#mobileErrorMsg").html("Mobile number required").css("color","red");
}
else if(mob.length < 10 || mob.length > 12){
$("#mobileErrorMsg").html("Enter only digits").css("color","red");
}
else if(!mob.match(mob_regex)){
$("#mobileErrorMsg").html("Please choose required format!").css("color","red");
}
else{
$("#mobileErrorMsg").html("*Mobile number accepted").css("color","green");
}
error_mob = true;
}
function check_dob(){
var dob = $("#datepicker").val();
if(dob == "" || dob == null){
$("#dobErrorMsg").html("*Dob is required").css("color","red");
}
else{
$("#dobErrorMsg").html("*Dob is accepted").css("color","green");
}
error_dob = true;
}
$(document).on("click","#add_submit",function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var pass = $("#pass").val();
var repass = $("#repass").val();
var addr = $("#address").val();
var mobile = $("#mobile").val();
var dob = $("#datepicker").val();
if((fname == "" || fname == null) && (lname == "" || lname == null) && (email == "" || email == null) && (pass == "" || pass == null) && (repass == "" || repass == null) && (addr == "" || addr == null) && (mobile == "" || mobile == null) &&(dob == "" || dob == null) ){
$("#fnameErrorMsg").html("*First name required!").css("color", "red");
$("#lnameErrorMsg").html("*Last name required!").css("color", "red");
$("#emailErrorMsg").html("*Email required!").css("color", "red");
$("#passErrorMsg").html("*Password required!").css("color", "red");
$("#repassErrorMsg").html("*Repassword required!").css("color","red");
$("#addressErrorMsg").html("*Address is required!").css("color","red");
$("#mobileErrorMsg").html("*Mobile number is required").css("color","red");
$("#dobErrorMsg").html("*Dob is required").css("color","red");
return false;
}
else if(fname == "" || fname == null){
$("#fnameErrorMsg").html("*First name required!").css("color", "red");
return false;
}
else if(lname == "" || lname == null){
$("#lnameErrorMsg").html("*Last name required!").css("color", "red");
return false;
}
else if(email == "" || email == null){
$("#emailErrorMsg").html("*Email required!").css("color", "red");
return false;
}
else if(pass == "" || pass == null){
$("#passErrorMsg").html("*Password required!").css("color", "red");
return false;
}
else if(repass == "" || repass == null){
$("#repassErrorMsg").html("*Repassword required!").css("color","red");
return false;
}
else if(addr == "" || addr == null){
$("#addressErrorMsg").html("*Address is required!").css("color","red");
return false;
}
else if(mobile == "" || mobile == null){
$("#mobileErrorMsg").html("*Mobile number is required").css("color","red");
return false;
}
else if(dob == "" || dob == null){
$("#dobErrorMsg").html("*Dob is required").css("color","red");
return false;
}
else{
// $("#testErrorMsg").html("*required").css("color","red");
return true;
}
// else if(lname == "" || lname == null){
// check_lname();
// $("#lname").focus();
// return false;
// }
// else if(email == "" || email == null){
// check_email();
// $("#email").focus();
// return false;
// }
// if($("Checkbox1").prop("checked", false)) {
// alert("not check");
// return false;
// }
});
});
/*
$("#form1").submit(function(){
if(error_fname == false){
check_fname();
return true;
}else{
return false;
}
});
});
*/
/*$(document).ready(function(){
alert("Hellooooo");
})*/
/*
$(document).on("click","#add_submit",function(){
var error_fname = false;
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var pass = $("#pass").val();
var repass = $("#repass").val();
var addr = $("#address").val();
var mobile = $("#mobile").val();
var dob = $("#datepicker").val();
if(fname =="" || fname ==null){
$("#fnameErrorMsg").html("Please enter first name").css("color", "red");
$("#fname").focus();
//check_fname();
return false;
}
else if(fname != ""){
var fname_length = $("#fname").val().lenght();
if(fname_length < 5 || fname_length > 20){
$("#fnameErrorMsg").html("Should be 5 to 20 characters").css("color", "red");
}
return false;
}
else if(lname =="" || lname ==null){
alert("Please enter last name");
$("#lname").focus();
return false;
}
else if(email == "" || email == null){
alert("Please enter email name");
$("#email").focus();
return false;
}
else if(pass == "" || pass == null){
alert("Please enter password");
$("#pass").focus();
return false;
}
else if(repass == "" || repass == null){
alert("Please enter retype password");
$("#repass").focus();
return false;
}
else if(addr == "" || addr == null){
alert("Please enter address");
$("#address").focus();
return false;
}
else if(mobile == "" || mobile == null){
alert("Please enter mobile");
$("#mobile").focus();
return false;
}
else if(dob == "" || dob == null){
alert("Please enter date of birth");
$("#datepicker").focus();
return false;
}
function check_fname(){
var fname_length = $("#fname").val().lenght();
if(fname_length < 5 || fname_length > 20){
$("#fnameErrorMsg").html("Should be 5 to 20 characters").css("color", "red");
}
}
})*/
|
const { EventEmitter } = require('events');
const Dispatcher = require('../dispatcher');
const CHANGE_EVENT = 'change';
const _settings = {
checkForUpdatesOnStartup: true
};
class SettingsStore extends EventEmitter {
emitChange() {
this.emit(CHANGE_EVENT);
}
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
}
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
get() {
return _settings;
}
};
const settingsStore = new SettingsStore();
SettingsStore.dispatchToken = Dispatcher.register((action) => {
switch(action.type) {
default:
// ignore
}
});
module.exports = settingsStore;
|
todoApp.service('LoginService', ['AuthService', '$http', '$q', function(AuthService, $http, $q) {
return {
'checkAuth': function(user) {
var defer = $q.defer();
$http.post('/auth', {email : user.email, password: user.password}).success(function(resp){
console.log("Going to AuthService to set token in browser");
AuthService.setToken(resp.token);
defer.resolve(resp);
}).error(function(err){
defer.reject(err);
});
return defer.promise;
},
'isLoggedIn': function() {
if (AuthService.getCurrentUser())
return true;
else
return false;
}
}
}]);
|
$(function () {
//ๆฅ่ฏข็จๆท็ปๅฝ็ถๆๅๅ ่ฝฝ็จๆทๅ่ฝ
$.ajax({
url:"../../stuIndexLoginer.do",
type:"get",
dataType:"json",
success:function(data){
console.log(data);
//ๅคๆญ็จๆทๆฏๅฆ็ปๅฝ
if(data=="101"){
location.href="login.html";
}else{
$(".sname").text(data.fullName); //่ฎพ็ฝฎ็จๆท็ปๅฝๅ
$(".toExam").click(function(){
location.href = "onlineExam.html?no="+data.IDNo;
})
$(".toStu").click(function(){
location.href = "studentFinish.html?no="+data.IDNo;
})
}
}
})
});
|
// NOTE: Do not fix lint issues with this file!
// It is expected to fail ESLint validation for testing purposes.
class Foo{
speak(){
console.log("hello");
}
}
let foo=new Foo();
foo.speak( )
|
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
function printText(text) {
var node = document.createElement("p");
var textnode = document.createTextNode(text);
node.appendChild(textnode);
var parent = document.querySelector(".dashboard");
parent.insertBefore(node, parent.firstChild);
}
function doAction() {
fetch('https://numbersapi.p.mashape.com/6/21/date', {
headers: {
'Accept': 'Accept: text/plain',
'X-Mashape-Key': '2caA1hl5c8msh85QDOmR2UgJMvXhp13ymIsjsnrupoGpud7nSQ'
}
}).then(function (resp) {
return resp.text();
}).then(function (text) {
printText('Yoda: ' + text)
});
return false;
}
|
'use strict';
const app = require('./app');
const port = process.env.PORT || 3000;
const logger = require('./logger');
// Database connection
require('./db-connection')();
const server = app.listen(port, function() {
logger.info('Server listening on port ' + port);
});
|
import React from 'react';
import {compose} from 'redux';
import {DragSource, DropTarget} from 'react-dnd';
import ItemTypes from '../constants/itemTypes';
import connect from '../libs/connect';
import NoteActions from '../actions/NoteActions';
import LaneActions from '../actions/LaneActions';
import Notes from './Notes';
import LaneHeader from './LaneHeader';
const Lane = ({
connectLaneDragSource,
isDragging,
connectLaneDropTarget,
isOver,
onMove,
connectDropTarget,
lane,
notes,
LaneActions,
NoteActions,
...props
}) => {
const activateNoteEdit = (noteId) => {
NoteActions.update({ id: noteId, editing: true });
};
const editNote = (noteId, task) => {
NoteActions.update({ id: noteId, task, editing: false });
};
const deleteNote = (noteId, event) => {
// Avoid bubbling to edit
event.stopPropagation();
LaneActions.detachFromLane({
laneId: lane.id,
noteId
});
NoteActions.delete(noteId);
};
const selectNotesByIds = (allNotes, noteIds = []) => {
return noteIds.reduce((notes, id) => notes.concat(
allNotes.filter(note => note.id === id)
), [])
};
return compose(connectLaneDragSource, connectLaneDropTarget, connectDropTarget)(
<div {...props}>
<LaneHeader lane={lane} />
<Notes
notes={selectNotesByIds(notes, lane.notes)}
onNoteClick={activateNoteEdit}
onEdit={editNote}
onDelete={deleteNote}
/>
</div>
);
};
Lane.propTypes = {
lane: React.PropTypes.shape({
id: React.PropTypes.string.isRequired,
editing: React.PropTypes.bool,
name: React.PropTypes.string,
notes: React.PropTypes.array
}).isRequired,
LaneActions: React.PropTypes.object,
NoteActions: React.PropTypes.object,
connectDropTarget: React.PropTypes.func
};
Lane.defaultProps = {
name: '',
notes: []
};
const noteTarget = {
hover(targetProps, monitor) {
const sourceProps = monitor.getItem();
const sourceId = sourceProps.id;
if (!targetProps.lane.notes.length) {
LaneActions.attachToLane({
laneId: targetProps.lane.id,
noteId: sourceId
});
}
}
};
const laneSource = {
beginDrag(props) {
return {
id: props.lane.id
};
}
};
const laneTarget = {
hover(targetProps, monitor) {
const targetId = targetProps.lane.id;
const sourceProps = monitor.getItem();
const sourceId = sourceProps.id;
if (sourceId !== targetId) {
targetProps.onMove({ sourceId, targetId });
}
}
};
export default compose(
DropTarget(ItemTypes.NOTE, noteTarget, connect => ({
connectDropTarget: connect.dropTarget()
})),
DragSource(ItemTypes.LANE, laneSource, (connect, monitor) => ({
connectLaneDragSource: connect.dragSource(),
isDragging: monitor.isDragging
})),
DropTarget(ItemTypes.LANE, laneTarget, (connect, monitor) => ({
connectLaneDropTarget: connect.dropTarget(),
isOver: monitor.isOver()
})),
connect(({ notes }) => ({
notes
}), {
NoteActions,
LaneActions
})
)(Lane);
|
function selectionSort(arr) {
var _a;
for (var i = 0; i < arr.length; i++) {
var min = i;
for (var j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (i !== min) {
_a = [arr[min], arr[i]], arr[i] = _a[0], arr[min] = _a[1];
}
}
console.log(arr);
return arr;
}
selectionSort([0, 5, 3, 4, 12, 1, 2, 8, 7]);
|
export { TransactionChart } from './transaction-chart';
|
// packages
const inquirer = require("inquirer");
const axios = require("axios");
const puppeteer = require("puppeteer");
const generateHTML = require("./generateHTML.js");
let html;
let profileFinal;
// User is prompted in Terminal for their Github Username
function getName() {
const username = inquirer.prompt({
type: "input",
message: "Enter your Github profile name?",
name: "username"
})
return username
}
// User is prompted in Terminal for their favorite color
function getColor() {
const color = inquirer.prompt({
type: "list",
message: "What is your favorite color?",
name: "color",
choices: ["Green", "Blue", "Pink", "Red"]
});
return color
}
//
function getGithub(username) {
return axios.get(`https://api.github.com/users/${username}`).then((res) => {
// console.log(res.data);
return res.data
})
};
function getStarLength(username) {
return axios.get(`https://api.github.com/users/${username}/starred`).then((res) => {
// console.log(res.data);
return res.data.length
})
};
async function init() {
let {username} = await getName();
// console.log("Your username is " + username);
let {color} = await getColor();
// console.log("Your favorite color is " + color);
let profile = await getGithub(username);
// console.log('\n'+'... getGithub Response ...')
// console.log(profile);
let { avatar_url, name, company, bio, public_repos, followers, following, html_url, blog, location } = profile;
profile.color = color;
// console.log("profile.color should be " + profile.color);
let star = await getStarLength(username);
// console.log('\n'+'... getStarLength Response ...')
// console.log(star);
profile.star = star;
profileFinal = username;
profile.star = star;
html = generateHTML(profile);
genPDF();
}
async function genPDF() {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.setViewport({
width: 1440,
height: 900,
deviceScaleFactor: 2
});
await page.pdf({
path: `${profileFinal}.pdf`,
printBackground: true,
format: "A4"
})
console.log("PDF file succesfully generated!")
await browser.close();
process.exit();
}
catch(err) {
console.log(err);
}
}
init();
|
import axios from 'axios'
const base_url = 'https://jsonplaceholder.typicode.com';
const baseConnection = axios.create({
baseURL: base_url
});
const axiosAPI = ({
getUsers: () => baseConnection.get('/users'),
createUser: (
id,
name,
username,
email
) => baseConnection.post('/users', {
id,
name,
username,
email
}),
getTweets: () => baseConnection.get('/posts'),
createTweet: (
userId,
id,
title,
body
) => baseConnection.post('/posts', {
userId,
id,
title,
body
})
})
export default axiosAPI;
|
var sql = require('../../connect_db');
var message = function (message) {
this.sender = message.sender;
this.receiver = message.receiver;
this.message = message.message;
};
message.loadAvailableUsersMessages = function (user, result) {
sql_query = "select * from tedi.messages where messages.receiver = ? order by messages.id DESC; " +
"select * from tedi.messages where messages.sender = ? order by messages.id DESC; ";
sql.query(sql_query, [user, user], function (err, res) {
if (err) {
console.log("Error: ", err);
result(null, err);
}
else {
result(null, res);
}
});
};
message.sendMessage = function (sender, receiver, msg, result) {
sql_query = "insert into tedi.messages(sender,receiver,message,state) values(?,?,?,0)";
sql.query(sql_query, [sender, receiver, msg], function (err, res) {
if (err) {
console.log("Error: ", err);
result(null, err);
}
else {
result(null, res);
}
});
};
message.checkMessages = function (username, result) {
sql.query('select count(state) as new_messages from tedi.messages where state = 0 and receiver = ?;', username, function (err, res) {
if (err) {
console.log("Error: ", err);
result(null, err);
}
else {
result(null, res);
}
});
};
message.changeState = function (id, result) {
sql.query('update tedi.messages set messages.state = 1 where messages.id = ?', id, function (err, res) {
if (err) {
console.log("Error: ", err);
result(null, err);
}
else {
result(null, res);
}
});
};
message.deleteMessage = function (id, result) {
sql.query('delete from tedi.messages where messages.id = ?', id, function (err, res) {
if (err) {
console.log("Error: ", err);
result(null, err);
}
else {
result(null, res);
}
});
};
module.exports = message;
|
import React from 'react';
import { Link } from 'react-router';
const Icon = React.createClass({
handleDeleteBoard: function() {
this.props.onDeleteBoard({
id: this.props.id,
board: this.props.boardID
});
},
render: function () {
return (
<div className="icons">
<Link to={this.props.title}>
<span
className="delete board-icon"
onClick={this.handleDeleteBoard}
>
<div>x</div>
</span>
{this.props.title}
</Link>
</div>
);
},
});
export default Icon;
|
const data = [{
durationAvg: 168.5,
durationMin: 147,
durationMax: 190,
durationLast: 147,
durationSum: 337,
sessionCount: 2,
requestSum: 18,
requestAvg: 9,
username: "jhon.doe",
__typename: "SessionsByUser"
}, {
durationAvg: 250,
durationMin: 250,
durationMax: 250,
durationLast: 250,
durationSum: 250,
sessionCount: 1,
requestSum: 13,
requestAvg: 13,
username: "jane.doe",
__typename: "SessionsByUser"
}]
export default data
|
var discipline = require('./discipline');
var media = require('./media');
var bookshelf = require('../custom_modules/bookshelf').plugin('registry');
module.exports = bookshelf.model('disciplinemedia', {
tableName: 'disciplinemedia',
discipline: function () {
return this.hasOne(discipline);
},
media: function () {
return this.hasOne(media);
}
});
|
/**
* ๅคๆญไธไธชๅผๆฏไธๆฏnullใ
*
* @since V0.1.3
* @public
* @param {*} value ้่ฆๅคๆญ็ฑปๅ็ๅผ
* @returns {boolean} ๅฆๆๆฏnull่ฟๅtrue๏ผๅฆๅ่ฟๅfalse
*/
export default function (value) {
return value === null;
};
|
var Controls = {
id: "fo-controls",
actions: ['start', 'restart', 'pause', 'unpause', 'close'],
buttons: {},
element: null
}
Controls.init = function() {
}
Controls.action = function (e) {
var btn = e.target
if (btn.hasAttribute('data-action') && !btn.hasAttribute('disabled')) {
Controls.onclick && Controls.onclick(btn)
}
return false
}
Controls.onclick = function(btn) {
var action = Game[btn.getAttribute('data-action')]
action && action()
Controls.refresh()
}
Controls.open = function() {
if (!Controls.element) {
var content = '<span id="fo-score">0</span>' +
Controls.actions.map(function(name) {
return '<a data-action="' + name + '"></a>'
}).join('')
var element = document.createElement('div')
element.id = Controls.id
element.innerHTML = content
Controls.actions.forEach(function(name) {
Controls.buttons[name] = element.querySelector('[data-action="' + name + '"]')
})
element.addEventListener('click', Controls.action)
Controls.element = element
Game.container.appendChild(element)
Controls.refresh()
}
}
Controls.apply = function(operation, names, value) {
if (!Array.isArray(names)) names = [names]
names.forEach(function(name) {
var btn = Controls.buttons[name]
switch (operation) {
case 'disable': btn.setAttribute('disabled', true); break
case 'enable': btn.removeAttribute('disabled'); break
case 'show': btn.style.display = ''; break
case 'hide': btn.style.display = 'none'; break
case 'setTitle': btn.title = value; break
case 'setShadow': btn.firstChild.style.boxShadow = value
}
})
return this
}
Controls.refreshScore = function() {
var score = document.getElementById('fo-score')
score.innerHTML = Game.score
}
Controls.refresh = function() {
if (!Game.running && !Game.dead) {
Controls.apply('show', ['start', 'close']).apply('hide', ['restart', 'pause', 'unpause'])
} else if(!Game.running && Game.dead) {
Controls.apply('show', ['restart', 'close']).apply('hide', ['start', 'pause', 'unpause'])
} else if (Game.running && !Game.paused) {
Controls.apply('show', ['pause', 'close']).apply('hide', ['unpause', 'start', 'restart'])
} else if (Game.running && Game.paused) {
Controls.apply('show', ['unpause', 'restart', 'close']).apply('hide', ['pause', 'start'])
}
}
Controls.close = function() {
if (Controls.element) {
Controls.element.parentNode.removeChild(Controls.element)
Controls.element = null
}
}
Controls.init()
|
import React from 'react';
import Note from './Note.jsx';
import Masonry from 'react-masonry-component';
import './NotesGrid.less';
export default class NotesGrid extends React.Component{
render() {
const masonryOptions = {
itemSelector: '.Note',
columnWidth: 250,
gutter: 10,
isFitWidth: true
}
return (
<Masonry
className='NotesGrid'
options={masonryOptions}
>
{
this.props.notes.map(note =>
<Note
key={note.id}
title={note.title}
onDelete={this.props.onNoteDelete.bind(null, note)}
color={note.color}
>
{note.text}
</Note>
)
}
</Masonry>
);
}
}
|
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
(function () {
// Get all of the images that are marked up to lazy load
var images = document.querySelectorAll('[data-plugin="defer-img-load"]');
var config = {
// If the image gets within 300px in the Y axis, start the download.
rootMargin: '300px 0px',
threshold: 0.01
};
var imageCount = images.length;
var observer = void 0;
var first = void 0;
if (!('IntersectionObserver' in window)) {
//load X images now - defer to rest to window.load event
var loadInitial = function loadInitial(numberDeferred) {
images = [].concat(_toConsumableArray(images));
var initialImages = images.splice(0, numberDeferred);
initialImages.forEach(function (image) {
return preloadImage(image);
});
moveToBackgroundImages(initialImages);
};
loadInitial(2);
// load rest of imgs after window load
window.addEventListener("load", function () {
images.forEach(function (image) {
return preloadImage(image);
});
moveToBackgroundImages(images);
});
} else {
observer = new IntersectionObserver(onIntersection, config);
images.forEach(function (image) {
if (image.hasAttribute('data-loaded')) return;
observer.observe(image);
});
}
function onIntersection(entries) {
// Disconnect if we've already loaded all of the images
if (imageCount === 0) {
observer.disconnect();
}
// Loop through the entries
entries.forEach(function (entry, index) {
// Are we in viewport?
if (entry.intersectionRatio > 0) {
imageCount--;
// Stop watching and load the image
observer.unobserve(entry.target);
preloadImage(entry.target, index);
}
});
}
function preloadImage(image, index) {
var src = image.dataset.src;
var srcset = image.dataset.srcset;
if (!src) return;
return applyImage(image, src, srcset);
}
function applyImage(img, src, srcset) {
// apply img
if (srcset) {
img.srcset = srcset;
}
if (src) {
img.src = src;
}
// Prevent this from being lazy loaded a second time.
img.setAttribute('data-loaded', 'true');
// remove attributes
img.removeAttribute('data-src');
img.removeAttribute('data-srcset');
}
})();
|
// @desc this component displays all email subscribers
// @author Sylvia Onwukwe
import React from "react";
// @material-ui/core components
import Grid from "@material-ui/core/Grid";
// core components
import GridItem from "../../components/Grid/GridItem";
import Card from "../../components/Card/Card";
import Snackbar from "@material-ui/core/Snackbar";
import CardHeader from "../../components/Card/CardHeader";
import CardBody from "../../components/Card/CardBody";
import BezopSnackBar from "../../assets/jss/bezop-mkr/BezopSnackBar";
import EnhancedTable from "../../bezopComponents/Table/EnhancedTable";
const columnData = [
{ id: "email", numeric: false, disablePadding: false, label: "Email Address" },
{ id: "frequency", numeric: false, disablePadding: false, label: "Frequency" },
]
const properties = [
{name: "email", component: false, padding: false, numeric: false, img: false},
{name: "frequency", component: false, padding: false, numeric: false, img: false}
];
class Subscribers extends React.Component {
constructor(props){
super(props);
this.state = {
sunscribers: [],
data: [],
snackBarOpenSuccess: false,
snackBarMessageSuccess: "",
deletedSubscriber: 0,
}
}
componentDidMount(){
this.props.fetchSubscribers();
}
componentWillReceiveProps(newProps){
if(newProps.subscriber.hasOwnProperty("subscribers")){
this.setState({
data: newProps.subscriber.subscribers
})
}
}
onCloseHandlerSuccess = () => {
this.setState({
snackBarOpenSuccess: false
})
}
handleDeleteClick = (subscriberIDs) => {
let counter = 0;
for(const subscriberID of subscriberIDs){
this.props.deleteSubscriber(subscriberID);
counter++;
if(counter === subscriberIDs.length){
let newData = this.state.data.filter( datum => subscriberIDs.indexOf(datum._id) === -1)
this.setState({
data: newData,
snackBarOpenSuccess: true,
snackBarMessageSuccess: `You have successfully deleted ${counter} email ${counter === 1 ? "subscriber" : "subscribers"}`
})
}
}
}
render () {
const { data, snackBarOpenSuccess, snackBarMessageSuccess } = this.state;
return (
<Grid container>
<GridItem xs={12} sm={12} md={12}>
<Card>
<CardHeader color="primary">
<h4>All Email Subscribers</h4>
<p>
List of All Active Email Subscribers
</p>
</CardHeader>
<CardBody>
<EnhancedTable
orderBy="name"
columnData={columnData}
data={data}
tableTitle="All Subscribers"
properties={properties}
onDeleteClickSpec={this.handleDeleteClick}
currentSelected = {[]}
itemName={{single : "Subscriber", plural: "Subscriber"}}
/>
</CardBody>
</Card>
<Snackbar
anchorOrigin={{vertical: "top", horizontal: "center"}}
open={snackBarOpenSuccess}
onClose={this.onCloseHandlerSuccess}
>
<BezopSnackBar
onClose={this.onCloseHandlerSuccess}
variant="success"
message={snackBarMessageSuccess}
/>
</Snackbar>
</GridItem>
</Grid>
);
}
}
export default Subscribers;
|
import React from 'react'
import { Link } from 'react-router-dom'
import './Footer.css'
const Footer = (props) => (
<footer className="footer-section pt-3">
<div className="container">
<div className="row">
<div className="col-sm-3 offset-sm-6 col-xs-12">
<h5 className="mb-4">Menu</h5>
<ul className="site-footer__links footer-collapse collapse show list-unstyled">
<li><Link to="/productos">Productos</Link></li>
<li><Link to="/ofertas">Ofertas</Link></li>
<li><Link to="/novedades">Novedades</Link></li>
<li><Link to="/contacto">Contacto</Link></li>
</ul>
</div>
<div className="col-sm-3 col-xs-12 footcont">
<h5 className="mb-4">Contacto </h5>
<div id="fcontact" className="footer-collapse collapse show">
<div className="address">
<ul className="list-unstyled">
<li>
<i className="fa fa-map-marker"></i> Tienda Online.
</li>
<li>
<i className="fa fa-phone"></i> +51 99995555
</li>
<li>
<i className="fa fa-envelope"></i> diego.g20x@gmail.com
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-md-12">
<p align="center" className="subtitle-footer mt-3">IdeasWebTec - Todos los derechos reservados ยฉ 2019</p>
</div>
</div>
</div>
</footer>
)
export default Footer
|
import { RELOAD_FLOCK_LIST } from './flockTypes';
const initialState = {
flockList: [],
};
const flock = (state = initialState, action) => {
switch (action.type) {
case RELOAD_FLOCK_LIST: {
// simple refresh, No reduction
if (!action.flockList) {
return initialState;
}
return {
flockList: action.flockList,
};
}
default:
return state;
}
};
export default flock;
|
import React from 'react';
export default React.createClass({
labels: {
N: 'none',
L: 'low',
M: 'moderate'
},
componentDidMount() {
$('.water.tooltipped').tooltip();
},
render() {
var water = this.props.water.map((waterCode) => {
var cls = 'tooltipped water '+waterCode;
var label = this.labels[waterCode]+' water';
return (
<span className={cls} data-position="bottom" data-tooltip={label} key={waterCode}></span>
);
});
return (
<div className="water-req">{water}</div>
);
}
});
|
import React from 'react';
import PropTypes from 'prop-types';
const Question = (props) => {
const {question, onAnswer} = props;
return(
<div>
<h2>Question: {question.question}</h2>
<div className="btnPart">
{question.answers.map((answer, index) =>
<div className="btn fullWidth fullHeight" key={index} onClick={() => onAnswer(index)}>{answer}</div>
)}
</div>
</div>
);
};
Question.propTypes = {
question: PropTypes.object.isRequired,
onAnswer: PropTypes.func.isRequired
};
export default Question;
|
import React, {useEffect} from 'react';
import {Link} from '@reach/router';
import axios from 'axios';
import DeleteButton from './DeleteButton';
const UserParent = ({users, setusers}) => {
useEffect(()=>{
axios.get("http://localhost:8000/api/user")
.then(res => setusers(res.data))
.catch(err => console.log(err))
}, [setusers])
const deleteHandler = UserId => {
const tempArr = users.filter( User => User._id !== UserId);
setusers(tempArr);
}
return(
<div>
<h1><Link to={"/create"}>Click Here</Link> to create a new User!</h1>
<table>
<tbody>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Actions</td>
</tr>
{
users.map((User, idx)=>{
return(
<tr key={idx}>
<td>
{User.fname}
</td>
<td>
{User.lname}
</td>
<td><button><Link to={`/update/${User._id}`}>EDIT</Link></button><DeleteButton deleteId={User._id} callback={deleteHandler}/></td>
</tr>
)
})
}
</tbody>
</table>
</div>
)
}
export default UserParent;
|
import React, { Component } from 'react';
import { Row, Col } from "reactstrap";
import ReactPaginate from "react-paginate";
import { CarCard, Filter, Sort, SearchBox } from "./../components";
import { Common } from '../utils';
// Component for rendering the cars and it's functionality
export class CarsContainer extends Component {
constructor(props){
super(props);
this.state = {
location: "",
selectedDate: null,
cars: [],
limit: 6,
offset: 0,
sort: "",
filters: {},
searchCar: "",
isLoading: false,
day: null
}
}
// Method for Modified date and location
componentWillReceiveProps(nextProps){
nextProps && this.getInitialCars(nextProps.location, nextProps.selectedDate, 0, 6, "", "", {})
}
// Method to get Initial cars from the API
getInitialCars = (location, selectedDate, offset, limit, sort, searchCar, filters) => {
let day = Common.getDay(new Date(selectedDate).getDay());
this.setState({isLoading: true})
Common.getCars()
.then(res => {
var pageLength = Common.getNoOfPages(res, location);
let allCars = Common.getCarsFromLocation(res, location);
var data = Common.getCarsForLimit(allCars, day, sort, filters, offset, limit, searchCar);
this.setState({
day,
allCars: allCars,
cars: data,
pageLength,
location,
selectedDate,
isLoading: false
})
})
.catch(err => {
console.log(err)
})
}
componentDidMount(){
let { offset, limit, sort, searchCar, filters } = this.state;
let { location, selectedDate } = this.props;
this.getInitialCars(location, selectedDate, offset, limit, sort, searchCar, filters);
}
// Method for pagination Navigation
handlePageClick = (value) => {
let { allCars } = this.state;
let newOffset = value.selected * 6;
let newLimit = 6 * (value.selected+1);
const newCars = allCars.slice(newOffset, newLimit);
this.setState({
cars: newCars,
offset: newOffset,
limit: newLimit
})
}
// Method for sorting the cars based on Price
onSort = (sort) => {
let { allCars, day, searchCar, filters } = this.state;
let cars = Common.getCarsForLimit(allCars, day, sort, filters, 0, 6, searchCar);
this.setState({
cars,
sort,
offset: 0,
limit: 6
})
}
// Method for searching a car or a cartype
onSearchChange = (searchCar) => {
let { allCars, day, sort, offset, limit, filters } = this.state;
let cars = Common.getCarsForLimit(allCars, day, sort, filters, offset, limit, searchCar);
this.setState({
cars,
searchCar
})
}
// Method to filter cars based on Transmission, CarType, FuelType
onFilter = (filters) => {
let { allCars, day, sort, offset, limit, searchCar } = this.state;
let cars = Common.getCarsForLimit(allCars, day, sort, filters, offset, limit, searchCar);
this.setState({
filters,
cars
})
}
render() {
const { cars, isLoading, day } = this.state;
if(isLoading){
return <div className="text-center" >Cars are loading...</div>
}
return (
<>
<Row className="my-4 d-flex flex-row justify-content-between align-items-center">
<Col className="col-12 col-md-7">
<Filter onFilter={this.onFilter} />
</Col>
<Col className="col-12 col-md-3">
<SearchBox onSearchChange={this.onSearchChange} />
</Col>
<Col className="col-12 col-md-2">
<Sort onSort={this.onSort} />
</Col>
</Row>
{
cars.length === 0 &&
<h4 className="text-center text-warning">Sorry, Currently we don't have cars as per your requirements</h4>
}
<Row>
{/* Rendering Method for carlist */}
{
cars && cars.length > 0 && cars.map( (car, index) => {
return (
<Col className="col-12 col-md-4" key={index}>
<CarCard car={car} day={day} />
</Col>
)
})
}
</Row>
{/* Pagination Render method */}
{
cars && cars.length > 0 && !isLoading &&
<Row>
<Col>
<ReactPaginate
previousLabel={'<'}
nextLabel={'>'}
pageCount={this.state.pageLength}
onPageChange={this.handlePageClick}
containerClassName={"d-flex flex-row justify-content-center align-items-center pagination"}
subContainerClassName={'pages pagination'}
activeClassName={'active'}
/>
</Col>
</Row>
}
</>
);
}
}
|
console.log("Starting migration to schema 98");
var path = "/integrations/:INTEGRATION_ID/";
console.log("Fetching path: " + path);
var obj=jsondb.get(path);
obj["description"]="UPGRADE INTEGRATION DESCRIPTION"
jsondb.update(path, obj);
console.log("Migration to schema 98 completed");
|
//const precioOriginal = 120;
//const descuento = 18;
function calcularPrecioConDcto(precio, dcto) {
const porcentajePrecioConDcto = 100 - dcto;
const precioConDcto = (precio * porcentajePrecioConDcto) / 100;
return precioConDcto;
}
//Soluciรณn #1: arrays y switch
// let coupons = [
// "comboForYou15",
// "comboForYou25",
// "comboForYou35",
// "comboForYou40"
// ]
//Soluciรณn #3: arrays y condicionales mucho mรกs inteligentes
const coupons1 = [
{
name: "comboForYou15",
discount: 15,
},
{
name: "comboForYou25",
discount: 25,
},
{
name: "comboForYou35",
discount: 35,
},
{
name: "comboForYou40",
discount: 40,
}
]
// function onClickButtonPriceDiscount() {
// const inputPrice = document.getElementById("inputPrice");
// const inputDiscount = document.getElementById("inputDiscount");
// const inputCoupons = document.getElementById("inputCoupons");
// if (inputDiscount.value !== "" && inputCoupons.value == "") {
// const priceValue = inputPrice.value;
// const discountValue = inputDiscount.value;
// const precioConDescuento = calcularPrecioConDcto(priceValue, discountValue);
// const resultPrice = document.getElementById("resultPrice");
// resultPrice.innerText = "El precio con descuento son $" + precioConDescuento;
// } else if (inputCoupons.value !== "" && inputDiscount.value == "") {
// //Soluciรณn #1: arrays y switch
// const priceValue = inputPrice.value;
// const couponsValue = inputCoupons.value;
// let descuento;
// switch(couponsValue) {
// case coupons[0]://comboForYou15
// descuento = 15;
// break;
// case coupons[1]://comboForYou25
// descuento = 25;
// break;
// case coupons[2]://comboForYou35
// descuento = 35;
// break;
// case coupons[3]://comboForYou40
// descuento = 40;
// break;
// }//otra forma es no usar switch y cada caso podria ser una condicional else if {}
// //ademas incluiria if (!coupons.includes(couponValue)) {
// // alert("El cupรณn " + couponValue + "no es vรกlido");
// // } esta seria la primera validacion antes de los casos.
// }
// const precioConCupon = calcularPrecioConDcto(priceValue, descuento);
// const resultPrice = document.getElementById("resultPrice");
// resultPrice.innerText = "El precio con descuento por cupรณn son $" + precioConCupon;
// } else if (inputCoupons.value !== "" && inputDiscount.value !== "" && inputPrice.value !== "") {
// const resultPrice = document.getElementById("resultPrice");
// resultPrice.innerText = "Solo es posible aplicar un descuento a su producto";
// }
// }
//innerText es una funcion que se comporta como un atributo
//console.log("El precio original es " + precioOriginal);
// console.log({
// precioOriginal,
// descuento,
// porcentajePrecioConDcto,
// precioConDcto
// })
//Soluciรณn #2: legibilidad, error first y muerte al switch
//es la solucion planteada con los else if
//Soluciรณn #3: arrays y condicionales mucho mรกs inteligentes
function onClickButtonPriceDiscount() {
const inputPrice = document.getElementById("inputPrice");
const inputCoupons = document.getElementById("inputCoupons");
const priceValue = inputPrice.value;
const couponsValue = inputCoupons.value;
const isCouponValueValid = function (coupon) {
return coupon.name === couponsValue;
}
const userCoupon = coupons1.find(isCouponValueValid);
if (!userCoupon) {
alert("El cupรณn " + couponsValue + "no es vรกlido");
} else {
const descuento = userCoupon.discount;
const precioConDescuento = calcularPrecioConDcto(priceValue, descuento);
const resultPrice = document.getElementById("resultPrice");
resultPrice.innerText = "El precio con descuento son: $" + precioConDescuento;
}
}
|
const budgets = [100, 120, 100, 120, 150];
const M = 400;
const solution = (budgets, M) => {
let answer = 0;
const sum = budgets.reduce((acc, cur) => {
return acc + cur;
}, 0);
//console.log(budgets);
if (sum <= M) {
let max = 0;
for (let i = 0; i < budgets.length; i++) {
if (budgets[i] > max) {
max = budgets[i];
}
}
return max;
} else {
let min = 0;
let max = M;
while (true) {
let num = Math.floor((max + min) / 2);
if (answer === num) return answer;
const calculateBudget = budgets.reduce((acc, cur) => {
if (cur > num) {
return acc + num;
} else {
return acc + cur;
}
}, 0);
if (calculateBudget === M) return num;
else if (calculateBudget < M) {
min = num;
answer = num;
} else {
max = num;
answer = num;
}
}
}
};
console.log(solution(budgets, M));
|
import React, { Component } from 'react';
import { Form, Button, Input, Upload, Icon, notification, Select } from 'antd';
import './EditToon.css';
import { fetchToonById, deleteToonThumbnail, fetchToonThumbnailById, uploadEditToon, uploadEditToonExceptFile } from '../util/APIAdmin';
const { Dragger } = Upload;
const { Option } = Select;
class EditToon extends Component {
constructor(props){
super(props);
this.state ={
title:'',
artist:'',
day:'mon',
genre:'',
fileList:[],
originFileName:''
};
this.onDayChange = this.onDayChange.bind(this);
this.onGenreChange = this.onGenreChange.bind(this);
this.onChangeTitle = this.onChangeTitle.bind(this);
this.onChangeArtist = this.onChangeArtist.bind(this);
this.onChange = this.onChange.bind(this);
this.loadToon = this.loadToon.bind(this);
this.loadToonThumbnail = this.loadToonThumbnail.bind(this);
this.deleteFile = this.deleteFile.bind(this);
this.uploadEditWebtoon = this.uploadEditWebtoon.bind(this);
}
onDayChange = value =>{
this.setState({ day: value}, function () {
console.log(this.state.day);
});
}
onGenreChange = value =>{
this.setState({ genre: value}, function () {
console.log(this.state.genre);
});
}
onChangeTitle = (e) => {
this.setState({title: e.target.value}, function(){
console.log(this.state)
})
}
onChangeArtist = (e) => {
this.setState({artist: e.target.value}, function(){
console.log(this.state)
})
}
onChange=({ fileList })=> {
this.setState({ fileList }, function(){
console.log(this.state)
})
}
// ๊ธฐ์กด ํน์ ๋งํ ๊ฐ์ ธ์ค๊ธฐ
componentDidMount() {
this.loadToon();
this.loadToonThumbnail();
}
loadToon() {
fetchToonById(parseInt(this.props.match.params.id, 10))
.then((res) => {
this.setState({
title : res.title,
artist : res.artist,
day : res.day,
genre : res.genre
}, function(){
console.log(this.state)
})
});
}
loadToonThumbnail() {
fetchToonThumbnailById(parseInt(this.props.match.params.id, 10))
.then((res) => {
this.setState({
originFileName : res.fileName
}, function(){
console.log(this.state)
})
});
}
deleteFile(id){
deleteToonThumbnail(id)
.then(res => {
this.setState({originFileName:null}, function(){
console.log(this.state)
})
})
}
uploadEditWebtoon(){
try {
if(this.state.originFileName !==null){ //์ธ๋ค์ผ ์์ ํ์ง ์์ ๊ฒฝ์ฐ
uploadEditToonExceptFile(parseInt(this.props.match.params.id, 10), this.state.title, this.state.artist, this.state.day, this.state.genre)
} else { //์ธ๋ค์ผ ์์ ํ ๊ฒฝ์ฐ
uploadEditToon(parseInt(this.props.match.params.id, 10), this.state.title, this.state.artist, this.state.day, this.state.genre, this.state.fileList[0].originFileObj)
}
this.props.history.push("/adminmenu");
notification.success({
message: 'Cheeze Toon',
description: "์ ์์ ์ผ๋ก ์ ์ฅ๋์์ต๋๋ค.",
});
} catch(error) {
notification.error({
message: 'Cheeze Toon',
description: error.message || '๋ค์ ์๋ํด์ฃผ์ธ์.'
});
}
}
render() {
return (
<div className="editToon-container">
<Form onSubmit={this.uploadEditWebtoon}>
<Form.Item label="์ํ ์ ๋ชฉ">
<Input type="text" name="title" size="large" placeholder="Title" value={this.state.title} onChange={this.onChangeTitle}></Input>
</Form.Item>
<Form.Item label="์๊ฐ">
<Input type="text" name="artist" size="large" placeholder="Artist" value={this.state.artist} onChange={this.onChangeArtist}></Input>
</Form.Item>
<Form.Item label="์ฐ์ฌ ์์ผ">
<Select name="day" value={this.state.day} size="large" onChange={this.onDayChange}>
<Option value="mon">์์์ผ</Option>
<Option value="tue">ํ์์ผ</Option>
<Option value="wed">์์์ผ</Option>
<Option value="thu">๋ชฉ์์ผ</Option>
<Option value="fri">๊ธ์์ผ</Option>
<Option value="sat">ํ ์์ผ</Option>
<Option value="sun">์ผ์์ผ</Option>
</Select>
</Form.Item>
<Form.Item label="์ฅ๋ฅด">
<Select name="genre" value={this.state.genre} size="large" onChange={this.onGenreChange}>
<Option value="๋ก๋งจ์ค">๋ก๋งจ์ค</Option>
<Option value="์ผ์">์ผ์</Option>
<Option value="๊ณตํฌ">๊ณตํฌ</Option>
<Option value="ํํ์ง">ํํ์ง</Option>
</Select>
</Form.Item>
<Form.Item label="์ธ๋ค์ผ">
{this.state.originFileName !== null &&
<div>
<span>{this.state.originFileName} </span>
<Button type="primary" size="small" onClick={() => this.deleteFile(parseInt(this.props.match.params.id, 10))}>Delete</Button>
</div>
}
<Dragger onChange={this.onChange} beforeUpload={() => false} >
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">Click or Drag your image</p>
<p className="ant-upload-hint">
์ธ๋ค์ผ ๊ถ์ฅ ์ฌ์ด์ฆ๋ 10 : 8 (๋น์จ) ์
๋๋ค.
</p>
</Dragger>
</Form.Item>
<Form.Item>
<Button type="primary" className="editToonButton" size="large" htmlType="submit">Save</Button>
</Form.Item>
</Form>
</div>
);
}
}
export default EditToon;
|
new Vue({
el:"#app",
data:{
gameIsOn:true,
gameStart:false,
showhome:false,
showdetails:false,
names:['linas','urshala'],
selectfrom:['Newton','Ellen','Einstien','pink floyd','luffy','rez','friends','love','hate','life'],
arr1:[],
arr2:[],
selections:[],
selectbox:true,
showform:false,
showform2:false,
changedPlayerName:'',
time:'',
min:'',
sec:'',
ms:'',
p1active:false,
p2active:false,
p1selection:'',
p2selection:'',
totalclick:0,
p1array:[],
p2array:[],
p1points:0,
p2points:0,
p1turn:false,
p2turn:false,
toremove:[],
winningScreen:false,
winner:'',
showchangename:true,
notvalid:false,
remainingBoxes:20,
music:{},
musicfile:'https://www.televisiontunes.com/uploads/audio/Game%20of%20Thrones.mp3',
clicksoundsrc:'audio/click.mp3',
GOT:true,
sounds:['audio/1.mp3','audio/2.mp3','','','audio/3.mp3','audio/4.mp3','audio/5.mp3','audio/6.mp3','audio/7.mp3','audio/8.mp3'],
conversation:{},
wrong:{},
thatswrong:'audio/thatswrong.mp3',
right:{},
thatsright:'audio/thatsright.mp3',
startaftergamefinish:false,
list:[],
bindingStyle:{
'opacity':'',
'background':''
},
boxes:[],
thisisdead:false,
gameisdraw:false,
playonemoretime:'audio/onemoretime.mp3',
newAudio:{},
},
methods:{
form1(){
this.showform = ! this.showform;
this.clickaudio();
},
form2(){
this.showform2 = ! this.showform2;
this.clickaudio();
},
changeNamep1(){
console.log(this.changedPlayerName);
this.clickaudio();
this.names[0]= this.changedPlayerName;
this.showform=false;
if(this.changedPlayerName.length==0){
this.names[0]='linas';
}
this.changedPlayerName= '';
},
changeNamep2(){
console.log(this.changedPlayerName);
this.clickaudio();
this.names[1]= this.changedPlayerName;
this.showform2=false;
if(this.changedPlayerName.length==0){
this.names[1]='urshala';
}
this.changedPlayerName= '';
},
startGame(){
this.clickaudio();
this.hideall();
this.gameIsOn= false;
this.gameStart = true;
this.showhome=true;
this.showdetails=true;
this.p1turn=true;
this.p1active=true;
this.showchangename=false;
this.gameisdraw=false;
this.startTime();
this.startms();
// console.log('game started');
// console.log(this.arr1);
for(var i = 0 ; this.arr1.length < this.selectfrom.length ; i++){
var random = this.selectfrom[Math.floor(Math.random()*this.selectfrom.length)];
if(!this.arr1.includes(random)){
this.arr1.push(random);
}
}
// console.log('array 1 is coming');
// console.log(this.arr1);
// console.log(this.arr2);
for(var i=0 ; this.arr2.length < this.selectfrom.length ; i++){
var random = this.selectfrom[Math.floor(Math.random()*this.selectfrom.length)];
if(!this.arr2.includes(random)){
this.arr2.push(random);
}
}
// console.log('array 2 is coming')
// console.log(this.arr2);
// console.log(this.selections);
this.selections = [...this.arr1,...this.arr2];
// console.log('selections are coming');
// console.log(this.selections);
},
restartGame(){
this.clickaudio();
this.gameIsOn=true;
this.arr1=[];
this.arr2=[];
this.selections=[];
this.p1points=0;
this.p2points=0;
this.gameStart=false;
this.p2turn=false;
this.remainingBoxes=20;
this.showdetails=true;
this.selectbox=true;
// this.hideall();
this.startGame();
},
currentTime(){
var date = new Date();
this.time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
},
home(){
this.clickaudio();
this.gameIsOn=true;
this.gameStart=false;
this.showhome=false;
this.winningScreen=false;
this.showdetails=false;
this.showchangename=true;
this.p1points=0;
this.p2points=0;
this.p1turn=false;
this.p2turn=false;
},
startTime(){
this.sec=0;
this.min=0;
setInterval(() => {
this.sec += 1;
if(this.sec>60){
this.min += 1;
this.sec=0;
}
}, 1000);
},
startms(){
setInterval(() => {
this.ms += 1;
if(this.ms>99){
this.ms=0;
}
}, 50);
},
selected(index){
this.clickaudio();
this.makeitvisible(index);
var clickedvalue=this.selections[index];
this.totalclick +=1;
if(this.p2active){
// console.log(`p2 is active.`);
if(this.selections[index]==' '){
this.gameStart=false;
this.thisisdead=true;
this.totalclick -= 1;
this.right.src='';
this.wrong.src='';
}
else{
/* if(this.totalclick==2){
this.p2selection='';
this.totalclick=0;
} */
this.p1active=false;
this.p1selection='';
this.p2selection = clickedvalue;
this.toremove.push(index);
this.p2array.push(clickedvalue);
if(this.p2array.length==2){
if(this.p2array[0]!=this.p2array[1]){
this.wrong = new Audio();
this.wrong.src=this.thatswrong;
this.wrong.play();
// if both the selection are different
console.log('hiding stuffs');
this.hideAgain(this.toremove);
}
}
if(this.p2array[0]===this.p2array[1]){
// both the selections are same
if(this.validate()){
//if the player has cheated
console.log('not accepted.');
this.gameStart=false;
this.notvalid=true;
this.p2array.pop();
this.toremove.pop();
this.totalclick -= 1;
}else{
//finally accepted
console.log('it is accepted.');
this.rightaudio();
this.remainingBoxes -= 2;
this.p2points += 10;
this.removeitems(this.toremove);
this.hideforever(this.toremove);
}
}
this.gamefinish();
/* changing the turns */
if(this.totalclick==2){
// console.log('total click is 2 now');
this.totalclick=0;
this.p2array = [];
this.p2selection='';
this.p2turn=false;
this.clickedvalue='';
this.p1active=true;
this.p1turn=true;
this.p2active=false;
this.toremove=[];
}
}
}
else{
if(this.selections[index]==' '){
this.gameStart=false;
this.thisisdead=true;
this.totalclick -= 1;
this.right.src='';
this.wrong.src='';
}
else{
// this.totalclick +=1;
this.p2active=false;
this.p1selection=clickedvalue;
/* if(this.totalclick==2){
this.p1selection='';
this.totalclick=0;
} */
this.p1array.push(clickedvalue);
this.toremove.push(index);
if(this.p1array.length==2){
if(this.p1array[0]!=this.p1array[1]){
this.wrong = new Audio();
this.wrong.src=this.thatswrong;
this.wrong.play();
// if both the selection are different
// console.log('hiding stuffs');
this.hideAgain(this.toremove);
}
}
if(this.p1array[0]===this.p1array[1]){
if(this.validate()){
console.log('not accepted');
this.gameStart=false;
this.notvalid= true;
this.p1array.pop();
this.toremove.pop();
this.totalclick -= 1 ;
}else{
console.log('it is accepted.');
this.rightaudio();
this.remainingBoxes -=2;
this.p1points += 10;
this.removeitems(this.toremove);
this.hideforever(this.toremove);
}
}
this.gamefinish();
/* changing the turns */
if(this.totalclick==2){
// console.log('total click is 2 now');
// checking whether both selection are equal or not
// console.log('it never reached here.');
this.totalclick=0;
this.p1array=[];
this.p1selection='';
clickedvalue='';
this.p1turn=false;
this.p2active=true;
this.p2turn=true;
this.p1active=false;
this.toremove=[];
}
}
}
},
validate(){
return this.toremove[0]===this.toremove[1];
},
removeitems(indexes){
// console.log(this.toremove);
Array.from(indexes).sort((a,b)=> b - a);
// console.log(this.indexes);
for(var i = 0; i<indexes.length ; i++){
// console.log(`removing index ${this.toremove[i]}`);
// console.log(this.selections);
// this.selections.splice(this.toremove[i],1);
this.selections[indexes[i]]= '';
// console.log(this.selections);
console.log(`removing${indexes[i]}`);
}
},
showWinner(){
var p1 = this.p1points;
var p2 = this.p2points;
if(p1==p2){
this.gameisdraw=true;
this.gameStart=false;
this.selectbox=false;
this.playonemoretimeaudio();
}else{
this.gameisdraw=false;
this.gameStart=false;
this.selectbox=false;
this.winningScreen= true;
if(p1>p2){
this.winner = this.names[0];
}else{
this.winner= this.names[1];
}
this.startaftergamefinish=true;
this.conversations();
}
},
backToGame(){
this.clickaudio();
this.gameStart=true;
this.notvalid=false;
this.thisisdead=false;
// this.gameisdraw=false;
// this.winningScreen=false;
},
gamefinish(){
if(this.remainingBoxes == 0){
this.showWinner();
}
},
startmusic(){
this.music = new Audio();
this.music.src=this.musicfile;
this.music.volume=0.23;
console.log(this.music);
},
clickaudio(){
var click= new Audio();
click.src=this.clicksoundsrc;
click.play();
},
turnoff(){
this.GOT = !this.GOT;
this.music.pause();
console.log('music is off');
},
turnon(){
this.startmusic();
this.GOT = !this.GOT;
// this.music.play();
this.music.loop=true;
this.music.autoplay=true;
console.log('music is on');
},
conversations(){
console.log('conversation should begin now.');
var i = 0;
setInterval(() => {
if(i<this.sounds.length){
this.conversation= new Audio();
this.conversation.src=this.sounds[i];
this.conversation.autoplay=true;
console.log(this.conversation.src);
console.log(i);
}
i++;
}, 2500);
},
rightaudio(){
// that's right audio
this.right=new Audio();
this.right.src=this.thatsright;
this.right.play();
},
playonemoretimeaudio(){
this.newAudio= new Audio();
this.newAudio.src= this.playonemoretime;
setTimeout(()=>{
this.newAudio.play();
},1200);
},
hideall(){
console.log('hiding all');
setTimeout(()=>{
this.bindingStyle.opacity=0;
this.bindingStyle.background='';
},1500);
// console.log(this.bindingStyle);
},
makeitvisible(index){
/* console.log('making the box visible');
console.log('visible innertext'); */
/* Array.from(boxes).forEach(element=>{
console.log(element);
}); */
this.boxes = document.getElementsByClassName('box');
// console.log(this.boxes);
// Array.from(this.boxes)[index].style="background:black";
this.list = document.getElementsByTagName('li');
// console.log(this.list);
Array.from(this.list)[index].style="opacity:1";
},
hideforever(toremove){
/* console.log(toremove);
console.log(this.list);
console.log(this.boxes); */
Array.from(toremove).forEach(element => {
this.boxes[element].style="background:black";
this.list[element].style="opacity:1";
this.list[element].style="color:white";
});
},
hideAgain(toremove){
// console.log(toremove);
Array.from(toremove).forEach(el=>{
// this.boxes[el].style="background:green";
this.list[el].style="opacity:0";
});
}
},
created(){
setInterval(() => {
this.currentTime();
}, 100);
}
})
|
import {
GET_CINEMAS_BY_ID_REQUEST,
GET_CINEMAS_BY_ID_SUCCESS,
GET_CINEMAS_BY_ID_FAILURE,
} from "../constants/heThongRap";
const initialState = {
selectedCinema: {},
isLoading: false,
error: null,
};
function selectedCinemaReducer(state = initialState, action) {
switch (action.type) {
case GET_CINEMAS_BY_ID_REQUEST: {
return {
selectedCinema: {},
isLoading: true,
error: null,
};
}
case GET_CINEMAS_BY_ID_SUCCESS: {
return {
selectedCinema: action.payload.data,
isLoading: false,
error: null,
};
}
case GET_CINEMAS_BY_ID_FAILURE: {
return {
selectedCinema: {},
isLoading: false,
error: action.payload.error,
};
}
default:
return state;
}
}
export default selectedCinemaReducer;
|
// import Login from './Login';
import Register from './Register';
import Login from './Login';
import Profile from './Profile';
import Verification from './Verification';
import ResetCode from './ResetCode';
import ForgetPassword from './ForgetPassword';
import CreateNewPassword from './CreateNewPassword';
import DashBoard from './DashBoard';
import Navigations from './Navigations';
import Logout from './Logout'
import Faq from './Faq';
import TermsConditions from './TermsConditions';
import SurpportDesk from './SurpportDesk';
import Message from './Message/index.js';
import ChangePhone from './ChangePhone/ChangePhone';
import AllReports from './AllReports/AllReports';
import Citation from './AllReports/AllReports';
import Category from './Category/Category';
import Division from './Division/Division';
import CategoryDetails from './CategoryDetails/CategoryDetails';
import ManageSubscription from './ManageSubscription/ManageSubscription';
import Subscribe from './Subscribe/Subscribe';
import Subscription from './Subscription/Subscription';
import ViewPlan from './ViewPlan/ViewPlan';
import FullReport from './FullReport/FullReport';
import CitedAuthorities from './CitedAuthorities/CitedAuthorities';
import PlainReport from './PlainReport/PlainReport';
import FavoriteList from './FavoriteList/FavoriteList';
import DivisionDetails from './DivisionDetails/DivisionDetails';
import ReadSavedReport from './ReadSavedReport/ReadSavedReport';
export default {
Register,
Login,
Profile,
Verification,
ResetCode,
Faq,
TermsConditions,
SurpportDesk,
Message,
ForgetPassword,
CreateNewPassword,
DashBoard,
Navigations,
Logout,
ChangePhone,
AllReports,
Citation,
Category,
Division,
CategoryDetails,
ManageSubscription,
Subscribe,
Subscription,
ViewPlan,
FullReport,
CitedAuthorities,
PlainReport,
FavoriteList,
DivisionDetails,
ReadSavedReport,
};
|
import {EventEmitter} from 'events';
import dispatcher from '../dispatcher';
class SnippetStore extends EventEmitter {
constructor () {
super();
this.snippets = [];
}
receiveSnippets (snippets) {
this.snippets = snippets;
this.emit('change');
}
getAll () {
return this.snippets;
}
handleActions (action) {
switch (action.type) {
case 'RECEIVE_SNIPPETS':
this.receiveSnippets(action.data);
break;
}
}
}
const snippetStore = new SnippetStore();
dispatcher.register(snippetStore.handleActions.bind(snippetStore));
export default snippetStore;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.