text
stringlengths 7
3.69M
|
|---|
export const GUARDAR_OTRO_A = "Desea agregar otro aspirante o ir al listado?"
export const EDITAR_AGAIN_A = "Desea seguir editando al aspirante o ir al listado?"
export const OK_EDIT_SAVE_BRANCH = "Desea continuar en el listado de ramas o ir a listados?"
export const OK_EDIT_SAVE_BRANCH_TITLE = "Se ha guardado con exito la rama"
export const ERR_EDIT_SAVE_BRANCH = "Desea intentar de nuevo o ir a listados?"
export const ERR_EDIT_SAVE_BRANCH_TITLE = "No se ha guardado con exito la rama"
export const ERR_STATUS_BRANCH_TITLE = "No se ha guardado con exito el estatus de la rama"
export const OK_STATUS_BRANCH_TITLE = "Se ha guardado con exito el estatus de la rama"
export const OK_EDIT_SAVE_POSITION = "Desea continuar en el listado de puestos o ir a listados?"
export const OK_EDIT_SAVE_POSITION_TITLE = "Se ha guardado con exito el puesto"
export const ERR_EDIT_SAVE_POSITION_TITLE = "No se ha guardado con exito el puesto"
export const ERR_STATUS_POSITION_TITLE = "No se ha guardado con exito el estatus del puesto"
export const OK_STATUS_POSITION_TITLE = "Se ha guardado con exito el estatus del puesto"
export const OK_EDIT_SAVE_STUDIES = "Desea continuar en el listado de nivel de estudios o ir a listados?"
export const OK_EDIT_SAVE_STUDIES_TITLE = "Se ha guardado con exito el nivel de estudio"
export const ERR_EDIT_SAVE_STUDIES_TITLE = "No se ha guardado con exito el nivel de estudio"
export const ERR_STATUS_STUDIES_TITLE = "No se ha guardado con exito el estatus del nivel de estudio"
export const OK_STATUS_STUDIES_TITLE = "Se ha guardado con exito el estatus del nivel de estudio"
export const DELETE_LEVEL = (name) => `¿Está seguro que desea eliminar ${name} de la lista?`
|
import { connect } from 'react-redux'
import { changePassword, login, register } from '../actions'
import Auth from '../components/Auth'
const connector = connect(
state => ({
password: state.auth.password,
}),
dispatch => ({
onChangePassword: ({ target }) => {
dispatch(changePassword(target.value))
},
onLogin: () => {
dispatch(login())
},
onRegister: () => {
dispatch(register())
},
}),
)
const Desktop = connector(Auth)
export default Desktop
|
// This file is the previous one that come sfrom the previous website, i do not use htis
// Send client entered Data to the server script using Ajax -> Check if establishment is Available and ask for some information
// Receiv Data returned by the server and handle them -> Display harvested information and Google Map
// var dataToSend = {"product_id":"62","product_quantity":"65"};
$(document).ready(function(){
moreCriteria();
$('#signaler-btn').click(function(){
var address = $('#address-autocomplete').val();
window.location = 'signalement.php?address=' + address;
});
});
function moreCriteria(){
//Click on "Plus de critères"
var isBtnClicked = 0;
$('#more_criteria_link').click(function(){
isBtnClicked = !isBtnClicked;
isBtnClicked ? $('#more_criteria_link').html('Moins de critères') : $('#more_criteria_link').html('Plus de critères');
$('#more_criteria').toggle();
clearFields();
});
$('#search-btn').click(function(){
var form_values = new Object();
form_values.queryType = "more_criteria";
form_values.form = get_form_values();
// console.log(form_values);
if(is_valid_form(form_values)){
sendData(form_values);
}
});
}
function get_form_values(){
var tmp_form = [];
tmp_form.push($('#more_criteria_nom').val());
tmp_form.push($('#more_criteria_ville').val());
tmp_form.push($('#more_criteria_activities').val());
// console.log(tmp_form);
return tmp_form;
}
function is_valid_form(form){
//Traiter le formulaire ici
return 1;
}
function clearFields(){
$('#nom_erp').html('');
$('#nom_erp_title').html('');
$('#access_text').html('');
}
function displayReturnedRows(recvData){
clearFields();
//If row(s) is not returned, if an address was not found from db
if((recvData._returnRow.length == 0) && (recvData._returnRow[0] == null)){
$('#access_text').html('Cet ERP ne s\'est pas déclaré conforme vis-à-vis de l\'accessibilité.');
return 1;
}
$('#nom_erp_title').html(recvData._returnRow.length + ' ERP à cette adresse:');
var arr = [];
var len = (recvData._returnRow).length;
for (var i = 0; i < len; i++)
{
arr = recvData._returnRow[i];
var tmpString = $('#nom_erp').html();
$('#nom_erp').html(tmpString + '<p>L\'ERP <span class="nom_erp_inmportant">"'+
arr.liste_ERP_nom_erp +'"</span> s\'est déclarée conforme vis-à-vis de l\'accessibilité'+
(!arr.listeERP_date_valid_adap ? '' : ' et celle-ci sera effective à partir du <span class="nom_erp_inmportant">' + arr.listeERP_date_valid_adap) +'</span>.</p>');
}
}
function sendData(dataToSend) {
$.ajax({
method: 'POST',
url: 'isAvailable.php',
// datatype: 'json',
//Query of our JSON data object
data: {
passedData: dataToSend
},
success: function(returnedData) {
//Decoding the JSON object returned by the server
var recvData = JSON.parse(returnedData);
// console.log(recvData);
//Add server returned content into our view
//Process to displaying content into different divs
displayReturnedRows(recvData);
},
//If any error
error: function() {
clearFields();
$("#errorMessage").html('Désolé, une erreur est survenue. Veuillez Réessayer plus tard.');
}
});
}
var autocomplete;
var map;
function initAutocomplete() {
//Get address text input field
var input = document.getElementById('address-autocomplete');
var options = {
//Return Only professional results
// types: ['establishment'],
//return Only establishments in France
componentRestrictions: {
country: 'fr'
}
};
//New instance of autocomplete obj with passed address and setted options
autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', addrProcessing);
}
//------------------------------------------------------------------------------------------------------//
// Coffee Function ;) : Create cleanObject, Display map of entered address, sendData to the server //
//------------------------------------------------------------------------------------------------------//
function addrProcessing() {
function createPlaceObj() {
var place = autocomplete.getPlace();
// console.log(place);
return place;
}
function createCleanObject(place) {
var cleanObject = new Object();
// ---------------- Create Addresse Components index ---------------- //
function creatAddrCompIndex() {
var tmpData = []; //Temp Array for adding data and then store it into object attribut
for (var i = 0; i < place.address_components.length; i++) { //Loop over Address Components indexes
tmpData.push(place.address_components[i]['long_name']); //Only Add 'long_name' index to tmp Array
}
return tmpData;
}
// ---------------- Create Geometry index ---------------- //
function createGeometryIndex() {
var tmpData = [place.geometry.viewport.f['b'], place.geometry.viewport.b['b']];
// console.log(tmpData);
return tmpData;
}
//Attributing returned values from functions to the cleanObject attributs
cleanObject.queryType = "standard"; //Simple query with given address
cleanObject.addrComp = creatAddrCompIndex();
cleanObject.geometry = createGeometryIndex();
return cleanObject;
}
var cleanObject = createCleanObject(createPlaceObj());
initMap(cleanObject.geometry);
sendData(cleanObject);
}
|
$(document).ready(function()
{
var contributions = [];
$('#chart div.solo').each(function(i, bar) {
var contribution = parseFloat($(bar).find('.contribution').text());
contributions.push(contribution);
});
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
var max = getMaxOfArray(contributions);
$('#chart div.solo').each(function(i, bar) {
var contribution = parseFloat($(bar).find('.contribution').text());
var bar_percent = (contribution / max) * .8 * 100;
$(bar).width(bar_percent+'%');
});
}
);
$(document).ready(function()
{
var contributions = [];
$('#chart div.group').each(function(i, bar) {
var contribution = parseFloat($(bar).find('.contribution').text());
contributions.push(contribution);
});
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
var max = getMaxOfArray(contributions);
$('#chart div.group').each(function(i, bar) {
var contribution = parseFloat($(bar).find('.contribution').text());
var bar_percent = (contribution / max) * .8 * 100;
$(bar).width(bar_percent+'%');
});
}
);
$(document).ready(function()
{
$(".agentTable").tablesorter();
}
);
|
module.exports = {
type: 'list',
name: 'type',
message: 'What are we building for ?',
default: 'react',
choices: ['react', 'wdio'],
validate: function(answer) {
if (answer.length < 1) {
return 'You must choose at least one ';
}
return true;
}
};
|
/**
* Created by samschmid on 23.03.14.
*/
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
function MongooseProvider(grunt) {
this.grunt = grunt;
}
MongooseProvider.prototype.createSchemeAndGetLibFile = function(doc) {
this.grunt.log.debug("create Scheme for: " + doc.json.title);
var template = this.grunt.file.read('./grunt/database/providers/mongoose/scheme.template');
template = template.replaceAll("{{{NAME}}}",doc.json.singular);
var model = doc.json.model;
var scheme = {};
for (var key in model) {
scheme[key] = model[key].type.capitalize();
}
template = template.replaceAll("{{{SCHEME}}}",JSON.stringify(scheme));
this.grunt.file.write(doc.schemefolder+ doc.json.singular+'.js', template);
return {"path": "./"+doc.schemefolder+ doc.json.singular+'.js', "scheme" : doc.json.singular, "version":doc.json.version};
}
module.exports = MongooseProvider;
|
import {
View,
Text,
StyleSheet,
ScrollView,
Dimensions,
Linking,
TouchableOpacity,
Platform
} from "react-native";
import React, { useEffect } from "react";
import MapView from "react-native-maps";
import { Marker } from "react-native-maps";
import { changeImg } from "../../redux/actions/serviceImg";
import { connect } from "react-redux";
const infostyle = StyleSheet.create({
title: {
paddingHorizontal: 10,
fontSize: 18,
marginBottom: 10,
paddingTop: 20,
color: "grey"
},
date: {
paddingHorizontal: 10,
paddingVertical: 5,
color: "grey"
},
address: {
paddingHorizontal: 10,
paddingVertical: 5,
flex: 1,
color: "grey"
},
dateContainer: { paddingBottom: 50 },
flex: {
display: "flex",
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
borderBottomColor: "lightgrey",
borderBottomWidth: 1
},
flexNo: {
display: "flex",
flex: 1,
flexDirection: "row",
justifyContent: "space-between"
},
bulle: {
width: "96%",
marginTop: 10,
marginBottom: 10,
paddingBottom: 10,
marginHorizontal: "2%",
borderRadius: 5,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.23,
shadowRadius: 2.62,
elevation: 4,
backgroundColor: "white"
}
});
function Info(props) {
let detail = props.route.params;
useEffect(() => {
const unsubscribe = props.navigation.addListener("focus", () => {
props.dispatch(changeImg(props.route.params.imgUrl));
console.log("Something");
});
return unsubscribe;
});
return (
<ScrollView>
<MapView
style={{
width: Dimensions.get("window").width,
height: Dimensions.get("window").height / 3.5,
marginBottom: 20
}}
region={{
latitude: detail.infos.lat,
longitude: detail.infos.lng,
latitudeDelta: 0.01,
longitudeDelta: 0.01
}}
showsUserLocation={true}
>
<Marker
coordinate={{
latitude: detail.infos.lat,
longitude: detail.infos.lng
}}
title={detail.infos.nom}
/>
</MapView>
<View style={infostyle.dateContainer}>
<Description description={detail.infos.description}></Description>
<Horaire style={infostyle.bulle} horaires={detail.horaires}></Horaire>
<View style={infostyle.bulle}>
<Text style={infostyle.title}>Contact</Text>
<TouchableOpacity
style={infostyle.flex}
onPress={() => Linking.openURL("tel:" + detail.infos.contacts)}
>
<Text style={infostyle.date}>Tel:</Text>
<Text style={infostyle.date}>{detail.infos.contacts}</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
if (Platform.OS === "ios") {
Linking.openURL(
`http://maps.apple.com/?daddr=${detail.infos.adresse}`
);
} else {
Linking.openURL(
`http://maps.google.com/?daddr=${detail.infos.adresse}`
);
}
}}
>
<View style={infostyle.flexNo}>
<Text style={infostyle.date}>Adresse:</Text>
<Text style={infostyle.address}>{detail.infos.adresse}</Text>
</View>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}
function Description(props) {
if (!props.description) return null;
return (
<View style={infostyle.bulle}>
<Text style={infostyle.title}>Description</Text>
<Text style={{ marginHorizontal: 10, color: "grey" }}>
{props.description}
</Text>
</View>
);
}
function Horaire(props) {
let flex = infostyle.flex;
if (props.horaires.length) {
return (
<View style={infostyle.bulle}>
<Text style={infostyle.title}>Horaires</Text>
{props.horaires.map((el, key) => {
let lastElem = key + 1 == props.horaires.length;
if (lastElem) flex = infostyle.flexNo;
if (!el.ferme) {
return (
<View style={flex} key={key}>
<Text style={infostyle.date}>{el.jour}</Text>
<Text style={infostyle.date}>{el.heure}</Text>
</View>
);
} else {
return (
<View style={flex} key={key}>
<Text style={infostyle.date}>{el.jour}</Text>
<Text style={infostyle.date}>Fermé</Text>
</View>
);
}
})}
</View>
);
}
return null;
}
function mapStateToProps(state) {
return state;
}
export default connect(mapStateToProps)(Info);
|
import Errors from '../widget/ui.errors';
import Gantt from 'devexpress-gantt';
export function getGanttViewCore() {
if (!Gantt) {
throw Errors.Error('E1041', 'devexpress-gantt');
}
return Gantt;
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
/**
* User login informtation
*/
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
required: true
},
/**
* History of user's sessions.
*/
history: [
/**
* Individual sessions.
* Multiple sessions in a single day are stored
* under the same document.
*/
{
id: Number,
date: Number,
/**
* Total time spent in seconds
*/
time: Number,
/**
* Activities array. Each activity is tracked
* individually. May implement suggestion/autocomplete
* in the future.
*/
activities: [
{
id: Number,
details: String,
timerOn: Boolean,
time: Number
}
]
}
]
}, {collection: 'users'});
const User = mongoose.model('User', userSchema);
module.exports = User;
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
export default function() {
class FixSortIconsController {
static get $inject() { return ['$element', '$timeout']; }
static get $$ngIsClass() { return true; }
constructor($element, $timeout) {
this.$element = $element;
this.$timeout = $timeout;
}
$onInit() {
this.$timeout(() => {
const icons = Array.from(this.$element[0].querySelectorAll('.md-numeric md-icon.md-sort-icon'));
icons.forEach(i => {
const parent = i.parentNode;
parent.insertBefore(i, parent.firstChild);
});
}, 0);
}
}
return {
restrict: 'A',
scope: false,
controller: FixSortIconsController
};
}
|
import React from "react";
import "./SearchSuggestion.scss";
const SearchSuggestion = (props) => {
const { id, name, country } = props;
const url = `/forecast/${id}`;
return (
<button onClick={props.onCitySelect} to={url} className="search_suggestion">
{name} <span>{country}</span>
</button>
);
};
export default SearchSuggestion;
|
//D3 radial progress
// creating circles with text in the middle (using json data)
// variables
var svgWidth = 1550,
svgHeight = 500;
var arcWidth = 960,
arcHeight = 500;
//Data fields to be used to create the Clock arcs
var arcFields = [
{value: 4, size: 4, label: " Years", update: function(date) {
return date.getYear();
}},
{value: 365, size: 365, label: " Days", update: function(date) {
return date.getDay();
}},
{value:24, size: 24, label: " Hours", update: function(date) {
return date.getHours();
}},
{value: 60, size: 60, label: " Minutes", update: function(date) {
return date.getMinutes();
}},
{value: 60, size: 60, label: " Seconds", update: function(date) {
return date.getSeconds();
}}
];
//creation of arcs
var clockArc = d3.arc()
.innerRadius(arcWidth / 6.5 - 20)
.outerRadius(arcWidth / 6.5 - 5)
.startAngle(0)
.endAngle(function(d) {
return (d.value / d.size) * 2 * Math.PI;
});
//creation and appending of SVG canvas
var svg = d3.select("div.clock--container")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight)
var field = svg.selectAll(".field")
.data(arcFields)
.enter().append("g")
.attr("transform", function(d, i){
return "translate(" + (i * 2 + 1.25) / 6.5 * arcWidth + "," + arcHeight / 2 + ")"; })
.attr("class", "field");
field.append("path")
.attr("class", "path path--background")
.attr("d", clockArc);
var path = field.append("path")
.attr("class", "path path--foreground");
var label = field.append("text")
.attr("class", "label")
.attr("dy", ".35em");
(function update() {
var now = new Date();
field
.each(function(d){ d.previous = d.value, d.value = d.update(now);});
d3.selectAll(".path--foreground").transition()
.ease(d3.easeElastic)
.duration(750)
.attrTween("d", arcTween);
label
.text(function(d) { return d.value + d.label; });
setTimeout(update, 1000 - (now % 1000));
})();
function arcTween(b) {
var i = d3.interpolate({value: b.previous}, b);
return function(t) {
return clockArc(i(t));
};
}
|
import { useState } from 'react'
import { LockClosedIcon } from '@heroicons/react/solid'
export const login = async body => {
try {
const res = await window.fetch('api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
if (res.status === 200) {
window.location.reload()
} else {
throw new Error(await res.text())
}
} catch (error) {
console.log('login error:', error)
return error.message
}
}
export const signup = async body => {
try {
const res = await window.fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
if (res.status === 200) {
await login(body)
} else {
throw new Error(await res.text())
}
} catch (error) {
console.error('signup error:', error)
return 'Sign up error, username might be used'
}
}
export default function AccountForm (props) {
const [errorMsg, setErrorMsg] = useState('')
const [submitType, setSubmitType] = useState('login')
const handleSubmit = async e => {
e.preventDefault()
const body = {
username: e.currentTarget.username.value,
password: e.currentTarget.password.value
}
if (submitType === 'login') {
const errMsg = await login(body)
setErrorMsg(errMsg)
} else if (submitType === 'signup') {
const errMsg = await signup(body)
console.log('errMsg:', errMsg)
setErrorMsg(errMsg)
}
}
return (
<div className='max-w-md w-full space-y-8 my-auto'>
<div>
<img
className='mx-auto h-12 w-auto'
src='https://tailwindui.com/img/logos/workflow-mark-indigo-600.svg'
alt='Workflow'
/>
<h2 className='mt-6 text-center text-3xl font-extrabold text-gray-900'>Who are you?</h2>
</div>
<form id='account-form' className='mt-8 space-y-6' onSubmit={handleSubmit}>
<input type='hidden' name='remember' defaultValue='true' />
<div className='rounded-md shadow-sm -space-y-px'>
<div>
<label htmlFor='username' className='sr-only'>
User name
</label>
<input
id='username'
name='username'
type='text'
autoComplete='text'
required
className='appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm'
placeholder='User name'
/>
</div>
<div>
<label htmlFor='password' className='sr-only'>
Password
</label>
<input
id='password'
name='password'
type='password'
autoComplete='current-password'
required
className='appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm'
placeholder='Password'
/>
</div>
</div>
{/* <div className="flex items-center justify-between">
<div className="flex items-center">
<input
id="remember_me"
name="remember_me"
type="checkbox"
className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
/>
<label htmlFor="remember_me" className="ml-2 block text-sm text-gray-900">
Remember me
</label>
</div>
<div className="text-sm">
<a href="#" className="font-medium text-indigo-600 hover:text-indigo-500">
Forgot your password?
</a>
</div>
</div> */}
<div>
<button
type='submit'
form='account-form'
className='group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
onClick={() => setSubmitType('login')}
>
<span className='absolute left-0 inset-y-0 flex items-center pl-3'>
<LockClosedIcon className='h-5 w-5 text-indigo-500 group-hover:text-indigo-400' aria-hidden='true' />
</span>
Log in
</button>
<button
type='submit'
form='account-form'
className='my-2 group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-red-400 hover:bg-red-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
onClick={() => setSubmitType('signup')}
>
Sign up
</button>
</div>
<div> {errorMsg}</div>
</form>
</div>
)
}
|
import React from 'react';
import { mount } from 'enzyme';
import withPageProductId from './withPageProductId';
let mockedProductId;
const mockedLogger = jest.fn();
jest.mock('../helpers/TaggedLogger', () => class MockedTaggedLogger {
// eslint-disable-next-line max-len
// eslint-disable-next-line class-methods-use-this, require-jsdoc, extra-rules/potential-point-free
warn(...args) {
mockedLogger(...args);
}
// eslint-disable-next-line max-len
// eslint-disable-next-line class-methods-use-this, require-jsdoc, extra-rules/potential-point-free
error(...args) {
mockedLogger(...args);
}
});
jest.mock('@shopgate/pwa-common/context', () => ({
RouteContext: {
Consumer: (props) => {
// eslint-disable-next-line react/prop-types
const Child = props.children;
return <Child params={{ productId: mockedProductId }} />;
},
},
}));
describe('connectors/withPageProductId', () => {
beforeEach(() => {
jest.clearAllMocks();
});
// eslint-disable-next-line react/prop-types, require-jsdoc
const MockedComponent = props => <div>{props.productId}</div>;
it('should render with productId', () => {
mockedProductId = '31323334';
const Component = withPageProductId(MockedComponent);
const component = mount(<Component otherProp={1} />);
expect(component.find('MockedComponent').props()).toEqual({
productId: '1234',
otherProp: 1,
});
});
it('should render with missing productId', () => {
mockedProductId = undefined;
const Component = withPageProductId(MockedComponent);
const component = mount(<Component otherProp={1} />);
expect(component.find('MockedComponent').props()).toEqual({
productId: null,
otherProp: 1,
});
expect(mockedLogger).toHaveBeenCalled();
});
it('should render with invalid productId', () => {
mockedProductId = '123';
const Component = withPageProductId(MockedComponent);
const component = mount(<Component otherProp={1} />);
expect(component.find('MockedComponent').props()).toEqual({
productId: false,
otherProp: 1,
});
expect(mockedLogger).toHaveBeenCalled();
});
});
|
const CREDENTIALS = {
residential: {
code: 'res-001',
pw: 'password'
},
commercial: {
code: 'comm-001',
pw: 'password'
}
}
export default CREDENTIALS;
|
/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const createMyModel1 = /* GraphQL */ `
mutation CreateMyModel1(
$input: CreateMyModel1Input!
$condition: ModelMyModel1ConditionInput
) {
createMyModel1(input: $input, condition: $condition) {
id
name
description
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
export const updateMyModel1 = /* GraphQL */ `
mutation UpdateMyModel1(
$input: UpdateMyModel1Input!
$condition: ModelMyModel1ConditionInput
) {
updateMyModel1(input: $input, condition: $condition) {
id
name
description
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
export const deleteMyModel1 = /* GraphQL */ `
mutation DeleteMyModel1(
$input: DeleteMyModel1Input!
$condition: ModelMyModel1ConditionInput
) {
deleteMyModel1(input: $input, condition: $condition) {
id
name
description
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
export const createMyModel2 = /* GraphQL */ `
mutation CreateMyModel2(
$input: CreateMyModel2Input!
$condition: ModelMyModel2ConditionInput
) {
createMyModel2(input: $input, condition: $condition) {
id
name
description
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
export const updateMyModel2 = /* GraphQL */ `
mutation UpdateMyModel2(
$input: UpdateMyModel2Input!
$condition: ModelMyModel2ConditionInput
) {
updateMyModel2(input: $input, condition: $condition) {
id
name
description
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
export const deleteMyModel2 = /* GraphQL */ `
mutation DeleteMyModel2(
$input: DeleteMyModel2Input!
$condition: ModelMyModel2ConditionInput
) {
deleteMyModel2(input: $input, condition: $condition) {
id
name
description
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
|
import React from "react";
import Joi from "joi";
import { Redirect, Link } from "react-router-dom";
import Form from "./common/form";
import auth from "../services/authService";
class LoginForm extends Form {
state = {
data: {
username: "",
password: "",
},
errors: {},
};
schema = Joi.object({
username: Joi.string()
.email({ tlds: { allow: false } })
.required()
.label("Username"),
password: Joi.string().min(5).required().label("Password"),
});
doSubmit = async () => {
try {
const { username, password } = this.state.data;
await auth.login(username, password);
const { state } = this.props.location;
window.location = state ? state.from.pathname : "/";
} catch (error) {
const errors = { ...this.state.errors };
errors.username = error.response.data;
this.setState({ errors });
}
};
render() {
if (auth.getCurrentUser()) return <Redirect to="/" />;
return (
<div className="auth-wrapper">
<div className="auth-inner">
<div>
<form onSubmit={this.handleSubmit}>
<h3>Sign In</h3>
{this.renderInput("username", "Username")}
{this.renderInput("password", "Password", "password")}
{this.renderSubmit("Login")}
</form>
</div>
</div>
</div>
);
}
}
export default LoginForm;
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { searchReducer } from './store/reducers/searchReducer';
import { viewRecipeReducer } from './store/reducers/viewRecipeReducer';
import { loveReducer } from './store/reducers/loveListReducer';
import { shoppingReducer } from './store/reducers/shoppingReducer';
import thunk from 'redux-thunk';
const rootReducer = combineReducers({
search: searchReducer,
recipe: viewRecipeReducer,
loveList: loveReducer ,
shopping: shoppingReducer
});
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancers(
applyMiddleware(thunk)
));
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
import { useAuth } from "../account/authHook";
import { Sidebar } from "./Sidebar";
import { Link } from "react-router-dom";
import { NavDropdown } from "react-bootstrap";
import "./Layout.scss";
import { useState } from "react";
export const Layout = ({ children }) => {
const auth = useAuth();
const [sidebarHidden, setHidden] = useState(false);
const toggle = () => {
setHidden(!sidebarHidden);
}
return (
<>
<Sidebar role={auth.user.role} isHide={sidebarHidden} />
<div className="header">
<div className="header-title">
<button className="toggle-sidebar" onClick={toggle} style={!sidebarHidden ? {visibility: "hidden"} : null}><i className="bi bi-list"></i></button>
<span><i className="bi bi-bug"></i>Bug Tracker</span>
<button className="toggle-sidebar" onClick={toggle} style={sidebarHidden ? {visibility: "hidden"} : null}><i className="bi bi-x-lg"></i></button>
</div>
<div className="header-user">Logged in as: <span>{auth.user.username}</span></div>
<NavDropdown title={auth.user.username} id="navbarScrollingDropdown">
<Link to="/profile" className="dropdown-item">Profile</Link>
<NavDropdown.Divider />
<Link to="/account/logout" className="dropdown-item">Logout</Link>
</NavDropdown>
</div>
<div className={`wrapper ${sidebarHidden ? "full" : ""}`}>
{children}
</div>
</>
);
}
|
import React, { Component } from 'react';
import '../stylesheets/tagline.css';
export class Tagline extends Component {
render() {
return (
<div className="text" style={this.props.divStyle} className={this.props.cols}>
<h1 style={this.props.style}>{this.props.text}</h1>
</div>
)
}
}
export default Tagline
|
OC.L10N.register(
"settings",
{
"Wrong current password" : "Chybné heslo",
"The new password cannot be the same as the previous one" : "Nové heslo nemůže být stejné jako to předchozí",
"No user supplied" : "Nebyl uveden uživatel",
"Authentication error" : "Chyba přihlášení",
"Please provide an admin recovery password; otherwise, all user data will be lost." : "Zadejte prosím administrátorské heslo pro obnovu, jinak budou všechna data ztracena.",
"Wrong admin recovery password. Please check the password and try again." : "Chybné administrátorské heslo pro obnovu. Překontrolujte správnost hesla a zkuste to znovu.",
"Backend doesn't support password change, but the user's encryption key was successfully updated." : "Úložiště nepodporuje změnu hesla, ale šifrovací klíč uživatele byl úspěšně aktualizován.",
"Unable to change password" : "Změna hesla se nezdařila",
"%s password changed successfully" : "%s heslo bylo změněno vpořádku",
"Couldn't send reset email. Please contact your administrator." : "Nepodařilo se odeslat email pro změnu hesla. Kontaktujte svého správce systému.",
"cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably." : "cURL používá zastaralou %s verzi (%s). Aktualizujte prosím svůj operační systém, jinak funkce jako %s nemusí spolehlivě pracovat.",
"Group already exists." : "Skupina již existuje.",
"Unable to add group." : "Nelze přidat skupinu.",
"Unable to delete group." : "Nelze smazat skupinu.",
"Saved" : "Uloženo",
"log-level out of allowed range" : "úroveň logování z povoleného rozpětí",
"Invalid email address" : "Chybná emailová adresa",
"test email settings" : "Test nastavení emailu",
"A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Při odesílání emailu nastala chyba. Překontrolujte prosím svá nastavení. (Error: %s)",
"Email sent" : "Email odeslán",
"You need to set your user email before being able to send test emails." : "Pro možnost odeslání zkušebních emailů musíte nejprve nastavit svou emailovou adresu.",
"Couldn't change the email address because the user does not exist" : "Email nemohl být změněn. Uživatel neexistuje",
"Couldn't change the email address because the token is invalid" : "Email nemohl být změněn. Token je chybný",
"Your %s account was created" : "Účet %s byl vytvořen",
"Invalid mail address" : "Neplatná emailová adresa",
"A user with that name already exists." : "Uživatel tohoto jména již existuje.",
"Unable to create user." : "Nelze vytvořit uživatele.",
"The token provided is invalid." : "Vložený token je neplatný.",
"The token provided had expired." : "Tokenu vypršela platnost.",
"Failed to create activation link. Please contact your administrator." : "Nepodařilo se vytvořit aktivační odkaz. Prosím kontaktujte svého správce systému.",
"Can't send email to the user. Contact your administrator." : "Nepodařilo se odeslat email uživateli. Kontaktujte svého správce systému.",
"Failed to set password. Please contact the administrator." : "Chyba při ukládání hesla. Kontaktujte prosím správce systému.",
"Failed to set password. Please contact your administrator." : "Chyba při ukládání hesla. Kontaktujte prosím svého správce systému.",
"Failed to send email. Please contact your administrator." : "Chyba při odesílání emailu. Prosím kontaktujte správce systému.",
"Unable to delete user." : "Nelze smazat uživatele.",
"Forbidden" : "Zakázáno",
"Invalid user" : "Neplatný uživatel",
"Unable to change mail address" : "Nelze změnit emailovou adresu",
"Email has been changed successfully." : "Email byl úspěšně změněn.",
"An email has been sent to this address for confirmation. Until the email is verified this address will not be set." : "Na tuto adresu byl odeslán email s potvrzením. Až do ověření emailu nebude tato adresa nastavena.",
"No email was sent because you already sent one recently. Please try again later." : "Email byl již nedávno odeslán. Prosím zkuste to znovu později.",
"Your full name has been changed." : "Vaše celé jméno bylo změněno.",
"Unable to change full name" : "Nelze změnit celé jméno",
"%s email address confirm" : "%s potvrzení emailové adresy",
"Couldn't send email address change confirmation mail. Please contact your administrator." : "Nepodařilo se odeslat potvrzovací změna e-mailové adresy. Obraťte se na správce.",
"%s email address changed successfully" : "%s emailová adresa úspěšně změněna",
"Couldn't send email address change notification mail. Please contact your administrator." : "Nelze odeslat e-mailovou adresu pro oznamování změn poštu. Obraťte se na správce.",
"Unable to enable/disable user." : "Nelze povolit/zakázat uživatele.",
"Owner language" : "Jazyk vlastníka",
"Create" : "Vytvořit",
"Change" : "Změnit",
"Delete" : "Smazat",
"Share" : "Sdílet",
"APCu" : "APCu",
"Redis" : "Redis",
"Language changed" : "Jazyk byl změněn",
"Invalid request" : "Neplatný požadavek",
"Admins can't remove themself from the admin group" : "Správci se nemohou sami odebrat ze skupiny správců",
"Unknown user" : "Neznámý uživatel",
"Couldn't remove app." : "Nepodařilo se odebrat aplikaci.",
"Official" : "Oficiální",
"Approved" : "Potvrzeno",
"All" : "Vše",
"Enabled" : "Povoleno",
"Not enabled" : "Vypnuto",
"No apps found for your version" : "Nebyly nalezeny aplikace pro vaši verzi",
"The app will be downloaded from the app store" : "Aplikace bude stažena z obchodu aplikací",
"Official apps are developed by and within the ownCloud community. They offer functionality central to ownCloud and are ready for production use." : "Oficiální aplikace jsou vyvíjeny komunitou ownCloud. Nabízejí funkce důležité pro ownCloud a jsou připraveny pro nasazení v produkčním prostředí.",
"Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use." : "Schválené aplikace jsou vyvíjeny důvěryhodnými vývojáři a prošly zběžným bezpečnostním prověřením. Jsou aktivně udržovány v repozitáři s otevřeným kódem a jejich správci je považují za stabilní pro občasné až normální použití.",
"This app is not checked for security issues and is new or known to be unstable. Install at your own risk." : "U této aplikace nebyla provedena kontrola na bezpečnostní problémy. Aplikace je nová nebo nestabilní. Instalujte pouze na vlastní nebezpečí.",
"Please wait...." : "Čekejte prosím...",
"Error while disabling app" : "Chyba při zakazování aplikace",
"Disable" : "Zakázat",
"Enable" : "Povolit",
"Error while enabling app" : "Chyba při povolování aplikace",
"Error: this app cannot be enabled because it makes the server unstable" : "Chyba: tuto aplikaci nelze zapnout, protože způsobuje nestabilitu serveru",
"Error: could not disable broken app" : "Chyba: nezdařilo se vypnout rozbitou aplikaci",
"Error while disabling broken app" : "Chyba při vypínání rozbité aplikace",
"Updating...." : "Aktualizuji...",
"Error while updating app" : "Chyba při aktualizaci aplikace",
"Updated" : "Aktualizováno",
"Uninstalling ...." : "Probíhá odinstalace ...",
"Error while uninstalling app" : "Chyba při odinstalaci aplikace",
"Uninstall" : "Odinstalovat",
"The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds." : "Aplikace byla povolena ale je třeba ji aktualizovat. Za 5 sekund budete přesměrování na stránku pro aktualizaci.",
"App update" : "Aktualizace aplikace",
"Experimental" : "Experimentální",
"No apps found for {query}" : "Nebyly nalezeny žádné aplikace pro {query}",
"Migration in progress. Please wait until the migration is finished" : "Migrace probíhá. Počkejte prosím než bude dokončena",
"Migration started …" : "Migrace spuštěna ...",
"An error occurred. Please upload an ASCII-encoded PEM certificate." : "Došlo k chybě. Nahrajte prosím ASCII-kódovaný PEM certifikát.",
"Valid until {date}" : "Platný do {date}",
"Disconnect" : "Odpojit",
"Error while loading browser sessions and device tokens" : "Chyba při načítání sezení prohlížeče a tokenů přístroje",
"Empty app name is not allowed." : "Prázdné jméno aplikace není dovoleno.",
"Error while creating device token" : "Chyba při vytváření tokenů přístroje",
"Error while deleting the token" : "Chyba při mazání tokenu",
"Are you sure you want to remove this domain?" : "Chcete odstranit tuto doménu?",
"CORS" : "CORS",
"Sending..." : "Odesílání...",
"Failed to change the email address." : "Chyba při změně emailové adresy.",
"Email changed successfully for {user}." : "Email pro {user} byl změněn.",
"An error occurred: {message}" : "Nastala chyba: {message}",
"Select a profile picture" : "Vyberte profilový obrázek",
"Very weak password" : "Velmi slabé heslo",
"Weak password" : "Slabé heslo",
"So-so password" : "Středně silné heslo",
"Good password" : "Dobré heslo",
"Strong password" : "Silné heslo",
"Groups" : "Skupiny",
"Unable to delete {objName}" : "Nelze smazat {objName}",
"Error creating group: {message}" : "Chyba vytvoření skupiny: {message}",
"A valid group name must be provided" : "Musíte zadat platný název skupiny",
"deleted {groupName}" : "smazána {groupName}",
"undo" : "vrátit zpět",
"You are about to delete a group. This action can't be undone and is permanent. Are you sure that you want to permanently delete {groupName}?" : "Chystáte se smazat skupina. Tuto akci není možné vrátit a je trvalá. Jste si jisti, že chcete smazat {groupName}?",
"Delete group" : "Smazat skupinu",
"never" : "nikdy",
"deleted {userName}" : "smazán {userName}",
"You are about to delete a user. This action can't be undone and is permanent. All user data, files and shares will be deleted. Are you sure that you want to permanently delete {userName}?" : "Chystáte se smazat uživatele. Tuto akci není možné vrátit a je trvalá. Všechna uživatelská data, soubory a příspěvky budou smazány. Jste si jisti, že chcete smazat {userName}?",
"Delete user" : "Smazat uživatele",
"add group" : "přidat skupinu",
"Invalid quota value \"{val}\"" : "Neplatná hodnota kvóty \"{val}\"",
"enabled" : "povoleno",
"disabled" : "zakázáno",
"User {uid} has been {state}!" : "Uživatel {uid} byl {state}!",
"no group" : "není ve skupině",
"Changing the password will result in data loss, because data recovery is not available for this user" : "Změna hesla bude mít za následek ztrátu dat, protože jejich obnova není pro tohoto uživatele dostupná.",
"Password successfully changed" : "Heslo bylo úspěšně změněno",
"A valid username must be provided" : "Musíte zadat platné uživatelské jméno",
"Error creating user: {message}" : "Chyba vytvoření uživatele: {message}",
"A valid password must be provided" : "Musíte zadat platné heslo",
"A valid email must be provided" : "Musíte zadat platný email",
"Use the following link to confirm your changes to the email address: {link}" : "Použijte tento odkaz pro potvrzení změn na emailové adrese: {link}",
"Email address changed to {mailAddress} successfully." : "Emailová adresa {mailAddress} úspěšně změněna.",
"Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Please set the password by accessing it: <a href=\"%s\">Here</a><br><br>" : "Ahoj,<br><br> toto je oznámení o nově vytvořeném %s účtu. <br><br> Uživatelské jméno: %s <br> Heslo je možné nastavit: <a href=\"%s\">Zde </a><br><br>",
"Cheers!" : "Ať slouží!",
"Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Ahoj,\n\ntoto je oznámení o nově vytvořeném %s účtu.\n\nUživatelské jméno: %s\nPřihlásit se dá zde: %s\n",
"Language" : "Jazyk",
"Apps Management" : "Správa aplikace",
"Developer documentation" : "Vývojářská dokumentace",
"by %s" : "%s",
"%s-licensed" : "%s-licencováno",
"Documentation:" : "Dokumentace:",
"User documentation" : "Dokumentace uživatele",
"Admin documentation" : "Dokumentace pro administrátory",
"Visit website" : "Navštívit webovou stránku",
"Report a bug" : "Nahlásit chybu",
"Show description …" : "Zobrazit popis ...",
"Hide description …" : "Skrýt popis ...",
"This app has no minimum ownCloud version assigned. This will be an error in ownCloud 11 and later." : "Tato aplikace nemá přiřazenou nejnižší verzi ownCloud. Toto povede k chybě v ownCloud 11 a vyšším.",
"This app has no maximum ownCloud version assigned. This will be an error in ownCloud 11 and later." : "Tato aplikace nemá přiřazenou nejvyšší verzi ownCloud. Toto povede k chybě v ownCloud 11 a vyšším.",
"This app cannot be installed because the following dependencies are not fulfilled:" : "Tuto aplikaci nelze nainstalovat, protože nejsou splněny následující závislosti:",
"Enable only for specific groups" : "Povolit pouze pro vybrané skupiny",
"Uninstall App" : "Odinstalovat aplikaci",
"Show enabled apps" : "Zobrazit povolené aplikace",
"Show disabled apps" : "Zobrazit zakázané aplikace",
"Cron" : "Cron",
"Last cron job execution: %s." : "Poslední cron proběhl: %s.",
"Last cron job execution: %s. Something seems wrong." : "Poslední cron proběhl: %s. Vypadá to, že něco není v pořádku.",
"Cron was not executed yet!" : "Cron ještě nebyl spuštěn!",
"Open documentation" : "Otevřít dokumentaci",
"Execute one task with each page loaded" : "Spustit jednu úlohu s každým načtením stránky",
"cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php je registrován u služby webcron, aby volal cron.php jednou za 15 minut přes http.",
"Use system's cron service to call the cron.php file every 15 minutes." : "Použít systémovou službu cron pro volání cron.php každých 15 minut.",
"SSL Root Certificates" : "Kořenové certifikáty SSL",
"Common Name" : "Common Name",
"Valid until" : "Platný do",
"Issued By" : "Vydal",
"Valid until %s" : "Platný do %s",
"Import root certificate" : "Import kořenového certifikátu",
"Server-side encryption" : "Šifrování na serveru",
"Enable server-side encryption" : "Povolit šifrování na straně serveru",
"Please read carefully before activating server-side encryption: " : "Pročtěte prosím důkladně před aktivací šifrování dat na serveru:",
"Once encryption is enabled, all files uploaded to the server from that point forward will be encrypted at rest on the server. It will only be possible to disable encryption at a later date if the active encryption module supports that function, and all pre-conditions (e.g. setting a recover key) are met." : "Poté co je zapnuto šifrování, jsou od toho bodu všechny nahrávané soubory šifrovány serverem. Vypnout šifrování bude možné pouze později, až bude šifrovací modul tuto možnost podporovat a po splnění všech nutných podmínek (tzn. nastavení klíčů pro obnovení).",
"Encryption alone does not guarantee security of the system. Please see ownCloud documentation for more information about how the encryption app works, and the supported use cases." : "Samotné šifrování nezajistí bezpečnost systému. Projděte si dokumentaci aplikace ownCloud pro více informací o tom jak šifrovací aplikace funguje a jejím správném použití.",
"Be aware that encryption always increases the file size." : "Mějte na paměti, že šifrování vždy navýší velikost souboru.",
"It is always good to create regular backups of your data, in case of encryption make sure to backup the encryption keys along with your data." : "Je vždy dobré vytvářet pravidelné zálohy svých dat, v případě zapnutého šifrování také zajistěte zálohu šifrovacích klíčů společně se zálohou dat.",
"This is the final warning: Do you really want to enable encryption?" : "Toto je poslední varování: Opravdu si přejete zapnout šifrování?",
"Enable encryption" : "Povolit šifrování",
"No encryption module loaded, please enable an encryption module in the app menu." : "Není načten žádný šifrovací modul, povolte ho prosím v menu aplikací.",
"Select default encryption module:" : "Vybrat výchozí šifrovací modul:",
"You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please enable the \"Default encryption module\" and run 'occ encryption:migrate'" : "Musíte přenést své šifrovací klíče ze staré verze šifrování (ownCloud <= 8.0) na novou. Povolte prosím \"Default encryption module\" a spusťte příkaz 'occ encryption:migrate'",
"You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one." : "Musíte přenést své šifrovací klíče ze staré verze šifrování (ownCloud <= 8.0) na novou.",
"Start migration" : "Spustit migraci",
"Sharing" : "Sdílení",
"Allow apps to use the Share API" : "Povolit aplikacím používat API sdílení",
"Allow users to share via link" : "Povolit uživatelům sdílení pomocí odkazů",
"Allow public uploads" : "Povolit veřejné nahrávání souborů",
"Enforce password protection for read-only links" : "Vynutit ochranu heslem pro odkazy pro čtení",
"Enforce password protection for upload-only (File Drop) links" : "Vynutit ochranu heslem pro odkazy pro nahrávání (File Drop)",
"Set default expiration date" : "Nastavit výchozí datum vypršení platnosti",
"Expire after " : "Vyprší po",
"days" : "dnech",
"Allow users to send mail notification for shared files" : "Povolit uživatelům odesílat emailová upozornění pro sdílené soubory",
"Allow users to share file via social media" : "Povolit uživatelům sdílení pomocí sociálních médií",
"Allow resharing" : "Povolit znovu-sdílení",
"Allow sharing with groups" : "Povolit sdílení se skupinami",
"Restrict users to only share with users in their groups" : "Povolit sdílení pouze mezi uživateli v rámci skupiny",
"Allow users to send mail notification for shared files to other users" : "Povolit uživatelům odesílat emailová upozornění na sdílené soubory ostatním uživatelům",
"Exclude groups from sharing" : "Vyjmout skupiny ze sdílení",
"These groups will still be able to receive shares, but not to initiate them." : "Těmto skupinám bude stále možno sdílet, nemohou ale sami sdílet ostatním.",
"Allow username autocompletion in share dialog. If this is disabled the full username needs to be entered." : "Povolit automatické vyplňování v dialogu sdílení. Pokud je toto vypnuto, je třeba ručně vyplňovat celé uživatelské jméno.",
"Restrict enumeration to group members" : "Omezení výčtu na členy skupiny",
"Extra field to display in autocomplete results" : "Zobrazit další pole pro automatické dokončování",
"None" : "Žádné",
"User ID" : "ID uživatele",
"Email address" : "Emailová adresa",
"Save" : "Uložit",
"Everything (fatal issues, errors, warnings, info, debug)" : "Vše (fatální problémy, chyby, varování, informační, ladící)",
"Info, warnings, errors and fatal issues" : "Informace, varování, chyby a fatální problémy",
"Warnings, errors and fatal issues" : "Varování, chyby a fatální problémy",
"Errors and fatal issues" : "Chyby a fatální problémy",
"Fatal issues only" : "Pouze fatální problémy",
"Log" : "Záznam",
"What to log" : "Co se má logovat",
"Download logfile (%s)" : "Stáhnout soubor logu (%s)",
"The logfile is bigger than 100 MB. Downloading it may take some time!" : "Soubor logu je větší než 100 MB. Jeho stažení zabere nějaký čas!",
"Login" : "Přihlásit",
"Plain" : "Čistý text",
"NT LAN Manager" : "Správce NT LAN",
"SSL/TLS" : "SSL/TLS",
"STARTTLS" : "STARTTLS",
"Email server" : "Emailový server",
"This is used for sending out notifications." : "Toto se používá pro odesílání upozornění.",
"Send mode" : "Mód odesílání",
"Encryption" : "Šifrování",
"From address" : "Adresa odesílatele",
"mail" : "email",
"Authentication method" : "Metoda ověření",
"Authentication required" : "Vyžadováno ověření",
"Server address" : "Adresa serveru",
"Port" : "Port",
"Credentials" : "Přihlašovací údaje",
"SMTP Username" : "SMTP uživatelské jméno ",
"SMTP Password" : "SMTP heslo",
"Store credentials" : "Ukládat přihlašovací údaje",
"Test email settings" : "Test nastavení emailu",
"Send email" : "Odeslat email",
"Security & setup warnings" : "Upozornění zabezpečení a nastavení",
"php does not seem to be setup properly to query system environment variables. The test with getenv(\"PATH\") only returns an empty response." : "php není nejspíše správně nastaveno pro dotazování na proměnné hodnoty systému. Test s getenv(\"PATH\") vrací pouze prázdnou odpověď.",
"Please check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation documentation ↗</a> for php configuration notes and the php configuration of your server, especially when using php-fpm." : "Zkontrolujte prosím konfiguraci php podle <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">instalační dokumentace ↗</a>, hlavně při použití php-fpm.",
"The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Konfigurace je nastavena pouze pro čtení. Toto znemožňuje některá nastavení přes webové rozhraní. Dále musí být pro každou změnu povolen zápis do konfiguračního souboru ručně.",
"PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP je patrně nastaveno tak, aby odstraňovalo bloky komentářů. Toto bude mít za následek nedostupnost množství hlavních aplikací.",
"This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Toto je pravděpodobně způsobeno aplikacemi pro urychlení načítání jako jsou Zend OPcache nebo eAccelerator.",
"Your database does not run with \"READ COMMITED\" transaction isolation level. This can cause problems when multiple actions are executed in parallel." : "Vaše databáze neběží s úrovní izolace transakcí \"READ COMMITED\". Toto může způsobit problémy při paralelním spouštění více akcí současně.",
"%1$s below version %2$s is installed, for stability and performance reasons we recommend updating to a newer %1$s version." : "Je nainstalován %1$s nižší verze než %2$s, z důvodu lepší stability a výkonu doporučujeme aktualizovat na novější verzi %1$s.",
"The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "Schází PHP modul 'fileinfo'. Doporučujeme jej povolit pro nejlepší výsledky detekce typů MIME.",
"Transactional file locking is disabled, this might lead to issues with race conditions. Enable 'filelocking.enabled' in config.php to avoid these problems. See the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a> for more information." : "Transakční uzamykání souborů je vypnuto, což může vést k problémům s \"race\" podmínkami. Pro zabránění těmto problémům povolte 'filelocking.enabled' v souboru config.php. Více informací lze nalézt v <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">dokumentaci ↗</a>.",
"Transactional file locking should be configured to use memory-based locking, not the default slow database-based locking. See the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a> for more information." : "Blokování transakčních souborů by mělo být nakonfigurováno tak, aby používaly blokování založené na paměti, nikoliv blokování založené na pomalé databázi. Další informace naleznete v <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\"> dokumentaci ↗ </a>.",
"System locale can not be set to a one which supports UTF-8." : "Není možné nastavit znakovou sadu, která podporuje UTF-8.",
"This means that there might be problems with certain characters in file names." : "To znamená, že se mohou vyskytnout problémy s určitými znaky v názvech souborů.",
"We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Velmi doporučujeme nainstalovat požadované balíčky do systému, pro podporu jednoho z následujících národních prostředí: %s.",
"If your installation is not installed in the root of the domain and uses system cron, there can be issues with the URL generation. To avoid these problems, please set the \"overwrite.cli.url\" option in your config.php file to the webroot path of your installation (Suggested: \"%s\")" : "Instalace mimo kořenový adresář domény a používání systémového příkazu cron může způsobit problém s generováním správné URL. Pro zabránění těmto chybám nastavte prosím správnou cestu ve svém config.php souboru v hodnotě \"overwrite.cli.url\" (Je doporučena tato: \"%s\")",
"SQLite is used as database. For larger installations we recommend to switch to a different database backend." : "Je použita databáze SQLite. Pro větší instalace doporučujeme přejít na robustnější databázi.",
"Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Obzvláště při používání klientské aplikace pro synchronizaci s desktopem není SQLite doporučeno.",
"To migrate to another database use the command line tool: 'occ db:convert-type', or see the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a>." : "Pro migraci na jinou databázi použijte v příkazovém řádku nástroj: 'occ db:convert-type' nebo nahlédněte do <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">dokumentace ↗</a>.",
"We recommend to enable system cron as any other cron method has possible performance and reliability implications." : "Doporučujeme povolit systémový cron, protože jakýkoli jiný cron má možné dopady na výkon a spolehlivost.",
"It was not possible to execute the cronjob via CLI. The following technical errors have appeared:" : "Nebylo možné spustit službu cron v CLI. Došlo k následujícím technickým chybám:",
"Please double check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation guides ↗</a>, and check for any errors or warnings in the <a href=\"#log-section\">log</a>." : "Prosím překontrolujte <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">instalační pokyny ↗</a> a zkontrolujte jakékoliv chyby a varování v <a href=\"#log-section\">logu</a>.",
"All checks passed." : "Všechny testy byly úspěšné.",
"System Status" : "Systém status",
"Tips & tricks" : "Tipy a triky",
"How to do backups" : "Jak vytvářet zálohy",
"Performance tuning" : "Ladění výkonu",
"Improving the config.php" : "Vylepšení souboru config.php",
"Theming" : "Vzhledy",
"Hardening and security guidance" : "Průvodce vylepšením bezpečnosti",
"Get the apps to sync your files" : "Získat aplikace pro synchronizaci vašich souborů",
"Desktop client" : "Aplikace pro počítač",
"Android app" : "Aplikace pro Android",
"iOS app" : "iOS aplikace",
"If you want to support the project\n\t\t\t<a href=\"https://owncloud.org/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">join development</a>\n\t\t\tor\n\t\t\t<a href=\"https://owncloud.org/promote\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">spread the word</a>!" : "Chcete-li podpořit tento projekt\n\t\t\t<a href=\"https://owncloud.org/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">spojit s vývojáři</a>\n\t\t\tnebo\n\t\t\t<a href=\"https://owncloud.org/promote\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">šířit projekt</a>!",
"Show First Run Wizard again" : "Znovu zobrazit průvodce prvním spuštěním",
"White-listed Domains" : "Seznam povolených domén",
"No Domains." : "Bez domén.",
"Domain" : "Doména",
"Add Domain" : "Přidat doménu",
"Add" : "Přidat",
"Profile picture" : "Profilový obrázek",
"Upload new" : "Nahrát nový",
"Select from Files" : "Vybrat ze Souborů",
"Remove image" : "Odebrat obrázek",
"png or jpg, max. 20 MB" : "png nebo jpg, max. 20 MB",
"Picture provided by original account" : "Obrázek je poskytován původním účtem",
"Cancel" : "Zrušit",
"Choose as profile picture" : "Vybrat jako profilový obrázek",
"Full name" : "Celé jméno",
"No display name set" : "Jméno pro zobrazení nenastaveno",
"Email" : "Email",
"Your email address" : "Vaše emailová adresa",
"Change email" : "Změna emailu",
"Set email" : "Nastavení emailu",
"For password recovery and notifications" : "Pro obnovení hesla a upozornění",
"No email address set" : "Emailová adresa není nastavena",
"You are member of the following groups:" : "Patříte do následujících skupin:",
"You are not a member of any groups." : "Nejste členem žádné skupiny.",
"Password" : "Heslo",
"Unable to change your password" : "Změna vašeho hesla se nezdařila",
"Current password" : "Současné heslo",
"New password" : "Nové heslo",
"Change password" : "Změnit heslo",
"Help translate" : "Pomoci s překladem",
"You are using %s" : "Používáte %s",
"You are using %s of %s (%s %%)" : "Používáte %s z %s (%s %%)",
"Developed by the {communityopen}ownCloud community{linkclose}, the {githubopen}source code{linkclose} is licensed under the {licenseopen}<abbr title=\"Affero General Public License\">AGPL</abbr>{linkclose}." : "Vyvíjeno {communityopen}komunitou ownCloud{linkclose}, {githubopen}zdrojový kód{linkclose} je licencován pod {licenseopen}<abbr title=\"Affero General Public License\">AGPL</abbr>{linkclose}.",
"Sessions" : "Sezení",
"These are the web, desktop and mobile clients currently logged in to your %s." : "Toto jsou klienti aktuálně přihlášení do instance %s přes web, počítač, či telefon.",
"Browser" : "Prohlížeč",
"Most recent activity" : "Nejnovější aktivity",
"App passwords / tokens" : "Hesla / tokeny aplikace",
"You've linked these apps." : "Připojili jste tyto aplikace.",
"Name" : "Název",
"App name" : "Jméno aplikace",
"Use the credentials below to configure your app or device." : "Použijte níže vypsané přihlašovací údaje k nastavení aplikace nebo přístroje.",
"Username" : "Uživatelské jméno",
"Password / Token" : "Heslo / Token",
"Done" : "Dokončeno",
"Version" : "Verze",
"The activation link has expired. Click the button below to request a new one and complete the registration." : "Odkazu pro aktivaci vypršela platnost. Kliknutím na tlačítko níže požádejte o nový a dokončete registraci.",
"Resend activation link" : "Znovu odeslat odkaz pro aktivaci",
"New Password" : "Nové heslo",
"Confirm Password" : "Potvrdit heslo",
"Please set your password" : "Prosím nastavte si heslo",
"Personal" : "Osobní",
"Admin" : "Administrace",
"Activation link was sent to an email address, if one was configured." : "Odkaz pro aktivaci byl odeslán na emailovou adresu, pokud byla nastavena.",
"Settings" : "Nastavení",
"Show enabled/disabled option" : "Zobrazení možnosti pro povolení/zakázání",
"Show storage location" : "Cesta k datům",
"Show last log in" : "Poslední přihlášení",
"Show user backend" : "Zobrazit uživatelskou podpůrnou vrstvu",
"Set password for new users" : "Nastavit heslo pro nové uživatele",
"Show email address" : "Emailová adresa",
"Show password field" : "Zobrazit pole pro heslo",
"Show quota field" : "Zobrazit pole pro kvótu",
"E-Mail" : "Email",
"Admin Recovery Password" : "Heslo obnovy správce",
"Enter the recovery password in order to recover the users files during password change" : "Zadejte heslo obnovy pro obnovení souborů uživatele při změně hesla",
"Add Group" : "Přidat skupinu",
"Group" : "Skupina",
"Everyone" : "Všichni",
"Admins" : "Administrátoři",
"Default Quota" : "Výchozí kvóta",
"Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Zvolte prosím kvótu pro úložiště (např. \"512 MB\" nebo \"12 GB\")",
"Unlimited" : "Neomezeně",
"Other" : "Jiný",
"Full Name" : "Celé jméno",
"Group Admin for" : "Správce skupiny ",
"Quota" : "Kvóta",
"Storage Location" : "Umístění úložiště",
"User Backend" : "Uživatelská podpůrná vrstva",
"Last Login" : "Poslední přihlášení",
"change full name" : "změnit celé jméno",
"set new password" : "nastavit nové heslo",
"change email address" : "změnit emailovou adresu",
"Default" : "Výchozí"
},
"nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n >= 2 && n <= 4 && n % 1 == 0) ? 1: (n % 1 != 0 ) ? 2 : 3;");
|
class BreadcrumbView {
/**
* @param {object} breadcrumbParts collection of DOM elements
*/
constructor(breadcrumbParts) {
this._breadcrumbParts = breadcrumbParts;
}
getBreadcrumbsAmount() {
return this._breadcrumbParts.breadcrumbs.children.length;
}
movePointerForward(nextBreadcrumb) {
this._breadcrumbParts.breadcrumbs
.children[nextBreadcrumb-1].classList.remove('current');
this._breadcrumbParts.breadcrumbs
.children[nextBreadcrumb].classList.add('current', 'active-breadcrumb');
}
movePointerBack(previousBreadcrumb) {
this._breadcrumbParts.breadcrumbs
.children[previousBreadcrumb+1]
.classList.remove('current', 'active-breadcrumb');
this._breadcrumbParts.breadcrumbs
.children[previousBreadcrumb].classList.add('current');
}
}
|
'use strict'
const express=require('express');
const Users=require('../controllers/project');
const Acounts=require('../controllers/Acounts');
const Task=require('../controllers/Task');
const multipart=require('connect-multiparty');
const multpartMiddleware=multipart({uploadDir:'./uploads'});
let router=express.Router();
// User login and sigup rutes
router.post('/login', Acounts.Login);
router.post('/save-user',Acounts.saveUser);//guardo usuario signup
//user crud admin
router.get('/user/:id?',Users.GetUser)//ruta obtener usuarios
router.get('/admin-all/:email?',Users.getAllAdmin);//obtengo todos los usuarios asignados al admin
//crear tareas,modificar, eliminar,obtener
router.post('/create-task',Task.CreateTask);//👌
router.get('/task/:id',Task.GetTask);//👌
router.delete('/task/:id',Task.EliminateTask);//👌
router.put('/task/:id',Task.ModifyTask);//👌
//usuarios
router.put('/edit/:id',Users.UserUpdate);
router.delete('/del/:id',Users.UserBeDelete);
router.post('/upload-image/:id',multpartMiddleware,Users.uploadImage);
router.get('/imagenes/:image',Users.getImage);
//eliminar usuarios
module.exports=router;
|
const i18nObject = {
header: {
shop: "Shop",
faq: "FAQ",
contact: "Contact",
login: "Log In",
visage: "VISAGE",
adults:"Adults",
kids: "Kids",
},
home: {
mostPopular: "Most Popular",
description: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas sequi quisquam eum et consequatur accusamus nam quia ratione minima recusandae placeat eius voluptatum animi ducimus nemo, maiores veniam ab! Voluptas eligendi, quam placeat ipsam maxime nemo vero ea voluptate quod ducimus enim cumque quisquam velit accusamus sequi quia nulla delectus!",
},
footer:{
shop: "Shop",
},
};
export default i18nObject;
|
Object.defineProperties(String.prototype,{
"contains":{
value:function(value, strict){
if(undefined == strict) strict = false
var val = this.toString()
var exact_type_value = _exact_type_of(value)
if( strict && (this.exact_type != exact_type_value) ) return false
// console.log("Exact type:"+this.exact_type)
if(exact_type_value == 'regexp')
{
return val.match(value) !== null
}
else
{
if(strict) return val == value
else return val.indexOf(value) > -1
}
// // Je ne comprends pas pourquoi j'avais écris ce code ci-dessous. Pourquoi
// // tester le type de l'élément si cette méthode s'applique aux strings ???.......
// switch(this.exact_type)
// {
// case 'string':
// if(exact_type_value == 'regexp')
// {
// return val.match(value) !== null
// }
// else
// {
// if(strict) return val == value
// else return val.indexOf(value) > -1
// }
// case 'array':
// return val.indexOf(value) > -1
// case 'object':
// if(typeof value == 'string'){
//
// }
// else if (typeof value == 'object'){
//
// }
// else throw LOCALES.messages['unabled to evaluate']+inspect(value)+LOCALES.messages['for a hash']
// default:
// throw LOCALES.messages['contains method cant be applied to']+"`"+this.to_s+"`"
// }
}
},
"not_contains":{value:function(value, strict){return ! this.contains(value,strict)}}
})
|
/*
* @Author: Harry
* @Date: 2019-09-18 03:39:07
* @Last Modified by: Harry-mac
* @Last Modified time: 2019-09-18 03:40:08
*/
export default {
linkPage(path) {
path = isHtml(path);
let url = window.location.href;
// console.log(url);
let endIdx = url.indexOf("#");
// console.log(endIdx);
let startIdx;
for (let i = endIdx; i >= 0; i--) {
if (url[i] === '/') {
startIdx = i;
break;
}
}
// console.log(startIdx);
let newUrl = url.substring(0, startIdx + 1) + path + "#/";
// console.log(newUrl);
return newUrl;
}
}
function isHtml(path){
let idx = path.indexOf(".");
if(idx == -1){
return path + ".html";
}
return path;
}
|
// @ts-check
/* eslint-disable react/static-property-placement */
import cn from 'classnames';
import React from 'react';
// BEGIN (write your solution here)
const Header = (props) => <div className="modal-header">
<div className="modal-title">{props.children}</div>
<button type="button" onClick = {props.toggle} className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
</div>;
const Body = (props) => <p className="modal-body">{props.children}</p>;
const Footer = (props) => <p className="modal-footer">{props.children}</p>;
class Modal extends React.Component {
static Header = Header;
static Body = Body;
static Footer = Footer;
static defaultProps = {
isOpen: false
}
constructor (props) {
super (props);
}
render() {
const { isOpen, children } = this.props;
const className = cn('modal', {
fade: isOpen,
show: isOpen,
});
const style = {
display: isOpen ? 'block' : 'none'
}
return <div className={className} style={style} role="dialog">
<div className="modal-dialog">
<div className="modal-content">
{this.props.children}
</div>
</div>
</div>;
}
}
export default Modal;
// END
|
import {Meteor} from 'meteor/meteor';
import {Session} from 'meteor/session';
import {Template} from 'meteor/templating';
import {Tabular} from 'meteor/aldeed:tabular';
import {EJSON} from 'meteor/ejson';
import {moment} from 'meteor/momentjs:moment';
import {_} from 'meteor/erasaur:meteor-lodash';
import {numeral} from 'meteor/numeral:numeral';
import {lightbox} from 'meteor/theara:lightbox-helpers';
// Lib
import {tabularOpts} from '../../../core/common/libs/tabular-opts.js';
// Collection
import {Location} from '../../imports/api/collections/location.js';
// Page
Meteor.isClient && require('../../imports/ui/pages/location.html');
tabularOpts.name = 'microfis.location';
tabularOpts.collection = Location;
tabularOpts.columns = [
{title: '<i class="fa fa-bars"></i>', tmpl: Meteor.isClient && Template.Microfis_locationAction},
{data: '_id', title: 'ID'},
{data: 'khName', title: 'Kh Name'},
{data: 'level', title: 'level'},
{
data: 'parentDoc',
title: 'Parent Doc',
render: function (val, type, doc) {
if (doc.level == 2) {
return `${val.khNamePro}`;
} else if (doc.level == 3) {
return `${val.khNamePro}, ${val.khNameDis}`;
} else if (doc.level == 4) {
return `${val.khNamePro}, ${val.khNameDis}, ${val.khNameCom}`;
}
}
}
];
// tabularOpts.extraFields = ['parentId'];
export const LocationTabular = new Tabular.Table(tabularOpts);
|
requirejs.config({
baseUrl: 'js',
paths: {
jquery: 'libraries/jquery.min',
react: 'libraries/react.min',
fastclick: 'libraries/fastclick.min',
domReady: 'libraries/domReady.min',
reuseComponents: 'components_compiled/reuseComponents',
}
});
require(['domReady', 'fastclick', 'components_compiled/mainPage'], function (domReady, fastclick, mainPage) {
this.wholePage = mainPage.startRender();
domReady(function () {
fastclick.attach(document.body);
});
});
|
const Context = require("./context");
const ProjectRepository = require("../repository/project-repository");
const TaskRepository = require("../repository/task-repository");
const context = new Context("./database.sqlite3");
const projectRepo = new ProjectRepository(context);
const taskRepo = new TaskRepository(context);
module.exports.createTable = () => {
return new Promise((resolve, reject) => {
projectRepo
.createTable()
.then(() => taskRepo.createTable())
.then(() => resolve("Create Table"))
.catch(err => reject("Create Table Error" + err));
});
};
|
/* global nonic, robotic, automaton, attachInline */
meiko.addEventListener(nonic.ai.meiko.nerve);
nonic.ai.meiko.ids = ['meiko'];
(function($start) { // Avoid conflicts with other libraries
var $meiko = $('#nonic','#ai','#meiko','#nerve');
nonic.mikuNerve = function(meiko ,string) {
if (meikoNerve !== null) {
status(meikoNerve);
meikoNerve = null;
}
return meiko;
};
})(jQuery);
|
$('.filterElements').change(function(){
document.getElementById('id_supervisor').getElementsByTagName('option')[0].selected = 'selected';
var cl = document.getElementById('id_faculty').getElementsByTagName('option')[this.selectedIndex].getAttribute("class");
console.log(cl)
$('option').hide();
$('option[class$="' + cl + '"]').show();
$('option[id$="select"]').show();
});
|
import { GifGridItem } from '../../components/GifGridItem';
//Importar para que funcione enzyme
import { shallow } from 'enzyme';
//Importar para poder utilizar JSX
import React from 'react';
describe('Pruebas de GifGridItem', () => {
const title = 'Título';
const url = 'http://urlprueba.com';
const wrapper = shallow(<GifGridItem title={ title } url={ url }/>);
test('Mostrar correctamente el componente a través de un snapshot sin parámetros', () => {
const wrapper = shallow(<GifGridItem />);
expect(wrapper).toMatchSnapshot();
//Cambiar algo en el componente para probar que no pasa el test. Luego dejar como estaba.
});
test('Mostrar correctamente el componente a través de un snapshot con parámetros', () => {
//Mover fuera de los tests para no repetir cada vez
// const wrapper = shallow(<GifGridItem title={ title } url={ url }/>);
expect(wrapper).toMatchSnapshot();
//Utilizar u en caso de querer actualizar el snapshot
//Cambiar title o url para probar que no pasa el test. Luego dejar como estaba.
});
test('Mostrar correctamente el título', () => {
//Mover fuera de los tests para no repetir cada vez
// const wrapper = shallow(<GifGridItem title={ title } url={ url }/>);
//Buscamos <p> porque ahí debe mostrarse el título
const p = wrapper.find('p');
expect(p.text().trim()).toBe(title);
});
test('Validar que la imagen tengo la url y el alt', () => {
//Buscamos <img> porque ahí debe mostrarse la imagen
const img = wrapper.find('img');
//Validar por comparación de texto en la propiedad de la etiqueta
// console.log(img.html('src'));
// expect(img.html('src').includes(url)).toBe(true);
// expect(img.html('alt').includes(title)).toBe(true);
//En lugar de utilizar html() y validar como string se puede utilizar props() y acceder directamente a las propiedades de la etiqueta
// expect(img.props().src).toBe(url);
// expect(img.props().alt).toBe(title);
//También se puede utilizar prop('<atributo>')
expect(img.prop('src')).toBe(url);
expect(img.prop('alt')).toBe(title);
});
test('Validar que el div tenga la clase animate__fadeIn', () => {
const div = wrapper.find('div');
//Obtener las clases
const className = div.prop('className');
// console.log(className);
//Validar con prop('<atributo>') y comparar por texto
// expect(className.includes('animate__fadeIn')).toBe(true);
// Validar por clase directamente
expect(div.hasClass('animate__fadeIn')).toBe(true);
});
})
|
import request from "../../utils/request/request"
Page({
/**
* 页面的初始数据
*/
data: {
banner: [],
personalized: []
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getBannerData()
this.getPersonalizedData()
},
// 获取轮播图数据
async getBannerData() {
let bannerData = await request("/banner")
this.setData({
banner: bannerData.banners
})
},
// 获取推荐歌单数据
async getPersonalizedData() {
let personalizedData = await request("/personalized")
this.setData({
personalized: personalizedData.result
})
}
})
|
import { stripTrailingSlash } from "../utils";
const BASE_DATA_MANAGEMENT_URL = stripTrailingSlash(
process.env.REACT_APP_BASE_DATA_MANAGEMENT_URL ||
process.env.REACT_APP_BASE_URL
);
export const ADD_MAINTENANCE_URI = `${BASE_DATA_MANAGEMENT_URL}/data/channels/maintenance/add`;
export const DEVICE_RECENT_FEEDS = `${BASE_DATA_MANAGEMENT_URL}/data/feeds/transform/recent`;
|
import React, { Component } from 'react';
export default class Timestamps extends Component{
render() {
return (
<div className="Timestamps">
<div className="Time Time--current">{this.convertTime(this.props.currentTime)}</div>
<div className="Time Time--total">{this.props.duration}</div>
</div>
)
}
convertTime(timestamp) {
let minutes = Math.floor(timestamp / 60);
let seconds = timestamp - (minutes * 60);
if (seconds < 10) { seconds = '0' + seconds; }
timestamp = minutes + ':' + seconds;
return timestamp;
}
}
|
function calculate(display = true){
//Set initial variables
var inputValue = document.getElementById('inputText').value;
var inputArray = [];
var sentenceArray = [];
var word = '';
var textStats = new Object();
textStats.wordCount = 0;
textStats.sentenceCount = 0;
textStats.spaceCount = 0;
textStats.avgWords = 0;
for (i = 0; i < inputValue.length; i++) {
word = word + inputValue[i];
if( (inputValue[i] === ' ') || (i === inputValue.length - 1) ) {
inputArray.push(word);
word = '';
if ( inputValue[i] === ' ' ) {
textStats.spaceCount++;
}
}
}
sentenceArray = inputValue.match(/[^\.!\?]+[\.!\?]+/g);
textStats.sentenceCount = sentenceArray.length;
textStats.wordCount = inputArray.length;
textStats.avgWords = textStats.wordCount / textStats.sentenceCount;
if ( display === true ){
displayStats(textStats);
}
}
function displayStats(textStats = false, consoleOutput = false) {
if ( textStats === false ){
console.log('Unable to calculate statistics!');
exit();
}
else
{
if ( consoleOutput === true ) {
console.log('Words: ' + textStats.wordCount + ' | Sentences: ' + textStats.sentenceCount + ' | Spaces: ' + textStats.spaceCount + ' | Average W/S: ' + textStats.avgWords);
}
}
}
|
#!/usr/bin/env node
[...Array(100).keys()].forEach(x=>console.log((x+1)%3!=0&&(x+1)%5!=0?(x+1):((x+1)%3==0&&(x+1)%5==0?"fizzbuzz":((x+1)%3==0?"fizz":"buzz"))));
|
var selected=-1;
var el=document.getElementsByClassName("element");
var boxes=document.getElementsByClassName("box");
var num = document.getElementsByClassName("number");
var n=[4,5,6,7,8,9,12,13,14,15,16,17,20,31,32,33,34,35,38,49,50,51,52,53,56,81,82,83];
function Load(){
var names=["Берилий","Бор","Въглерод","Азот","Кислород","Флуор","Магнезий","Алуминий","Силиций","Фосфор","Сяра","Хлор","Калций","Галий","Германий","Арсен","Селен","Бром","Стронций","Индий","Калай","Антимон","Телур","Йод","Барий","Талий","Олово","Бисмут"];
/*var num=document.getElementByClassName("box");*/
for (var i = 0; i < num.length; i++) {
do {
rand=Math.floor(Math.random()*n.length);
} while (
rand==el[0].getAttribute("data-n")
||rand==el[1].getAttribute("data-n")
||rand==el[2].getAttribute("data-n")
||rand==el[3].getAttribute("data-n")
||rand==el[4].getAttribute("data-n")
);
num[i].innerHTML=n[rand];
el[i].innerHTML=names[rand];
/*num[i].setAttribute('data-n',rand);*/
el[i].setAttribute('data-n',rand);
}
var a;
var b;
var c;
var an;
var bn;
for (var i = 0; i < 10; i++) {
a=Math.floor(Math.random()*el.length);
b=Math.floor(Math.random()*el.length);
c=el[a].innerHTML;
an=el[a].getAttribute("data-n");
bn=el[b].getAttribute("data-n");
el[a].innerHTML=el[b].innerHTML;
el[a].setAttribute("data-n",bn);
el[b].setAttribute("data-n",an);
el[b].innerHTML=c;
}
}
function Buf(sel){
if (sel==selected) {
el[selected].style.color="blue";
el[selected].style.border="2px solid black";
selected=-1;
return;
}
if (selected>-1) {
el[selected].style.color="blue";
el[selected].style.border="2px solid black";
}
selected=sel;
el[selected].style.color="grey";
el[selected].style.border="2px solid grey";
}
function Put(sel){
for (var i = 0; i < el.length; i++) {
if (el[selected].innerHTML==boxes[i].innerHTML&&i!=sel) {
alert('Вече е използван!');
return;
}
}
if (selected>-1) {
boxes[sel].innerHTML=el[selected].innerHTML;
var b=el[selected].getAttribute("data-n");
boxes[sel].setAttribute("data-n",b);
boxes[sel].style.color="black";
Buf(selected);
}
}
function checkGame(){
var er=0;
for (var i = 0; i < boxes.length; i++) {
if(n[boxes[i].getAttribute("data-n")]==num[i].innerHTML){
boxes[i].style.background="#66ff66";
}
else{
boxes[i].style.background="red";
boxes[i].style.color="transparent";
boxes[i].innerHTML="Елемент";
er=er+1;
}
}
if (er>0) {
document.getElementById("message").innerHTML="Имаш " + er + " грешки";
document.getElementById("message").style.color="red";
}
else{
document.getElementById("message").style.color="green";
document.getElementById("message").innerHTML="Отлично!";
}
}
|
function snapCrackle(maxValue){
let snap = []
for(let i=1; i<=maxValue; i++){
if((i%5===0)&&(i%2===1)){
snap.push("SnapCrackle")
}
else if(i%2===1){
snap.push("Snap")
}
else if(i/i === 1){
snap.push(i)
}
}
return snap.join(', ')
}
console.log(snapCrackle(20))
//---------------------------------------------
function snapCracklePrime(maxValue){
let snap = []
for(let i=1; i<=maxValue; i++){
if(primo(i)&&(i%5===0)&&(i%2===1)){
snap.push("SnapCracklePrime")
}
else if((i%5===0)&&(i%2===1)){
snap.push("SnapCrackle")
}
else if(primo(i)&&i%2===1&&i!==1){
snap.push("SnapPrime")
}
else if(i%2===1){
snap.push("Snap")
}
else if(i===2){
snap.push("Prime")
}
else if(i/i === 1){
snap.push(i)
}
}
return snap.join(', ')
}
console.log(snapCrackle(200))
function primo (maxValue) {
for (let i = 2; i < maxValue; i++)
if (maxValue % i === 0) {
return false
}
return maxValue
}
|
import * as vec3 from '../gl-vec3/index.js'
import {normalize} from './normalize.js'
import {set_axis_angle} from './set_axis_angle.js'
var tmp_vec3 = [0, 0, 0]
var x_vec3 = [1, 0, 0]
var y_vec3 = [0, 1, 0]
/**
* Sets a quaternion to represent the shortest rotation from one
* vector to another.
*
* Both vectors are assumed to be unit length.
*
* @param {quat} out the receiving quaternion.
* @param {vec3} a the initial vector
* @param {vec3} b the destination vector
* @returns {quat} out
*/
export function rotation_to (out, a, b) {
var vec_dot = vec3.dot(a, b)
if (vec_dot < -0.999999) {
vec3.cross(tmp_vec3, x_vec3, a)
if (vec3.length(tmp_vec3) < 0.000001) {
vec3.cross(tmp_vec3, y_vec3, a)
}
vec3.normalize(tmp_vec3, tmp_vec3)
set_axis_angle(out, tmp_vec3, Math.PI)
return out
}
if (vec_dot > 0.999999) {
out[0] = 0
out[1] = 0
out[2] = 0
out[3] = 1
return out
}
vec3.cross(tmp_vec3, a, b)
out[0] = tmp_vec3[0]
out[1] = tmp_vec3[1]
out[2] = tmp_vec3[2]
out[3] = 1 + vec_dot
return normalize(out, out)
}
|
/**
* Internal graphics debug system - gpu markers and similar. Note that the functions only execute in the
* debug build, and are stripped out in other builds.
*
* @ignore
*/
class DebugGraphics {
/**
* An array of markers, representing a stack.
*
* @type {string[]}
* @private
*/
static markers = [];
/**
* Clear internal stack of the GPU markers. It should be called at the start of the frame to
* prevent the array growing if there are exceptions during the rendering.
*/
static clearGpuMarkers() {
DebugGraphics.markers.length = 0;
}
/**
* Push GPU marker to the stack on the device.
*
* @param {import('./graphics-device.js').GraphicsDevice} device - The graphics device.
* @param {string} name - The name of the marker.
*/
static pushGpuMarker(device, name) {
DebugGraphics.markers.push(name);
device.pushMarker(name);
}
/**
* Pop GPU marker from the stack on the device.
*
* @param {import('./graphics-device.js').GraphicsDevice} device - The graphics device.
*/
static popGpuMarker(device) {
if (DebugGraphics.markers.length) {
DebugGraphics.markers.pop();
}
device.popMarker();
}
/**
* Converts current markers into a single string format.
*
* @returns {string} String representation of current markers.
*/
static toString() {
return DebugGraphics.markers.join(" | ");
}
}
export { DebugGraphics };
|
import React, { useContext } from "react";
import ThemeMode from "../theme/ThemeMode";
import { ThemeContext } from "../../context/ThemeContext";
const CurrentWeather = ({ weather }) => {
const { themeObj } = useContext(ThemeContext);
return (
<div className="current-container">
<ThemeMode />
<h5 className="current-title" style={{ color: themeObj.fg }}>
Current Temperature
</h5>
<h1 className="current-temp" style={{ color: themeObj.fg }}>
{weather.currently.temperature}
<span style={{ padding: "5px", color: themeObj.fg }}>℃</span>
</h1>
</div>
);
};
export default CurrentWeather;
|
const UDP = require('dgram');
const MESSAGE = new Buffer('FREEPORT');
const usage = () => {
console.log("Usage: freeports <ip address> # scan with <ip address> server");
console.log("In order to run your own freeports server, see freeports-srv");
}
const main = (argv) => {
if (argv.length !== 3) {
usage();
return;
}
const host = argv.pop();
if (!/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/.test(host)) {
console.log("argument must be an ipv4 address such as 1.2.3.4");
return;
}
const client = UDP.createSocket('udp4');
client.on('message', (msg, rinfo) => {
if (msg.toString('utf8') !== 'PORTFREE') { return; }
console.log('Free Port: ' + rinfo.port);
})
let port = 1;
console.log('Scanning...');
setInterval(() => {
if (!(port % 50)) {
console.log("Port " + port);
}
client.send(MESSAGE, 0, MESSAGE.length, port++, host, (err, bytes) => {
if (err) { console.log(err); }
});
}, 1000);
};
main(process.argv);
|
angular.module('palpite.megasena')
.factory('PalpiteMesena', ['$resource', function($resource) {
return $resource('/api/v1/palpites/megasena');
}
]);
|
customerAdd.onshow=function(){
txtCustomers_contents.style.height = "100px"
let query = "SELECT * FROM customer"
req = Ajax("https://ormond.creighton.edu/courses/375/ajax-connection.php", "POST", "host=ormond.creighton.edu&user=cns02770&pass=" + pw + "&database=cns02770&query=" + query)
let message = ""
for (i = 0; i <= results.length -1; i ++)
message = message + results [i][1] + "\n"
txtCustomers.value = message
}
btnAddCustomer.onclick=function(){
let query = "INSERT INTO customer (name,street,city,state,zipcode) VALUES ('Jesse Antiques', '1113 F St', 'Omaha', 'NE', '68178')"
alert(query)
req = Ajax("https://ormond.creighton.edu/courses/375/ajax-connection.php", "POST", "host=ormond.creighton.edu&user=cns02770&pass=" + pw + "&database=cns02770&query=" + query)
if (req.responseText == 500) {
lblAddMessage.textContent = "You have successfully added Jesse Antiques!"
query = "Select name From customer"
req = Ajax("https://ormond.creighton.edu/courses/375/ajax-connection.php", "POST", "host=ormond.creighton.edu&user=cns02770&pass=" + pw + "&database=cns02770&query=" + query)
results = JSON.parse(req.responseText)
let message = ""
for (i = 0; i <= results.length - 1; i++)
message = message + results[i] + "\n"
txtAllCustomers.value = message
for (i = 0; i <= results.length - 1; i++){
txtAllCustomers.addItem(results[i])
}
} else {
lblAddMessage.textContent = "There was a problem with adding the Jesse Antiques to the database."
}
}
btnPage.onclick=function(){
ChangeForm(customerUpdate)
}
|
import { setRedirectToDispatch, getDispatch } from '../utils/funcs';
export default {
namespace: '_init',
state: {},
subscriptions: {
init({ dispatch, history }) {
return history.listen(({ pathname }) => {
// set redirect.
if (!getDispatch()) { setRedirectToDispatch(dispatch); }
//todo: do something for init.
});
},
},
};
|
export const roleMapping = {
DUO_CARRY: "ADC",
DUO_SUPPORT: "Support",
JUNGLE: "Jungle",
MIDDLE: "Middle",
TOP: "Top"
};
export const reverseRoleMapping = {
ADC: "DUO_CARRY",
Support: "DUO_SUPPORT",
Jungle: "JUNGLE",
Middle: "MIDDLE",
Top: "TOP"
};
export const leagueMapping = {
Bronze: "bronze",
Silver: "silver",
Gold: "gold",
Platinum: "platinum",
"Platinum+": "plat_plus"
};
function desc(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
export function stableSort(array, cmp) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = cmp(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map(el => el[0]);
}
export function getSorting(order, orderBy) {
return order === "desc"
? (a, b) => desc(a, b, orderBy)
: (a, b) => -desc(a, b, orderBy);
}
export const styles = theme => ({
root: {
width: "90%",
marginRight: "auto",
marginLeft: "auto",
marginTop: theme.spacing.unit * 3
},
table: {
minWidth: 800
},
tableWrapper: {
overflowX: "auto"
},
row: {
display: "flex",
justifyContent: "flex-start",
alignItems: "center",
height: 49
},
avatar: {
marginRight: 10
},
loadingBlob: {
width: 128,
height: 128,
display: "block",
marginTop: 300,
paddingBottom: 300,
marginLeft: "auto",
marginRight: "auto"
}
});
|
var Job = require('./job')
var events = require('events')
var util = require('util')
var factory = module.exports = function() {
this.jobs = [];
this.activeJobs = [];
this.threads = 1;
this.state = false;
};
// So will act like an event emitter
util.inherits(factory, events.EventEmitter);
factory.prototype.runQuta = function() {
if (this.state && this.activeJobs.length < this.threads && this.jobs.length >= 1) {
var nextJob = this.jobs.shift();
var nextJobRun = nextJob.run();
if (nextJobRun) {
var self = this;
nextJobRun.on('done', function() {
self.emit('encode', nextJobRun);
self.activeJobs.splice(nextJobRun, 1);
self.runQuta();
})
this.activeJobs.push(nextJobRun);
this.emit('quota', nextJobRun);
} else {
this.emit('error', nextJob)
}
var self = this;
process.nextTick(function() {
self.runQuta()
})
}
return this
};
factory.prototype.createEncode = function(vid) {
//console.log(vid)
this.jobs.push(new Job(vid))
return this
};
factory.prototype.setThreads = function(threadCount) {
this.threads = threadCount;
};
factory.prototype.open = function() {
this.state = true;
return this
};
factory.prototype.close = function() {
this.state = false;
return this
};
|
import React, { Component } from 'react'
import { Switch, Route } from 'react-router-dom'
import Petlist from './Petlist'
import PetDetail from './PetDetail'
class Routes extends Component {
render() {
const getPet = props => {
let name = props.match.params.name;
let currPet = this.props.myPets.find(
pet => pet.name.toLowerCase() === name.toLowerCase()
);
return <PetDetail {...props} pet={currPet} />
}
return (
<Switch>
<Route exact path='/pets/' render={() => <Petlist pet={this.props.myPets} />} />
<Route exact path='/pets/:name' render={getPet} />
</Switch>
)
}
}
export default Routes;
|
module.exports = function(grunt) {
var manifest = require('manifest');
var _ = require('underscore');
//var config = grunt.file.read("slingshotConfig.json");
grunt.registerTask("list", "get em", function() {
grunt.log.writeln("download image");
// download files from test.com
// as specified in the manifest file "http://test.com/manifest"
// to the current working directory
var total = 163;
for(i=0;i<total;i++){
grunt.log.writeln("open:dev"+i);
}
// var indexConfigObj = new Object();
// indexConfigObj.cssSlingshot = "http://tgtfiles.target.com/run/slingshot/public/css/packages/compiled/slingshot-main.css";
// indexConfigObj.jsScript = "http://tgtfiles.target.com/run/slingshot/public/vendor/require.js";
// indexConfigObj.require = "http://tgtfiles.target.com/run/slingshot/public/common.js";
// indexConfigObj.basePath = "http://tgtfiles.target.com/run/slingshot/public/";
// indexConfigObj.cssImgPath = "http://tgtfiles.target.com/run/slingshot/public/images/slingshot/";
// var pathScss = "./public/css/includes/_path.scss";
// var newPathScss = grunt.template.process(grunt.file.read( "gruntTemplates/_pathTemplate.scss" ), {data: indexConfigObj});
// grunt.file.write(pathScss, newPathScss);
// var json_import = [];
// var sling_cache_files = [];
// grunt.file.expand({
// filter: 'isFile',
// cwd: 'public/images/slingshot'
// }, ['**/*']).forEach(function(file){
// sling_cache_files.push(indexConfigObj.basePath+'images/slingshot/' + file);
// });
// var html_export = "";
// grunt.file.expand({
// filter: 'isFile',
// cwd: 'public/modules/slingshot/component_library'
// }, ['**/*']).forEach(function(file){
// var fileContents = grunt.file.read(process.cwd() + '/public/modules/slingshot/component_library/' + file);
// var description = "";
// var runApproved = "";
// var slingshotApproved= "";
// if (fileContents.match('slingshotDescription')){
// var index = fileContents.match('slingshotDescription').index;
// description = fileContents.slice(index);
// description = description.split("'")[1];
// }
// if (fileContents.match('runApproved')){
// runApproved = "<span class='approved'>**RUN APPROVED**</span>";
// }
// if (fileContents.match('slingshotApproved')){
// slingshotApproved = "<span class='approved'>**SLINGSHOT APPROVED**</span>";
// }
// sling_cache_files.push(indexConfigObj.basePath+"modules/slingshot/component_library/"+file);
// json_import = json_import + "<script src=\'"+indexConfigObj.basePath+"modules/slingshot/component_library/"+file+"?ver="+(new Date().getTime())+"'></script>";
// var name = file.split(".js")[0];
// name = name.split("/");
// name = name[name.length - 1];
// var h4 = "<h4 class=\'sling-description\'>"+ description +"</h4>";
// var aTag = " <a href=\'"+indexConfigObj.basePath+"modules/slingshot/component_library/"+file+"\' target=\'blank\' style=\'color: blue !important;text-decoration: underline !important;display: inline-block !important; font-size: 16px;\'>view json</a> ";
// var h2 = "<h2 class=\'slingtemp\'>" + name + aTag + runApproved + slingshotApproved + "</h2>";
// var div = "<div class=\'run_component\'><div id=\'"+name+"\'></div></div><hr>";
// html_export = html_export + h2 + h4 + div;
// });
// indexConfigObj.json_import = json_import;
// indexConfigObj.html_export = html_export;
// var akamaiPaths = grunt.config.get("akamai");
// grunt.log.writeln("akamai.options.urls: ");
// grunt.log.writeln(akamaiPaths["options"]["urls"]);
// grunt.log.writeln("");
// var existing_urls = akamaiPaths["options"]["urls"];
// for(i=0;i < existing_urls.length - 1; i++){
// sling_cache_files.push(existing_urls[i]);
// }
// grunt.log.writeln("");
// grunt.log.writeln(sling_cache_files);
// akamaiPaths.options.urls = sling_cache_files;
// grunt.config.set("akamai", akamaiPaths);
// var indexTemplate = grunt.template.process(grunt.file.read( "gruntTemplates/slingshotTemplate.ejs" ), {data: indexConfigObj});
// grunt.log.writeln("rewriting slingshotTemplate.ejs...");
// var indexFile = './generated/slingshot.html';
// grunt.file.write( indexFile, indexTemplate );
// var commonConfig = new Object();
// commonConfig.baseURL = "http://tgtfiles.target.com/run/slingshot/public/vendor";
// grunt.log.writeln(commonConfig.baseUrl);
// var commonConfigJSTemplate = grunt.template.process(grunt.file.read( "gruntTemplates/commonTemplate.js" ), {data: commonConfig});
// //grunt.log.writeln(grunt.file.read("gruntTemplates/commonTemplate.js"));
// grunt.log.writeln("rewriting common.js...");
// var commonConfigFile = 'public/common.js';
// grunt.file.write( commonConfigFile, commonConfigJSTemplate );
// grunt.log.writeln(commonConfigFile);
});
};
|
import React from "react";
import "./Navigation.css";
const Navigation = (props) => {
const { signedIn, routeChange } = props;
if (signedIn) {
return (
<nav>
<button
className="btn-link"
style={{ color: "red" }}
onClick={() => routeChange("login")}
>
<i className="fas fa-sign-out-alt"></i>
SignOut
</button>
</nav>
);
} else {
return (
<nav>
<button className="btn-link" onClick={() => routeChange("register")}>
Register
</button>
<button className="btn-link" onClick={() => routeChange("login")}>
Login
</button>
</nav>
);
}
};
export default Navigation;
|
/**
* @file components/asDialog.js
* @author leeight
*/
import u from 'lodash';
import {defineComponent} from 'san';
import Dialog from './Dialog';
import Button from './Button';
export function asDialog(Klass) {
if (Klass.__dialogComponent) {
return Klass.__dialogComponent;
}
const dataTypes = u.keys(Klass.dataTypes || Klass.prototype.dataTypes || {});
const klassTemplate = dataTypes.length <= 0
? '<x-biz payload="{{payload}}" />'
: '<x-biz ' + u.map(dataTypes, prop => `${prop}="{{payload.${prop}}}"`).join(' ') + ' />';
const WrappedComponent = defineComponent({
template: `<template>
<ui-dialog open="{{open}}" width="{{width}}" s-ref="dialog" foot="{{!!foot}}">
<span slot="head">{{title}}</span>
${klassTemplate}
<div slot="foot" s-if="foot">
<ui-button on-click="onConfirmDialog" skin="primary">{{foot.okBtn.label || '确定'}}</ui-button>
</div>
</ui-dialog>
</template>`,
components: {
'x-biz': Klass,
'ui-button': Button,
'ui-dialog': Dialog
},
initData() {
return {
open: true,
title: '确认',
payload: null
};
},
inited() {
// 设置foot默认值
if (this.data.get('foot') === undefined) {
this.data.set('foot', {
okBtn: {
label: '确定'
}
});
}
},
messages: {
resize() {
this.ref('dialog').__resize();
}
},
onConfirmDialog() {
this.fire('confirm');
this.data.set('open', false);
}
});
Klass.__dialogComponent = WrappedComponent;
return WrappedComponent;
}
|
// banner animations
$(function () {
var duration = 0.5;
var wait = 4;
var tween;
setTimeout(function animate () {
tween = new TimelineMax();
tween.repeat(-1);
tween.to('.banner__questions.one', duration, { x: '0'});
tween.to('.banner__questions.one', wait, { x: '0'});
tween.to('.banner__questions.one', duration, { x: '100%'});
tween.to('.banner__questions.two', duration, { x: '0'});
tween.to('.banner__questions.two', wait, { x: '0'});
tween.to('.banner__questions.two', duration, { x: '100%'});
tween.to('.banner__questions.three', duration, { x: '0'});
tween.to('.banner__questions.three', wait, { x: '0'});
tween.to('.banner__questions.three', duration, { x: '100%'});
}, 1000);
});
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './MovieItem.scss';
export default class MovieItem extends Component {
render() {
const { tenPhim, hinhAnh, maPhim, ngayKhoiChieu } = this.props.movie;
return (
<div className="col-lg-3 col-sm-6 movieItem">
<div className="card">
<img className="card-img-top" src={hinhAnh !== ''? hinhAnh : ('Coming Soon')} alt='Coming Soon'/>
<div className="card-body" style={{backgroundColor: "#ffffff"}}>
<h4 className="card-title text-truncate ">{tenPhim}</h4>
<h6 className="card-text text-truncate">Show time: {new Date(ngayKhoiChieu).toLocaleDateString()}</h6>
<Link to={`/movie-detail/${maPhim}`} className="btn btn-info">View Detail</Link>
</div>
</div>
</div>
)
}
}
|
export const convertLabelToId = (label) => {
const whitespace = /\s/g;
return label.toLowerCase().replace(whitespace, '');
};
export const checkIfEmailValid = (email) => {
const emailPattern = /^\S+@\S+\.\S+$/;
return emailPattern.test(email);
};
export const checkIfDateValid = (dateString) => {
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
const matchesPattern = datePattern.test(dateString);
if (matchesPattern) {
const date = new Date(dateString);
try {
date.toISOString();
} catch {
return false;
}
return true;
}
return false;
};
|
define([
'./line'
],
function (Line) {
return Line.extend({
y0: function (index) {
var val = this.graph.getY0Pos(index, this.valueAttr);
return this.scales.y(val);
},
render: function () {
Line.prototype.render.apply(this, arguments);
this.renderArea();
},
renderArea: function () {
var getX = _.bind(function (model, index) { return this.x(index); }, this);
var getY = _.bind(function (model, index) { return this.y(index); }, this);
var getY0 = _.bind(function (model, index) { return this.y0(index); }, this);
var area = d3.svg.area()
.x(getX)
.y1(getY)
.y0(getY0)
.defined(function (model, index) { return getY(model, index) !== null; });
var path = this.componentWrapper.insert('g', ':first-child').attr('class', 'group')
.append('path').attr('class', 'stack ' + this.className);
path.datum(this.collection.toJSON())
.attr('d', area);
},
renderBaseLine: function () {
if (this.grouped) {
this.componentWrapper.selectAll('.baseline').remove();
var baseline = _.bind(function (model, index) {
if (model[this.valueAttr] === null) {
return null;
} else {
return this.y0(index);
}
}, this);
this.renderLine(baseline).classed('baseline', true);
}
},
renderCursorLine: function (index) {
Line.prototype.renderCursorLine.apply(this, arguments);
if (this.grouped) {
var x = this.x(index);
var y = this.y(index);
if (y !== null) {
this.componentWrapper.append('line').attr({
'class': 'cursorLine line selected ' + this.className,
x1: x,
y1: this.y0(index),
x2: x,
y2: y
});
}
}
},
renderSelectionPoint: function (index) {
Line.prototype.renderSelectionPoint.apply(this, arguments);
if (this.grouped) {
var x = this.x(index);
var y = this.y0(index);
var className = 'selectedIndicator line ' + this.className;
this.componentWrapper.append('circle').attr({
'class': className,
cx: x,
cy: y,
r: 4
});
}
},
select: function () {
this.componentWrapper.select('path.stack').classed('selected', true).classed('not-selected', false);
this.renderBaseLine();
Line.prototype.select.apply(this, arguments);
},
// put line into dis-emphasised state when other lines are selected
deselect: function () {
this.componentWrapper.selectAll('.baseline').remove();
Line.prototype.deselect.apply(this, arguments);
this.componentWrapper.select('path.stack').classed('selected', false).classed('not-selected', true);
},
// put line into default state when no lines are selected
unselect: function () {
this.componentWrapper.selectAll('.baseline').remove();
Line.prototype.unselect.apply(this, arguments);
this.componentWrapper.select('path.stack').classed('selected', false).classed('not-selected', false);
}
});
});
|
import React, { Component } from 'react';
import logo from './logo.svg';
import MyForm from './Form'
import Header from './partials/header'
import Footer from './partials/Footer'
import 'flexboxgrid/dist/flexboxgrid.css'
// import './App.css';
const AlertaSafari=(props)=>{
return(
<div class="modal">
<div class="modal__inner">
<div class="modal__header">
<h4>¿Estas Usando Safari?</h4>
<button className="modal__close" onClick={props.closeModal}>X</button>
</div>
<div class="modal__body">
<p>Este sitio web fue testeado en Chrome y Firefox. Para obtener los mejores resultados, recomendamos utilizar uno de estos navegadores.</p>
</div>
</div>
</div>
)
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
isSafari:false,
}
this.closeAlert = this.closeAlert.bind(this);
}
closeAlert(){
this.setState({
isSafari:false
})
}
componentDidMount(){
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
this.setState({
isSafari:true
})
}
}
render() {
return (
<div className="App" style={{paddingBottom:55}}>
{this.state.isSafari &&
<AlertaSafari closeModal={this.closeAlert}/>
}
<Header />
<MyForm />
<Footer />
</div>
);
}
}
export default App;
|
// 引入mongoose库, 该库是nodejs来操作mongodb的
const mongoose = require('mongoose')
// 连接mongo, 并且使用dva-todo这个集合
const DB_URL = 'mongodb://localhost:27017/dva-todo'
mongoose.connect(DB_URL)
// 定义表结构
const models = {
todo: {
'text': {type: String, require: true},
'checked': {type: Boolean, require: true},
}
}
// 快速生成对应结构的表
for (let m in models){
mongoose.model(m, new mongoose.Schema(models[m]))
}
// 输出获取数据库的方法
module.exports = {
getModel(name) {
return mongoose.model(name)
}
}
|
var cache = require('memory-cache');
let jsonfile = require('jsonfile');
let Workflow = require('@accionlabs/approval-workflow');
var WorkflowOperations = require('../operations');
var errbackFunc = require('../utility/errback');
module.exports = function(req, res, next){
if(!req.params.workflowId){
return res.status(400).send("Workflow id is required");
}
let workflowOperations = new WorkflowOperations();
workflowOperations.workflowModel({"workflowId":req.params.workflowId}, errbackFunc, function (err,workflowInstance) {
if(!workflowInstance){
return res.status(404).send("Invalid Workflow id");
}
req.workflowInstance = new Workflow(workflowInstance, req.body.document);
next();
});
}
|
/**
* Contains route for user registration.
* @module register
*/
var express = require('express');
var router = express.Router();
var passport = require('passport');
var verificationModel = require('../models/verification');
var credentials = require('../config/credentials');
var nodemailer = require('nodemailer');
var loginUtility = require('../utilities/loginUtility');
var emailUtility = require('../utilities/emailUtility');
var async = require('async');
var log = require('../utilities/logUtility');
/**
* Route for registering a user.
* @name post/register
* @function
* @param {Object} req - Request object containing email and password
* @param {Object} res - Response object
*/
router.post('/register', function(req, res) {
async.waterfall([
// try to register
function(callback) {
register(req, res, callback);
},
// try to login
login,
// try to create verification token
createVerificationToken,
// send verification email
sendVerificationEmail
// process the registration result and return it
], function(err, info, result) {
processResult(err, res, result);
});
});
/**
* Registers a user.
* @param {Object} req - Request object containing email and password
* @param {Object} res - Response object
* @param {Object} callback - Next function to call once user is registered
*/
function register(req, res, callback) {
passport.authenticate('local-signup', function(err, user, info) {
if (err) {
callback(err);
} else {
callback(null, req, user, info);
}
})(req, res);
}
/**
* Determines if a user was created and attempts to log them in to the current session.
* @param {Object} req - Request object
* @param {Object} user - User object
* @param {Object} info - Info object containing error message
* @param {Object} callback - Next function to call once user is logged in
*/
function login(req, user, info, callback) {
if (!user) {
callback(new Error(info.message));
} else {
req.logIn(user, function(err) {
if (err) {
callback(err);
} else {
callback(null, user);
}
});
}
}
/**
* Creates and stores a verification token.
* @param {Object} user - User object
* @param {Object} callback - Next function to call once verification token is created
*/
function createVerificationToken(user, callback) {
// user created, send verification email
var verificationToken = new verificationModel({
_userId: user._id
});
verificationToken.createVerificationToken(function(err, token) {
if (err) {
callback(err);
} else {
callback(null, user, token);
}
});
}
/**
* Sends an email to the address specified by the user with a verification token.
* @param {Object} user - User object
* @param {Object} token - Token used to verify a user's email
* @param {Object} callback - Next function to call once verification email is sent
*/
function sendVerificationEmail(user, token, callback) {
// token created so construct verification email message
var message = {
email: user.local.email,
subject: 'Please verify email address',
verifyURL: token
};
// send verification email
emailUtility.sendVerificationEmail(message, function(err, info) {
callback(err, info, user);
});
}
/**
* Processes the result of the registration and returns it.
* @param {Object} err - Error
* @param {Object} res - Response object
* @param {Object} result - User object
*/
function processResult(err, res, result) {
if (err) {
log.info(err);
res.status(401).send({
message: err.message
});
} else {
// return 200 and user object
res.status(200).send(result.toObject());
}
}
module.exports = router;
|
const addBurger = document.getElementById("create-form");
if (addBurger) {
addBurger.addEventListener("submit", (e) => {
console.log("asdasdasd");
e.preventDefault();
const newBurger = {
burger_name: document.getElementById("burger").value.trim(),
devoured: false,
};
fetch("/api/burgers", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(newBurger),
}).then(() => {
document.getElementById("burger").value = "";
console.log("created new burger");
location.reload();
});
});
}
const devour = document.querySelectorAll(".eat");
if (devour) {
devour.forEach((button) => {
button.addEventListener("click", (e) => {
const id = e.target.getAttribute("data-id");
const newDevour = e.target.getAttribute("data-newdevour");
const newDevourState = {
devoured: true,
};
fetch(`/api/burgers/${id}`, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(newDevourState),
}).then((response) => {
location.reload("/");
});
});
});
}
|
import { Tabs } from 'antd';
const TabByDay = ({ callback }) => {
const { TabPane } = Tabs;
return (
<Tabs defaultActiveKey="today" onChange={callback} className="site-page-tab">
<TabPane tab="Yesterday" key="yesterday" />
<TabPane tab="Today" key="today" />
<TabPane tab="Tomorrow" key="tomorrow" />
</Tabs>
)
}
export default TabByDay
|
export const ADD_REMINDER = "ADD_REMINDER";
export const REMOVE_REMINDER = "REMOVE_REMINDER";
export const CLEAN_REMINDER = "CLEAN_REMINDER";
|
export default {
dsn: process.env.SENTRY_DSN,
// dsn: 'https://ad4441b7d3c74fe69bbdbb67f81d84d8@sentry.io/1855062',
};
|
function solve(year, mounth, day){
let mounthAndDate = (mounth + " " + day + " " + year).toString();
let currentDay = new Date(mounthAndDate);
let nextDay = new Date(currentDay);
nextDay.setDate(currentDay.getDate() + 1)
console.log(nextDay.getFullYear() + "-" + (nextDay.getMonth() + 1) + "-" + nextDay.getDate());
}
solve(1,1,1);
|
export const buildings = function(state = {}, action) {
if (action.type === 'BUILDING_HIGHLIGHT') {
return {
...state,
highlighted: state.highlighted === action.id ? null : action.id
}
}
if (action.type === 'BUILDING_ADDRESS_LOADED') {
return { ...state, bubble: action.address, addressedAt: new Date().getTime() }
}
if (action.type === 'BUILDING_ADDRESS_REMOVE') {
return { ...state, bubble: null, addressedAt: new Date().getTime() }
}
if (action.type === 'BUILDING_LOADED') {
const { buildings } = action
const info = action.meta ? action.meta.info : `Found ${buildings.length} results.`
return { ...state, building: null, highlighted: null, buildings, message: info, loadedAt: new Date().getTime() }
}
if (action.type === 'BUILDING_SELECTED') {
const { building } = action
return { ...state, building, highlighted: null } //, highlighted: action.building.id }
}
if (action.type === 'BUILDING_DESELECT') {
return { ...state, building: null, highlighted: null }
}
return state
}
|
import utils from '../../helpers/utils';
const buildDestinationModalAddForm = () => {
let domString = '';
domString += '<form id="formAddDestination">';
domString += '<div class="form-group">';
domString += '<label for="formAddLocationName">Location name</label>';
domString += '<input type="text" class="form-control" id="formAddLocationName" placeholder="For ex, Baxter State Park, ME">';
domString += '</div>';
domString += '<div class="form-group">';
domString += '<label for="formAddLocationImageUrl">Link to a photo</label>';
domString += '<input type="text" class="form-control" id="formAddLocationImageUrl" placeholder="Find a pic!">';
domString += '</div>';
domString += '<div class="form-group">';
domString += '<label for="formAddLocationDescription">Why do you want to go there?</label>';
domString += '<textarea class="form-control" id="formAddLocationDescription" rows="3"></textarea>';
domString += '</div>';
domString += '</form>';
utils.printToDom('modalAddDestinationForm', domString);
};
export default { buildDestinationModalAddForm };
|
import React from 'react';
import './Persona.css'
// This is quite similar to the general Datasource component, but has different props and styling
function Persona (props) {
const classes = props.selected ?
'flexContainerRow persona_container persona_selected' :
'flexContainerRow persona_container';
return (
<div className={classes}>
<div className={props.selected ? "persona_button_selected" : "persona_button"}><p><</p></div>
<img src={props.avatarSrc} alt='persona icon' className='persona_image' />
<div className='flexDynamicSize persona_text'>
<div className="heading">
{props.nameAge}
</div>
<p className="text">
{props.location}
</p>
<p className="text">
{props.currentJob}
</p>
<p className="text">
{props.description}
</p>
</div>
</div>
);
}
export default Persona;
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.audio.record.RecordingJobCreatedEvent');
goog.require('audioCat.audio.record.Event');
goog.require('audioCat.utility.Event');
/**
* An event marking the creation of a new recording job.
* @param {!audioCat.audio.record.RecordingJob} recordingJob The newly created
* job recording.
* @constructor
* @extends {audioCat.utility.Event}
*/
audioCat.audio.record.RecordingJobCreatedEvent = function(recordingJob) {
goog.base(this, audioCat.audio.record.Event.DEFAULT_RECORDING_JOB_CREATED);
/**
* The newly made recording job.
* @type {!audioCat.audio.record.RecordingJob}
*/
this.recordingJob = recordingJob;
};
goog.inherits(
audioCat.audio.record.RecordingJobCreatedEvent, audioCat.utility.Event);
|
// Copyright 2014 Thinh Pham
angular.module('dongnat.directives')
.directive('advancedFileUpload', function($http, $ionicActionSheet, $ionicGesture, $rootScope, SettingsService, UserService) {
return {
restrict: 'EA',
replace: true,
scope: {
onFinish: '&'
},
link: function(scope, element, attrs) {
element.on('change', function(event) {
scope.state = 'loading';
var formData = new FormData();
formData.append('token', UserService.info().token);
formData.append('file', event.target.files[0]);
if(typeof scope.onStart === 'function') {
scope.onStart();
}
$http({
url: SettingsService.API_URL + '/file/upload',
method: 'POST',
data: formData,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(scope.onSuccess).error(scope.onError);
});
$rootScope.$on('product::clear', function() {
scope.state = 'empty';
scope.oldFile = null;
scope.file = null;
});
},
controller: function($scope) {
$scope.onSuccess = function(response) {
$scope.state = 'loaded';
$scope.file = response.file;
$scope.file.url = SettingsService.API_URL + '/media/thumb/128x128/' + $scope.file.id
var _ref;
$scope.onFinish({
oldFileId: (_ref = $scope.oldFile) != null ? _ref.id : void 0,
newFileId: $scope.file.id
});
$scope.oldFile = $scope.file;
}
$scope.onError = function(error) {
console.log('upload error', error);
}
$scope.state = 'empty';
},
templateUrl: 'templates/directives/advanced_file_upload.html'
};
});
|
import React, {Component} from 'react';
import './MyAccount.css';
import axios from 'axios';
import { setLoginHomepage } from '../../reducers';
import { connect } from 'react-redux';
// import { Redirect } from 'react-router';
import HeaderRoot from './HeaderRoot.js';
class MyAccount extends Component
{
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: null,
redirect: null,
items: []
};
this.urlListRoom = '/getListRoom';
}
componentDidMount = async() => {
var _this = this;
await axios.get(this.urlListRoom, {
headers: {
'Content-Type': 'application/json'
}
})
.then(function(response){console.log(response); _this.setState({
items: response.data
})})
.catch(
error => {
console.log(error)
this.setState({ redirect: '/'})
});
}
returnRoom = async(event) => {
event.preventDefault();
if(event.target[0]) {
let roomIdUse = event.target[0].value;
await axios.post(this.urlBookRoom + roomIdUse, {
headers: {
'Content-Type': 'application/json'
},
})
.then(function(response){
console.log(response.data);
this.setState({ userId: response.data.userId})
// this.setState({ redirect: 'my-account'})
})
.catch(
error => {
//
});
}
}
checkout = (event) => {
event.preventDefault();
}
render() {
const {items, redirect, error, isLoaded} = this.state;
if (redirect !== null || error) {
// return <Redirect to={redirect}/>;
return <HeaderRoot />
} else if(isLoaded) {
return <div>Loading ...</div>
} else {
return(
<div>
<HeaderRoot />
<div className='container container-body'>
<div className="row col-md-6">
<h3>Booking Rooms</h3>
<table className="table table-striped cus-tab">
<thead>
<tr>
<th>Name</th>
<th>Content</th>
<th>Price</th>
<th>Size</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{items.map(function (item, index) {
return(
<tr key={index}>
<td>{item.title}</td>
<td>{item.content}</td>
<td>{item.price}</td>
<td>{item.size}</td>
<td>
<button>View</button>
</td>
</tr>
)}
)}
</tbody>
</table>
</div>
</div>
</div>
)
}
}
}
const mapStateToProps = state => ({
login: state.login,
});
const mapDispatchToProps = {
setLoginHomepage
};
export default connect(mapStateToProps,mapDispatchToProps)(MyAccount);
|
// LibraryView.js - Defines a backbone view class for the music library.
var LibraryView = Backbone.View.extend({
tagName: "div",
initialize: function() {
this.render();
this.collection.on('play', function () {
this.render();
}, this);
},
render: function(){
// to preserve event handlers on child nodes, we must call .detach() on them before overwriting with .html()
// see http://api.jquery.com/detach/
this.$el.children().detach();
this.$el.addClass('panel panel-default');
$panelHeading = $('<div></div>').addClass('panel-heading').html('<h3 class="panel-title">Library</h3>');
$table = $('<table><thead><tr><th>Artist</th><th>Song Name</th><th>Play Count</th></tr></thead></table>')
.addClass('table table-hover');
$tableBody = $('<tbody></tbody>')
.append(this.collection.map(function(song){
return new LibraryEntryView({model: song}).render();
})
);
$table.append($tableBody);
this.$el.append($panelHeading);
this.$el.append($table);
// this.$el.html('<table><th>Library</th></table>').append(
// this.collection.map(function(song){
// return new LibraryEntryView({model: song}).render();
// })
// );
}
});
|
var Dota2 = require("../index"),
util = require("util");
// Events
/**
* Emitted when the server wants the client to create a pop-up
* @event module:Dota2.Dota2Client#popup
* @param {number} id - Type of the pop-up.
* @param {CMsgDOTAPopup} popup - The raw pop-up object. Can contain further specifications like formattable text
*/
// Handlers
var handlers = Dota2.Dota2Client.prototype._handlers;
var onPopUp = function onPopUp(message) {
var popup = Dota2.schema.lookupType("CMsgDOTAPopup").decode(message);
this.Logger.debug("Received popup: "+popup.custom_text);
this.emit("popup", popup.id, popup);
};
handlers[Dota2.schema.lookupEnum("EDOTAGCMsg").values.k_EMsgGCPopup] = onPopUp;
|
/**
* jquery.freshline.lightbox - jQuery Plugin for lightbox gallery
* @version: 1.0 (22.11.11)
* @requires jQuery v1.2.2 or later
* @author themepunch
* All Rights Reserved, use only in freshline Templates or when Plugin bought at Envato !
**/
(function($,undefined){
//////////////////////////////////////
// THE LIGHTBOX PLUGIN STARTS HERE //
/////////////////////////////////////
$.fn.extend({
// OUR PLUGIN HERE :)
tplightboxsolo: function(options) {
////////////////////////////////
// SET DEFAULT VALUES OF ITEM //
////////////////////////////////
var defaults = {
style:"dark-lightbox",
showGoogle:"yes",
showFB:"yes",
showTwitter:"yes",
urlDivider:"?",
vimeo_markup: '<iframe src="{path}?title=0&byline=0&portrait=0" width="{width}" height="{height}" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>',
youtube_markup:'<iframe src="{path}?hd=1&wmode=opaque&autohide=1&showinfo=0" height="{height}" width="{width}" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>',
flvmarkup:'<a href="{path}" style="display:block;width:{width};height:{height}"> </a>',
flvplayer:"'.$template_uri_shortcodes.'/js/flowplayer_plugins/flowplayer-3.2.7.swf"
};
options = $.extend({}, $.fn.tplightboxsolo.defaults, options);
return this.each(function(i) {
var opt=options;
var item=$(this);
setRollOver(item,opt);
//alert(item.data('link'));
//if (!item.data('link') == true) item.click(function() {return false});
})
///////////////////////////////////
// Generate Same Item Group List //
///////////////////////////////////
function generateList(item) {
if (item.data('rel')==undefined) item.data('rel',"nogroup");
// CHECK IF THERE IS ANY PORTFOLIO SELECTOR
if ($('body').find('.selected_selector').length>0)
var rel =$('body').find('.selected_selector').data('group');
else
var rel = item.data('rel');
//console.log("Searched Word:"+rel);
// COLLECT ALL ITEMS IN THE SAME GROUPS
var list=[];
$('body').find('.lightbox').each(function(i) {
var item=$(this);
//console.log("LightBox Nr."+i+" Rel:"+item.data('rel')+" Check to:"+rel);
if (item.data('rel').match(rel)) {
list.push(item);
item.data('id',list.length-1);
}
})
$('body').data('tp-lightbox-list',list);
}
////////////////////////////////////////////////////////////
// SET THE ROLL OVER AND ROLL OUT FUNCTIONS ON THUMBNAILS //
////////////////////////////////////////////////////////////
function setRollOver(item,opt) {
item.data('opt',opt);
item.live('click',function() {
if (item.width()<70) startLightBoxSolo(item,item.data('opt'));
return false;
});
item.find('.hover_plus').live('click',function() {
startLightBoxSolo(item,item.data('opt'));
return false;
});
}
//////////////////////
// SET THE LI ITEMS //
/////////////////////
function checkMobile() {
if( navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/)
){
return true;
} else {
return false;
}
}
function checkiPhone() {
var iPhone=((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
return iPhone;
}
function checkiPad() {
var iPad=navigator.userAgent.match(/iPad/i);
return iPad;
}
///////////////////////////
// GET THE URL PARAMETER //
///////////////////////////
function getParameters(from,hashdivider)
{
var vars = [], hash;
var hashes = from.slice(from.indexOf(hashdivider) + 1).split("&");
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
/////////////////////////////////////////
// START THE LIGHTBOX HERE AFTER CLICK //
////////////////////////////////////////
function addNewLightBoxItem(item,opt,direction) {
// MEDIA AND TYP
var imgsrc = item.data('mediasrc');
if (imgsrc==undefined || imgsrc==null) var imgsrc = item.attr('rel')
var imgtyp = item.find(opt.image).data('typ');
// TRY TO READ OUT THE PARAMETERS FROM THE HREF
var urlsrc=getParameters(imgsrc,"&")[0]
var iframewidth=getParameters(imgsrc,"&")["width"];
var iframeheight=getParameters(imgsrc,"&")["height"];
// ADD THE RIGHT MEDIA TO THE LIGHTBOX
$('body').append('<div id="tp-lightboxactitem" class="'+opt.style+' lightboxitem"></div>');
// ADD THE IMAGE TO THE HOLDER
var lboxitem = $('body').find('#tp-lightboxactitem');
if (checkMobile()) {
lboxitem.css({'position':'absolute'});
$('html, body').animate({ scrollTop: 0 }, 0);
}
//CHECK IF VIDEO OR IMAGE
if (iframewidth!=undefined) {
var ww= iframewidth;
var hh= iframeheight
var flvvideo=0;
var flvid="";
if (urlsrc.indexOf("youtube")>0)
var videosrc=opt.youtube_markup.replace('{path}',urlsrc);
else
if (urlsrc.indexOf("vimeo")>0)
var videosrc=opt.vimeo_markup.replace('{path}',urlsrc);
else {
var videosrc=opt.flvmarkup.replace('{path}',urlsrc);
flvid="flv-"+Math.floor(Math.random()*999999);
videosrc=videosrc.replace('{id}',flvid);
flvvideo=1;
}
//flvmarkup:'<a href="flvsrc" style="display:block;width:{width};height:{height}"> </a>'
//flvplayer:"'.$template_uri_shortcodes.'/js/flowplayer_plugins/flowplayer-3.2.7.swf"
//flowplayer("flvIDdesObjektes", "'.$template_uri_shortcodes.'/js/flowplayer_plugins/flowplayer-3.2.7.swf");
videosrc=videosrc.replace('{width}',iframewidth);
videosrc=videosrc.replace('{height}',iframeheight);
lboxitem.append('<div class="tp-mainimage" style="width:'+ww+'px;height:'+hh+'px">'+videosrc+'</div>');
if (flvvideo==1) {
flowplayer(flvid, opt.flvplayer,{clip: {autoPlay: false, autoBuffering: true}});
}
} else {
lboxitem.append('<div><img class="tp-mainimage" src="'+imgsrc+'"></div>');
}
lboxitem.css({'display':'none'});
// ADD AN INFOFIELD TO THE LIGHTBOX
lboxitem.append('<div class="'+opt.style+' infofield"></div>');
var infofield=lboxitem.find('.infofield');
//ADD THE TITLE TO THE HOLDER
infofield.append('<div class="'+opt.style+' title">'+item.data('title')+'</div>');
var loader = $('body').find('#tp-lightboxloader');
var list=$('body').data('tp-lightbox-list');
var actEntryNr=item.data('id');
var maxEntry=list.length;
lboxitem.data('opt',opt);
lboxitem.data('id',actEntryNr);
lboxitem.data('rel',item.data('rel'));
// ADD THE PAGE TEXT TO THE LIGHTBOX
pagetext = (actEntryNr+1)+"/"+maxEntry;
// ADD THE N PAGE OF M PAGES DIV
infofield.append('<div class="'+opt.style+' rightbutton"></div>');
infofield.append('<div class="'+opt.style+' pageofformat">( '+pagetext+' )</div>');
infofield.append('<div class="'+opt.style+' leftbutton"></div>');
infofield.append('<div class="clear"></div>');
//ADD THE Description TO THE HOLDER
try{
if (item.data('desc').length>0 && item.data('desc') !=undefined)
infofield.append('<div class="'+opt.style+' description">'+item.data('desc')+'</div>');
} catch(e) { }
infofield.append('<div class="clear"></div>');
/////////////////////////////
// THE DEEP LINK FUNCTION //
/////////////////////////////
var urllink=document.URL; //+opt.urlDivider+"_id="+actEntryNr;
// ADD THE SOCIAL ICONS
var twit=$('<div class="twitter"><div class="social_tab"><a href="http://twitter.com/share" class="twitter-share-button" data-url="'+urllink+'" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div></div>');
var face=$('<div class="facebook"><div class="social_tab"><iframe src="//www.facebook.com/plugins/like.php?href='+urllink+'&send=false&layout=button_count&width=250&show_faces=false&action=like&colorscheme=light&font=arial&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:21px;" allowTransparency="true"></iframe></div></div>');
var gplus=$('<div class="googleplus"><!-- +1 Button from plus.google.com --><div class="social_tab"><script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script><g:plusone size="medium" href="'+urllink+'"></g:plusone></div></div>');
infofield.append('<div class="'+opt.style+' lightboxsocials"></div>');
var soc=infofield.find('.lightboxsocials');
soc.css({'opacity':'0.0'});
soc.data('opt',opt);
if (opt.showTwitter=="yes") {
soc.data('twit',twit);
soc.append('<div class="twitter fakesoc"></div>');
}
if (opt.showFB=="yes") {
soc.data('face',face);
soc.append('<div class="twitter fakesoc"></div>');
}
if (opt.showGoogle=="yes") {
soc.data('gplus',gplus);
soc.append('<div class="twitter fakesoc"></div>');
}
soc.append('<div class="clear"></div>');
infofield.append('<div class="clear"></div>');
//ADD THE BUTTONS
lboxitem.append('<div class="'+opt.style+' closebutton"></div>');
var cbutton = lboxitem.find('.closebutton');
var lbutton = infofield.find('.leftbutton');
var rbutton = infofield.find('.rightbutton');
cbutton.css({'opacity':'0.0'});
cbutton.click(function() {
removeLightBox();
$('body').find('#tp-lightboxloader').remove();
});
lbutton.click(
function() {
var item=$(this).parent().parent();
var actEntry=item.data('id');
var opt=item.data('opt');
var list=$('body').data('tp-lightbox-list');
var maxEntry=list.length;
var newEntry=actEntry-1;
if (newEntry<0) newEntry=maxEntry-1;
var newitem=list[newEntry];
lightBoxItemOut(2);
addNewLightBoxItem(newitem,opt,2);
});
rbutton.click(
function() {
var item=$(this).parent().parent();
var actEntry=item.data('id');
var opt=item.data('opt');
var list=$('body').data('tp-lightbox-list');
var maxEntry=list.length;
var newEntry=actEntry+1;
if (newEntry==maxEntry) newEntry=0;
var newitem=list[newEntry];
lightBoxItemOut(1);
addNewLightBoxItem(newitem,opt,1);
});
// TOUCH ENABLED SCROLL
lboxitem.swipe( {data:lboxitem,
swipeLeft:function()
{
var lboxitem = $('body').find('#tp-lightboxactitem');
lboxitem.find('.rightbutton').click();
},
swipeRight:function()
{
var lboxitem = $('body').find('#tp-lightboxactitem');
lboxitem.find('.leftbutton').click();
},
allowPageScroll:"auto"} );
// WAIT TILL IMAGE IS LOADED, AND THAN SET POSITION, ANIMATION, ETC....
lboxitem.waitForImages(function() {
if (direction!=1 && direction!=2) direction=1;
lightBoxItemIn(1);
lboxitem.addClass('tp-lightboxactitem-loaded');
});
$('body').find('#notimportant').remove();
}
////////////////////////////////
// REMOVE LIGHTBOX FROM STAGE //
////////////////////////////////
function removeLightBox() {
lightBoxItemOut(1);
setTimeout(function() {
$('body').find('#tp-lightboxoverlay').cssAnimate({'opacity':'0.0'},{duration:400,queue:false});
$('body').find('#tp-lightboxloader').cssAnimate({'opacity':'0.0'},{duration:400,queue:false});
},200);
setTimeout(function() {
$('body').find('#tp-lightboxoverlay').remove();
$('body').find('#tp-lightboxloader').remove();
$('body').find('#tp-lightboxactitem').remove();
},600);
}
//////////////////////////////////////
// MOVE THE BIG IMAGE TO THE STAGE //
//////////////////////////////////////
function lightBoxItemIn(dir) { // DIR 1: <- DIR2: -> //
var lboxitem = $('body').find('#tp-lightboxactitem');
var loader = $('body').find('#tp-lightboxloader');
var lbutton = lboxitem.find('.leftbutton');
var rbutton = lboxitem.find('.rightbutton');
var soc=lboxitem.find('.lightboxsocials');
clearTimeout(loader.data('anim'));
loader.cssAnimate({'top':(($(window).height()/2))+'px','opacity':'0.0'},{duration:200,queue:false});
setTimeout(function() {
var opt=soc.data('opt');
if (opt.showTwitter=="yes") soc.append(soc.data('twit'));
if (opt.showFB=="yes") soc.append(soc.data('face'));
if (opt.showGoogle=="yes") soc.append(soc.data('gplus'));
soc.find('.fakesoc').remove();
soc.css({'display':'block','opacity':'0.0'});
setTimeout(function() {soc.cssAnimate({'opacity':'1.0'},{duration:400,queue:false})},500);
},1300);
// LIGHTBOX PROBLEM FOR iPAD && iPhone
var ts=0;
if (checkMobile()) ts=jQuery(window).scrollTop();
lboxitem.css({
'display':'block',
});
var imgg = lboxitem.find('.tp-mainimage');
var thisw = imgg.width();
var imgh = imgg.height();
imgg.data('orgw',thisw);
imgg.data('orgh',imgh);
var thish = lboxitem.height();
if (thish<300) {
rbutton.addClass("small");
lbutton.addClass("small");
lboxitem.find('.closebutton').addClass("small");
}
var newW = thisw;
var win=$(window);
if (imgg.width() > win.width() || imgg.data('orgw')>win.width() || (imgg.width()<imgg.data('orgw') && imgg.width()<win.width())) {
newW = (win.width()-20);
if (newW>imgg.data('orgw')) newW = imgg.data('orgw');
imgg.width(newW);
lboxitem.width(newW);
lboxitem.css({'height':'auto'});
var thisw = imgg.width();
var thish = lboxitem.height();
lboxitem.find('iframe').css({'width':newW+"px", 'height':(newW*0.5625)+"px"});
}
var iandm = 0;
if (checkMobile() || navigator.userAgent.indexOf("Mac OS X")!=-1) {
if (lboxitem.find('iframe').length>0) {
thish = (newW*0.5625)+40;
lboxitem.find('.infofield').css({'position':'absolute','top':(thish-30)+"px"});
var infheight = lboxitem.find('.infofield').outerHeight();
infheight = infheight + lboxitem.outerHeight();
lboxitem.css({'height':infheight+"px"});
iandm = 1;
}
}
lboxitem.css({'width':thisw+"px"});
lboxitem.css({'top':'50px'});
var img = lboxitem.find('.tp-mainimage')
img.animate({'opacity':'toggle'},0);
lboxitem.find('.infofield').animate({'opacity':'toggle'},0);
lboxitem.find('.closebutton').animate({'opacity':'toggle'},0);
lbutton.animate({'opacity':0},0);
rbutton.animate({'opacity':0},0);
if (iandm==0) {
lbutton.css({'top':(thish/2)+"px"});
rbutton.css({'top':(thish/2)+"px"});
} else {
lbutton.css({'top':((thish-80)/2)+"px"});
rbutton.css({'top':((thish-80)/2)+"px"});
}
lboxitem.css({
'left':(-5+$(window).width()/2 - thisw/2)+'px',
'top':($(window).height()/2 - thish/2)+'px',
'opacity':0
});
setTimeout(
function() {
lboxitem.animate({'left':(-5+$(window).width()/2 - thisw/2)+'px',
'top':($(window).height()/2 - thish/2)+'px',
'opacity':1
//'width':thisw+"px",
// 'height':thish+"px"
},{duration:500,queue:false});
setTimeout(function() {
img.animate({'opacity':'toggle'},0);
lboxitem.find('.infofield').animate({'opacity':'toggle'},0);
lboxitem.find('.closebutton').animate({'opacity':'toggle'},0);
lbutton.animate({'opacity':0},0);
rbutton.animate({'opacity':0},0);
},0);
// Turn On Close Button Functions...
lboxitem.live('mouseover',
function() {
var $this=$(this);
$this.find('.closebutton').cssAnimate({'opacity':'1.0'},{duration:100,queue:false});
lbutton.animate({'opacity':'1.0'},{duration:200,queue:false});
rbutton.animate({'opacity':'1.0'},{duration:200,queue:false});
});
lboxitem.live('mouseleave', function() {
var $this=$(this);
$this.find('.closebutton').cssAnimate({'opacity':'0.0'},{duration:100,queue:false});
rbutton.animate({'opacity':0},{duration:200,queue:false});
lbutton.animate({'opacity':0},{duration:200,queue:false});
});
},10);
}
//////////////////////////////////////////
// MOVE THE BIG IMAGE OUT OF THE STAGE //
/////////////////////////////////////////
function lightBoxItemOut(dir) { // DIR 1: <- DIR2: -> //
var lboxitem = $('body').find('#tp-lightboxactitem');
var loader = $('body').find('#tp-lightboxloader');
var lbutton = lboxitem.find('.leftbutton');
var rbutton = lboxitem.find('.rightbutton');
lboxitem.attr('id',"tp-lightbox-OLD-item");
var img = lboxitem.find('.tp-mainimage')
var thisw = lboxitem.find('.tp-mainimage').width();
var ll=0;
var tt=0;
var ww=0;
var hh=0;
if (lboxitem.length>0) {
var ll=lboxitem.offset().left;
var tt=lboxitem.offset().top;
var ww=lboxitem.outerWidth();
var hh=lboxitem.outerHeight();
lboxitem.width(ww);
lboxitem.height(hh);
}
//img.remove();
img.animate({'opacity':0},250);
if (lboxitem.length>0) {
//lboxitem.find('.infofield').remove();
//lboxitem.find('.closebutton').remove();
lboxitem.find('.infofield').animate({'opacity':0},350);
lboxitem.find('.closebutton').remove();//animate({'opacity':0},2);
lboxitem.find('.leftbutton').remove();//animate({'opacity':0},2);
lboxitem.find('.rightbutton').remove();//animate({'opacity':0},2);
}
loader.data('anim',setTimeout(function() {loader.cssAnimate({'top':(($(window).height()/2))+'px','opacity':'1.0'},{duration:200,queue:false});},400));
setTimeout(function() {
lboxitem.animate({ opacity:0,},{duration:500,queue:false});
},100);
setTimeout(function() {lboxitem.remove()},650);
}
/////////////////////////////////////////
// START THE LIGHTBOX HERE AFTER CLICK //
////////////////////////////////////////
function startLightBoxSolo(item,opt) {
// ADD A BIG OVERLAY ON THE SCREEN
generateList(item);
$('body').append('<div id="tp-lightboxoverlay" class="'+opt.style+' overlay"></div>');
var overlay=$('body').find('#tp-lightboxoverlay');
var targetOpacity = overlay.css('opacity');
// LIGHTBOX PROBLEM FOR iPAD && iPhone
var ts=0;
if (checkMobile()) ts=jQuery(window).scrollTop();
overlay.css({
'width':$(window).width()+'px',
'height':($(window).height()+150)+'px',
'opacity':'0.4',
'top':'0px',
'left':'0px'
});
overlay.cssAnimate({'opacity':targetOpacity},{duration:500,queue:false});
$('body').append('<div id="tp-lightboxloader" class="'+opt.style+' loader"></div>');
var loader=$('body').find('#tp-lightboxloader');
loader.css({
'top':(ts+$(window).height()/2)+'px',
'left':$(window).width()/2+'px'});
addNewLightBoxItem(item,opt);
overlay.click(function() {
$('body').find('#tp-lightboxloader').remove();
removeLightBox();
});
/////////////////////////////////////////////////////////////////////////////////////
// DEPENDING ON THE SCROLL OR RESIZING EFFECT, WE SHOULD REPOSITION THE LIGHTBOX //
/////////////////////////////////////////////////////////////////////////////////////
if (!checkMobile()) $(window).bind('resize scroll', resizeMeNow);
}
/////////////////////////////////////////////////////
// RESIZE THE WINDOW, AND OPEN THE MAIN IMAGE HERE //
/////////////////////////////////////////////////////
function resizeMeNow(dontshowinfo) {
var $this=$(window);
var overlay=$('body').find('#tp-lightboxoverlay');
// LIGHTBOX PROBLEM FOR iPAD && iPhone
var ts=0;
if (checkMobile()) ts=jQuery(window).scrollTop();
ts=0;
overlay.css({'width':$this.width()+'px',
'height':($this.height()+150)+'px',
'top':ts+'px'
});
// SET THE LOADER POSITION IN THE RIGHT POSITION
var loader=$('body').find('#tp-lightboxloader');
loader.css({
'top':(ts+$(window).height()/2)+'px',
'left':$(window).width()/2+'px'});
// SET THE ACTUAL SHOWN MAIN ITEM POSITION
var lboxitem = $('body').find('.tp-lightboxactitem-loaded');
var img = lboxitem.find('.tp-mainimage');
var thisw=lboxitem.width();
var thish=lboxitem.height();
lboxitem.stop();
if (img!=undefined) {
/*if (img.width() > $this.width() || img.data('orgw')>$this.width() || (img.width()<img.data('orgw') && img.width()<$this.width())) {
var newW = ($this.width()-20);
console.log(newW+" "+img.data('orgw'));
if (newW>img.data('orgw')) newW=img.data('orgw');
img.css({width:(newW)+"px"});
lboxitem.find('iframe').css({'width':newW+"px", 'height':(newW*0.5625)+"px"});
lboxitem.css({width:'auto',height:'auto'});
}*/
lboxitem.animate({'left':(-5 + $(window).width()/2 - thisw/2)+'px', 'top':ts+ ($(window).height()/2 - thish/2)+'px' },{duration:100,queue:false});
}
}
//////////////////////////////////////
// GET THE PAGESCROLL SETTINGS HERE //
//////////////////////////////////////
function getPageScroll() {
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
return yScroll;
}
}
})
})(jQuery);
|
(function(){
'use strict';
angular
.module('everycent.common')
.directive('ecBindingCount', ecBindingCount);
function ecBindingCount(){
var directive = {
restrict:'E',
template: '<button class="btn btn-info btn-xs" ng-click="vm.updateBindingCount()">{{ vm.total }} bindings.</button>',
scope: {
},
controller: controller,
controllerAs: 'vm',
bindToController: true
};
return directive;
}
controller.$inject = [];
function controller(){
/* jshint validthis: true */
var vm = this;
vm.updateBindingCount = updateBindingCount;
function getScopeList(rs) {
var scopeList = [];
function traverseScope(s) {
scopeList.push(s);
if (s.$$nextSibling) {
traverseScope(s.$$nextSibling);
}
if (s.$$childHead) {
traverseScope(s.$$childHead);
}
}
traverseScope(rs);
return scopeList;
}
function updateBindingCount(){
var scopes = getScopeList(angular.element(document.querySelectorAll("[ng-app]")).scope());
vm.total = _.uniq(_.flatten(scopes.map(function(s) { return s.$$watchers; }))).length;
}
}
})();
|
/**
* 定义变量 n = 1, s = 'glj', o = {}, a = [1, 2]
* 1.执行 typeof n 和 n instanceof Number,并说明出现结果的原因
* 2.执行 typeof s 和 s instanceof String,并说明出现结果的原因
* 3.执行 typeof null 和 null instanceof Object,并说明出现结果的原因
* 4.执行 typeof o 和 o instanceof Object,并说明出现结果的原因
* 5.执行 typeof a 和 a instanceof Object,并说明出现结果的原因
* 6.理解 instanceof 的意义 p72
*/
function test1() {
const n = 1;
const s = 'glj';
const o = {};
const a = [1, 2];
console.log(typeof n, n instanceof Number); /** n 为 Number 类型,instanceof 检测基本类型会始终返回 false 因为基本类型不是对象 */
console.log(typeof s, s instanceof String); /** s 为 String 类型,instanceof 检测基本类型会始终返回 false 因为基本类型不是对象 */
console.log(typeof null, null instanceof Object); /** n 为 Object 类型,instanceof 检测基本类型会始终返回 false 因为基本类型不是对象 */
console.log(typeof o, o instanceof Object); /** o 为一个空对象,对象为 object 类型,因此 instanceof 返回 true */
console.log(typeof a, a instanceof Object); /** o 为一个数组,数组为 object 类型,因此 instanceof 返回 true */
}
test1();
|
!(function () {
var cache = {},
cssurl = {};
window.amd = {
version: '1.0.0',
author: 'guosheng (QQ:9169775)',
add: function (namespace, modulename, url) {
if (namespace) {
cache[namespace + '.' + modulename] = url;
}
},
ls: function (keyword) {
if (console) {
console.log(cache);
}
},
addcss: function () {
},
loadcss: function (url) {
if (!cssurl[url]) {
cssurl[url] = 1;
var d = document,
cssLink = d.createElement('link'),
head = d.getElementsByTagName('head')[0];
cssLink.rel = 'stylesheet';
cssLink.type = 'text/css';
cssLink.href = url;
d.getElementsByTagName('head')[0].appendChild(cssLink);
}
},
use: function (arr) {
var dtd = $.Deferred();
require(getArr(arr), function () {
dtd.resolve.apply(this, arguments);
});
return dtd.promise();
}
};
function getArr(arr) {
var _arr = [];
for (var i = 0, k; k = arr[i++];) {
if (cache[k]) {
_arr.push(cache[k]);
} else {
throw ('not find module ' + k);
}
}
return _arr;
}
}());
amd.add('kyo', 'cookie', 'http://static.test.lmhcdn.com/amd/module/kyo/cookie/jquery.cookie.js');
amd.add('kyo', 'jBox', 'http://static.test.lmhcdn.com/amd/module/kyo/jbox/jbox.js');
amd.add('kyo', 'lightbox', 'http://static.test.lmhcdn.com/amd/module/kyo/lightbox2/js/lightbox.min.js');
|
import React from 'react'
function PageQuantity({ selectPageQuantity }) {
const pageQuantity = [2, 4, 8, 10]
return (
<div>
<select
name="selectPage"
id="selectPage"
className="custom-select"
onChange={(e) => selectPageQuantity(e.target.value)}
>
{pageQuantity.map((el, index) => {
return (
<option key={index} value={el}>
{el}
</option>
)
})}
</select>
</div>
)
}
export default PageQuantity
|
//Ручка-перо
function pen(){
var isDipped = false; //var ограничивает доступ извне (private)
this.dip = function(){
isDipped = true;
return "The pen is now dipped in ink";
}
this.write = function(){
if (isDipped){
isDipped = false;
return "You wrote and the pen is no longer dipped in ink";
}
else {
return "The pen isn't dipped in ink!";
}
}
}
|
/**
* Created by rpowar on 8/11/18.
*/
import React, {Component} from 'react';
class Sidebar extends Component {
constructor(props) {
super(props);
}
render() {
let sideBarData = this.props.sideBar;
let imageSrc = sideBarData.image;
let title = sideBarData.title;
let subTitle = sideBarData.subtitle;
let tags = sideBarData.tags.map(data =>
<span className="badge badge-light tagVal">{data}</span>
);
return (
<div className="col-sm-3 sideNav">
<div className="row productDetails">
<img src={imageSrc} alt="itemImage" width="150" height="150"/>
<h5>{title}</h5>
<span>{subTitle}</span>
</div>
<div className="row tags">
{tags}
</div>
<div className="row third">
<div>
<span className="glyphicon glyphicon-home"></span>
<span>Overview</span>
</div>
<div>
<span className="glyphicon glyphicon-signal"></span>
<span>Sales</span>
</div>
</div>
</div>
)
}
}
export default Sidebar;
|
const express = require("express")
const fs = require("fs")
const ejs = require("ejs")
const router = express.Router()
const api = require("../../Activity")
const GetMain = (req, res) => {
let i=0;
let htmlstream = ""
let data_one
let data_two
let data_three
htmlstream =
fs.readFileSync(__dirname + "/../../views/navBar_p.ejs", "utf8")
htmlstream = htmlstream + fs.readFileSync(
__dirname + "/../../views/p_saving.ejs",
"utf8"
)
api
.balance({
FinAcno: "00820100005370000000000001067"
})
.then((data) => {
data_one=data.data.Ldbl
if(data_one==data.data.Ldbl){
data_one=data.data.Ldbl
api
.balance({
FinAcno: "00820100005370000000000007205"
})
.then((data)=>{
data_two=data.data.Ldbl
if(data_two==data.data.Ldbl){
data_two=data.data.Ldbl
api
.balance({
FinAcno: "00820100005370000000000007151"
})
.then((data)=>{
data_three=data.data.Ldbl
if(data_one === undefined){
data_one = 10000
}
if(data_two === undefined){
data_two = 20000
}
if(data_three === undefined){
data_three = 30000
}
console.log(data_one, data_two, data_three)
res.end(ejs.render(htmlstream,{
one:data_one,
two:data_two,
three:data_three,
four:(parseInt(data_one)+parseInt(data_two)+parseInt(data_three)).toLocaleString(),
type:"saving"
}))
})
}
})
}
})
}
router.get("/", GetMain)
module.exports = router
|
const express = require("express");
const exphbs = require('express-handlebars');
const userRouter = require("./routes/users");
const mongoose = require("mongoose");
const bodyParser = require('body-parser');
const User = require("./models/User");
const Comment = require("./models/Comment");
const flash = require("connect-flash");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const passport = require("passport");
const app = express();
const PORT = 5000 || process.env.PORT;
// Flash Middlewares
app.use(cookieParser("passporttutorial"));
app.use(
session({
cookie: { maxAge: 60000 },
resave:true,
secret:"passporttutorial",
saveUninitialized:true
}));
app.use(flash());
// Passport Initialize
app.use(passport.initialize());
app.use(passport.session());
// Global - Res.Locals - Middleware
app.use((req,res,next) =>{
// Our own flash
res.locals.flashSuccess = req.flash("flashSuccess");
res.locals.flashError = req.flash("flashError");
// Passport Flash
res.locals.passportFailure = req.flash("error");
res.locals.passportSuccess = req.flash("success");
// Our Logged In User
res.locals.user = req.user;
next();
});
// MongoDB Connection
mongoose.connect("mongodb://localhost/passportdb",{
useNewUrlParser : true
});
const db = mongoose.connection;
db.on("error",console.error.bind(console,"Connection Error"));
db.once("open", () => {
console.log("Connected to Database");
});
// Template Engine MiddleWare
app.engine('handlebars', exphbs({defaultLayout: 'mainLayout'}));
app.set('view engine', 'handlebars');
// Body Parser
app.use(bodyParser.urlencoded({extended:false}));
// Router Middleware
app.use(userRouter);
app.listen(PORT,() => {
console.log("App Started");
});
app.get("/",(req,res,next) => {
User.find({})
.then(users => {
res.render("pages/index",{users})
})
.catch(err => console.log(err));
});
app.get("/comments",(req,res,next) => {
Comment.find({})
.then(comments => {
res.render("pages/comments",{comments})
})
.catch(err => console.log(err));
});
app.get("/newComment",(req,res,next) => {
Comment.find({})
.then(comments => {
res.render("pages/newComment",{comments})
})
.catch(err => console.log(err));
});
app.use((req,res,next) => {
res.render("static/404");
})
|
import '@testing-library/jest-dom/extend-expect'
import FDBFactory from 'fake-indexeddb/build/FDBFactory'
import FDBKeyRange from 'fake-indexeddb/build/FDBKeyRange'
import { Crypto } from '@peculiar/webcrypto'
import { ResizeObserver } from 'd2l-resize-aware/resize-observer-module.js'
import { deleteDatabase } from '../src/database/databaseLifecycle'
import styles from '../node_modules/.cache/emoji-picker-element/styles.js'
if (!global.performance) {
global.performance = {}
}
if (!global.performance.mark) {
global.performance.mark = () => {}
}
if (!global.performance.measure) {
global.performance.measure = () => {}
}
jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
jest.setTimeout(60000)
global.fetch = require('node-fetch')
global.Response = fetch.Response
global.crypto = new Crypto()
global.ResizeObserver = ResizeObserver
process.env.NODE_ENV = 'test'
process.env.STYLES = styles
global.IDBKeyRange = FDBKeyRange
global.indexedDB = new FDBFactory()
beforeAll(() => {
jest.spyOn(global.console, 'log').mockImplementation()
jest.spyOn(global.console, 'warn').mockImplementation()
})
afterEach(async () => {
// fresh indexedDB for every test
const dbs = await global.indexedDB.databases()
await Promise.all(dbs.map(({ name }) => deleteDatabase(name)))
})
|
let nam=sessionStorage.getItem("name");
let points=sessionStorage.getItem("points");
let user_time=sessionStorage.getItem("time")
document.querySelector(".name").innerHTML=nam;
document.querySelector(".point").innerHTML=points;
document.querySelector(".time").innerHTML=user_time;
|
var saveButton = document.querySelector('#save-button');
var backgroundButtons = document.querySelector('.backgrounds');
var allGarments;
window.addEventListener('load', instantiateOufits);
saveButton.addEventListener('click', saveOutfit);
backgroundButtons.addEventListener('click', assignBackgroundChoice)
function instantiateOufits() {
//Get outfits from local localStorage --> localStorage.getItem --> should return an array of string elements
var retrievedOutfits = localStorage.getItem('savedOutfits');
//Parse items back into objects --> JSON.Parse --> This should return an array of uninstantiated objects
var parsedRetrievedOutfits = JSON.parse(retrievedOutfits);
//Loop over the objects within the array to reinstantiate each property of the outfit object as an instance
if (localStorage) {
for (var i = 0; i < parsedRetrievedOutfits.length; i++) {
var outfit = new Outfit(parsedRetrievedOutfits[i].title, parsedRetrievedOutfits[i].background, parsedRetrievedOutfits[i].id);
}
}
//Push reinstantiated outfit back into the allGarment array
allGarments.push(outfit)
}
function saveOutfit() {
var outfitNameInput = document.querySelector('input');
backgroundChoice = localStorage.getItem('background');
uniqueID = generateUniqueID();
var outfit = new Outfit(outfitNameInput.value, backgroundChoice, uniqueID)
localStorage.removeItem('background');
console.log(outfit);
}
function generateUniqueID() {
return Math.random().toString(36).substr(2, 9);
}
function assignBackgroundChoice() {
var backgroundSelection = event.target.id;
localStorage.setItem('background', backgroundSelection);
}
|
function fetchquote(){
fetch("https://goquotes-api.herokuapp.com/api/v1/random?count=1")
.then(function(response){
return response.json()
})
.then(function(data){
document.getElementById('quotetext').innerHTML = data.quotes[0].text
})
}
fetchquote()
|
var router = require('express').Router();
var dishesController = require('../controllers/dishes');
router.get('/categories', dishesController.getDishCategories);
router.get('/categories/:category', dishesController.getDishesByCategory);
router.get('/', dishesController.getDishes);
router.get('/:id', dishesController.getDish);
router.post('/', dishesController.createDish);
router.delete('/:id', dishesController.removeDish);
router.put('/:id', dishesController.updateDish);
module.exports = router;
|
'use strict';
/*global angular: false */
let music = angular.module('Music', ['mtz-share', 'mtz-directives']);
music.controller('MusicCtrl', ['$scope', $scope => {
$scope.manageActions = [
{
name: 'Foo',
action() {
console.log('You clicked Foo.');
}
},
{
name: 'Bar',
action() {
console.log('You clicked Bar.');
}
},
{
glyph: 'tree-conifer',
title: 'Christmas Tree',
action(album) {
alert('Merry Christmas ' + album.artist + '!');
}
}
];
$scope.searchActions = [
{
glyph: 'tower',
title: 'Your Move!',
action() {
alert('Consider castling.');
}
}
];
}]);
|
import React from 'react';
import { Collapse } from 'reactstrap';
import BrandingHeader from '../layout/BrandingHeader.jsx';
import NavigationMenu from '../layout/NavigationMenu.jsx';
export default class App extends React.Component {
constructor(props) {
super(props);
this.toggleNavBar = this.toggleNavBar.bind(this);
this.state = {
navigationMenuIsOpen: false,
};
}
toggleNavBar() {
this.setState({ navigationMenuIsOpen: !this.state.navigationMenuIsOpen });
}
render() {
return (
<div>
<BrandingHeader toggler={this.toggleNavBar} />
<Collapse isOpen={this.state.navigationMenuIsOpen} navbar>
<NavigationMenu />
</Collapse>
</div>
);
}
}
|
const checkJWTToken = require("../lib/security").checkToken;
module.exports = function verifyUser() {
return function (req, res, next) {
const authorization =
req.headers["Authorization"] ?? req.headers["authorization"];
if (!authorization) {
res.sendStatus(401);
return;
}
// Authorization: BASIC token
// Authorization: Bearer token
const [type, token] = authorization.split(/\s+/);
switch (type) {
case "Basic":
// const [clientId, clientSecret] = decodeBasicToken(token);
// Check base client credentials
// req.merchant = credentials.merchant
next();
break;
case "Bearer":
checkJWTToken(token)
.then((user) => {
// reload user form base
req.user = user;
// if(user.merchant) req.merchant = user.merchant
next();
})
.catch(() => res.sendStatus(401));
break;
default:
res.sendStatus(401);
break;
}
};
};
|
// Strict Mode On (엄격모드)
"use strict";
"use warning";
/**
* @author Lazuli
*/
var PurchasePopup = new function() {
var INSTANCE = this;
var listener;
var frameCnt = 0;
var focus = 0;
var type = 0;
var isKeyLock;
var back;
var btn_cancel_off;
var btn_cancel_on;
var btn_gem_off;
var btn_gem_on;
var btn_gold_off;
var btn_gold_on;
var productImg;
var price;
var amount;
INSTANCE.setProduct = function(_img, _price, _amount, _type) {
productImg = _img;
price = _price;
amount = _amount;
type = _type;
};
INSTANCE.clear = function() {
back = null;
btn_cancel_off = null;
btn_cancel_on = null;
btn_gem_off = null;
btn_gem_on = null;
btn_gold_off = null;
btn_gold_on = null;
productImg = null;
};
INSTANCE.setResource = function(onload) {
var imgParam = [
[back = new Image(), ROOT_IMG + "popup/purchase/back" + EXT_PNG],
[btn_cancel_off = new Image(), ROOT_IMG + "popup/purchase/btn_cancel_off" + EXT_PNG],
[btn_cancel_on = new Image(), ROOT_IMG + "popup/purchase/btn_cancel_on" + EXT_PNG],
[btn_gem_off = new Image(), ROOT_IMG + "popup/purchase/btn_gem_off" + EXT_PNG],
[btn_gem_on = new Image(), ROOT_IMG + "popup/purchase/btn_gem_on" + EXT_PNG],
[btn_gold_off = new Image(), ROOT_IMG + "popup/purchase/btn_gold_off" + EXT_PNG],
[btn_gold_on = new Image(), ROOT_IMG + "popup/purchase/btn_gold_on" + EXT_PNG]
];
ResourceMgr.makeImageList(imgParam, function() {
imgParam = null;
onload();
}, function(err) {
onload();
appMgr.openDisconnectPopup("PurchasePopup setResource Fail!!!!", this);
});
};
var lackCheck = function(_code, _price) {
var str;
var code = _code;
var remainAmount;
if (code == "GOLD") {
remainAmount = ItemManager.checkPrice(code, _price);
str = "골드가";
} else if (code == "GEM") {
remainAmount = ItemManager.checkPrice(code, _price);
str = "보석이";
}
if (remainAmount < 0) {
PopupMgr.openPopup(appMgr.getMessage2BtnPopup(str + " 부족합니다.|충전하러 이동 하시겠습니까?"), function (code, data) {
if (data == ("0")) {
PopupMgr.closePopup(POPUP.POP_MSG_2BTN);
if (_code == "GOLD") {
type = 1;
} else if (_code == "GEM") {
type = 0;
}
} else {
PopupMgr.closePopup(POPUP.POP_MSG_2BTN);
}
});
return true;
}
return false;
};
var enterKeyAction = function(_focus) {
if (listener) listener(INSTANCE, focus + "");
};
return {
toString: function() {
return "PurchasePopup";
},
init: function(onload, callback) {
focus = 0;
isKeyLock = false;
listener = callback;
onload();
},
start: function() {
},
run: function() {
frameCnt++;
UIMgr.repaint();
},
paint: function() {
g.drawImage(back, 300, 121);
g.setFont(FONT_30);
g.setColor(COLOR_WHITE);
if (amount.length > 1) {
g.drawImage(productImg, 452, 225);
if (amount.length == 2) {
for (var i = 0; i < amount.length; i++) {
HTextRender.oriRender(g, amount[i], 740, 295 + (i * 36), HTextRender.CENTER);
}
} else if (amount.length == 5) {
for (var i = 0; i < amount.length; i++) {
HTextRender.oriRender(g, amount[i], 740, 240 + (i * 36), HTextRender.CENTER);
}
} else {
for (var i = 0; i < amount.length; i++) {
HTextRender.oriRender(g, amount[i], 740, 280 + (i * 36), HTextRender.CENTER);
}
}
g.setFont(FONT_22);
HTextRender.oriRender(g, "아이템을 구매하시겠습니까?", 640, 451, HTextRender.CENTER);
g.setFont(FONT_18);
g.setColor(COLOR_RED);
HTextRender.oriRender(g, "※구매한 상품은 우편함에서 확인하세요!", 640, 482, HTextRender.CENTER);
} else {
g.drawImage(productImg, 562, 213);
HTextRender.oriRender(g, amount, 640, 393, HTextRender.CENTER);
g.setFont(FONT_22);
HTextRender.oriRender(g, "아이템을 구매하시겠습니까?", 640, 467, HTextRender.CENTER);
}
if (type == 0) {
g.drawImage(btn_gem_off, 481, 502);
} else {
g.drawImage(btn_gold_off, 481, 502);
}
g.drawImage(btn_cancel_off, 641, 502);
if (focus == 0) {
if (type == 0) {
g.drawImage(btn_gem_on, 481, 502);
} else {
g.drawImage(btn_gold_on, 481, 502);
}
} else {
g.drawImage(btn_cancel_on, 641, 502);
}
g.setFont(FONT_24);
g.setColor(COLOR_WHITE);
HTextRender.oriRender(g, price, 580, 542, HTextRender.CENTER);
},
stop: function() {
},
onKeyPressed: function(key) {
if (isKeyLock) return;
switch(key) {
case KEY_ENTER :
isKeyLock = true;
enterKeyAction(focus);
break;
case KEY_LEFT:
focus = HTool.getIndex(focus, -1, 2);
break;
case KEY_RIGHT:
focus = HTool.getIndex(focus, 1, 2);
break;
case KEY_PREV:
case KEY_PC_F4:
if (listener) listener(INSTANCE, "1");
break;
default:
break;
}
UIMgr.repaint();
},
onKeyReleased: function(key) {
switch(key) {
case KEY_ENTER :
break;
}
},
getInstance: function() {
return INSTANCE;
}
};
};
|
import React from 'react';
import Dropzone from 'react-dropzone';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
var res;
export class FileUpload extends React.Component {
constructor (props) {
super(props);
this.state = {
excelData : [],
isLoading : true,
isDataReadinProgress : true,
dbData : [],
resData:[],
axisData: 'Quarter',
chartData: 'State',
State:[],
Region:[],
xsData: [],
dataColumns: [],
dataset: {},
isCheckedXAxis:true,
isCheckedYAxis:true,
typeOfChart:'line',
axisDataX:[],
tableData: [],
tableHeaders: [],
size: 3
};
this.generateHeaders = this.generateHeaders.bind(this);
}
onDrop = (acceptedFiles, rejectedFiles) => {
this.setState({ excelData : [], isLoading : true});
var opts = { errors : {
badfile : function() {
alert('This file does not appear to be a valid Excel file. If we made a mistake, please send this file to <a href="mailto:saravanakvp1983@gmail.com?subject=I+broke+your+stuff">saravanakvp1983@gmail.com</a> so we can take a look.', function(){});
},
pending : function() {
alert('Please wait until the current file is processed.', function(){});
},
large : function(len, cb) {
confirm("This file is " + len + " bytes and may take a few moments. Your browser may lock up during this process. Shall we play?", cb);
},
failed : function(e) {
alert('We unfortunately dropped the ball here. We noticed some issues with the grid recently, so please test the file using the <a href="/js-xlsx/">raw parser</a>. If there are issues with the file processor, please send this file to <a href="mailto:saravanakvp1983@gmail.com?subject=I+broke+your+stuff">saravanakvp1983@gmail.com</a> so we can make things right.', function(){});
},
} , on : {
sheet : (json, sheetnames) => {
const { chartData, axisData } = this.state;
var headerArr = []
var jsonObject = [];
if(!json) json = [];
headerArr = json[0]
this.setState({ tableData: json, tableHeaders: headerArr});
json.forEach(function(record,rowIndex) {
if(rowIndex>1){
var obj = {};
record.forEach(function(item,colIndex){
obj[headerArr[colIndex]] = item;
});
jsonObject.push(obj);
}
});
var inp = jsonObject;
console.log(jsonObject);
// console.log('inp', inp);
this.setState({ excelData : jsonObject, isLoading : false, resData: res});
console.log(this.state.excelData);
//this.getXAxis(axisData, res);
// this.getChartData(chartData, res, xAxisData);
//this.getMapData(res);
///this.generateMap();
}
}
};
var rABS = typeof FileReader !== 'undefined' && FileReader.prototype && FileReader.prototype.readAsBinaryString;
var f = acceptedFiles[0];
var reader = new FileReader();
function fixdata(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l)
o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(o.length)));
return o;
}
function to_json(workbook) {
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header:1});
if(roa.length > 0) result[sheetName] = roa;
});
return result;
}
function process_wb(wb, sheetidx) {
var sheet = wb.SheetNames[sheetidx||0];
var json = to_json(wb)[sheet];
opts.on.sheet(json, wb.SheetNames);
}
var name = f.name;
reader.onload = function(e) {
var data = e.target.result;
var wb, arr;
var readtype = {type: rABS ? 'binary' : 'base64' };
if(!rABS) {
arr = fixdata(data);
data = btoa(arr);
}
function doit() {
try {
wb = XLSX.read(data, readtype);
// console.log(wb);
process_wb(wb);
} catch(e) { console.log(e); opts.errors.failed(e); }
}
if(e.target.result.length > 1e6) opts.errors.large(e.target.result.length, function(e) { if(e) doit(); });
else { doit(); }
};
if(rABS) {
reader.readAsBinaryString(f);
} else {
reader.readAsArrayBuffer(f);
}
} //onDrop emd here
generateHeaders = function() {
var cols = this.state.tableHeaders;
// generate our header (th) cell components
return cols.forEach(function(headerName, index) {
console.log(headerName);
return <th>{headerName}</th>;
});
};
generateRows = function() {
var cols = this.props.cols, // [{key, label}]
data = this.props.data;
return data.map(function(item) {
// handle the column data within each row
var cells = cols.map(function(colData) {
// colData.key might be "firstName"
return <td> {item[colData.key]} </td>;
});
return <tr key={item.id}> {cells} </tr>;
});
}
render() {
let dropzoneRef;
return (
<div>
<div className="well mb-4 col-sm-12">
<div className="input-group-sm col-md-4">
<label htmlFor="ApplicationName">Application name:</label>
<input type="text" id="ApplicationName" className="form-control-sm" />
</div>
<div className="input-group-sm col-md-4">
<label htmlFor="DataContent">Data content:</label>
<select id="DataContent" className="form-control-sm">
<option value="T">Transaction data</option>
<option value="M">Master data</option>
</select>
</div>
{/* </div>
<div className="row mb-4 col-sm-12"> */}
<div className="input-group-sm">
<label htmlFor="UserGroup">Authorize User Group:</label>
<input type="text" id="UserGroup" className="form-control-sm" />
</div>
</div>
<div className="row mb-3">
<div className="col-sm-2">
{/* <button className="btn btn-success" type="button" onClick={() => { dropzoneRef.open() }}>Browse file</button> */}
<a href="#" onClick={() => { dropzoneRef.open() }}>Browse file</a>
</div>
<div className="col-sm-10">
<Dropzone ref={(node) => { dropzoneRef = node; }} onDrop={(files) => this.onDrop(files)} style={{width:'100%', height:'50px', borderWidth: '2px', borderColor: 'rgb(102, 102, 102)', borderStyle: 'dashed', borderRadius: '5px'}}>
<div style={{padding:'12px'}}>Try dropping some files here, or click to select files to upload.</div>
</Dropzone>
</div>
</div>
<span>Data preview</span>
<BootstrapTable data={this.state.excelData} keyField='S.No'>
{ this.state.tableHeaders.map((name, index) => <TableHeaderColumn key={index} dataField={name}>{name}</TableHeaderColumn>) }
</BootstrapTable>
</div>
);
}
}
|
import React, { Component } from 'react';
import { Route, withRouter, Switch } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import Loadable from 'react-loadable';
import { Loader } from 'react-overlay-loader';
import Navbar from './components/Navbar';
const Loading = () => (
<Loader
fullPage
loading={true}
containerStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.4)' }}
textStyle={{ color: 'rgb(255, 255, 255)' }}
/>
);
const MarketResearch = Loadable({
loader: () => import('./pages/MarketResearch'),
loading: Loading,
});
const Login = Loadable({
loader: () => import('./pages/Login'),
loading: Loading,
});
const Register = Loadable({
loader: () => import('./pages/Register'),
loading: Loading,
});
const Wallet = Loadable({
loader: () => import('./pages/Wallet'),
loading: Loading,
});
const AccountSettings = Loadable({
loader: () => import('./pages/AccountSettings'),
loading: Loading,
});
const RegisterSeed = Loadable({
loader: () => import('./pages/RegisterSeed'),
loading: Loading,
});
const CreateSurvey = Loadable({
loader: () => import('./pages/CreateSurvey'),
loading: Loading,
});
const NotFound = Loadable({
loader: () => import('./pages/NotFound'),
loading: Loading,
});
@withRouter
@inject('store')
@observer
export default class App extends Component {
constructor(props) {
super(props);
this.store = this.props.store.ux;
}
render() {
return (
<div className="wrapper">
{/* <DevTools /> */}
<Navbar />
<Loader
fullPage
loading={this.store.isLoading}
containerStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.4)' }}
textStyle={{ color: 'rgb(255, 255, 255)' }}
text={this.store.loadingText || 'Loading...'}
/>
<div className="container">
<Switch>
<Route exact path="/" component={MarketResearch} />
<Route exact path="/wallet" component={Wallet} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path="/create" component={CreateSurvey} />
<Route exact path="/register/seed" component={RegisterSeed} />
<Route exact path="/settings" component={AccountSettings} />
<Route component={NotFound} />
</Switch>
</div>
<footer>
Copyright © Review.Network {new Date().getFullYear()}
• All rights reserved.
</footer>
</div>
);
}
}
|
module.exports = (server) => {
const produtoController = require('../controller/produto.controller')
server.post('/api/produtos', produtoController.create)
server.get('/api/produtos', produtoController.findAll)
server.get('/api/produtos/:id', produtoController.findById)
server.put('/api/produtos/:id', produtoController.update)
server.delete('/api/produtos/:id', produtoController.delete)
}
|
define(["jquery", "underscore", "backbone", "text!./GeneratorBooleanVariable.html"], function(e, t, n, i) {
return n.View.extend({
template: t.template(i),
className: "control-group",
events: {
"change input": "onChangeInput"
},
initialize: function(e) {
this.variableDef = e.variableDef, this.render()
},
render: function() {
var e = this.template({
variableDef: this.variableDef
});
this.$el.html(e), this.$input = this.$("input")
},
setValue: function(e) {
this.$input.prop("checked", !!e)
},
onChangeInput: function() {
var e = this.$input.prop("checked");
this.trigger("change", e)
}
})
});
|
import { useContext } from "react";
import { Link } from "react-router-dom";
import { SET_HOME_IMAGE, SET_NAVBAR_ACTIVEITEM,SET_COOKIE_IMAGE } from "../utils/constants"
import { StoreContext } from "../store"
import battle from "../json/home_img1.json"
import kingdom from "../json/home_img2.json"
import adventure from "../json/home_img3.json"
import cookie from "../json/home_img4.json"
import pvp from "../json/home_img5.json"
import adCookie from "../json/ad.json"
import attackCookie from "../json/attack.json"
import bumpCookie from "../json/bump.json"
import flyattackCookie from "../json/flyattack.json"
import healCookie from "../json/heal.json"
import magicCookie from "../json/magic.json"
import supCookie from "../json/support.json"
import tankCookie from "../json/tank.json"
import { setPage } from "../actions"
export default function NavItem(props){
const { children, to, className, activeClassName } = props
const { state, dispatch } = useContext(StoreContext);
const getJSON = url => {
switch(url){
case "/home/battle":
return battle;
case "/home/kingdom":
return kingdom;
case "/home/adventure":
return adventure;
case "/home/cookie":
return cookie;
case "/home/pvp":
return pvp;
default:
return battle;
}
}
const getCookie = url =>{
switch(url){
case "/cookie/adcarry":
return adCookie;
case "/cookie/attack":
return attackCookie;
case "/cookie/bump":
return bumpCookie;
case "/cookie/fly_attack":
return flyattackCookie;
case "/cookie/heal":
return healCookie;
case "/cookie/magic":
return magicCookie;
case "/cookie/support":
return supCookie;
case "/cookie/tank":
return tankCookie;
}
}
const onClick = () => {
console.log(children)
dispatch({
type: SET_HOME_IMAGE,
payload: getJSON(to),
});
dispatch({
type: SET_NAVBAR_ACTIVEITEM,
payload: to,
});
dispatch({
type:SET_COOKIE_IMAGE,
payload:getCookie(to),
});
};
return (
<Link to={to}>
<div
onClick={onClick}
className={`
${className}
${state.navBar.activeItem === to ? activeClassName : ""}`}
>
{children}
</div>
</Link>
);
}
|
// 가상 api 페이지...
// admin페이지로 부터 요청을 받아 쿠키의 a_name을 확인한다.
export default (req, res) => {
res.status(200).json({ name: req.cookies.a_name })
}
|
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect(process.env.CONNECTION_STRING || 'mongodb://localhost/regularExpressions');
mongoose.connection.once('open', function() {
console.log("DB connection established!!!");
}).on('error', function(error) {
console.log('CONNECTION ERROR:', error);
});
app.listen(3001, function () {
console.log("what do you want from me! get me on 3001 ;-)");
});
|
$(document).ready(function() {
var num
$.get('/users/myid')
.then(function(data){
console.log(data)
num = data[0].id
//get id
// function getUrlParameter(sParam) {
// const sPageURL = decodeURIComponent(window.location.search.substring(1));
// const sURLVariables = sPageURL.split('&');
// let id;
// sURLVariables.forEach((paraName) => {
// const sParameterName = paraName.split('=');
// if (sParameterName[0] === sParam) {
// id = sParameterName[1] === undefined ? false : sParameterName[1];
// }
// });
// return id;
// }
var userId = num
console.log(userId);
$('#send').click(function(e){
e.preventDefault()
$.post('/users', {
phone: $('#phone').val()
})
.then(function(data){
window.location = '/econtacts.html'
})
.catch(function(err){
console.log(err)
})
})
var userContacts = []
$.get(`/users/econtactbyuser/${userId}`, (data) => {
data.forEach((element) => {
userContacts.push(element)
})
console.log(userContacts)
var source = $("#emergency-contact-template").html();
var template = Handlebars.compile(source);
userContacts.forEach((element) => {
var html = template(element)
$('.emergency-contacts-placeholder').append(html)
})
$(".delete-contact-button").on("click", function(){
console.log("alsdkfjsa;")
console.log("datatatatddaddatdadtadatdat")
var contactIdToDelete = $(this).data('id');
console.log("contactIdToDelete is: " + contactIdToDelete)
$.ajax({
url: 'users/removecontact/'+contactIdToDelete,
type: 'DELETE',
success: function(result){
location.reload(true)
}
})
})
})
})
})
// });
// $.get('/users/econtactbyuser/' +num)
// .then(function(data){
// console.log(data)
// data.forEach(function(el){
// var $newcontact = $('<li>')
// $newcontact.append('<p>Name: '+el.firstname+' '+el.lastname+'</p><p>E-mail: '+el.email+'</p><p>Phone Number: '+el.phone+'</p>')
// $newcontact.attr('id', el.id)
// $('#contacts').append($newcontact.clone())
// })
// })
// })
// $(document).ready(function(){
// $.get('/isloggedin')
// .then(function(data){
// console.log(data)
// if (data != false){
// $.get('/users/myid')
// .then(function(data){
// console.log(data)
// if (data.length < 1){
// window.location = '/addphone.html'
// }
// })
// .catch(function(err){
// window.location = '/addphone.html'
// })
// }
// })
// })
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.