text stringlengths 7 3.69M |
|---|
import React from "react";
import { List, ListItem, Link, Icon, Chip } from 'framework7-react';
import crypto from 'crypto-js';
import { dict } from "../../Dict";
import Moment from 'react-moment';
import JDate from 'jalali-date';
import 'moment-timezone';
import 'moment/locale/fa';
const SimpleList = (props) => {
if (props.statuses) {
function addLink(status) {
if (props.addStatus) {
return (<Link onClick={() => props.addStatus(status.id)}>{dict.select}</Link>)
}
}
return (
<List>
{props.statuses.map((status) =>
<ListItem
title={
<div className="chip" >
<div className="chip-media" style={{ backgroundColor: status.the_color }} >
<i className="icon f7-icons if-not-md">plus_circle</i>
<i className="icon material-icons md-only"></i>
</div>
<div className="chip-label">{status.title}</div>
</div>}
after={addLink(status)}
/>
)}
</List>
)
} else {
return (<ul></ul>)
}
}
export default SimpleList;
|
import React,{Component} from 'react';
import Main from './main.js';
const Home = () =>(
<div className="container">
<div className="wrap">
<div className="wrap__content">
<Main />
</div>
</div>
</div>
);
export default Home;
|
/**
* Module dependencies.
*/
var BasicStrategy = require('./strategies/basic');
var DigestStrategy = require('./strategies/digest');
/**
* Export constructors.
*/
exports.BasicStrategy = BasicStrategy;
exports.DigestStrategy = DigestStrategy;
|
// 引入axios
import axios from '@/utils/myaxios.js'
// 获取所有角色的全部权限
export const getAllRightList = (type) => {
return axios({
url: `rights/${type}`
})
}
// 角色授权
export const grantRight = (roleId, rids) => {
// console.log(roleId, rids)
return axios({
url: `roles/${roleId}/rights`,
method: 'post',
data: { rids }
})
}
// 获取左侧菜单项
export const leftMenuList = () => {
return axios({
url: 'menus'
})
}
|
import { combineReducers } from 'redux';
import * as actions from './actions';
import * as appActions from '../app/actions';
const d = new Date();
const day = d.getDate();
const currday = (day < 10) ? `0${day}` : day;
const month = (d.getMonth() + 1);
const currmonth = (month < 10) ? `0${month}` : month;
const curryear = d.getFullYear();
const currdate = `${curryear}-${currmonth}-${currday}`;
export const reports = (state = [], action) => {
switch (action.type) {
case actions.GET_INIT_REPORTS_REQUEST_SUCCEEDED:
return action.payload;
case actions.GET_REPORT_REQUEST_SUCCEEDED:
return action.payload;
case actions.GET_REPORTS_REQUEST_SUCCEEDED:
return action.payload;
default:
return state;
}
};
export const report = (state = {}, action) => {
switch (action.type) {
default:
return state;
}
};
export const users = (state = [], action) => {
switch (action.type) {
case actions.GET_INIT_USERS_REQUEST_SUCCEEDED:
return action.payload;
case actions.GET_USER_REQUEST_SUCCEEDED:
return action.payload;
case actions.GET_USERS_REQUEST_SUCCEEDED:
return action.payload;
default:
return state;
}
};
export const user = (state = '', action) => {
switch (action.type) {
case actions.USER_CHANGED:
return action.payload;
default:
return state;
}
};
export const newUser = (state = '', action) => {
switch (action.type) {
case appActions.USER_SAVING_SUCCEDED:
return '';
case actions.NEW_USER_CHANGED:
return action.payload;
default:
return state;
}
};
export const dateReported = (state = currdate, action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return currdate;
case actions.DATE_REPORTED_CHANGED:
return action.payload;
default:
return state;
}
};
export const spot = (state = '', action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return '';
case actions.SPOT_CHANGED:
return action.payload;
default:
return state;
}
};
export const windDirection = (state = 0, action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return 0;
case actions.WIND_DIRECTION_CHANGED:
return action.payload;
default:
return state;
}
};
export const windSpeed = (state = 0, action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return 0;
case actions.WIND_SPEED_CHANGED:
return action.payload;
default:
return state;
}
};
export const swellSize = (state = 0, action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return 0;
case actions.SWELL_SIZE_CHANGED:
return action.payload;
default:
return state;
}
};
export const satisfaction = (state = 0, action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return 0;
case actions.SATISFACTION_CHANGED:
return action.payload;
default:
return state;
}
};
export const freeText = (state = '', action) => {
switch (action.type) {
case appActions.REPORT_SAVING_SUCCEDED:
return '';
case actions.FREETEXT_CHANGED:
return action.payload;
default:
return state;
}
};
export default combineReducers({
reports,
report,
users,
user,
newUser,
dateReported,
satisfaction,
spot,
swellSize,
windDirection,
windSpeed,
freeText,
});
|
function initiateStuff(){
document.getElementById("selector").style.top = 9;
}
function clearWindow(windowToClear){
windowToClear.innerHTML = "";
}
function makeObject(objectType, objectId, parentObject){
object = document.createElement(objectType);
parentObject.appendChild(object);
object.id = objectId;
}
function keyPressed(event) {
lineShift = parseInt(document.getElementById("selector").style.top);
//Up Key
if (event.keyCode == 38 || event.keyCode == 87) {
if(lineShift != 9){
lineShift -= 25;
}
}
//Down Key
if (event.keyCode == 40 || event.keyCode == 83) {
if(lineShift != 309){
lineShift += 25;
}
}
//Enter Key
if (event.keyCode == 13) {
}
//Making what is in each window
clearWindow(document.getElementById("previewWindow"));
//superhot.exe
if(lineShift == 9){
makeObject("p", "superhotPreviewText", document.getElementById("previewWindow"));
document.getElementById("superhotPreviewText").className = "text";
document.getElementById("superhotPreviewText").className += " previewText";
document.getElementById("superhotPreviewText").innerHTML = '"Superhot is the most innovative game I' + "'" + 've played in years" - Team Superhot';
}
//readme.txt
if(lineShift == 34){
makeObject("p", "readmePreviewText", document.getElementById("previewWindow"));
document.getElementById("readmePreviewText").className = "text";
document.getElementById("readmePreviewText").className += " previewText";
document.getElementById("readmePreviewText").innerHTML = "JJakk proudly presents piOS, designed by Team Superhot";
}
//quite.exe
if(lineShift == 59){
makeObject("p", "quitePreviewText", document.getElementById("previewWindow"));
document.getElementById("quitePreviewText").className = "text previewText";
document.getElementById("quitePreviewText").innerHTML = "app: quit.exe |--file-> 50";
document.getElementById("quitePreviewText").style.whiteSpace = "pre";
}
//settings
if(lineShift == 109){
makeObject("p", "settingsPreviewText", document.getElementById("previewWindow"));
document.getElementById("settingsPreviewText").className = "text previewText";
document.getElementById("settingsPreviewText").innerHTML = "directory:SETTINGS |>FOLDER<";
document.getElementById("settingsPreviewText").style.whiteSpace = "pre";
}
//apps
if(lineShift == 134){
makeObject("p", "appsPreviewText", document.getElementById("previewWindow"));
document.getElementById("appsPreviewText").className = "text previewText";
document.getElementById("appsPreviewText").innerHTML = "directory:APPS |>FOLDER<";
document.getElementById("appsPreviewText").style.whiteSpace = "pre";
}
//demos
if(lineShift == 159){
makeObject("p", "demosPreviewText", document.getElementById("previewWindow"));
document.getElementById("demosPreviewText").className = "text previewText";
document.getElementById("demosPreviewText").innerHTML = "directory:DEMOS |>FOLDER<";
document.getElementById("demosPreviewText").style.whiteSpace = "pre";
}
//cellular
if(lineShift == 184){
makeObject("p", "cellularPreviewText", document.getElementById("previewWindow"));
document.getElementById("cellularPreviewText").className = "text previewText";
document.getElementById("cellularPreviewText").innerHTML = "directory:CELLULAR |>FOLDER<";
document.getElementById("cellularPreviewText").style.whiteSpace = "pre";
}
//wires
if(lineShift == 209){
makeObject("p", "wiresPreviewText", document.getElementById("previewWindow"));
document.getElementById("wiresPreviewText").className = "text previewText";
document.getElementById("wiresPreviewText").innerHTML = "directory:WIRES |>FOLDER<";
document.getElementById("wiresPreviewText").style.whiteSpace = "pre";
}
//games
if(lineShift == 234){
makeObject("p", "gamesPreviewText", document.getElementById("previewWindow"));
document.getElementById("gamesPreviewText").className = "text previewText";
document.getElementById("gamesPreviewText").innerHTML = "directory:GAMES |>FOLDER<";
document.getElementById("gamesPreviewText").style.whiteSpace = "pre";
}
//vr
if(lineShift == 259){
makeObject("p", "vrPreviewText", document.getElementById("previewWindow"));
document.getElementById("vrPreviewText").className = "text previewText";
document.getElementById("vrPreviewText").innerHTML = "directory:VR |>FOLDER<";
document.getElementById("vrPreviewText").style.whiteSpace = "pre";
}
//art
if(lineShift == 284){
makeObject("p", "artPreviewText", document.getElementById("previewWindow"));
document.getElementById("artPreviewText").className = "text previewText";
document.getElementById("artPreviewText").innerHTML = "directory:ART |>FOLDER<";
document.getElementById("artPreviewText").style.whiteSpace = "pre";
}
//videos
if(lineShift == 309){
makeObject("p", "videosPreviewText", document.getElementById("previewWindow"));
document.getElementById("videosPreviewText").className = "text previewText";
document.getElementById("videosPreviewText").innerHTML = "directory:VIDEOS |>FOLDER<";
document.getElementById("videosPreviewText").style.whiteSpace = "pre";
}
document.getElementById("selector").style.top = lineShift;
}
|
import Command from "../../processing/commands/Command";
import { name, description, group, guildOnly, format } from "../../processing/commands/decorators";
import { ls, ll } from "../../utils/LocalizedString";
import i18next from "i18next";
import Guild from "../../models/Guild";
import { defaults } from "../../../config";
@name("guild")
@group("locale")
@description(ls`commands:locale.guild.description`)
@format(ls`commands:locale.guild.format`)
@guildOnly
export default class GuildLocaleCommand extends Command {
hasPermissions(member) {
return member.hasPermission("MANAGE_GUILD")
|| ll`messages:errors.missingPermissions`();
}
async run(message, [value]) {
const [guild] = await Guild.findOrBuild({
where: { id: message.guild.id },
defaults: { id: message.guild.id, locale: defaults.locale }
});
if (!value) {
return ll`commands:locale.guild.messages.get`({ locale: guild.locale });
}
if (value == guild.locale) {
return ll`commands:locale.guild.messages.sameLocale`();
}
if (!i18next.languages.includes(value)) {
return ll`commands:locale.guild.messages.invalidLocale`({ locale: value });
}
const oldLocale = guild.locale;
guild.locale = value;
await guild.save();
return ll`commands:locale.guild.messages.set`({ from: oldLocale, to: value });
}
} |
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const compression = require("compression");
const books = require("./routes/books/books");
const server = express();
//accept only JSON
server.use(bodyParser.json());
server.use(cors());
server.use(compression());
// healthcheck API
server.get("/api/ping", (req, res) => res.send("pong"));
server.use("/api", books);
//set port and log to the console
server.listen(3000, () => console.log("server listening"));
|
'use strict'
// Logs current date
let displayDate = function() {
let currentDate = new Date();
console.log('The current date is: ' + currentDate);
console.log('The date is a type of: ' + typeof(currentDate));
}
displayDate();
// Convert number to string
let convertNumber = function(x) {
let newString = x.toString();
console.log('The string is: ' + newString);
console.log('The string is a type of: ' + typeof(newString));
}
convertNumber(15);
// Convert string to number
let convertString = function(x) {
let newNumber = parseInt(x);
console.log('The number is: ' + newNumber);
console.log('The string is a type of: ' + typeof(newNumber));
}
convertString('6');
// Display datatype of variable
let dataTypes = function(y) {
let newType = typeof(y);
console.log('This is type of: ' + newType);
}
dataTypes('true');
// Adding two integers
let calculator = function(a, b){
let sum = a + b;
console.log('This sum of the two numbers is: ' + sum);
console.log('The sum is type of: ' + typeof(sum));
}
calculator(2, 6);
// Run if both things are true
let twoTruths = function(c,d){
if ( c > 0 && d > 0 ) {
console.log('Both expressions are true');
} else {
console.log('One expression is false');
}
}
twoTruths(3, 6);
// Run if one of two things are true
let oneTruth = function(e,f){
if ( e > 0 || f > 0 ) {
console.log('One expression is true');
} else {
console.log('Neither expression is true');
}
}
oneTruth(-3, 6);
// Run if both things are false
let twoFalse = function(g,h){
if ( g < 0 && h < 0 ) {
console.log('One expression is true');
} else if ( g < 0 || h < 0 ) {
console.log('One expression is true');
} else {
console.log('Both expressions are False');
}
}
twoFalse(3, 6);
|
import PropTypes from 'prop-types';
export default Object.freeze({
telemetry: {
battery: PropTypes.string,
lastActivity: PropTypes.string
}
});
|
import React from "react";
import PropTypes from "prop-types";
import { StyleSheet } from "react-native";
import { connect } from "react-redux";
import { Content, Text, View } from "native-base";
import InfoBar from "../components/InfoBar";
import SimpleHighchart from "../components/SimpleHighchart";
import NoDataWarning from "../components/NoDataWarning";
import WaitForLoading from "../components/WaitForLoading";
const styles = StyleSheet.create({
content: {
flex: 1,
},
textView: {
flex: 1,
backgroundColor: "#fff",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
},
text: {
color: "#666666",
alignItems: "center",
justifyContent: "center",
textAlign: "center",
},
});
class _GraphScreen extends React.Component {
componentDidMount() {
if (!this.props.isMeasuresLoaded) this.props.loadMeasures();
}
render() {
let probes;
if (this.props.isMeasuresLoaded) {
probes = this.props.probes.filter(
probe => probe.site.id === this.props.site.id && probe.isActive,
);
}
return (
<React.Fragment>
<InfoBar
lastReloadTime={this.props.lastReloadTime}
load={this.props.loadMeasures}
/>
{this.props.isLoading ? (
<WaitForLoading />
) : !this.props.isConnexionSucess ||
probes === undefined ||
!this.props.isMeasuresLoaded ? (
<NoDataWarning />
) : probes && probes.length === 0 ? (
<View style={styles.textView}>
<Text style={styles.text}>
{
"Veulliez sélectionner une ou plusieurs séries à afficher dans l'onglet liste"
}
</Text>
</View>
) : (
<Content>
{probes.map((probe, index) => {
const measures = this.props.measures
.filter(measure => measure.probe.id === probe.id)
.map(item => [Date.parse(item.dateTime), item.value]);
return (
<SimpleHighchart
key={index}
data={measures}
title={probe.name}
/>
);
})}
</Content>
)}
</React.Fragment>
);
}
}
_GraphScreen.propTypes = {
measures: PropTypes.any.isRequired,
probes: PropTypes.any.isRequired,
site: PropTypes.any.isRequired,
lastReloadTime: PropTypes.string.isRequired,
isMeasuresLoaded: PropTypes.bool.isRequired,
isConnexionSucess: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired,
loadMeasures: PropTypes.func,
};
const mapState = ({ probesModel, sitesModel, measuresModel, rootModel }) => ({
site: sitesModel.selectedSite,
measures: measuresModel.measures,
probes: probesModel.probes,
isMeasuresLoaded: measuresModel.isMeasuresLoaded,
isLoading: rootModel.isLoading,
lastReloadTime: measuresModel.lastReloadTime,
isConnexionSucess: rootModel.isConnexionSucess,
});
const mapDispatch = ({ measuresModel }) => ({
loadMeasures: measuresModel.loadMeasures,
});
const GraphScreen = connect(
mapState,
mapDispatch,
)(_GraphScreen);
export default GraphScreen;
|
$(function(){
var standardType='全部',nature='全部',standardStatus=3
$(".search_box>img").click(function(){
console.log(111)
});
// 点击筛选条件
(function(){
let li =$(".standard_content>ul>li")
for(var i=1;i<li.length;i+=2){
li.eq(i).css("background-color", "#eee");
}
var standardItem1=false,standardItem2=false,standardItem3=false;
$('.classfiy>ul>li').click(function(e){
e.stopPropagation();
let getClass = $(this).attr('class');
if(getClass == 'active'){
$(this).removeClass('active')
$(this).children('i').removeClass('active_bottom')
$(this).children('div').css('display',"none")
}else if(!getClass){
//增加样式前先删除掉其它li标签的样式
$(this).siblings('li').removeClass('active')
$(this).siblings('li').children('i').removeClass('active_bottom')
$(this).siblings('li').children('div').css('display',"none")
$(this).addClass('active')
$(this).children('i').addClass('active_bottom')
$(this).children('div').css('display',"block")
}
let standardItem=$(this).children().first().html();
if(standardItem=='类型'){
standardItem1=true
}
if(standardItem=='状态'){
standardItem2=true
}
if(standardItem=='性质'){
standardItem3=true
}
});
//点击筛选条件
$(".select_content>ul>li").click(function(e){
e.stopPropagation();
let getClass = $(this).attr('class');
if(getClass == 'active'){
$(this).removeClass('active')
}else if(!getClass){
//增加样式前先删除掉其它li标签的样式
$(this).siblings('li').removeClass('active')
$(this).siblings('li').children('div').css('display',"none")
$(this).addClass('active')
$(this).children('div').css('display',"block")
}
getStandard()
});
var standardType='全部',standardStatus='全部',nature='全部';
$(".select_content1>ul>li").click(function(e){
$(".select_content1").css("display","none")
if(standardItem1==true){
standardType=$(this).children().first().html()
}
getStandard()
})
$(".select_content2>ul>li").click(function(e){
$(".select_content2").css("display","none")
if(standardItem2==true){
standardStatus=$(this).children().first().html()
if(standardStatus=='即将实施'){
standardStatus=0
}else if(standardStatus=='现行'){
standardStatus=1
}else if(standardStatus=='废止'){
standardStatus=2
}else if(standardStatus=='全部'){
standardStatus=3
}
}
getStandard()
})
$(".select_content3>ul>li").click(function(e){
$(".select_content3").css("display","none")
if(standardItem3==true){
nature=$(this).children().first().html()
}
})
function getStandard(){
if(location.search.indexOf("&")!=-1){
var icsCode=location.search.split("&")[0].split('=')[1];
}
var data={"moudle":"4003","icsCode":icsCode,"typeName":"标准信息","standardType":standardType,"nature":nature,"standardStatus":standardStatus}
data.standardType=="全部"?delete data.standardType:data
data.nature=="全部"?delete data.nature:data
data.standardStatus=="全部"?delete data.standardStatus:data
$.ajax({
url : "/BZCX/standard/searchSecond",
type : "post",
async : true,
data:data,
success : function(res) {
let content=res.data
var item=$(".standard_content>ul").empty();
if(res.data.length>0){
let content_item=''
for(let i=0;i<content.length;i++){
content_item+=` <li onclick="jump1('${da[i].standardNo}')">
<span>${content[i].standardNo}</span>
<span>${content[i].standardCnName}</span>
</li>`
}
item.append(content_item)
//内容隔行变色
let content_li=$(".standard_content>ul>li")
for(let i=0;i<content_li.length;i++){
if(i % 2 == 0){
content_li[i].style.background="#fff"
}else{
content_li[i].style.background="#f5f5f5"
}
}
}else{
let null_content="<img style='width:3rem;height:3.5rem;margin-top:3rem' src='./img/pic_weikong.png'>"
item.append(null_content)
}
}
})
}
$(".search_box>img").click(function(){
simple_search($(".search_box>input").val())
})
$(".search_box").keydown(function(e){
if(event.keyCode == 13) {
simple_search($(".search_box>input").val())
}
})
//搜索
function simple_search(input) {
var data = {
"moudle" : "4001",
"typeName" :"标准信息",
"paramNo":input,
"paramCnName" :input,
}
$.ajax({
url : "/BZCX/standard/searchSecond",
type : "post",
data : data,
async : true,
success : function(res) {
let content=res.data
var item=$(".standard_content>ul").empty();
if(res.data.length>0){
let content_item=''
for(let i=0;i<content.length;i++){
content_item+=` <li onclick="jump1('${da[i].standardNo}')">
<span>${content[i].standardNo}</span>
<span>${content[i].standardCnName}</span>
</li>`
}
item.append(content_item)
//内容隔行变色
let content_li=$(".standard_content>ul>li")
for(let i=0;i<content_li.length;i++){
if(i % 2 == 0){
content_li[i].style.background="#fff"
}else{
content_li[i].style.background="#f5f5f5"
}
}
}else{
let null_content="<img style='width:3rem;height:3.5rem;margin-top:3rem' src='./img/pic_weikong.png'>"
item.append(null_content)
}
}
});
}
getStandard()
jump1=function (noTrim){
$.ajax({
url : "/BZCX/standard/getStdFileId",
type : "post",
data : {typeName:"标准信息",noTrim:noTrim},
async : true,
success : function(res) {
window.location.href = `details.html?id=${res.data.stdFileId}&page=1`
}
})
}
})()
})
|
$("table tbody").delegate(".del","click",function(){
var number = $(this).attr("data_num");
var cont={"number":number}
$.ajax({ //删除
method:"post",
url:"/remove",
data:cont
}).done(function(data){
show(data)
})
});
$("table tbody").delegate(".alter","click",function(){
$("#myModal").modal();
var number = $(this).attr("data_n");
// console.log(number)
$("#fixnum").val(number).attr("readOnly","readOnly")
});
$("#bt").click(function () {
$("#myModal").modal("show");
$("#fixnum").val("").removeAttr("readonly");
})
$(".myform").submit(function(){ //form的class属性
var data = $(this).serialize();
$.ajax({
method:"post",
url:"/insert", //插入数据
data:data
}).done(function(data){
show(data);
});
return false;
});
ajax();
function ajax(){
$.ajax({
method:"get",
url:"/student"
}).done(function(data){
console.log(data);
show(data);
})
}
function show(elem){
$("table tbody tr").empty();
for( var i in elem){
var $tr=$("<tr>");
for(var j in elem[i]){
if(j!="_id"){
var text=elem[i][j];
var $td=$("<td>");
$td.text(text);
$tr.append($td)
}
}
$tr.append("<td><button class='del' data_num='"+ elem[i].number +"'>删除</button></td>")
$tr.append("<td><button class='alter' data_n='"+ elem[i].number +"'>修改</button></td>")
$("table tbody").append($tr)
}
}
$(".btn2").click(function () {
$.ajax({
method:"post",
url:"/screen" //排序
}).done(function(data){
show(data)
})
});
$(".btn3").click(function () {
$.ajax({
method:"post",
url:"/screen1" //排序
}).done(function(data){
show(data)
})
});
$(".btn4").click(function () {
$.ajax({
method:"post", //分数
url:"/sort"
}).done(function(data){
show(data)
})
});
|
import {observable, action} from 'mobx';
import React from 'react';
import { toJS } from 'mobx';
import axios from "axios";
//import appUrl from "../config/appUrl";
import {ViewStore} from "../config/Root"
import URLSearchParams from "url-search-params"
var cookies = require('js-cookie');
let appUrl = "https://everyone-can-vote.herokuapp.com"
//let appUrl = "https://fcc-vote-simonbryatov.c9users.io"
class ApiStore {
constructor() {
this.fetchPollsList();
this.prepareToken()
if (this.userToken.get()) {
console.log("logged in")
this.isLoggedIn.set(true)
this.userName.set(cookies.get("userName"))
}
console.log("Api store is ready")
}
@observable userPolls = null;
currentPoll_Id = null;
isLoggedIn = observable(false)
fetching = observable(false)
userToken = observable(null)
userName = observable(null)
voted = observable(false);
lastVote = observable(null);
newOption = observable("")
pollName = observable("")
pollOptions = observable("")
@action.bound renderOnLoginStatus(guestOpt, userOpt)
{
return this.isLoggedIn.get() ? userOpt : guestOpt;
}
@action.bound logOut() {
console.log("Logging out")
this.userToken.set(null);
this.userName.set(null);
this.isLoggedIn.set(false);
cookies.remove('userToken');
cookies.remove('userName');
}
@action.bound getUserPolls() {
this.fetching.set(true);
axios
.get(appUrl + `/api/userPolls`)
.then(res => {
{
console.log(res.data)
this.userPolls = res.data;
this.fetching.set(false)
}
})
.catch((err) => {console.log(err.response.data)})
}
@action.bound prepareToken() {
var urlParams = new URLSearchParams(window.location.search);
var token = urlParams.get("token");
console.log(token, "curr params")
if (token) {
console.log("Got the token " + token)
cookies.set('userToken', token, {secure: true, expires: 14});
cookies.set('userName', urlParams.get("userName"))
}
token = cookies.get("userToken");
console.log("checked the cookies", token)
if (token) {
this.userToken.set(token);
this.userName.set(cookies.get("userName"))
console.log("curr token", this.userToken.get())
}
}
@action.bound fetchPollsList = (lastVote) => {
this.fetching.set(true)
axios.get(appUrl + "/api/pollsList")
.then(res => {
console.log("I've got the power of Polls... Again!", res.data)
ViewStore.setProperty("pollsList", res.data)
this.fetching.set(false);
if (lastVote >= 0) {
this.lastVote.set(lastVote)
}
if (this.currentPoll_Id) {
ViewStore.setPollView(this.currentPoll_Id);
}
})
}
@action.bound createNewPoll() {
console.log("New Poll is " + this.pollName + " " + this.pollOptions + "!")
var opts = this.pollOptions.get().split(`\n`);
let newPoll = {name: this.pollName.get(), options: opts};
console.log(JSON.stringify(newPoll));
axios
.post(appUrl + `/api/createNewPoll?data=${JSON.stringify(newPoll)}`, {firstName: 123})
.then(res => {
{
console.log(res.data)
this.pollName.set("");
this.pollOptions.set("");
this.fetchPollsList();
}
})
.catch((err) => {alert(err.response.data)})
}
reset() {
console.log("reset")
this.newOption.set("");
this.pollName.set("");
this.pollOptions.set("");
this.userPolls = null;
ViewStore.chosenOptionIndex.set(null);
}
@action.bound deletePoll(id) {
console.log("Deleting poll " + id)
let pollsList = ViewStore.getProperty("pollsList");
let poll = pollsList.find((poll) => {if (poll["_id"] == id) return true})
if (confirm('Do you really want to delete poll "'+ poll.name +'"?' + `\nThis action is permanent.`)) {
axios
.get(appUrl + `/api/deletePoll`, {params: {pollId: id}})
.then(res => {
console.log(res.data, this)
this.fetchPollsList();
this.getUserPolls();
})
}
}
@action.bound vote() {
if (this.newOption.get() == "") {
console.log(ViewStore.chosenOptionIndex.get(), "wow")
console.log("Last voted for ", this.lastVote.get())
let vote_id = ViewStore.currentPoll.options[ViewStore.chosenOptionIndex]["_id"];
console.log(vote_id, "voting");
console.log("Voting for" + this.pollName + " " + this.pollOptions + "!")
axios.get(appUrl + `/api/vote`, {params: {optId: vote_id, pollId: ViewStore.currentPoll["_id"]}})
.then(res => {
console.log("Last voted for ", this.lastVote.get())
this.fetchPollsList(ViewStore.chosenOptionIndex.get());
console.log(res.data, 5555534)
}).catch((err) => {alert(err.response.data)})
} else axios.get(appUrl + `/api/vote`, {params: {optName: this.newOption.get(), pollId: ViewStore.currentPoll["_id"]}})
.then(res => {
this.fetchPollsList(ViewStore.chosenOptionIndex.get());
}).catch((err) => {alert(err.response.data)})
}
}
export default ApiStore; |
import React from 'react';
import PropTypes from 'prop-types';
import AlertDescriptions from 'pages/home/information/Alerts';
import CompensationDescriptions from 'pages/home/information/Compensations';
import IndicatorDescriptions from 'pages/home/information/Indicators';
import PortfolioDescriptions from 'pages/home/information/Portfolio';
import SearchDescriptions from 'pages/home/information/Searches';
import CbmdDescriptions from 'pages/home/information/Cbmd';
class Information extends React.Component {
constructor(props) {
super(props);
this.state = {
activeItem: 'queEs',
};
this.contentInfo = {
search: SearchDescriptions,
indicator: IndicatorDescriptions,
portfolio: PortfolioDescriptions,
compensation: CompensationDescriptions,
alert: AlertDescriptions,
cbmdashboard: CbmdDescriptions,
};
}
static getDerivedStateFromProps(nextProps) {
return { activeModule: nextProps.activeModule };
}
render() {
const { activeModule } = this.props;
const { activeItem } = this.state;
const { title, description } = this.contentInfo[activeModule]
? this.contentInfo[activeModule][activeItem] : { title: '', description: '' };
return (
<div className="menuline">
<menu>
<button
type="button"
className={`btnhome btn1 ${(activeItem === 'queEs') ? 'active' : ''}`}
onClick={() => this.setState({ activeItem: 'queEs' })}
>
<b>
01
</b>
{' ¿Qué es?'}
</button>
<button
type="button"
className={`btnhome btn2 ${(activeItem === 'porque') ? 'active' : ''}`}
onClick={() => this.setState({ activeItem: 'porque' })}
>
<b>
02
</b>
{' ¿Por qué?'}
</button>
<button
type="button"
className={`btnhome btn3 ${(activeItem === 'quienProduce') ? 'active' : ''}`}
onClick={() => this.setState({ activeItem: 'quienProduce' })}
>
<b>
03
</b>
{' ¿Quién produce?'}
</button>
<button
type="button"
className={`btnhome btn4 ${(activeItem === 'queEncuentras') ? 'active' : ''}`}
onClick={() => this.setState({ activeItem: 'queEncuentras' })}
>
<b>
04
</b>
{' ¿Qué encuentras?'}
</button>
</menu>
<div className={`${activeModule}`}>
<div className={`content ${activeItem}`}>
<h1>
{title}
</h1>
{description}
</div>
</div>
</div>
);
}
}
Information.propTypes = {
activeModule: PropTypes.string,
};
Information.defaultProps = {
activeModule: '',
};
export default Information;
|
/*
* The MIT License (MIT)
* Copyright (c) 2019. Wise Wild Web
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author : Nathanael Braun
* @contact : n8tz.js@gmail.com
*/
import shortid from "shortid";
export const WIDGET_CHANGED = 'WIDGET_CHANGED';
export const WIDGET_NEW = 'WIDGET_NEW';
export const WIDGET_RM = 'WIDGET_RM';
export const SELECTED_WIDGET_CHANGED = 'SELECTED_WIDGET_CHANGED';
export * from './(*)/actions.js';
export function selectWidget( wid ) {
return {
type: SELECTED_WIDGET_CHANGED,
wid
}
}
export function newWidget( record ) {
return {
type : WIDGET_NEW,
record: {
_id : shortid.generate(),
size : { width: 350, height: 400 },
position: {
x: 100 + ~~(Math.random() * 600),
y: 100 + ~~(Math.random() * 600)
},
...record
}
}
}
export function updateWidget( record ) {
return {
type: WIDGET_CHANGED,
record
}
}
export function rmWidget( wid ) {
return {
type: WIDGET_RM,
wid
}
}
|
/* eslint-disable class-methods-use-this */
import React, { Component } from 'react';
import '../styles/DataGenerator.scss';
// create a form
// takes inputs to generate topics, producers, consumers, etc.
class DataGenerator extends Component {
constructor(props) {
super(props);
this.state = {
command: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
// updates the state of command string based on form input
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
// should send ksql command string to server to be run in terminal
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit} id="ksql-form">
<h2>KSQL CLI</h2>
<label>Enter KSQL:</label>
<input
type="text"
id="command"
name="command"
value={this.state.command}
onChange={this.handleChange}
/>
<button id="submit-command" name="submit" type="submit">
Run Query
</button>
<button id="end-command" name="submit" type="submit">
End Query
</button>
</form>
);
}
}
export default DataGenerator;
|
import React from 'react';
import Item from './item.js';
const listItems = props => {
const all = props.data.map((item, key) => {
if ((item.type === props.type || props.type === "all") && (item.namePl.toLowerCase().indexOf(props.text.toLowerCase()) === 0))
return <Item key={key} namePl={item.namePl} nameEng={item.nameEng} type={item.type} path={item.path} id={item.id} click={props.click}></Item>
else
return null
})
return (
<div id="list">
{all}
</div>);
}
export default listItems;
|
// Write a program that takes as input two numbers and a string denoting the operation (“+”, “-”, “*”, “/”) and prints out the appropriate result. Watch out for division by zero!
var x = 5;
var y = 2;
var operation = "+";
switch (operation) {
case "+":
console.log(x + y);
break;
case "-":
console.log(x - y);
break;
case "*":
console.log(x * y);
break;
case "/":
if (y !== 0) {
console.log(x / y);
} else {
console.log(" Can not be divided by 0");
}
break;
default:
break;
} |
// @flow
export { default as parseTile } from './parseTile'
export { default as serialize } from './serialize'
export { default as VectorTile } from './vectorTile'
export { default as VectorTileFeature } from './vectorTileFeature'
export { default as VectorTileLayer } from './vectorTileLayer'
|
import './theme/base.scss';
|
"use strict";
const Content = require('../../models/Content');
/**
* ContentCService
* @type {Xpresser.Controller.Services|*}
*/
const ContentCService = {};
ContentCService.namespace = "content";
ContentCService.add = async (opt, {http, boot: {user}, error}) => {
const user_id = user.id;
const isApi = opt === 'api';
let exists = true;
let text = http.body('content', undefined);
if (!text || (text && !text.trim().length)) {
const message = `Content is empty.`;
const type = 'empty_content';
if (isApi) {
return error({type, message}, 422);
} else {
return error(message);
}
}
text = text.trim();
const isUrl = $$.validURL(text);
const type = isUrl ? 'url' : 'text';
let content = await Content.query().where({user_id, content: text}).first();
if (!content) {
content = await Content.query().insert({
code: $.helpers.randomStr(20),
type,
user_id,
content: text,
});
exists = false;
}
content.$pick(Content.jsPick);
const data = {content, exists};
return isApi ? $$.toApi(http, data) : http.toApi(data);
};
module.exports = ContentCService;
|
import React, { Component } from 'react';
class Item extends Component {
render() {
// 上傳到下用props
// this.props 屬性
//this.props.children 用在jsx裡面
return <li>{this.props.text}{this.props.children} {this.props.price+1}</li>
}
}
export default Item; |
//Utils
const mongoHandler = require('../utils/mongo-handler');
//Init DB
import {initPermissions,initAdminRole,initRootUser} from "../../src/services/InitService";
//Service to Test
import {
apiKey,
auth
} from "../../src/services/AuthService";
import {findUserByUsername} from "../../src/services/UserService";
//Service dependencies
import {findRoleByName} from "../../src/services/RoleService";
describe("UserService", () => {
let connection;
beforeAll(async () => {
await mongoHandler.connect()
await initPermissions()
await initAdminRole()
await initRootUser()
});
afterAll(async () => {
await mongoHandler.clearDatabase();
await mongoHandler.closeDatabase();
})
test('LoginOk', async () => {
let user = {username: 'root', password: 'root.123'}
await expect(auth(user, null))
.resolves.toHaveProperty('token')
}, 2000);
test('LoginFail', async () => {
let user = {username: 'root', password: 'badpassword'}
await expect(auth(user, null))
.rejects.toMatch('BadCredentials');
}, 2000);
test('LoginUserDoesntExist', async () => {
let user = {username: 'iamlegend', password: '321'}
await expect(auth(user, null))
.rejects.toMatch('UserDoesntExist');
}, 2000);
test('Apikey', async () => {
let user = await findUserByUsername('root')
let result = await apiKey(user.id, null)
await expect(result).toHaveProperty('token',)
}, 2000);
})
|
import api from 'helpers/api';
import { normalize } from 'normalizr';
import { sessionSchema } from './schemas';
import { ENTITIES_FETCH_START, ENTITIES_FETCH_COMPLETE, ENTITIES_FETCH_ERROR } from './types';
const createAction = (name, method, entitySchema) => (...args) => dispatch => {
dispatch({
type: ENTITIES_FETCH_START,
meta: {
name,
},
});
return method
.bind(api)(...args)
.then(response => {
const entities = response ? normalize(response, entitySchema) : {};
dispatch({
type: ENTITIES_FETCH_COMPLETE,
payload: {
...entities,
},
});
return Promise.resolve(response);
})
.catch(error => {
dispatch({
type: ENTITIES_FETCH_ERROR,
payload: {
error,
},
});
return Promise.reject(error);
});
};
// eslint-disable-next-line import/prefer-default-export
export const listSessions = createAction('LIST_SESSIONS', api.listSessions, [sessionSchema]);
export const createSession = createAction('CREATE_SESSION', api.createSession, sessionSchema);
|
const express = require("express");
const authController = require("../controllers/authController");
const isNoUserRegistred = require("../middleware/isNoUserRegistred");
const schemaValidation = require("../middleware/schemaValidation");
const {
registerSchema,
forgotPasswordSchema,
updatePasswordSchema,
refreshTokenSchema,
loginSchema,
} = require("../validations/authSchemas");
const router = express.Router();
router.post(
"/register",
schemaValidation(registerSchema),
isNoUserRegistred,
authController.register.bind(authController)
);
router.post(
"/login",
schemaValidation(loginSchema),
authController.login.bind(authController)
);
router.post(
"/forgot_password",
schemaValidation(forgotPasswordSchema),
authController.forgotPass.bind(authController)
);
router.post(
"/update_password",
schemaValidation(updatePasswordSchema),
authController.updatePassword.bind(authController)
);
router.post(
"/refresh_token",
schemaValidation(refreshTokenSchema),
authController.refreshToken.bind(authController)
);
module.exports = router;
|
import { precacheAndRoute } from "workbox-precaching";
console.log("⚙️ Hello from Service Worker");
workbox.routing.registerRoute(
// add the URL to be cached in as a regular expression, like:
/https:\/\/jsonplaceholder\.typicode\.com/,
new workbox.strategies.NetworkFirst()
);
// uncomment only when service worker should activate a.s.a.p.
// workbox.skipWaiting();
addEventListener("message", event => {
if (event.data && event.data.type === "SKIP_WAITING") {
skipWaiting();
}
});
precacheAndRoute(self.__WB_MANIFEST) |
/**
* Create a Restify reference
*/
var Server = require('./lib/server')
, startServer = Server.start
, debug = require('debug')('app')
, router = require('./lib/router')
, routes = require('./lib/routes')
, models = require('./lib/models')
, middleware = require('./lib/middleware')
, Database = require('./lib/database')
, App = require('./lib/app')
;
/**
* Create a server instance.
*/
var server = new Server({
//certificate: fs.readFileSync('/code/calicom/voiceof/etc/certs/voiceof.crt'),
//key: fs.readFileSync('/code/calicom/voiceof/etc/certs/voiceof.key'),
name: 'VoiceOf',
});
var database = new Database(process.env.MONGOLAB_URI);
/**
* Install routes on app.
*/
Promise.all([
database
.connect()
, //router( server )
App.create(server, database, models(database))
.then( middleware.install )
.then( routes.install )
.then( app => startServer(process.env.PORT || 3030)(app.server) ) // start Server
.catch( err => debug('Error starting the server', err) )
]).then(app => debug('App started'))
.catch( err => debug('Error starting app', err) ) |
import styled from 'styled-components'
const TitleWrapper = styled.div`
color: ${({ theme }) => theme.colors.title.hoverText};
box-shadow: 3px 4px 2px ${({ theme }) => theme.colors.title.boxShadow};
border: 2px solid;
padding: 5px 10px;
border-radius: 5px;
margin: 15px 0px;
transition: .3s all;
cursor: pointer;
span {
padding-left: 10px;
}
&:hover {
color: ${({ theme }) => theme.colors.title.text};
box-shadow: 1px 1px 1px ${({ theme }) => theme.colors.title.boxShadow};
text-shadow: 0px 1px ${({ theme }) => theme.colors.title.hoveTextShadow};
transition: .3s all;
}
@media (min-width: 768px) {
margin: 30px 0px;
}
`;
export { TitleWrapper }
|
/**
* Created by Leandro on 08/10/2015.
*/
window.onload = function(){
function mostrarVentana(){
var div = document.getElementById("popUP");
div.style.display = "block";
}
setTimeout(mostrarVentana,3000);
}; |
const express = require("express")
const router = express.Router()
const Venue = require('../db/models/Venue')
router.get('/', (req, res) => {
Venue.find({})
.then(place => {
res.json(place)
})
})
router.get('/:name', (req, res) => {
let courseName = req.params.name
Venue.findOne({ name: courseName }).then(doc => {
res.json(doc)
})
})
router.post('/', (req, res) => {
Venue.create(req.body)
.then(place => {
res.json(place)
})
})
router.put('/:id', (req, res) => {
Venue.findOneAndUpdate({_id: req.params.id}, req.body)
.then(updated => {
res.json(updated)
})
})
router.delete('/:name', (req, res) => {
Venue.deleteOne({name: req.params.name})
.then(deleted => {
res.json(deleted)
})
})
module.exports = router |
const appSecrets = {
facebook: {
appId: process.env.FACEBOOK_APP_ID,
appSecret: process.env.FACEBOOK_APP_SECRET
},
twitter: {
appId: process.env.TWITTER_APP_ID,
appSecret: process.env.TWITTER_APP_SECRET
},
yelp: {
appId: process.env.YELP_APP_ID,
appSecret: process.env.YELP_APP_SECRET
}
}
if (process.env.NODE_ENV !== 'production') {
appSecrets.facebook.callbackURL = 'http://127.0.0.1:3000/auth/facebook/callback'
appSecrets.twitter.callbackURL = 'http://127.0.0.1:3000/auth/twitter/callback'
} else {
appSecrets.facebook.callbackURL = 'https://wo-fcc.herokuapp.com/auth/facebook/callback'
appSecrets.twitter.callbackURL = 'https://wo-fcc.herokuapp.com/auth/twitter/callback'
}
module.exports = appSecrets
|
// Import modules
var express = require('express');
var fs = require('fs');
var os = require('os');
// Create global object for monitor.js and load configuration
global.monitor = {};
monitor.config = {};
monitor.config.host = os.hostname();
monitor.config.login = 'admin:admin';
monitor.config.port = process.ARGV[2] || 7000;
monitor.config.auth_method = "basic";
monitor.config.time_to_reauthenticate = 500;
// Load monitor.js modules
monitor.app = express.createServer();
monitor.utils = require('./modules/utils.js');
monitor.auth = require('./modules/auth.js');
var plugins = {};
fs.readdir(__dirname + '/plugins', function(error, files) {
// Load plugins (plugins CANNOT be aware of one another)
monitor.config.plugins = [];
if (files === undefined || error) {
if (error) {
console.error(error.message);
}
throw "Could not load plugins.";
}
for(var plugin_iterator = 0; plugin_iterator < files.length; plugin_iterator++) {
// Determine module name from filename
filename = files[plugin_iterator];
plugin_name = filename.replace('.js', '');
// Import plugin module
plugins[plugin_name] = require(__dirname + "/plugins/" + filename);
monitor.config.plugins.push(plugin_name);
// Load route for plugin
monitor.app.get('/' + plugin_name,
monitor.auth[monitor.config.auth_method],
plugins[plugin_name].get);
}
});
// Load frontend
monitor.app.get("/", monitor.auth[monitor.config.auth_method], function(request, response) {
response.sendfile(__dirname +"/frontend/index.html");
});
monitor.app.use(express['static'](__dirname + '/frontend'));
// Start server
monitor.utils.log("Web service listening on port " + monitor.config.port);
monitor.app.listen(monitor.config.port); |
import React, { Component } from "react";
class ContactMe extends Component {
render() {
return (
<div>
<h1>My Contact Deatails</h1>
<p>9421160486</p>
<p>abc@gmail.com</p>
<hr />
<form
action="mailto:daghalerahul0@gmail.com"
method="post"
encType="text/plain"
>
<label>Your Name</label>
<input type="text" name="yourName" id="" />
<br />
<label>Your Email</label>
<input type="email" name="yourEmail" id="" />
<br />
<label> Your Message</label>
<br />
<textarea name="yourMessage" id="" cols="30" rows="10" />
<br />
<input type="submit" name="" value="Submit" />
</form>
</div>
);
}
}
export default ContactMe;
|
export { asyncBlockerReducer } from './async-blocker-reducer';
export { asyncBlocker } from './async-blocker-utils';
export { AsyncBlocker } from './async-blocker';
export { ASYNC_BLOCKER_STORE_KEY } from './async-blocker-constants';
|
var mongoose = require( 'mongoose' );
var bcrypt = require( 'bcrypt-nodejs');
var userSchema = mongoose.Schema({
uniqueToken : String,
admin : {
// 0 is user, 1 is admin
accessLevel : Number
},
local: {
email : String,
password : String
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
userName : String
},
google : {
id : String,
token : String,
email : String,
name : String
},
targetLocation : {
longtitude : String,
latitude : String
},
currentLocation : {
longtitude : String,
latitude : String
},
formattedTargetAddress : {
address : String,
place_id : String
}
});
// methods
// generate a hash
userSchema.methods.generateHash = function( password ){
return bcrypt.hashSync( password, bcrypt.genSaltSync( 8 ), null );
};
// check for valid password
userSchema.methods.validPassword = function( password ){
return bcrypt.compareSync( password, this.local.password );
};
// create model for user and expose to app
module.exports = mongoose.model( 'User', userSchema );
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "41962eaa3c34080c7f76eeb822cd7c31",
"url": "/index.html"
},
{
"revision": "4e1b6f8b338cda7a7575",
"url": "/static/css/main.21b75a60.chunk.css"
},
{
"revision": "9a5583737cf7421aa3d9",
"url": "/static/js/2.ef40040d.chunk.js"
},
{
"revision": "54e197b865c82f5802a437a963a8eac9",
"url": "/static/js/2.ef40040d.chunk.js.LICENSE.txt"
},
{
"revision": "4e1b6f8b338cda7a7575",
"url": "/static/js/main.fd9dcbaf.chunk.js"
},
{
"revision": "74f9644b57ea2c32f374",
"url": "/static/js/runtime-main.2afb3774.js"
},
{
"revision": "625fa74b98925357eb89fa56d4d11719",
"url": "/static/media/bg.625fa74b.jpg"
}
]); |
import React, { Component } from 'react';
import CoInfo from './CoInfo';
import { observer, inject } from 'mobx-react';
import './CoInfoContainer.css';
@inject('marketStore')
@observer
class CoInfoContainer extends Component {
componentDidMount() {
const { getMarketCode } = this.props.marketStore;
getMarketCode();
}
render() {
const { list, chart } = this.props;
return <CoInfo chart={chart} list={list} />;
}
}
export default CoInfoContainer;
|
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Login from '../components/Login';
import Profile from '../components/Profile';
import ProductPage from '../components/Products';
import Index from '../components';
import SearchResponse from '../components/SearchResponse';
import cart from '../components/cart';
const routes = () => (
<Switch>
<Route path="/login" component={Login} />
<Route path="/profile" component={Profile} />
<Route exact path="/articles" component={ProductPage} />
<Route exact path="/search" component={SearchResponse} />
<Route exact path="/cart" component={cart} />
<Route path="/" component={Index} />
</Switch>
);
export default routes; |
const fs = require('fs');
const input = fs.readFileSync('./day1_input.txt', { encoding: 'utf8' })
.trim()
.split(/[,\s]+/)
.map(item => {
return [item.charAt(0), Number(item.substr(1))]
});
function part1() {
const dirs = [
'up',
'right',
'down',
'left'
];
let dir = 'up';
const pos = [0, 0];
for (const item of input) {
let i = dirs.indexOf(dir);
if (item[0] == 'L') {
i--;
if (i < 0) i = dirs.length - 1;
} else {
i++;
if (i >= dirs.length) i = 0;
}
dir = dirs[i];
switch (dir) {
case 'up':
pos[1] += item[1];
break;
case 'left':
pos[0] -= item[1];
break;
case 'right':
pos[0] += item[1];
break;
case 'down':
pos[1] -= item[1];
break;
}
}
return Math.abs(pos[0]) + Math.abs(pos[1]);
}
function part2() {
const dirs = [
'up',
'right',
'down',
'left'
];
let dir = 'up';
const visited = new Set(['0,0']);
const pos = [0, 0];
for (const item of input) {
let i = dirs.indexOf(dir);
if (item[0] == 'L') {
i--;
if (i < 0) i = dirs.length - 1;
} else {
i++;
if (i >= dirs.length) i = 0;
}
dir = dirs[i];
let k = 1;
while (k++ <= item[1]) {
move();
const loc = pos.join(',');
if (visited.has(loc)) {
return Math.abs(pos[0]) + Math.abs(pos[1]);
}
visited.add(loc);
}
function move() {
switch (dir) {
case 'up':
pos[1]++;
break;
case 'down':
pos[1]--;
break;
case 'left':
pos[0]--;
break;
case 'right':
pos[0]++;
break;
}
}
}
}
console.log('Part 1: %d', part1());
console.log('Part 2: %s', part2());
|
import Homepage from './Homepage.component';
export default Homepage;
|
const docEl = window.document.documentElement;
const metaEl = document.querySelector('meta[name="viewport"]');
const dpr = window.devicePixelRatio || 1;
const scale = 1 / dpr;
const setRemUnit = () => {
// const { width } = domEl.getBoundingClientRect()
// // 设置viewport,进行缩放,达到高清效果
// // metaEl.setAttribute('content', `width=${dpr * width} ,initial-scale=${scale},maximum-scale=${scale}, minimum-scale=${scale},user-scalable=no`);
// // 设置data-dpr属性,留作的css hack之用
// domEl.setAttribute('data-dpr', dpr);
// const rem = (width * dpr) / 10
// domEl.style.fontSize = `${rem}px`
// window.dpr = dpr;
const { width } = docEl.getBoundingClientRect()
let rem = width / 7.5
rem = rem > 102.4 ? 102.4 : rem
docEl.style.fontSize = `${rem}px`
document.getElementsByTagName('body')[0].style.width = `${rem * 7.5}px`
document.getElementsByTagName('body')[0].style.margin = 'auto'
}
setRemUnit()
export default setRemUnit
|
analytics.directive('agendaDetails', function () {
return {
restrict: 'E',
scope: {
'date' : '=',
'endTime' : '='
},
templateUrl: 'js/directives/agendaDetails.html'
}
}); |
class Product {
constructor(name, image, price) {
this.name = name;
this.image = image;
this.price = price
}
getHtml() {
let html =`<div class="product-item">
<img style="width: 200px; height: 150px" src="${this.image}" alt="">
<div class="product-item-text">
<p><span>${this.price}</span><sup>đ</sup></p>
<h1 style="font-weight: boil; font-size: 16px;">${this.name}</h1>
</div>
<button>Thêm vào giỏ hàng</button>
</div>`;
return html;
}
} |
function ucfirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
console.log(ucfirst('hello world!'));
function capitalize(string) {
return string.toLowerCase().split(' ').map((s) => s.charAt(0).toUpperCase() + s.substring(1)).join(' ');
}
console.log(capitalize(' hello world '));
function camelCase(string) {
return capitalize(string).split(' ').join('');
}
console.log(camelCase('Je fais Du JS'));
function snake_case(string) {
return string.toLowerCase().split(' ').join('_');
}
console.log(snake_case('PelOo World world'));
function leet(string) {
var str = string;
var mapObj = {
a:4,
e:3,
i:1,
o:'O',
u:'(_)',
y:7
};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
return mapObj[matched];
});
return str;
}
console.log(leet('anaconda'));
function verlan(string) {
var str = string.split(' ');
var str2 = "";
for(var i = 0; i < str.length; i++) {
str2 += str[i] . split('').reverse().join('') + ' ';
}
return str2;
}
console.log(verlan('Hello World'));
function yoda(string) {
var str = string.split(' ');
return str.reverse().join(' ');
}
console.log(yoda('Hello World'));
function prop_access(string) {
}
console.log(prop_access('chien'));
function vig(string1, string2) {
}
console.log(vig('wikipedia', 'crypto'));
|
import React, { useContext, useState } from 'react';
import { makeStyles, TextField, MenuItem, Button } from '@material-ui/core';
import CovidContext from '../context/covidContext'
import Error from './Error'
const FormCountry = () => {
const classes = useStyles();
const covidCon = useContext(CovidContext)
const {
countries,
selectCountryFunc
} = covidCon
const [country, setCountry] = useState('')
const [error, setError] = useState(false)
const handleChange = e => {
setCountry(e.target.value)
}
const handleSumbit = e => {
e.preventDefault()
if(country.trim()=== ''){
setError(true)
return
}
selectCountryFunc(country)
}
return (
<form className={classes.root} noValidate autoComplete="off" onSubmit={handleSumbit}>
<TextField
className={classes.select}
select
label="Select Country"
value={country}
onChange={handleChange}
helperText="Please select your country"
>
{countries.map((c) => (
<MenuItem key={c.CountryCode} value={c.CountryCode}>
{c.Country}
</MenuItem>
))}
</TextField>
{error ? <Error msg="Selecciona un pais para continuar"/>: null}
<Button variant="contained" type="submit" className={classes.button}>
Submit
</Button>
</form>
);
}
const useStyles = makeStyles((theme) => ({
root: {
display:'flex',
flexFlow: 'column wrap',
justifyContent:'center',
textAlign:'center',
'& .MuiTextField-root': {
margin: theme.spacing(1),
width: '25ch',
},
},
select : {
margin:'auto!important'
},
button: {
marginTop: '2rem',
marginBottom: '.5rem',
backgroundColor: '#ff9800',
color: 'white',
fontWeight: 'bold',
width:'10rem',
marginLeft:'auto!important',
marginRight:'auto!important',
'&:hover':{
backgroundColor: '#0d47a1',
}
},
}));
export default FormCountry; |
'use strict';
var DeviceView = React.createClass({
displayName: 'DeviceView',
getInitialState: function () {
return {
'currentDeviceId': undefined,
'devices': {},
'control': false,
'controlForm': {} };
},
componentDidMount: function () {
// FIXME listener leaks.
var deviceAdded = function () {
console.log(1);
this.setState({
'devices': deviceStore.getDevices()
});
}.bind(this);
var deviceSelected = function () {
console.log(2);
this.setState({
'currentDeviceId': deviceSelectedStore.getDeviceId(),
'control': false,
'controlForm': {}
});
}.bind(this);
var deviceUpdated = function () {
// pass... deviceAdded will be called eventually.
}.bind(this);
deviceStore.registerDeviceDetailAdded(deviceAdded);
deviceStore.registerDeviceDetailUpdated(deviceUpdated);
deviceSelectedStore.registerDeviceSelected(deviceSelected);
},
handleControlToggle: function (event) {
var control = this.state['control'];
var checked = event.target.checked;
if (!control && checked) {
var deviceId = this.state['currentDeviceId'];
var device = this.state['devices'][deviceId];
var controlForm = {};
for (var i = 0; i < device['property'].length; i++) {
var prop = device['property'][i];
if (prop.records.length > 0) {
controlForm[prop['name']] = prop.records[0]['value'];
} else {
controlForm[prop['name']] = undefined;
}
}
this.setState({
'control': event.target.checked,
'controlForm': controlForm
});
} else if (control && !checked) {
this.setState({
'control': event.target.checked,
'controlForm': {}
});
}
},
setBoolean: function (name, event) {
var controlForm = this.state['controlForm'];
controlForm[name] = event.target.checked;
this.setState({
'controlForm': controlForm
});
},
updateInteger: function (name, event) {
var controlForm = this.state['controlForm'];
// TODO checking.
controlForm[name] = event.target.value;
this.setState({
'controlForm': controlForm
});
},
updateNumber: function (name, event) {
var controlForm = this.state['controlForm'];
// TODO checking.
controlForm[name] = event.target.value;
this.setState({
'controlForm': controlForm
});
},
updateString: function (name, event) {
var controlForm = this.state['controlForm'];
// TODO checking.
controlForm[name] = event.target.value;
this.setState({
'controlForm': controlForm
});
},
applyChange: function () {
// prepare data
var controlForm = this.state['controlForm'];
var device = this.state['devices'][this.state['currentDeviceId']];
var data = {
'device': device,
'update': controlForm
};
var action = Actions.createUpdateDeviceDetailAction(data);
dispatcher.dispatch(action);
showMsg('update request has been sent');
this.setState({
'control': false,
'controlForm': {}
});
},
render: function () {
var notReadyUi = React.createElement(
'div',
null,
' '
);
if (!this.state['currentDeviceId']) {
return notReadyUi;
}
var devices = this.state['devices'];
var currentDeviceId = this.state['currentDeviceId'];
if (!_.has(devices, currentDeviceId)) {
return React.createElement(
'div',
null,
' waiting '
);
}
var device = devices[currentDeviceId];
var control = this.state['control'];
var ui = undefined;
if (!control) {
var dataUi = _.map(device['property'], function (prop) {
var value;
var time;
if (prop['records'].length == 0) {
value = 'Not Available';
time = 'Not Available';
} else {
value = prop['records'][0]['value'] + '';
time = prop['records'][0]['time'] + '';
}
return React.createElement(
'tr',
null,
React.createElement(
'td',
null,
' ',
prop['name'],
' '
),
React.createElement(
'td',
null,
' ',
value,
' '
),
React.createElement(
'td',
null,
' ',
time,
' '
)
);
});
ui = React.createElement(
'div',
{ className: 'panel panel-primary' },
React.createElement(
'div',
{ className: 'panel-heading' },
React.createElement(
'h3',
{ className: 'panel-title' },
device['name']
)
),
React.createElement(
'div',
{ className: 'panel-body' },
React.createElement(
'div',
{ className: 'row' },
' ',
device['description'],
' '
),
React.createElement(
'div',
{ className: 'row' },
React.createElement(
'table',
{ className: 'table' },
React.createElement(
'thead',
null,
' ',
React.createElement(
'tr',
null,
React.createElement(
'td',
null,
' name '
),
React.createElement(
'td',
null,
' value '
),
React.createElement(
'td',
null,
' time '
)
),
' '
),
React.createElement(
'tbody',
null,
dataUi
)
)
)
)
);
} else {
var formUi = _.map(device['property'], function (prop) {
var name = prop['name'];
var controlForm = this.state['controlForm'];
var value = controlForm[name] !== undefined ? controlForm[name] : '';
// 0 means not controllable
if (prop['controllable'] == 0) {
return React.createElement(
'tr',
null,
React.createElement(
'td',
null,
' ',
prop['name'],
' '
),
React.createElement(
'td',
null,
' ',
value + '',
' '
)
);
} else {
var tdInput = React.createElement(
'td',
null,
'????'
);
if (prop['type'] == 'boolean') {
tdInput = React.createElement(
'td',
null,
'True',
React.createElement(
'div',
{ className: 'input-group' },
React.createElement(
'span',
{ className: 'input-group-addon' },
'True:',
React.createElement('input', { type: 'checkbox', 'aria-label': 'control',
onChange: this.setBoolean.bind(this, name) })
)
)
);
} else if (prop['type'] == 'integer') {
tdInput = React.createElement(
'td',
null,
React.createElement('input', { type: 'number', 'class': 'form-control',
value: value,
onChange: this.updateInteger.bind(this, name) })
);
} else if (prop['type'] == 'number') {
tdInput = React.createElement(
'td',
null,
React.createElement('input', { type: 'number', 'class': 'form-control',
value: value,
onChange: this.updateNumber.bind(this, name) })
);
} else if (prop['type'] == 'string') {
tdInput = React.createElement(
'td',
null,
React.createElement('input', { type: 'text', 'class': 'form-control',
value: value,
onChange: this.updateString.bind(this, name) })
);
} else {
showMsg('data corrupted?');
}
return React.createElement(
'tr',
null,
React.createElement(
'td',
null,
' ',
prop['name'],
' '
),
tdInput
);
}
}, this);
ui = React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'panel panel-primary' },
React.createElement(
'div',
{ className: 'panel-heading' },
React.createElement(
'h3',
{ className: 'panel-title' },
device['name']
)
),
React.createElement(
'div',
{ className: 'panel-body' },
React.createElement(
'div',
{ className: 'row' },
' ',
device['description'],
' '
),
React.createElement(
'div',
{ className: 'row' },
React.createElement(
'table',
{ className: 'table' },
React.createElement(
'thead',
null,
' ',
React.createElement(
'tr',
null,
React.createElement(
'td',
null,
' name '
),
React.createElement(
'td',
null,
' value '
)
),
' '
),
React.createElement(
'tbody',
null,
formUi
)
)
)
)
),
React.createElement(
'div',
null,
React.createElement(
'span',
{ className: 'btn btn-primary', onClick: this.applyChange },
'Apply'
)
)
);
}
var controlBtn = React.createElement(
'div',
{ className: 'row' },
React.createElement(
'div',
{ className: 'input-group' },
React.createElement(
'span',
{ className: 'input-group-addon' },
'Control:',
React.createElement('input', { type: 'checkbox', 'aria-label': 'control', checked: control,
onChange: this.handleControlToggle })
)
)
);
return React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'row' },
' ',
controlBtn,
' '
),
React.createElement(
'div',
{ className: 'row' },
' ',
ui,
' '
)
);
}
});
|
define(['zepto', 'underscore', 'backbone',
'swiper', 'echo','app/api', 'app/refreshtoken',
'app/utils',
'text!templates/my.html'
],
function($, _, Backbone, Swiper, echo, Api, Token, utils, myTemplate) {
var $page = $("#my-page");
var type =1;//需要先判断是否登陆
var $categoryList;
var $usserInfoContaniter;
var $userInfoItem;
var imageRenderToken = null;
var myView = Backbone.View.extend({
el: $page,
render: function(id, name) {
utils.showPage($page, function() {
$page.empty().append(myTemplate);
$usserInfoContaniter = $page.find(".usser_info_contaniter");
$userInfoItem = $page.find("#user_info_item");;
//得到登陆状态
getLoginStatus();
});
},
events: {
//登陆
"tap .login":"login",
//设置
"tap .ui-icon-set":"mySetting",
//我的消息
"tap .ui-icon-message":"myMessage",
//个人信息
"tap .user_head_img":"personalInfo",
//梦想币 红包 积分 充值
"tap .personal_info .item":"aboutMoney",
//查询 夺宝记录,中奖纪录 .. 我的晒单,充值记录....
"tap ul li": "queryRecords",
},
login: function(){
utils.storage.set("loginSuccessBack",window.location.hash);
window.location.href = window.LOGIN_REDIRECT_URL;
},
mySetting: function(){
window.location.hash = "mySetting";
},
myMessage: function(){
window.location.hash = "myMessage";
},
personalInfo: function(){
if( utils.isLogined()){
window.location.hash = "personalInfo";
}else {
//登陆
window.location.href = window.LOGIN_REDIRECT_URL ;
}
},
aboutMoney: function(e){
e.stopImmediatePropagation();
$this = $(e.currentTarget);
var dataHref = $this.data("href");
if(dataHref){
window.location.hash = dataHref;
}
},
queryRecords: function( e ){
e.stopImmediatePropagation();
$this = $(e.currentTarget);
var dataHref = $this.data("href");
if( dataHref ){
//debugger
if(dataHref == "share"){
window.location.hash = dataHref + "/my";
}else{
window.location.hash = dataHref;
}
}
}
});
var getLoginStatus = function(){
if( utils.isLogined()){
initMembersInfo();
}else{
$(".user_info_container").find(".login").show().siblings(".user_name").hide();
}
};
//获取个人信息
var initMembersInfo = function(){
Api.getMembersInfo(null, function(successData){
var template = _.template($userInfoItem.html());
$usserInfoContaniter.empty().append(template(successData.result));
asynLoadImage();
$(".user_info_container").find(".login").hide().siblings(".user_name").show();
}, function(errorData){
//token过期 刷新token
if( errorData.err_code == 20002 ){
Token.getRefeshToken(type,function(data){
initMembersInfo();
},function(data){
window.location.href = window.LOGIN_REDIRECT_URL;
});
}
});
};
var asynLoadImage = function () {
echo.init({
throttle: 250,
});
if (imageRenderToken == null) {
imageRenderToken = window.setInterval(function () {
echo.render();
}, 350);
}
};
return myView;
});
|
'use strict';
import './styles/score-box.css';
/* import all content scripts */
import './webpage';
|
import React from 'react';
import './style.css';
import Button from '@material-ui/core/Button';
class MailForm extends React.Component {
constructor() {
super();
this.state = {
fields: {},
errors: {}
}
this.handleChange = this.handleChange.bind(this);
this.submitMailForm = this.submitMailForm.bind(this);
};
handleChange(e) {
let fields = this.state.fields;
fields[e.target.name] = e.target.value;
this.setState({
fields
});
}
submitMailForm(e) {
// e.preventDefault();
if (this.validateForm()) {
let fields = {};
fields["f_emailid"] = "";
fields["t_emailid"] = "";
fields["subj"] = "";
fields["message"] = "";
// this.setState({fields:fields});
//alert("Mail Sent");
}
}
validateForm() {
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if (!fields["f_emailid"]) {
formIsValid = false;
errors["f_emailid"] = "*Please enter your email-ID.";
}
if (typeof fields["f_emailid"] !== "undefined") {
//regular expression for email validation
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (!pattern.test(fields["f_emailid"])) {
formIsValid = false;
errors["f_emailid"] = "*Please enter valid email-ID.";
}
}
if (!fields["t_emailid"]) {
formIsValid = false;
errors["t_emailid"] = "*Please enter email-ID.";
}
if (typeof fields["t_emailid"] !== "undefined") {
//regular expression for email validation
pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (!pattern.test(fields["t_emailid"])) {
formIsValid = false;
errors["t_emailid"] = "*Please enter valid email-ID.";
}
}
if (!fields["subj"]) {
formIsValid = false;
errors["subj"] = "*Please enter the subject.";
}
if (!fields["message"]) {
formIsValid = false;
errors["message"] = "*Please enter the message.";
}
this.setState({
errors: errors
});
return formIsValid;
}
render() {
return (
<div id="main-composing-container">
<div id="send">
<h3>Create your mail</h3>
<form name="MailForm" onSubmit= {this.submitMailForm} method="POST" action="http://localhost/t1.php" >
<label>From</label>
<input type="text" name="f_emailid" value={this.state.fields.f_emailid} onChange={this.handleChange} />
<div className="errorMsg">{this.state.errors.f_emailid}</div>
<label>To</label>
<input type="text" name="t_emailid" value={this.state.fields.t_emailid} onChange={this.handleChange} />
<div className="errorMsg">{this.state.errors.t_emailid}</div>
<label>Subject</label>
<input type="text" name="subj" value={this.state.fields.subj} onChange={this.handleChange} />
<div className="errorMsg">{this.state.errors.subj}</div>
<label>Content</label>
<input type="textarea" name="message" rows="50" cols="50" value={this.state.fields.message} onChange={this.handleChange} />
<div className="errorMsg">{this.state.errors.message}</div>
<center><Button variant="contained" color="primary" type="submit">
SEND
</Button></center>
</form>
</div>
</div>
);
}
}
export default MailForm; |
import React, { Component } from 'react';
import RandomUser from './components/RandomUser';
import UserData from './UserData';
import './App.css';
class App extends Component {
state = {
userData: UserData,
}
render() {
return (
<div className="App">
<header className="App-header">
<h1>Random User</h1>
</header>
<RandomUser userData={this.state.userData.results[0]}/>
</div>
);
}
}
export default App;
|
module.exports = {
"Hoshido Noble": {
name: "Hoshido Noble",
baseStats:{hp:19,str:10,mag:4,skl:5,spd:6,lck:4,def:7,res:3,mov:6}
other: "–"
},
"Samurai": {
name: "Samurai",
baseStats:{hp:17,str:4,mag:0,skl:5,spd:8,lck:3,def:3,res:3,mov:5}
other: "–"
},
"Swordmaster": {
name: "Swordmaster",
baseStats:{hp:18,str:6,mag:2,skl:7,spd:11,lck:4,def:5,res:5,mov:6}
other: "Crt +10, Avo +10"
},
"Master of Arms": {
name: "Master of Arms",
baseStats:{hp:20,str:8,mag:0,skl:6,spd:9,lck:3,def:7,res:3,mov:6}
other: "–"
},
"Oni Savage": {
name: "Oni Savage",
baseStats:{hp:18,str:6,mag:1,skl:2,spd:5,lck:0,def:7,res:1,mov:5}
other: "–"
},
"Oni Chieftain": {
name: "Oni Chieftain",
baseStats:{hp:19,str:9,mag:5,skl:2,spd:7,lck:0,def:10,res:5,mov:6}
other: "–"
},
"Blacksmith": {
name: "Blacksmith",
baseStats:{hp:21,str:8,mag:0,skl:9,spd:8,lck:3,def:8,res:2,mov:6}
other: "–"
},
"Spear Fighter": {
name: "Spear Fighter",
baseStats:{hp:17,str:6,mag:0,skl:6,spd:6,lck:2,def:5,res:2,mov:5}
other: "–"
},
"Spear Master": {
name: "Spear Master",
baseStats:{hp:18,str:9,mag:0,skl:8,spd:8,lck:3,def:7,res:3,mov:6}
other: "Crt +10, CEv +10"
},
"Basara": {
name: "Basara",
baseStats:{hp:20,str:7,mag:5,skl:7,spd:7,lck:5,def:7,res:6,mov:6}
other: "–"
},
"Diviner": {
name: "Diviner",
baseStats:{hp:15,str:0,mag:4,skl:5,spd:6,lck:1,def:1,res:3,mov:5}
other: "–"
},
"Onmyoji": {
name: "Onmyoji",
baseStats:{hp:16,str:0,mag:7,skl:6,spd:7,lck:2,def:3,res:6,mov:6}
other: "–"
},
"Monk": {
name: "Monk",
baseStats:{hp:16,str:0,mag:3,skl:5,spd:5,lck:4,def:2,res:5,mov:5}
other: "CEv +10"
},
"Shrine Maiden": {
name: "Shrine Maiden",
baseStats:{hp:16,str:0,mag:3,skl:5,spd:5,lck:4,def:2,res:5,mov:5}
other: "CEv +10"
},
"Great Master": {
name: "Great Master",
baseStats:{hp:19,str:8,mag:6,skl:6,spd:8,lck:5,def:6,res:7,mov:6}
other: "–"
},
"Priestess": {
name: "Priestess",
baseStats:{hp:19,str:6,mag:7,skl:6,spd:9,lck:5,def:5,res:8,mov:6}
other: "–"
},
"Sky Knight": {
name: "Sky Knight",
baseStats:{hp:16,str:3,mag:0,skl:5,spd:7,lck:4,def:2,res:6,mov:7}
other: "–"
},
"Falcon Knight": {
name: "Falcon Knight",
baseStats:{hp:18,str:5,mag:4,skl:6,spd:10,lck:5,def:5,res:9,mov:8}
other: "–"
},
"Kinshi Knight": {
name: "Kinshi Knight",
baseStats:{hp:17,str:4,mag:1,skl:9,spd:8,lck:5,def:4,res:7,mov:8}
other: "–"
},
"Archer": {
name: "Archer",
baseStats:{hp:17,str:5,mag:0,skl:7,spd:5,lck:2,def:4,res:1,mov:5}
other: "–"
},
"Sniper": {
name: "Sniper",
baseStats:{hp:19,str:7,mag:0,skl:10,spd:9,lck:3,def:6,res:2,mov:6}
other: "Hit +10, Crt +10"
},
"Ninja": {
name: "Ninja",
baseStats:{hp:16,str:3,mag:0,skl:8,spd:8,lck:1,def:3,res:3,mov:5}
other: "–"
},
"Master Ninja": {
name: "Master Ninja",
baseStats:{hp:17,str:5,mag:0,skl:10,spd:11,lck:2,def:4,res:8,mov:6}
other: "Hit, Crt, Avo, CEv +5"
},
"Mechanist": {
name: "Mechanist",
baseStats:{hp:18,str:7,mag:0,skl:9,spd:7,lck:2,def:6,res:6,mov:7}
other: "–"
},
"Apothecary": {
name: "Apothecary",
baseStats:{hp:18,str:6,mag:0,skl:4,spd:4,lck:2,def:6,res:2,mov:5}
other: "–"
},
"Merchant": {
name: "Merchant",
baseStats:{hp:20,str:8,mag:0,skl:6,spd:5,lck:4,def:8,res:5,mov:6}
other: "–"
},
"Kitsune": {
name: "Kitsune",
baseStats:{hp:16,str:5,mag:1,skl:6,spd:8,lck:4,def:1,res:4,mov:5}
other: "–"
},
"Nine Tails": {
name: "Nine Tails",
baseStats:{hp:19,str:6,mag:2,skl:9,spd:10,lck:5,def:2,res:8,mov:6}
other: "Crt +5, Avo +10, CEv +10"
},
"Songstress": {
name: "Songstress",
baseStats:{hp:16,str:3,mag:0,skl:6,spd:5,lck:3,def:2,res:3,mov:5}
other: "–"
},
"Villager": {
name: "Villager",
baseStats:{hp:17,str:5,mag:0,skl:4,spd:5,lck:3,def:4,res:0,mov:5}
other: "–"
},
"Nohr Prince(ss)": {
name: "Nohr Prince(ss)",
baseStats:{hp:17,str:7,mag:3,skl:4,spd:5,lck:2,def:5,res:2,mov:5}
other: "–"
},
"Nohr Noble": {
name: "Nohr Noble",
baseStats:{hp:18,str:8,mag:6,skl:4,spd:7,lck:2,def:6,res:6,mov:6}
other: "–"
},
"Cavalier": {
name: "Cavalier",
baseStats:{hp:17,str:6,mag:0,skl:5,spd:5,lck:3,def:5,res:3,mov:7}
other: "–"
},
"Paladin": {
name: "Paladin",
baseStats:{hp:19,str:8,mag:1,skl:7,spd:7,lck:4,def:7,res:6,mov:8}
other: "–"
},
"Great Knight": {
name: "Great Knight",
baseStats:{hp:21,str:10,mag:0,skl:6,spd:6,lck:3,def:10,res:2,mov:7}
other: "–"
},
"Knight": {
name: "Knight",
baseStats:{hp:19,str:8,mag:0,skl:5,spd:3,lck:3,def:8,res:1,mov:4}
other: "–"
},
"General": {
name: "General",
baseStats:{hp:22,str:11,mag:0,skl:7,spd:3,lck:4,def:12,res:3,mov:5}
other: "–"
},
"Fighter": {
name: "Fighter",
baseStats:{hp:19,str:7,mag:0,skl:6,spd:6,lck:2,def:4,res:1,mov:5}
other: "–"
},
"Berserker": {
name: "Berserker",
baseStats:{hp:24,str:12,mag:0,skl:8,spd:9,lck:0,def:5,res:0,mov:6}
other: "Crt +20, CEv -5"
},
"Mercenary": {
name: "Mercenary",
baseStats:{hp:17,str:5,mag:0,skl:7,spd:6,lck:2,def:5,res:2,mov:5}
other: "–"
},
"Hero": {
name: "Hero",
baseStats:{hp:20,str:8,mag:0,skl:10,spd:8,lck:3,def:7,res:2,mov:6}
other: "–"
},
"Bow Knight": {
name: "Bow Knight",
baseStats:{hp:18,str:6,mag:0,skl:8,spd:9,lck:3,def:5,res:6,mov:8}
other: "–"
},
"Outlaw": {
name: "Outlaw",
baseStats:{hp:16,str:3,mag:1,skl:4,spd:8,lck:1,def:2,res:4,mov:5}
other: "–"
},
"Adventurer": {
name: "Adventurer",
baseStats:{hp:17,str:4,mag:6,skl:6,spd:10,lck:2,def:3,res:8,mov:6}
other: "–"
},
"Wyvern Rider": {
name: "Wyvern Rider",
baseStats:{hp:17,str:6,mag:0,skl:5,spd:4,lck:2,def:7,res:0,mov:7}
other: "–"
},
"Wyvern Lord": {
name: "Wyvern Lord",
baseStats:{hp:19,str:8,mag:0,skl:9,spd:6,lck:3,def:10,res:1,mov:8}
other: "–"
},
"Malig": {
name: "Malig",
baseStats:{hp:Knight,str:18,mag:7,skl:6,spd:6,lck:5,def:0,res:8,mov:6}
other: "8 –"
},
"Dark": {
name: "Dark",
baseStats:{hp:Mage,str:16,mag:0,skl:6,spd:3,lck:3,def:1,res:3,mov:5}
other: "5 –"
},
"Sorcerer": {
name: "Sorcerer",
baseStats:{hp:17,str:0,mag:9,skl:4,spd:6,lck:1,def:5,res:8,mov:6}
other: "Hit +5, Crt +10, CEv +5"
},
"Dark": {
name: "Dark",
baseStats:{hp:Knight,str:19,mag:8,skl:6,spd:6,lck:5,def:3,res:8,mov:6}
other: "8 –"
},
"Troubadour": {
name: "Troubadour",
baseStats:{hp:15,str:0,mag:3,skl:7,spd:5,lck:4,def:1,res:4,mov:7}
other: "CEv +10"
},
"Strategist": {
name: "Strategist",
baseStats:{hp:16,str:0,mag:7,skl:6,spd:7,lck:5,def:2,res:7,mov:8}
other: "–"
},
"Maid": {
name: "Maid",
baseStats:{hp:18,str:4,mag:5,skl:9,spd:8,lck:4,def:5,res:4,mov:6}
other: "–"
},
"Butler": {
name: "Butler",
baseStats:{hp:18,str:4,mag:5,skl:9,spd:8,lck:4,def:5,res:4,mov:6}
other: "–"
},
"Wolfskin": {
name: "Wolfskin",
baseStats:{hp:19,str:8,mag:0,skl:4,spd:6,lck:0,def:4,res:0,mov:5}
other: "–"
},
"Wolfssegner": {
name: "Wolfssegner",
baseStats:{hp:22,str:11,mag:0,skl:6,spd:7,lck:1,def:7,res:1,mov:6}
other: "Hit +10, Crt +5, CEv +10"
},
}
|
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';
export const Trips = new Mongo.Collection('trips');
if (Meteor.isServer) {
Meteor.publish('trips', function tripsPublication() {
return Trips.find();
});
Accounts.onCreateUser((options, user) => {
user.admin = true;
user.currTrip = null;
user.homeAddress = null;
if (options.profile) {
user.profile = options.profile;
}
return user;
});
Meteor.publish('users', function() {
if(!this.userId) return null;
return Meteor.users.find(this.userId, {fields: {
currTrip: 1,
admin: 1,
homeAddress:1,
}});
});
}
if (Meteor.isClient) {
Deps.autorun(function(){
Meteor.subscribe('users');
});
}
Meteor.methods({
'trips.insert'(dTime, capacity, travelMode, startingAddress) {
if (! Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
Trips.insert({
dTime: dTime,
capacity: capacity,
currCapacity: 0,
travelMode: travelMode,
startingAddress: startingAddress,
users: [],
createdAt: new Date(),
owner: Meteor.userId(),
username: Meteor.user().profile.name,
});
},
'trips.remove'(tripId) {
check(tripId, String);
Trips.remove(tripId);
},
'trips.update'(tripId, newCapacity, newUsers, address, username) {
check(tripId, String);
// create new user object and push
var newUser = {
userId: Meteor.userId(),
username: username,
homeAddress: address,
}
newUsers.push(newUser);
Trips.update(tripId, {
$set: { currCapacity: newCapacity, users: newUsers},
});
Meteor.users.update(Meteor.userId(), {
$set: { currTrip: tripId }
});
},
'trips.deregister'(tripId, newCapacity, newUsers) {
check(tripId, String);
// Remove user with given id
var index = -1;
for(var i = 0, len = newUsers.length; i < len; i++) {
if (newUsers[i].userId === Meteor.userId()) {
index = i;
break;
}
}
newUsers.splice(index, 1);
// need to find a new way to find index
Trips.update(tripId, {
$set: { currCapacity: newCapacity, users: newUsers},
});
Meteor.users.update(Meteor.userId(), {
$set: { currTrip: null }
});
},
'trips.updateUser'(homeAddress) {
Meteor.users.update(Meteor.userId(), {
$set: { homeAddress: homeAddress, }
});
},
}); |
/**
* Created by ashwin.kc on 8/22/2018.
*/
({
doInit: function (component, event, helper) {
try {
//get time zone of current logged in user
var timeZone = $A.get("$Locale.timezone");
component.set("v.userTimeZone", timeZone);
helper.getFilterDropDown(component, event, helper);
helper.getCaseDetail(component, event, helper);
helper.isConsoleView(component,event,helper);
} catch (e) {
console.error(e);
}
},
onFilterChange: function (component, event, helper) {
try {
helper.getCasesRelated(component, event, helper);
} catch (e) {
console.error(e);
}
},
spinnerShow: function (component, event, helper) {
let m = component.find('spinner');
$A.util.removeClass(m, "slds-hide");
},
spinnerHide: function (component, event, helper) {
let m = component.find('spinner');
$A.util.addClass(m, "slds-hide");
},
openRelatedCase: function (component, event, helper) {
try{
let caseId = event.currentTarget.getAttribute("data-caseId");
helper.openCase(component,event,helper,caseId);
}catch(e){
console.error(e);
}
}
}) |
class User {
nameRegex = /^[a-zA-Z]*$/;
emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
constructor(
name,
email,
password,
confirmPassword,
city,
state,
checktermCondtion
) {
this.name = name;
this.email = email;
this.password = password;
this.confirmPassword = confirmPassword;
this.city = city;
this.state = state;
this.checktermCondtion = checktermCondtion;
this.role = "admin";
}
validation() {
if (this.nameRegex.test(this.name) == false) {
alert("Please Enter valid name");
return false;
}
if (this.emailRegex.test(this.email) == false) {
alert("Please enter valid email");
return false;
}
if (this.password == "" || this.confirmPassword == "") {
alert("Please Enter password");
return false;
}
if (this.password != this.confirmPassword) {
alert("Please confirm the passwords");
return false;
}
if (this.checktermCondtion == false) {
alert("Please Checked This checkbox");
return false;
}
return true;
}
}
if (sessionStorage.getItem("userData") == null) {
userData = [];
sessionStorage.setItem("userData", JSON.stringify(userData));
}
function registerUser() {
var name = registerForm.txtName.value;
var email = registerForm.txtEmail.value;
var password = registerForm.txtPassword.value;
var confirmPassword = registerForm.txtConfirmPassword.value;
var city = registerForm.dropdownCity.value;
var state = registerForm.dropdownState.value;
var checktermCondtion = document.querySelector("#checkTermsCondition")
.checked;
var admin = new User(
name,
email,
password,
confirmPassword,
city,
state,
checktermCondtion
);
if (admin.validation()) {
userData = JSON.parse(sessionStorage.getItem("userData"));
// console.log(userData);
userData.push(admin);
sessionStorage.setItem("userData", JSON.stringify(userData));
sessionStorage.setItem("registerBtnValue", 1);
sessionStorage.setItem("adminName", name);
window.location.href = "dashboard.html";
} else {
console.log("validation errror");
}
}
|
var listaFrutas = ["Banana", "Maça", "Kiwi", "Abacate", "Limão"];
//For simples
for (numero = 1; numero <= 10; numero++) {
console.log("Numero atual: " + numero);
}
//For in, ele itera e agrega o valor na constante sacola
for (const sacola in listaFrutas) {
console.log(listaFrutas[sacola]);
}
|
const config = require('../config/config.js');
class WebRequsetAction {
run(url) {
return new Promise(async (fulfill, reject) => {
let https;
if(url.startsWith("http://")) {
https = require('http');
} else {
https = require('https');
}
https.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
fulfill({ 'status': 'done', 'data': JSON.parse(data).explanation });
});
}).on("error", (err) => {
fulfill({ 'status': 'error', 'data': err.message });
});
});
}
}
module.exports = new WebRequsetAction(); |
const GOOGLE_API_KEY = "AIzaSyAi23ZtW4_Lfk9qeM1LNvMk1uT5myhx47E";
const MAP_GENERAL_STYLES = [
{
"featureType": "poi",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.highway",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.local",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "landscape",
"elementType": "labels.icon",
"stylers": [
{"visibility": "off"}
]
}
];
const MAP_DAY_STYLES = [
...MAP_GENERAL_STYLES,
];
const MAP_NIGHT_STYLES = [
{
"elementType": "geometry",
"stylers": [
{
"color": "#242f3e"
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#746855"
}
]
},
{
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#242f3e"
}
]
},
{
"featureType": "administrative.locality",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#9c8876"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"color": "#38414e"
}
]
},
{
"featureType": "road",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#212a37"
}
]
},
{
"featureType": "road",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#9ca5b3"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry",
"stylers": [
{
"color": "#625a58"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#1f2835"
}
]
},
{
"featureType": "road.highway",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#f3d19c"
}
]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#17263c"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#515c6d"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#17263c"
}
]
},
{
"featureType": "administrative.country",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#838b99"
}
]
},
...MAP_GENERAL_STYLES
];
export default {
GOOGLE_API_KEY,
MAP_GENERAL_STYLES,
MAP_DAY_STYLES,
MAP_NIGHT_STYLES
}
|
import DateBox from './date_box/ui.date_box';
export default DateBox; |
import React from "react";
import "../App.css";
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
const Team = (props) => {
const [styleLogo, setStyle] = useState({ width: "80px", height: "80px" });
useEffect(() => {
if (props.isChoosed) {
setStyle(
{
width: "80px",
height: "80px",
boxShadow: "0 0 7px #ccc",
borderRadius: "55%",
transform: "scale(1.5)",
},
styleLogo
);
} else setStyle({ width: "80px", height: "80px" }, styleLogo);
// eslint-disable-next-line
}, [props]);
// Conditional rendering of img style based on the selected team
return (
<React.Fragment>
<Link to={`../players/${props.teamId}`}>
<img
className={props.isChoosed ? "" : "zoom"}
src={props.img}
alt={props.name}
style={styleLogo}
></img>
</Link>
</React.Fragment>
);
};
export default Team;
|
import React, {useEffect, useState} from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import { Tabs, Tab, Row, Form, Spinner } from 'react-bootstrap'
import ReactEcharts from "echarts-for-react";
import * as echarts from "echarts";
import {API_URL, coinList } from './Dash'
const Markets = () => {
const [month, setMonth] = useState({art: null, aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null})
const [week, setWeek] = useState({art: null, aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null})
const [day, setDay] = useState({art: null, aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null})
const getPriceList = async () => {
let monthlyPriceList = {art: null, aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null}
let weeklyPriceList = {art: null, aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null}
let dailyPriceList = {art: null, aNEAR: null, aBTC: null, aGOLD: null, aSPY: null, aEUR: null}
for(const p in monthlyPriceList){
let res1 = await fetch(`${API_URL}/${p}/1M`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
res1 = await res1.json()
monthlyPriceList[p] = res1
}
for(const p in weeklyPriceList){
let res2 = await fetch(`${API_URL}/${p}/1W`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
res2 = await res2.json()
weeklyPriceList[p] = res2
}
for(const p in dailyPriceList) {
let res3 = await fetch(`${API_URL}/${p}/1D`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
res3 = await res3.json()
dailyPriceList[p] = res3
}
setMonth(monthlyPriceList)
setWeek(weeklyPriceList)
setDay(dailyPriceList)
}
const getPrice = (array) => {
return array.map((arr) => arr.price.toFixed(2))
}
const getDate = (array) => {
return array.map((arr) => arr.time)
}
useEffect(() => {
async function fetchData() {
await getPriceList()
}
fetchData()
}, [])
const getOption = (title, data, date) => {
return {
title: {
text: title,
textStyle: {
fontWeight: 'bolder',
fontSize: 20
}
},
tooltip: {
trigger: "axis",
},
xAxis: [
{
type: "category",
boundaryGap: false,
data: date,
},
],
yAxis: [
{
type: "value",
splitLine: {
lineStyle: {
color: "white",
},
},
axisLabel : {
formatter: function (value) {
return value > 1000 ? value/1000 + 'k' : value
}
}
},
],
series: [
{
name: "Price: ",
type: "line",
lineStyle: {
color: "#9c87f7",
width: 1,
},
symbol: 'none',
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: "rgb(207, 196, 255)",
},
{
offset: 1,
color: "rgba(236, 232, 255, 0.1)",
},
]),
},
data: data,
},
],
};
};
const Charts = ({index}) => {
return (
<Tabs defaultActiveKey="daily" id="price">
<Tab eventKey="daily" title="1 Day">
<ReactEcharts
option={getOption( index + ' / aUSD', getPrice(day[index]), getDate(day[index]))}
style={{width: '100%', height: '500px'}}
/>
</Tab>
<Tab eventKey="week" title="1 Week">
<ReactEcharts
option={getOption( index + ' / aUSD', getPrice(week[index]), getDate(week[index]))}
style={{width: '100%', height: '780px'}}
/>
</Tab>
<Tab eventKey="month" title="1 Month">
<ReactEcharts
option={getOption( index + ' / aUSD', getPrice(month[index]), getDate(month[index]))}
style={{width: '100%', height: '780px'}}
/>
</Tab>
</Tabs>
);
}
const assetItems = coinList.map((k) =>
<option key={k}>
{k}
</option>
)
const [currentAsset, setCurrentAsset] = useState('art')
return (
<>
<Row noGutters className="p-2" style={{background: '#fff'}}>
<Form.Group controlId="formSelect">
<Form.Control
value={currentAsset}
as="select"
onChange={(event) => {
if (event) {
const value = event.target !== null ? event.target.value : "";
setCurrentAsset(value)
}
}}>
{assetItems}
</Form.Control>
</Form.Group>
</Row>
{day.art !== null ?
<div>
<Charts index={currentAsset} />
</div>
: <Row className="m-2 p-2">
<Spinner animation="border" />
<Spinner animation="border" />
<Spinner animation="border" />
</Row>
}
</>
)
}
export default Markets
|
/*
*
* DenominacaoPage actions
*
*/
import {GET_POSTS, LOAD_POSTS_SUCCESS, LOAD_DENOMINATION_ERROR, CREATE_DENOMINATION, CREATED_DENOMINATION, UPDATE_DENOMINATION, UPDATED_DENOMINATION, DELETE_POST, DELETED_POST, CLEAR_MESSAGE, } from './constants';
export function createDenomination(denomination, user) {
return {
type: CREATE_DENOMINATION,
denomination,
user,
};
}
export function createdDenomination(denomination) {
return {
type: CREATED_DENOMINATION,
denomination,
};
}
export function updateDenomination(denomination, user) {
return {
type: UPDATE_DENOMINATION,
denomination,
user,
};
}
export function updatedDenomination(denomination) {
return {
type: UPDATED_DENOMINATION,
denomination,
};
}
export function getPosts() {
return {
type: GET_POSTS,
};
}
export function postsLoaded(posts) {
return {
type: LOAD_POSTS_SUCCESS,
posts,
};
}
export function denominationLoadingError(error) {
return {
type: LOAD_DENOMINATION_ERROR,
error,
};
}
export function clearMessage() {
return {
type: CLEAR_MESSAGE,
};
}
|
// Esto son primitivos = [1,2,3]
//40 = numeros
// "Diego De Granda" = String o cadenas de texto
// true = Bolianos
// falso
// null = Empty Values or vacios o placeholder
// undefined
// Esto es un Objeto = {nombre: Diego}
|
module.exports = {
port: 3000,
database: {
name: 'twitch-project',
url: 'mongodb://127.0.0.1:27017',
},
secretKey: 'cle_secrete_chakal',
};
|
import { API_URL, GET_CATEGORY_REQUEST, GET_CATEGORY_SUCCESS,
GET_CATEGORY_ERROR } from './../constants';
import fetch from 'isomorphic-fetch';
export const getCategoryReq = () => {
return {
type: GET_CATEGORY_REQUEST
};
};
export const getCategorySuc = (data) => {
return {
type: GET_CATEGORY_SUCCESS,
categories: data
};
};
export const getCategoryErr = (data) => {
return {
type: GET_CATEGORY_ERROR,
error: data
};
};
export const fetchMenuCategory = () => {
return function (dispatch) {
dispatch(getCategoryReq());
return fetch(`${API_URL}/categories/menu`)
.then(function(response) {
if (response.status >= 400) throw new Error("Bad response from server");
return response.json();
})
.then(function(data) {
dispatch(getCategorySuc(data));
});
};
};
|
import {
init
} from './main.js';
import {
initjscolor
} from './jscolor-2.0.5/jscolor.js';
// Initializes all controls and color picker
window.onload = _ => {
initjscolor();
init();
}
|
import React, { Component } from 'react';
import { StyleSheet, View, ScrollView, Text, Image, AsyncStorage, FlatList, TouchableWithoutFeedback, ActivityIndicator } from 'react-native';
import { Card } from 'react-native-elements';
import * as Progress from 'react-native-progress';
import { connect } from 'react-redux';
import * as actions from '../actions';
import _values from 'lodash/values';
import { SectionDescription } from '../components';
import { SCROLL_PADDING_BOTTOM } from 'app/config';
const NumericMetric = props => {
const {
key,
title,
value,
} = props;
return (
<View
key={key}
style={styles.metricContainer}>
<Text
style={styles.metricTitle}>{title}</Text>
<Text
style={styles.numericMetric}>{value}</Text>
</View>
)
}
const CircleMetric = props => {
const {
key,
title,
value,
} = props;
return (
<View
key={key}
style={styles.metricContainer}>
<Text
style={styles.metricTitle}>{title}</Text>
<Progress.Circle
style={styles.circleMetric}
animated={false}
progress={value}
size={55}
borderColor={'#00008b'}
color={'#00008b'}
showsText={true} />
</View>
)
}
const BarMetric = props => {
const {
key,
title,
value,
} = props;
return (
<View
key={key}
style={styles.metricContainer}>
<Text
style={styles.metricTitle}>{title}</Text>
<Progress.Bar
progress={value}
width={300}
borderColor={'#00008b'}
color={'#00008b'} />
</View>
)
}
const PieMetric = props => {
const {
key,
title,
value,
} = props;
return (
<View
key={key}
style={styles.metricContainer}>
<Text
style={styles.metricTitle}>{title}</Text>
<Progress.Pie
style={styles.pieMetric}
progress={value}
size={50}
animated
borderColor={'#00008b'}
color={'#00008b'} />
</View>
)
}
class ProgressScreen extends Component {
static navigationOptions = ({ navigation }) => {
const { navigate } = navigation;
return {
title: 'Progress',
headerTitle: 'Progress',
};
}
componentDidMount() {
this.props.fetchAndHandleUserProgress(this.props.user.info.uid);
}
_getMetricComponent(componentType, id, title, value) {
switch (componentType) {
case 'numeric':
return (
<NumericMetric
key={id}
title={title}
value={value} />
);
case 'progress-circle':
return (
<CircleMetric
key={id}
title={title}
value={value} />
);
case 'pie-chart':
return (
<PieMetric
key={id}
title={title}
value={value} />
);
}
}
render() {
const {isFetching, error, progress } = this.props.user;
const { navigate } = this.props.navigation;
if (isFetching) {
return (
<View style={{ flex: 1, justifyContent: 'center' }}>
<ActivityIndicator size="large" />
</View>
);
} else if (error) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>{error}</Text>
</View>
)
}
return (
<ScrollView>
{progress && _values(progress).length > 1
? _values(progress).map(progressCard => {
return (
<TouchableWithoutFeedback
key={progressCard.id} >
<Card
containerStyle={styles.cardContainer} >
<SectionDescription
title={progressCard.title}
description={progressCard.description} />
<View
style={styles.metricSectionContainer} >
{progressCard.metrics.map(metric => {
return this._getMetricComponent(metric.type, metric.id, metric.title, metric.value)
})}
</View>
</Card>
</TouchableWithoutFeedback>
)
})
: <Text style={{ flex: 1, alignSelf: 'center' }}>
{'Please choose your progress cards in your settings'}
</Text>
}
</ScrollView>
);
}
}
const mapStateToProps = ({ user }) => {
return {
user,
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
},
contentContainer: {
padding: 20,
paddingBottom: SCROLL_PADDING_BOTTOM,
},
cardContainer: {
shadowColor: 'rgba(0,0,0, .2)',
shadowOffset: { height: 2, width: 2 },
shadowOpacity: 1,
shadowRadius: 2,
},
metricSectionContainer: {
flexDirection: 'row',
},
metricContainer: {
flex: 1
},
metricTitle: {
flex: 1,
flexWrap: 'wrap',
fontSize: 16,
alignSelf: 'center',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
paddingBottom: 10,
color: 'grey',
},
numericMetric: {
flex: 1,
fontSize: 35,
alignSelf: 'center',
color: 'darkblue',
},
pieMetric: {
flex: 1,
alignSelf: 'center'
},
circleMetric: {
flex: 1,
alignSelf: 'center',
},
});
export default connect(mapStateToProps, actions)(ProgressScreen);
|
import styled from 'styled-components';
export const FieldContainer = styled.div`
background-color: ${props => (props.isDimmed ? '#f5f5f5 !important' : '#f1f4f6')};
width: 100%;
min-height: 56px;
display: flex;
flex-direction: row;
justify-content: space-between;
padding: 7px 16px;
// margin: 4px 0px;
border-radius: 8px;
border: ${props =>
props.isValid ? '1px solid #e3e6ea !important' : '1px solid #db3226 !important'};
cursor: ${props => (props.isDimmed ? 'unset !important' : 'pointer')};
${props => (props.extendDropDownStyle ? props.extendDropDownStyle : '')};
`;
export const LabelValueContainer = styled.div`
width: 90%;
display: inline-flex;
flex-direction: column;
align-items: center;
justify-content: center;
`;
export const FieldLabel = styled.div`
color: #9c9c9c;
width: 100%;
font-size: ${props => (props.isValueSelected ? '12px' : '16px')};
line-height: ${props => (props.isValueSelected ? '18px' : '40px')};
`;
export const FieldValue = styled.p`
width: 100%;
font-size: 16px;
line-height: 24px;
color: #484848;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
export const ListContainer = styled.div`
position: absolute;
filter: drop-shadow(0px 4px 16px rgba(0, 0, 0, 0.16));
background-color: #fff;
width: 100%;
z-index: 2;
max-height: 210px;
overflow: auto;
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-thumb {
background: #9c9c9c;
border-radius: 15px;
}
box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.16);
border-radius: 8px;
${props => (props.extendDropDownList ? props.extendDropDownList : '')};
`;
export const ListItem = styled.div`
box-shadow: inset 0px -1px 0px #f1f4f6;
padding: 8px 12px 8px 16px;
font-size: 16px;
line-height: 24px;
cursor: ${props => (props.isMultipleSelection ? 'unset' : 'pointer')};
${props => (props.extendDropDownListItem ? props.extendDropDownListItem : '')};
`;
export const ItemLabel = styled.p`
color: #484848;
`;
export const ItemDescription = styled.p`
font-size: 13px;
line-height: 20px;
color: #9c9c9c;
direction: ${props => (props.language === 'ar' ? 'ltr' : 'unset')};
text-align: ${props => (props.language === 'ar' ? 'right' : 'unset')};
`;
export const ItemContentContainer = styled.div`
display: flex;
flex-direction: row;
`;
export const CheckBox = styled.input`
width: 24px;
height: 24px;
margin: 2% 0%;
`;
export const SearchInput = styled.input`
width: 100%;
border: unset;
font-size: 16px;
line-height: 24px;
&:focus {
outline: none;
}
`;
export const IsRequiredNote = styled.p`
display: inline-flex;
margin: 0px 3px;
color: #db3226;
`;
export const DisableOverLay = styled.div`
width: 100%;
min-height: 100%;
border: 1px solid #e3e6ea;
border-radius: 8px;
background-color: #f1f4f69c;
position: absolute;
display: ${props => (!props.isDisabled ? 'none' : 'block')};
`;
|
var lang = "ch";
var localizableStrings = {
"requireUsername":"必须填写用户名",
"usernameMinLength":"用户名至少为2个字符",
"usernameMaxLength":"用户名至多为23个字符",
"requirePassword":"用户名至多为23个字符",
"passwordMinLength":"密码至少为6个字符",
"passwordMaxLength":"密码至多为23个字符",
"usernameFormatError":"用户名必须是2-23个字符,不包含空格",
"passwordFormatError":"密码由6到23个数字、字母和特殊字符组成"
}; |
import HolbertonCourse from './2-hbtn_course';
const c1 = new HolbertonCourse('ES6', 1, ['Bob', 'Jane']);
console.log(c1.name);
c1.name = 'Python 101';
console.log(c1);
try {
c1.name = 'test';
} catch (err) {
console.log(err);
}
try {
const c2 = new HolbertonCourse('ES6', 1, ['Bob', 'Jane']);
console.log(c2)
} catch (err) {
console.log(err);
}
|
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import Aos from "aos";
import "aos/dist/aos.css"
// component
import CartItem from "../components/CartItem";
// Actions
import { addToCart, removeFromCart } from "../redux/actions/cartActions";
function CartScreen() {
useEffect(() => {
Aos.init({ duration: 1500 });
}, [])
const dispatch = useDispatch();
const cart = useSelector((state) => state.cart);
const { cartItems } = cart;
const qtyChangeHandler = (id, qty) => {
dispatch(addToCart(id, qty));
};
const removeHandler = (id) => {
dispatch(removeFromCart(id));
};
const getCartCount = () => {
return cartItems.reduce((qty, item) => Number(item.qty) + qty, 0);
}
const getCartSubtotal = () => {
return cartItems.reduce((price, item) => item.price * item.qty + price, 0);
}
return (
<div className="container p-sm-5">
<h2 className="pt-3 pt-sm-0 pb-4 text-center fs-2 fw-bold">
Shopping Cart
</h2>
<div className="row">
{cartItems.length === 0 ? (
<div>
Your Cart is empty <Link to="/">Go Back</Link>
</div>
) : (
cartItems.map((item) => (
<CartItem
key={item.product}
item={item}
qtyChangeHandler={qtyChangeHandler}
removeHandler={removeHandler}
/>
))
)}
<div className="col-sm-3 mt-3 mt-sm-0">
<div className="card boxShadow" data-aos="fade-up" style={{ width: "18rem" }}>
<ul className="list-group mb-2">
<li className="list-group-item">
<h5>Subtotal ({getCartCount()}) items</h5>
<p>#{getCartSubtotal().toFixed(2)}</p>
</li>
</ul>
<p className="text-center mb-2">
<button className="btn btn-outline-info">
Proceed to checkbox
</button>
</p>
</div>
</div>
</div>
</div>
);
}
export default CartScreen;
|
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import styled, { keyframes } from 'styled-components'
import { hideToast } from '../features/appSlice'
const Toast = ({toast,}) => {
const dispatch = useDispatch()
const [show, setShow] = useState(true)
useEffect(()=>{
setShow(true)
setTimeout(() => {
setShow(false)
setTimeout(() => {
dispatch(hideToast())
}, 700);
}, 3000);
},[toast])
return (
<StyledToast show={show}>
{toast.message}
</StyledToast>
)
}
const showAnim = keyframes`
from{transform: translateY(200%)}
to{transform: translateX(0)}
`
const hideAnim = keyframes`
from{transform: translateX(0)}
to{transform: translateY(200%)}
`
const StyledToast = styled.div`
position: fixed;
bottom:0;
left:0;
border-radius:5px;
background-color: rgb(40,40,40);
margin: 22px;
padding: .7rem 1rem;
min-width: min(25rem,80vw);
z-index:101;
color:#fafafa;
animation: ${p => p.show?showAnim:hideAnim} .7s linear forwards;
transform: translateX(-200%);
`
export default Toast
|
'use strict'
let mongoose = require('mongoose'),
Schema = mongoose.Schema
let aliveSchema = new Schema({
raspberryid : String,
alivedate : String
})
module.exports = mongoose.model('Alive', aliveSchema)
|
import React from 'react';
import PropTypes from 'prop-types';
import '../../styles/flashcard.css';
import FlashcardDecksComp from './FlashcardDecksComp';
import SelectLevelComp from './SelectLevelComp';
import ActionBarComp from '../ActionBarComp';
import ReviewComp from './ReviewComp';
class FlashcardPlayComp extends React.Component {
constructor() {
super();
this.state = {
showAdd: true,
showBack: false,
headerText: 'Play Decks',
currentDeck: {},
currentView: 'FlashcardDecks',
};
}
handleAddClick = () => {
const { onAdd } = this.props;
onAdd();
}
setView = (newView = 'FlashcardDecks') => {
let showAdd = false;
let headerText = '';
let viewName = newView;
switch (newView) {
case 'FlashcardDecks':
headerText = 'Play Decks';
showAdd = true;
break;
case 'SelectLevel':
headerText = 'Choose Level';
showAdd = false;
break;
case 'Review':
headerText = 'Review';
break;
case 'Recognize':
headerText = 'Recognize';
break;
case 'Produce':
headerText = 'Produce';
break;
case 'Phrase':
headerText = 'Phrase';
break;
default:
viewName = 'FlashcardDecks';
headerText = 'Play Decks';
showAdd = true;
}
this.setState({
currentView: viewName,
showAdd,
headerText,
});
}
handleDeckSelect = (deck) => {
console.log('select deck 2, need to render game select screen');
console.log('deck is ', deck);
this.setState({ currentDeck: deck });
this.setView('SelectLevel');
}
handleLevelSelect = (level) => {
console.log('level selected: ', level);
this.setView(level);
}
handleReviewDone = () => {
console.log('review done for this level');
this.setView('SelectLevel');
}
render() {
const {
currentView,
currentDeck,
showAdd,
showBack,
headerText,
} = this.state;
return (
<div className="FlashcardPlayComp">
<ActionBarComp
showAdd={showAdd}
showBack={showBack}
headerText={headerText}
onAdd={this.handleAddClick}
/>
{ (currentView === 'FlashcardDecks')
? <FlashcardDecksComp onDeckSelect={this.handleDeckSelect} />
: null
}
{ (currentView === 'SelectLevel')
? <SelectLevelComp onLevelSelect={this.handleLevelSelect} />
: null
}
{ (currentView === 'Review')
? <ReviewComp deck={currentDeck} onReviewDone={this.handleReviewDone} />
: null
}
</div>
);
}
}
FlashcardPlayComp.defaultProps = {
onAdd: () => { },
};
FlashcardDecksComp.propTypes = {
onAdd: PropTypes.func,
};
export default FlashcardPlayComp;
|
function find(num, i) {
let bitStatus = num & (1 << (i - 1));
if (bitStatus) {
console.log("set");
} else {
console.log("Not set");
}
}
find(14, 4);
find(14, 1); |
const { MessageEmbed, Message, Client } = require("discord.js");
const config = require("../config.json");
class BoltyGiveaways {
/**
* @param {Message} message
* @param {Client} client
*/
static BoltyGiveawayEmbed(client, message) {
return new MessageEmbed()
.setFooter(`Bolty * Giveaway Manager`, client.user.displayAvatarURL())
.setAuthor(`Giveaway Manager`, client.user.displayAvatarURL())
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.setTimestamp(new Date())
.setColor(config.colors.differentYellow);
}
static BoltyEmotes = {
info: "<:info:855396289798078465>",
fun: "<a:fun:855398438547619860>",
mod: "<:mod:855399096315019294>",
wrong_error: "<:error:856125687567613973>",
success: "<:success:855888059978743819>",
};
static BoltyUrls = {
successLink: "https://cdn.discordapp.com/emojis/801791545060884510.png?v=1",
errorLink: "https://emoji.discord.st/emojis/Error.png",
};
}
module.exports = BoltyGiveaways;
|
import React from "react"
import { Embed } from "@theme-ui/components"
const Video = ({ value }) => {
const split = value && value.url && value.url.split("/")
const id = split && split[split.length - 1]
const url = `https://streamja.com/embed/${id}`
if (!id) {
return <div>Missing Youtube url</div>
}
return <Embed src={url} sx={{ width: "100%", height: "100%" }} />
}
export default Video
|
function setup() {
createCanvas(500, 500);
graphic = createGraphics(500, 500);
graphic.fill("#ef5236");
graphic.textSize(400);
graphic.textAlign(CENTER, CENTER);
graphic.text("01", width / 2, height / 2);
graphic1 = createGraphics(500, 500);
graphic1.fill("#ef5236");
graphic1.textSize(400);
graphic1.textAlign(CENTER, CENTER);
graphic1.text("23", width / 2, height / 2);
}
function draw() {
background("#ecf072");
let val = sin(frameCount * 0.03) * 250;
copy(graphic, 0, 0, 250 + val, 500, 0, 0, 250 + val, 500)
copy(graphic1, 250 + val, 0, 250 - val, 500, 250 + val, 0, 250 - val, 500)
} |
(function () {
/**
* 一些Handlebar的指令
*
* @param {any} src
* @param {any} callback
*/
Handlebars.registerHelper("equal", function (v1, v2, options) {
if (v1 == v2) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Util.loadCSS(Util.getBasePath(document.currentScript.src) + '/style.css')
})()
window.PointTypes = (function () {
var currentScriptSrc = Util.getBasePath(document.currentScript.src)
// 点读点类型
var POINTTYPES = [
{
title: '通用',
types: [
{ label: '视频', type: 'video', text: '点击上传MP4格式的视频文件', tip: '视频须为AVC(h264)编码格式的MP4文件<br/>视频点设置可定制图片和播放区域' },
{ label: '音频', type: 'audio', text: '点击上传MP3格式的音频文件', tip: 'MP3文件音频点设置可定制图片和播放区域' },
{ label: '注解', type: 'imgtext', text: '点击上传注解', tip: '注解可以使用图片和文字来展示一些需要描述的文案' },
{ label: '测试', type: 'exam', text: '点击上传测试考题', tip: '点读里面的测试考题,分为单选,多选,判断题' },
{ label: '超链接', type: 'set-url', text: '点击设置超级链接', tip: '超链接就是点击点读点,跳转到指定的链接地址' },
{ label: '3D观察器', type: 'viewer3d', text: '请上传obj模型文件', tip: '3D文件限定为obj模型文件,可以进行缩放和旋转操作' },
]
},
{
title: '单图特效',
hide: true,
types: [
{ label: '开关图', type: 'on-off', text: '点击设置开关', tip: '设置最初隐藏或显示的图片,在图片位置或其他指定位置,点击后切换显隐状态。' },
{ label: '摇摆图', type: 'sway', text: '请直接采用点触发进行设置', tip: '摇摆图是简单的动画,就是点击图片后,图片摆动或者适当缩放,并可配置音效' },
]
}
]
/**
* 点读点类型弹窗
* @param {any} selector 弹窗对应的点读点
* @param {any} selectedType 选中的类型
*/
function PointTypes(options) {
var that = this
Util.getTpl(currentScriptSrc + '/tpl.html', function (tpl) {
var tpls = Handlebars.compile(tpl)
var configData = POINTTYPES || []
configData.selected = options.selectedType
$('#__pointTypes__').remove()
var div = document.createElement('div')
div.setAttribute('id', '__pointTypes__')
document.body.append(div)
$(div).append(tpls(configData))
$(div).css({ left: options.offset.left - 140, top: options.offset.top - 320 })
that.initVar(options)
that.bindEvent()
that.setData(options)
})
}
// 初始化变量
PointTypes.prototype.initVar = function (options) {
options = options || {}
this.closeCallback = options.closeCallback
this.$container = $('#__pointTypes__')
this.$pointTypeItem = this.$container.find('.point-types__item')
this.$tip = this.$container.find('.js-pt-tip')
this.$wrapper = this.$container.find('.js-point-types-wrapper')
this.$categoryTitle = this.$container.find('.point-types__category-title')
}
// 绑定点击事件
PointTypes.prototype.bindEvent = function () {
var that = this
this.$wrapper.on('click', function () {
that.close()
})
// 点读类型点击事件
this.$pointTypeItem
.on('click', function (e) {
var $cTar = $(e.currentTarget)
$.each(that.$pointTypeItem, function (item, el) {
$(el).removeClass('pt-selected')
})
$cTar.addClass('pt-selected')
that.data = $.extend(that.data, $cTar.data())
if (that.closeCallback) {
that.closeCallback(that.data)
}
that.close()
})
.on('mouseover', function (e) {
that.$tip.show()
var $cTar = $(e.currentTarget)
var tip = $cTar.data('tip')
var html = '<p>' + tip + '</p>'
that.$tip.html(html)
})
.on('mouseout', function (e) {
that.$tip.html('')
that.$tip.hide()
})
//显示隐藏点读点类别
this.$categoryTitle.on('click', function (e) {
var $cTar = $(e.currentTarget)
var $categoryContent = $cTar.next()
if ($categoryContent.hasClass('point-types__category--hide')) {
$categoryContent.removeClass('point-types__category--hide')
} else {
$categoryContent.addClass('point-types__category--hide')
}
})
}
// 编辑设置数据
PointTypes.prototype.setData = function () {
this.data = {}
}
// 编辑设置数据
PointTypes.prototype.close = function () {
this.$container.remove()
}
return PointTypes
})()
|
export default (state = [], action) => {
let {type, payload} = action
switch(type){
//Admin reducers
case 'CREATE_FLIGHT': return [payload, ...state]
case 'FETCH_FLIGHTS': return payload
case 'FETCH_FLIGHT': return payload
case 'DELETE_FLIGHT': return state.filter(item => item._id !== payload._id)
//User reducers
case 'FLIGHT_SEARCH': return payload.flightsOut
case 'ASCENDING_FIRST_CLASS_FILTER' : return payload.sort((flightA, flightB) => flightA.firstClassPrice - flightB.firstClassPrice)
case 'DESCENDING_FIRST_CLASS_FILTER': return payload.sort((flightA, flightB) => flightB.firstClassPrice - flightA.firstClassPrice)
case 'ASCENDING_MAIN_CABIN_FILTER' : return payload.sort((flightA, flightB) => flightA.standardClassPrice - flightB.standardClassPrice)
case 'DESCENDING_MAIN_CABIN_FILTER' : return payload.sort((flightA, flightB) => flightB.standardClassPrice - flightA.standardClassPrice)
case 'ASCENDING_TIME_FILTER': return payload.sort((flightA, flightB) => flightA.departureMilitary - flightB.departureMilitary)
case 'DESCENDING_TIME_FILTER': return payload.sort((flightA, flightB) => flightB.departureMilitary - flightA.departureMilitary)
default: return state
}
} |
var routerApp = angular.module('myApp', [ 'ui.router' ]);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url : '/home',
views : {
'' : {
templateUrl : 'partial-home.html',
controller : 'schoolDataControllerHome'
}
}
})
// ABOUT PAGE AND MULTIPLE NAMED VIEWS =================================
.state('about', {
url : '/about',
views : {
'' : {
templateUrl : 'partial-about.html'
},
'columnOne@about' : {
template : 'Look I am a column!'
},
'columnTwo@about' : {
templateUrl : 'table-data.html',
controller : 'schoolDataControllerAbout'
}
}
});
});
|
// Initialize Firebase
var config = {
apiKey: "AIzaSyDAH4ttxo62nfrq_bWy1XHThcliADAkxSk",
authDomain: "poll-4bd5d.firebaseapp.com",
databaseURL: "https://poll-4bd5d.firebaseio.com",
projectId: "poll-4bd5d",
storageBucket: "poll-4bd5d.appspot.com",
messagingSenderId: "421307063575"
};
firebase.initializeApp(config);
|
JournalApp.Views.PostForm = Backbone.View.extend({
template: JST['posts/form'],
events: {
"submit form" : "addPost"
},
render: function () {
var content = this.template( { post: this.model });
this.$el.html(content);
return this;
},
addPost: function(event) {
event.preventDefault();
this.$el.find($('.error')).empty();
var formData = $('form').serializeJSON();
this.model.save(
formData.post, {
update: true,
wait: true,
success: function() {
Backbone.history.navigate("posts/" + this.model.id, {trigger: true});
}.bind(this),
error: function (model, response) {
this.$el.append($('<p>').addClass('error').text(response.responseJSON));
}.bind(this)
});
}
});
|
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
let quotes = [
{
quote: "Roads? Where we're going, we don't need roads.",
author: "Doc Emmet Brown"
},
{
quote: "I'll be back.",
author: "T-800"
},
{
quote: "I'm sorry, Dave. I'm afraid I can't do that.",
author: "HAL2000"
},
{
quote: "Lets rock.",
author: "Pvt. Vasquez"
},
{
quote: "Every champion was once a contender who refused to give up.",
author: "Rocky Balboa"
},
{
quote: "There's no place like home.",
author: "Dorothy Gale"
},
{
quote: "Go ahead. Make my Day.",
author: "Harry Callahan"
},
{
quote: "Try not. Do or do not. There is no try.",
author: "Yoda"
},
]
class Application extends React.Component {
constructor(props) {
super(props)
//drawed state with default number of quote at first time render
this.state = {
drawedNumber: 1
}
this.drawQuote = this.drawQuote.bind(this);
}
//Method to generate new random number from quotes number range
drawQuote() {
this.setState({
drawedNumber: Math.floor(Math.random() * quotes.length)
})
}
render() {
// selectedQuotes with exact quote selected by random number from drawQuote method
let selectedQuote = quotes[this.state.drawedNumber]
return (
<div clasName="container">
<h1>{selectedQuote.quote}</h1>
<p>{selectedQuote.author}
</p>
<button className='buttonf' onClick={this.drawQuote}>Pick another quote</button>
</div>
)
}
}
ReactDOM.render(<Application />, document.getElementById('app')); |
import ActionTypes from './ActionTypes';
import BranchStateApi from '../data/BranchStateApi';
import { PAGE_SIZE } from '../constants/ModuleBuildActivity';
const computeBuildNumberOffset = (buildHistory, page) => {
if (page === 1) return null;
const startingBuildNumber = buildHistory.get('startingBuildNumber');
return startingBuildNumber - (page - 1) * PAGE_SIZE;
};
export const loadModuleBuildHistory = (moduleId, maybePage) => {
return (dispatch, getState) => {
const requestStartTime = Date.now();
dispatch({
type: ActionTypes.REQUEST_MODULE_BUILD_HISTORY,
payload: {moduleId, requestStartTime}
});
const buildHistory = getState().moduleBuildHistoriesByModuleId.get(moduleId);
const page = maybePage || buildHistory.get('page');
const offset = computeBuildNumberOffset(buildHistory, page);
return BranchStateApi.fetchModuleBuildHistory(moduleId, offset, PAGE_SIZE)
.then((moduleActivityPage) => {
dispatch({
type: ActionTypes.RECEIVE_MODULE_BUILD_HISTORY,
payload: {moduleId, moduleActivityPage, page}
});
});
};
};
export const selectPage = (moduleId, page) => {
return (dispatch) => {
dispatch({
type: ActionTypes.SELECT_MODULE_BUILD_HISTORY_PAGE,
payload: {moduleId, page}
});
dispatch(loadModuleBuildHistory(moduleId, page));
};
};
|
var rJS = require('./rewriteJS.js');
var cfgb = require('./callBuilder.js');
var abst = rJS.rewriteJS('simpleCode.js')
var genStates = cfgb.build(abst);
//console.log(genStates.all);
var pr = require('./printGraph.js');
pr.print(genStates.all, './graph.gv');
var lattice = require('./simpleIntegerLattice.js');
var eng = require('./fixPointEngine.js');
eng.init(genStates.all, lattice);
eng.run(genStates.all);
eng.printAllVariablesAtTheEnd(genStates.last);
|
import React, { PureComponent } from "react";
import FormSignup from "../common/FormSignup"
export default class AuthSignup extends PureComponent {
render() {
return (
<FormSignup/>
);
}
}
|
'use strict';
/**
* Returns the config for the dashboard.
*/
module.exports = function * () {
try {
// Init output object.
const output = {};
// Set the config.
output.settings = {
url: strapi.config.url,
i18n: strapi.config.i18n
};
// Set the models.
output.models = strapi.models;
// Format `config.api` for multi templates models.
_.forEach(strapi.api, function (api, key) {
if (api.templates) {
output.models[key].templates = {};
}
// Assign the template attributes with the model attributes.
_.forEach(api.templates, function (template, templateName) {
output.models[key].templates[templateName] = {};
output.models[key].templates[templateName].attributes = {};
_.forEach(template.attributes, function (value, attributeKey) {
output.models[key].templates[templateName].attributes[attributeKey] = _.cloneDeep(output.models[key].attributes[attributeKey]);
});
output.models[key].templates[templateName].displayedAttribute = template.displayedAttribute;
});
});
// User count.
const promises = [];
promises.push(strapi.orm.collections.user.count());
// Execute promises.
const response = yield promises;
// Define if the app is considered as new.
const userCount = response[0];
output.settings.isNewApp = !userCount;
// Finally send the result in the callback.
this.body = output;
} catch (err) {
this.status = 500;
this.body = err;
}
};
|
import React, { Component } from "react";
export default class Todo extends Component {
shouldComponentUpdate(nextProps){
let {data:nextData} = nextProps;
let {data} = this.props;
// console.log(nextData.done,nextData.title,"next");
// console.log(data.done,data.title,"now");
// if(nextData.done===data.done&&nextData.title==data.title){
// return false;
// }
// return true;
return !(nextData.done===data.done&&nextData.title===data.title);
}
render(){
let {data,remove,changeDone} = this.props;
let {id,title,done} = data;
console.log("render",id);
return <li>
<div className={"todo "+ (done?"done":"")}>
<div className="display">
<input
className="check"
type="checkbox"
checked={done}
onChange={({target})=>{
changeDone(id,target.checked)
}}
/>
<div className="todo-content">{title}</div>
<span className="todo-destroy" onClick={()=>{
remove(id);
}}></span>
</div>
</div>
</li>
}
} |
'use strict';
/*jslint latedef:false*/
(function() {
angular.module('o19s.splainer-search')
.factory('SolrSearcherFactory', [
'$http',
'$q',
'$sce',
'$log',
'SolrDocFactory',
'SearcherFactory',
'activeQueries',
'defaultSolrConfig',
'solrSearcherPreprocessorSvc',
SolrSearcherFactory
]);
function SolrSearcherFactory(
$http, $q, $sce, $log,
SolrDocFactory, SearcherFactory,
activeQueries, defaultSolrConfig,
solrSearcherPreprocessorSvc
) {
var Searcher = function(options) {
SearcherFactory.call(this, options, solrSearcherPreprocessorSvc);
};
Searcher.prototype = Object.create(SearcherFactory.prototype);
Searcher.prototype.constructor = Searcher; // Reset the constructor
Searcher.prototype.addDocToGroup = addDocToGroup;
Searcher.prototype.pager = pager;
Searcher.prototype.search = search;
Searcher.prototype.explainOther = explainOther;
function addDocToGroup (groupedBy, group, solrDoc) {
/*jslint validthis:true*/
var self = this;
if (!self.grouped.hasOwnProperty(groupedBy)) {
self.grouped[groupedBy] = [];
}
var found = null;
angular.forEach(self.grouped[groupedBy], function(groupedDocs) {
if (groupedDocs.value === group && !found) {
found = groupedDocs;
}
});
if (!found) {
found = {docs:[], value:group};
self.grouped[groupedBy].push(found);
}
found.docs.push(solrDoc);
}
// return a new searcher that will give you
// the next page upon search(). To get the subsequent
// page, call pager on that searcher ad infinidum
function pager () {
/*jslint validthis:true*/
var self = this;
var start = 0;
var rows = self.config.numberOfRows;
var nextArgs = angular.copy(self.args);
if (nextArgs.hasOwnProperty('rows')) {
rows = parseInt(nextArgs.rows);
}
if (nextArgs.hasOwnProperty('start')) {
start = parseInt(nextArgs.start) + rows;
if (start >= self.numFound) {
return null; // no more results
}
} else {
start = rows;
}
nextArgs.rows = ['' + rows];
nextArgs.start = ['' + start];
var pageConfig = defaultSolrConfig;
pageConfig.sanitize = false;
var options = {
fieldList: self.fieldList,
url: self.url,
args: nextArgs,
queryText: self.queryText,
config: pageConfig,
type: self.type,
HIGHLIGHTING_PRE: self.HIGHLIGHTING_PRE,
HIGHLIGHTING_POST: self.HIGHLIGHTING_POST,
};
var nextSearcher = new Searcher(options);
return nextSearcher;
}
// search (execute the query) and produce results
// to the returned future
function search () {
/*jslint validthis:true*/
var self = this;
var url = self.callUrl;
self.inError = false;
var thisSearcher = self;
var getExplData = function(solrResp) {
if (solrResp.hasOwnProperty('debug')) {
var dbg = solrResp.debug;
if (dbg.hasOwnProperty('explain')) {
return dbg.explain;
}
}
return {};
};
var getOthersExplained = function(solrResp) {
if (solrResp.hasOwnProperty('debug')) {
var dbg = solrResp.debug;
if (dbg.hasOwnProperty('explainOther')) {
return dbg.explainOther;
}
}
};
var getHlData = function(solrResp) {
if (solrResp.hasOwnProperty('highlighting')) {
return solrResp.highlighting;
}
return {};
};
activeQueries.count++;
return $q(function(resolve, reject) {
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, { jsonpCallbackParam: 'json.wrf' })
.then(function success(resp) {
var solrResp = resp.data;
activeQueries.count--;
var explDict = getExplData(solrResp);
var hlDict = getHlData(solrResp);
thisSearcher.othersExplained = getOthersExplained(solrResp);
var parseSolrDoc = function(solrDoc, groupedBy, group) {
var options = {
groupedBy: groupedBy,
group: group,
fieldList: self.fieldList,
url: self.url,
explDict: explDict,
hlDict: hlDict,
highlightingPre: self.HIGHLIGHTING_PRE,
highlightingPost: self.HIGHLIGHTING_POST,
};
return new SolrDocFactory(solrDoc, options);
};
if (solrResp.hasOwnProperty('response')) {
angular.forEach(solrResp.response.docs, function(solrDoc) {
var doc = parseSolrDoc(solrDoc);
thisSearcher.numFound = solrResp.response.numFound;
thisSearcher.docs.push(doc);
});
} else if (solrResp.hasOwnProperty('grouped')) {
angular.forEach(solrResp.grouped, function(groupedBy, groupedByName) {
thisSearcher.numFound = groupedBy.matches;
// add docs for a top level group
//console.log(groupedBy.doclist.docs);
if (groupedBy.hasOwnProperty('doclist')) {
angular.forEach(groupedBy.doclist.docs, function (solrDoc) {
var doc = parseSolrDoc(solrDoc, groupedByName, solrDoc[groupedByName]);
thisSearcher.docs.push(doc);
thisSearcher.addDocToGroup(groupedByName, solrDoc[groupedByName], doc);
});
}
// add docs for Field Collapsing results
angular.forEach(groupedBy.groups, function(groupResp) {
var groupValue = groupResp.groupValue;
angular.forEach(groupResp.doclist.docs, function(solrDoc) {
var doc = parseSolrDoc(solrDoc, groupedByName, groupValue);
thisSearcher.docs.push(doc);
thisSearcher.addDocToGroup(groupedByName, groupValue, doc);
});
});
});
}
resolve();
}, function error(msg) {
activeQueries.count--;
thisSearcher.inError = true;
msg.searchError = 'Error with Solr query or server. Contact Solr directly to inspect the error';
reject(msg);
}).catch(function(response) {
$log.debug('Failed to run search');
return response;
});
});
} // end of search()
function explainOther (otherQuery, fieldSpec) {
/*jslint validthis:true*/
var self = this;
// var args = angular.copy(self.args);
self.args.explainOther = [otherQuery];
solrSearcherPreprocessorSvc.prepare(self);
// TODO: revisit why we perform the first search, doesn't seem to have
// any use!
return self.search()
.then(function() {
var start = 0;
var rows = self.config.numberOfRows;
if ( angular.isDefined(self.args.rows) && self.args.rows !== null ) {
rows = self.args.rows;
}
if ( angular.isDefined(self.args.start) && self.args.start !== null ) {
start = self.args.start;
}
var solrParams = {
qf: [fieldSpec.title + ' ' + fieldSpec.id],
rows: [rows],
start: [start],
q: [otherQuery]
};
var otherSearcherOptions = {
fieldList: self.fieldList,
url: self.url,
args: solrParams,
queryText: otherQuery,
config: {
numberOfRows: self.config.numberOfRows
},
type: self.type,
HIGHLIGHTING_PRE: self.HIGHLIGHTING_PRE,
HIGHLIGHTING_POST: self.HIGHLIGHTING_POST,
};
var otherSearcher = new Searcher(otherSearcherOptions);
return otherSearcher.search()
.then(function() {
self.numFound = otherSearcher.numFound;
self.docs = otherSearcher.docs;
});
}).catch(function(response) {
$log.debug('Failed to run explainOther');
return response;
});
}
// Return factory object
return Searcher;
}
})();
|
'use strict';
require('dotenv').config(); // MARK: Import sections
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = require(path.dirname(require.main.filename) + '/../../config/sequelize');
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.database.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database.database, config.database.username, config.database.password, { ...config.database });
}
import User from './user'
import Teacher from './teacher'
import Course from './course'
import CourseUser from './course_user'
const models = {
User: User.init(sequelize, Sequelize),
Teacher: Teacher.init(sequelize, Sequelize),
Course: Course.init(sequelize, Sequelize),
CourseUser: CourseUser.init(sequelize, Sequelize)
};
// Run `.associate` if it exists,
// ie create relationships in the ORM
Object.values(models)
.filter(model => typeof model.associate === "function")
.forEach(model => model.associate(models));
const db = {
...models,
sequelize,
Sequelize
};
module.exports = db;
|
const OMDbApi = 'http://www.omdbapi.com/?i=tt3896198&apikey=9b41e244';
const weatherURL = 'https://api.openweathermap.org/data/2.5/weather?';
const fourURL = 'https://api.foursquare.com/v3/places/search?near=';
async function getPlaces() {
const options = {
method: 'GET',
Headers: {
Accept: 'application/json',
Authorization: 'fsq308P0zTuLC+KTx8lsm5gUA+BfockSNCmE7QZHhErNY2Q=',
},
mode: 'no-cors',
};
try {
const city = document.getElementById('fours').value;
const urlToFetch = `${fourURL}${city}&limit=5`;
const response = await fetch(urlToFetch, options);
if (response.ok) {
console.log(response);
}
} catch (error) {
console.log(error);
}
}
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', function () {
getPlaces();
});
|
/*
Copyright 2017 Linux Academy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const { test } = require('ava');
const sinon = require('sinon');
const getOrCreateS3BucketId = require('../../middleware/getOrCreateS3BucketId.js');
const verifyMocks = (t) => {
t.context.mockRes.json.verify();
t.context.mockRes.status.verify();
t.context.mockReq.app.locals.dynamodb.getItem.verify();
t.context.mockReq.app.locals.dynamodb.putItem.verify();
t.context.mockReq.app.locals.uuid.verify();
t.context.mockNext.verify();
};
test.beforeEach((t) => {
// eslint-disable-next-line no-param-reassign
t.context.mockRes = {
json: sinon.mock(),
status: sinon.mock(),
};
// eslint-disable-next-line no-param-reassign
t.context.mockReq = {
app: {
locals: {
dynamodb: {
getItem: sinon.mock(),
putItem: sinon.mock(),
},
s3Bucket: 'testBucket',
table: 's3-photos-bucket-id',
uuid: sinon.mock(),
},
},
};
// eslint-disable-next-line no-param-reassign
t.context.mockNext = sinon.mock();
});
test.cb('should set the s3Bucket from if record does not exist', (t) => {
t.context.mockReq.app.locals.uuid
.once()
.withArgs()
.returns('111');
t.context.mockReq.app.locals.dynamodb.putItem
.once()
.callsFake((item) => {
t.is(item.Item.id.S, '1');
t.is(item.Item.s3BucketId.S, '111');
t.is(item.TableName, t.context.mockReq.app.locals.table);
return {
promise: sinon.mock().resolves({}),
};
});
t.context.mockReq.app.locals.dynamodb.getItem.never();
t.context.mockRes.status.never();
t.context.mockRes.json.never();
t.context.mockNext
.once()
.callsFake(() => {
t.is(t.context.mockReq.app.locals.s3Bucket, '111');
verifyMocks(t);
t.end();
});
getOrCreateS3BucketId(t.context.mockReq, t.context.mockRes, t.context.mockNext);
});
test.cb('should set the s3Bucket from dynamo if record already exists', (t) => {
t.context.mockReq.app.locals.uuid
.once()
.withArgs()
.returns('222');
t.context.mockReq.app.locals.dynamodb.putItem
.once()
.callsFake((item) => {
t.is(item.Item.id.S, '1');
t.is(item.Item.s3BucketId.S, '222');
t.is(item.TableName, t.context.mockReq.app.locals.table);
return {
promise: sinon.mock().rejects({ code: 'ConditionalCheckFailedException' }),
};
});
t.context.mockReq.app.locals.dynamodb.getItem
.once()
.callsFake((item) => {
t.is(item.Key.id.S, '1');
t.is(item.TableName, t.context.mockReq.app.locals.table);
return {
promise: sinon.mock().resolves({
Item: {
id: { S: '1' },
s3BucketId: { S: '111' },
},
}),
};
});
t.context.mockRes.status.never();
t.context.mockRes.json.never();
t.context.mockNext
.once()
.callsFake(() => {
t.is(t.context.mockReq.app.locals.s3Bucket, '111');
verifyMocks(t);
t.end();
});
getOrCreateS3BucketId(t.context.mockReq, t.context.mockRes, t.context.mockNext);
});
test.cb('should call res.json if DynamoDB table is still being created', (t) => {
t.context.mockReq.app.locals.uuid
.once()
.withArgs()
.returns('111');
t.context.mockReq.app.locals.dynamodb.putItem
.once()
.callsFake((item) => {
t.is(item.Item.id.S, '1');
t.is(item.Item.s3BucketId.S, '111');
t.is(item.TableName, t.context.mockReq.app.locals.table);
return {
promise: sinon.mock().rejects({ code: 'ResourceNotFoundException' }),
};
});
t.context.mockReq.app.locals.dynamodb.getItem.never();
t.context.mockRes.status
.once()
.withArgs(500)
.returns(t.context.mockRes);
t.context.mockRes.json
.once()
.callsFake((e) => {
t.is(e.code, 'ResourceNotFoundException');
verifyMocks(t);
t.end();
});
t.context.mockNext.never();
getOrCreateS3BucketId(t.context.mockReq, t.context.mockRes, t.context.mockNext);
});
test.cb('should call res.json if DynamoDB table rejects with unexpected error', (t) => {
t.context.mockReq.app.locals.uuid
.once()
.withArgs()
.returns('222');
t.context.mockReq.app.locals.dynamodb.putItem
.once()
.callsFake((item) => {
t.is(item.Item.id.S, '1');
t.is(item.Item.s3BucketId.S, '222');
t.is(item.TableName, t.context.mockReq.app.locals.table);
return {
promise: sinon.mock().rejects(new Error('oops')),
};
});
t.context.mockReq.app.locals.dynamodb.getItem.never();
t.context.mockRes.status
.once()
.withArgs(500)
.returns(t.context.mockRes);
t.context.mockRes.json
.once()
.callsFake((e) => {
t.is(e.message, 'oops');
verifyMocks(t);
t.end();
});
t.context.mockNext.never();
getOrCreateS3BucketId(t.context.mockReq, t.context.mockRes, t.context.mockNext);
});
|
/**
* @provides javelin-behavior-dashboard-tab-panel
* @requires javelin-behavior
* javelin-dom
* javelin-stratcom
*/
JX.behavior('dashboard-tab-panel', function() {
JX.Stratcom.listen('click', 'dashboard-tab-panel-tab', function(e) {
e.kill();
var ii;
var idx = e.getNodeData('dashboard-tab-panel-tab').idx;
var root = e.getNode('dashboard-tab-panel-container');
var data = JX.Stratcom.getData(root);
// Give the tab the user clicked a selected style, and remove it from
// the other tabs.
var tabs = JX.DOM.scry(root, 'li', 'dashboard-tab-panel-tab');
for (ii = 0; ii < tabs.length; ii++) {
JX.DOM.alterClass(tabs[ii], 'phui-list-item-selected', (ii == idx));
}
// Switch the visible content to correspond to whatever the user clicked.
for (ii = 0; ii < data.panels.length; ii++) {
var panel = JX.$(data.panels[ii]);
if (ii == idx) {
JX.DOM.show(panel);
} else {
JX.DOM.hide(panel);
}
}
});
});
|
var structBrowserState =
[
[ "entry", "structBrowserState.html#aa19b29c955ad5d70625e74635ad9c04c", null ],
[ "imap_browse", "structBrowserState.html#afe46fc676a2a691f2a4abbdde7c55c9b", null ],
[ "folder", "structBrowserState.html#a103b46ca5b0d6d1c3982aef869343601", null ]
]; |
/**
* Created by epr on 18/09/14.
*/
function jobsController($scope,$http){
}
|
export * from './products/productActions'
|
/// <reference types="cypress" />
//elements
const titleOfTesterHotelOverviewPage = 'Testers Hotel'
const contentToConfirm = 'New Client'
const navSaveClient = 'a.btn:nth-child(2)'
const nameField = ':nth-child(1) > input'
const emailField = ':nth-child(2) > input'
const teleField = ':nth-child(3) > input'
//functions
function checkNewClientsPage(cy){
cy.title().should('eq', titleOfTesterHotelOverviewPage)
cy.contains(contentToConfirm)
}
function enterUser(cy, name, email, tele){
cy.get(nameField).type(name)
cy.get(emailField).type(email)
cy.get(teleField).type(tele)
}
function ClickSaveNewClient(cy){
cy.get(navSaveClient).click()
}
//exports
module.exports = {
ClickSaveNewClient,
enterUser,
checkNewClientsPage
}
|
$(document).ready(function() {
$('.masthead').addClass('bg');
$('.masthead').removeClass('zoomed');
$('.ui.button.primary').hover(function(){
$(this).css('opacity','0.75')
},function(){
$(this).css('opacity','1')
});
$('.rounded.big.square.icon').hover(function(){
$(this).addClass('activeicon');
},function(){
$(this).removeClass('activeicon');
});
if($(window).width() > 600) {
$('body').visibility({
offset : -10,
observeChanges : false,
once : false,
continuous : false,
onTopPassed: function() {
requestAnimationFrame(function() {
$('.following.bar').addClass('light fixed')
.find('.menu').removeClass('inverted');
$('.following .additional.item').transition('scale in', 750);
});
},
onTopPassedReverse: function() {
requestAnimationFrame(function() {
$('.following.bar').removeClass('light fixed')
.find('.menu').addClass('inverted')
.find('.additional.item').transition('hide');
});
}
});
}
// create sidebar and attach to menu open
$('.ui.sidebar').sidebar('attach events', '.toc.item');
$('#studies').click( function(){
window.location = '../../../studies';
});
});
|
/* Clase 34 - Eliminar Nodos */
(function(){
'use strict';
document.addEventListener('DOMContentLoaded', function(){
var primerPost = document.querySelector('main article');
primerPost.parentNode // Revisamos el nodo padre
// Los elemento solo se pueden borrar desde el padre
primerPost.parentNode.removeChild(primerPost);
// Borrar el primer celular
var enlaces = document.querySelector('#navegacion nav ul li a');
enlaces.parentNode.removeChild(enlaces);
// Borrar uno en especifico
var enlaces = document.querySelector('#navegacion nav ul li a')[10];
enlaces.parentNode.removeChild(enlaces);
});
})(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.