text stringlengths 7 3.69M |
|---|
import React from 'react';
import {
ScrollView,
Text,
View,
} from 'react-native';
import { Button} from 'antd-mobile-rn';
import {storage} from '../RNAsyncStorage';
import {IsEmpty} from '../components/IsEmpty';
export default class ShowEntertain extends React.Component {
constructor(){
super();
this.state={
showContent:{"low":[],"medium":[],"high":[]},
movie:'',
game:'',
book:'',
tvShow:'',
networkVideo:'',
others:''
}
}
componentWillMount(){
storage.load({
key: 'entertain',
}).then(ret => {
this.setState({
movie:ret.movie,
game:ret.game,
book:ret.book,
tvShow:ret.tvShow,
networkVideo:ret.networkVideo,
others:ret.others
})
//然后全部进行遍历找出符合时间要求的,规定要求?
//时间,急不急这个得加一个参数(优先级),在这里添加删除功能
let temp=this.state.showContent;
if (!IsEmpty(this.state.movie)) {
for (let i = 0; i < this.state.movie.length; i++) {
if (this.props.index.state.freeTime>=1) {
temp[this.state.movie[i]["youxianji"]].push(this.state.movie[i]);
}
}
}
if (!IsEmpty(this.state.game)) {
for (let i = 0; i < this.state.game.length; i++) {
if (this.props.index.state.freeTime>=0.5) {
temp[this.state.game[i]["youxianji"]].push(this.state.game[i]);
}
}
}
if (!IsEmpty(this.state.book)) {
for (let i = 0; i < this.state.book.length; i++) {
if (this.props.index.state.freeTime>=0.5) {
temp[this.state.book[i]["youxianji"]].push(this.state.book[i]);
}
}
}
if (!IsEmpty(this.state.tvShow)) {
for (let i = 0; i < this.state.tvShow.length; i++) {
if (this.props.index.state.freeTime>=0.75) {
temp[this.state.tvShow[i]["youxianji"]].push(this.state.tvShow[i]);
}
}
}
if (!IsEmpty(this.state.networkVideo)) {
for (let i = 0; i < this.state.networkVideo.length; i++) {
temp[this.state.networkVideo[i]["youxianji"]].push(this.state.networkVideo[i]);
}
}
if (!IsEmpty(this.state.others)) {
for (let i = 0; i < this.state.others.length; i++) {
temp[this.state.others[i]["youxianji"]].push(this.state.others[i]);
}
}
this.setState({
showContent:temp
})
}).catch(err => {
console.warn(err.message);
})
}
static navigationOptions = {
title: '展示娱乐内容',
};
showContent(){
let self=this;
let renderData=[];
if (!IsEmpty(self.state.showContent["high"])) {
self.state.showContent["high"].map((item,index)=>{
//在这里添加删除功能
renderData.push(
<View key={index}>
<Text>一共需要花{item["time"]}小时</Text>
<Text>{item["content"]}</Text>
<Text>优先级:{item["youxianji"]}</Text>
<Button onClick={self.pick.bind(self,index,item)}>
<Text>删除</Text>
</Button>
</View>
)
})
}
if (!IsEmpty(self.state.showContent["medium"])) {
self.state.showContent["medium"].map((item,index)=>{
//在这里添加删除功能
renderData.push(
<View key={index}>
<Text>一共需要花{item["time"]}小时</Text>
<Text>{item["content"]}</Text>
<Text>优先级:{item["youxianji"]}</Text>
<Button onClick={self.pick.bind(self,index,item)}>
<Text>删除</Text>
</Button>
</View>
)
})
}
if (!IsEmpty(self.state.showContent["low"])) {
self.state.showContent["low"].map((item,index)=>{
//在这里添加删除功能
renderData.push(
<View key={index}>
<Text>一共需要花{item["time"]}小时</Text>
<Text>{item["content"]}</Text>
<Text>优先级:{item["youxianji"]}</Text>
<Button onClick={self.pick.bind(self,index,item)}>
<Text>删除</Text>
</Button>
</View>
)
})
}
return renderData
}
pick(e,v){
let self=this;
switch (v["type"]) {
case 'movie':
let temp1=self.state.movie;
for (let i = 0; i < temp1.length; i++) {
if (temp1[i]["content"]==v["content"]) {
temp1.splice(i,1);
i=i-1;
}
}
self.setState({
movie:temp1
})
break;
case 'game':
let temp2=self.state.game;
for (let i = 0; i < temp2.length; i++) {
if (temp2[i]["content"]==v["content"]) {
temp2.splice(i,1);
i=i-1;
}
}
self.setState({
game:temp2
})
break;
case 'book':
let temp3=self.state.movie;
for (let i = 0; i < temp3.length; i++) {
if (temp3[i]["content"]==v["content"]) {
temp3.splice(i,1);
i=i-1;
}
}
self.setState({
movie:temp3
})
break;
case 'tvShow':
let temp4=self.state.movie;
for (let i = 0; i < temp4.length; i++) {
if (temp4[i]["content"]==v["content"]) {
temp4.splice(i,1);
i=i-1;
}
}
self.setState({
movie:temp4
})
break;
case 'networkVideo':
let temp5=self.state.movie;
for (let i = 0; i < temp5.length; i++) {
if (temp5[i]["content"]==v["content"]) {
temp5.splice(i,1);
i=i-1;
}
}
self.setState({
movie:temp5
})
break;
case 'others':
let temp6=self.state.movie;
for (let i = 0; i < temp6.length; i++) {
if (temp6[i]["content"]==v["content"]) {
temp6.splice(i,1);
i=i-1;
}
}
self.setState({
movie:temp6
})
break;
default:
break;
}
storage.save({
key: 'entertain', // 注意:请不要在key中使用_下划线符号!
data: {
movie:self.state.movie,//每一个类目要有一个数组
game:self.state.game,
book:self.state.book,
tvShow:self.state.tvShow,
networkVideo:self.state.networkVideo,
others:self.state.others
}
});
}
back(){
let self=this;
self.props.index.setState({
showResult:false
})
}
render() {
return (
<ScrollView>
<Text>展示娱乐模块</Text>
{this.showContent()}
<Button onClick={this.back.bind(this)}>
<Text>返回</Text>
</Button>
</ScrollView>
);
}
} |
import TextField from "@material-ui/core/TextField"
import React from "react"
import { useUserState } from "../state/user"
import { getCurrentUser } from "../utils/auth"
export default ({ handleChange }) => {
const { user } = useUserState()
// Auth
const loggedInUser = getCurrentUser()
const defaultEmailValue = loggedInUser.email ? loggedInUser.email : user._email
return (
<>
<TextField
required
name="_replyto"
label="Адрес эл. почты"
defaultValue={defaultEmailValue}
variant="outlined"
type="email"
onChange={handleChange}
margin="normal"
fullWidth
/>
<TextField
required
name="_pickup"
label="Время и дата самовывоза"
defaultValue={user.pickup}
variant="outlined"
type="text"
onChange={handleChange}
margin="normal"
multiline
rows={3}
fullWidth
/>
</>
)
}
|
import { withRouter } from "next/router";
const Nav = (await import("test1/nav")).default;
export async function getStaticPaths() {
return {
paths: [1, 2, 3, 4, 5, 6].map((id) => ({
params: {
id: id.toString(),
},
})),
fallback: false,
};
}
export async function getStaticProps(context) {
return {
props: context.params,
};
}
const SongPage = withRouter(({ id }) => (
<div>
<Nav />
<div>Page for {id}</div>
</div>
));
export default SongPage;
|
import test from "ava";
import TemplateRender from "../src/TemplateRender";
import path from "path";
// Haml
test("Haml", t => {
t.is(new TemplateRender("haml").getEngineName(), "haml");
});
test("Haml Render", async t => {
let fn = await new TemplateRender("haml").getCompiledTemplate("%p= name");
t.is((await fn({ name: "Zach" })).trim(), "<p>Zach</p>");
});
|
import { moduleFor } from 'ember-qunit';
import test from 'vault-password-manager/tests/ember-sinon-qunit/test';
moduleFor('controller:index', 'Unit | Controller | index', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
test('it transitions once the vault has sealed', function(assert) {
let controller = this.subject();
this.stub(controller, "transitionToRoute");
controller.send('vaultSealed');
assert.ok(controller.transitionToRoute.calledOnce);
});
|
module.exports = function(app, reservationService){
//Create a new reservation
app.post('/api/reservation', function(req, res){
reservationService.createReservation(req.body, function(err, insertedData) {
if (err){
res.status(500).send(err);
}else{
res.json({ message: 'Reservation booked!', body: insertedData});
}
});
});
//Get a reservation by its id
app.get('/api/reservation/:reservation_id', function(req,res){
reservationService.getReservationById(req.params.reservation_id, function(err, reservation) {
if (err){
res.status(500).json({error: err});
}
res.json(reservation);
});
});
//Get all reservations for a certain listing
app.get('/api/reservations/:listing_id', function(req,res) {
reservationService.getReservationsByListingId(req.params.listing_id, function(err, reservations) {
if (err){
res.status(500).json({error: err});
}
res.json(reservations);
});
});
//Get the reservations for a renter profile
app.get('/api/renter_reservations/:user_id', function(req,res){
reservationService.getReservationsByBookingUserId(req.params.user_id, function(err, reservations) {
if (err){
res.status(404).json({error: err, message: "Reservations could not be found."});
}
res.json(reservations);
});
});
//Get the reservations for a property owner profile
app.get('/api/owner_reservations/:user_id', function(req,res){
reservationService.getReservationsByPropertyOwnerUserId(req.params.user_id, function(err, reservations) {
if (err){
res.status(404).json({error: err, message: "Reservations could not be found."});
}
res.json(reservations); // return all nerds in JSON format
});
});
//Update a reservation by its id
app.put('/api/reservation/:reservation_id', function(req, res){
reservationService.updateReservationById(req.params.reservation_id, req.body, function(err, insertedData) {
if (err) {
console.log(err);
res.status(500).send(err);
}
res.json({ message: 'Reservation updated! Please wait while the page redirects.', body: insertedData });
});
});
//TODO: come back once stripe controller is done
//Delete a reservation with a cancellation charge
app.post('/api/delete-reservation/:reservation_id', function(req, res) {
//process the charge to the cancelling user
var stripeToken = req.body.token;
var amount = req.body.amount * 100;
var description = "User "+ req.body.cancelling_user +" cancelling a reservation for "+req.body.num_nights+" night(s) from "+
req.body.start_date +" to "+ req.body.end_date +" at a rate of "+ req.body.rate +" per night.\n\n"+
"Cancelled User: "+req.body.cancelled_user+ "\n";
stripeService.createCharge(amount, stripeToken, description, null, function(err, charge) {
if (err) {
console.log(JSON.stringify(err, null, 2));
res.status(err.statusCode).json({msg:err});
}else{
//Delete the reservation once the cancelling user has been charged
reservationService.deleteReservationById(req.params.reservation_id, function(err, info) {
if (err){
console.log(err);
res.status(500).json({error: err, message: "Error cancelling reservation. Please contact will@middoffcampus.com to complete the reservation cancellation."});
}
// console.log(info);
res.json({ message: 'Successfully deleted' });
});
}
})
});
//Just delete a reservation by its id (no charge)
app.delete('/api/reservation/:reservation_id', function(req, res) {
reservationService.deleteReservationById(req.params.reservation_id, function(err, info) {
if (err){
console.log(err);
res.status(500).json({error: err, message: "Error cancelling reservation. Please contact will@middoffcampus.com to complete the reservation cancellation."});
}
// console.log(info);
res.json({ message: 'Successfully deleted' });
});
});
}
|
google.load('maps', '3', { other_params: 'libraries=geometry&sensor=false' });
var Gmaps4Rails = {
//map config
map: null, //contains the map we're working on
visibleInfoWindow: null,
//Map settings
map_options: {
id: 'gmaps4rails_map',
type: "ROADMAP", // HYBRID, ROADMAP, SATELLITE, TERRAIN
center_latitude : 0,
center_longitude : 0,
zoom : 1,
maxZoom: null,
minZoom: null,
auto_adjust : false, //adjust the map to the markers if set to true
auto_zoom: true, //zoom given by auto-adjust
bounds: [] //adjust map to these limits. Should be [{"lat": , "lng": }]
},
//markers + info styling
markers_conf: {
picture : "",
width : 22,
length : 32,
//clustering config
do_clustering: true, //do clustering if set to true
clusterer_gridSize: 50, //the more the quicker but the less precise
clusterer_maxZoom: 5, //removes clusterer at this zoom level
randomize: false, //Google maps can't display two markers which have the same coordinates. This randomizer enables to prevent this situation from happening.
max_random_distance: 100, //in meters. Each marker coordinate could be altered by this distance in a random direction
list_container : null //id of the ul that will host links to all markers
},
//Stored variables
markers : [], //contains all markers. A marker contains the following: {"description": , "longitude": , "title":, "latitude":, "picture": "", "width": "", "length": "", "sidebar": "", "google_object": google_marker}
bounds_object: null, //contains current bounds from markers, polylines etc...
polygons: [], //contains raw data, array of arrays (first element could be a hash containing options)
polylines: [], //contains raw data, array of arrays (first element could be a hash containing options)
circles: [], //contains raw data, array of hash
markerClusterer: null, //contains all marker clusterers
//Polygon Styling
polygons_conf: { //default style for polygons
strokeColor: "#FFAA00",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#000000",
fillOpacity: 0.35
},
//Polyline Styling
polylines_conf: { //default style for polylines
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 2
},
//Circle Styling
circles_conf: { //default style for circles
fillColor: "#00AAFF",
fillOpacity: 0.35,
strokeColor: "#FFAA00",
strokeOpacity: 0.8,
strokeWeight: 2
},
//Direction Settings
direction_conf: {
panel_id: null,
display_panel: false,
origin: null,
destination: null,
waypoints: [], //[{location: "toulouse,fr", stopover: true}, {location: "Clermont-Ferrand, fr", stopover: true}]
optimizeWaypoints: false,
unitSystem: "METRIC", //IMPERIAL
avoidHighways: false,
avoidTolls: false,
region: null,
travelMode: "DRIVING" //WALKING, BICYCLING
},
//initializes the map
initialize: function(){
this.map = new google.maps.Map(document.getElementById(this.map_options.id), {
maxZoom: this.map_options.maxZoom,
minZoom: this.map_options.minZoom,
zoom: this.map_options.zoom,
center: new google.maps.LatLng(this.map_options.center_latitude, this.map_options.center_longitude),
mapTypeId: google.maps.MapTypeId[this.map_options.type]
});
//resets sidebar if needed
this.reset_sidebar_content();
//launch callbacks if any
if(typeof gmaps4rails_callback == 'function') {
gmaps4rails_callback();
}
},
create_direction: function(){
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(this.map);
//display panel only if required
if (this.direction_conf.display_panel) { directionsDisplay.setPanel(document.getElementById(this.direction_conf.panel_id)); }
directionsDisplay.setOptions({
suppressMarkers: true,
suppressInfoWindows: false,
suppressPolylines: false
});
var request = {
origin: this.direction_conf.origin,
destination: this.direction_conf.destination,
waypoints: this.direction_conf.waypoints,
optimizeWaypoints: this.direction_conf.optimizeWaypoints,
unitSystem: google.maps.DirectionsUnitSystem[this.direction_conf.unitSystem],
avoidHighways: this.direction_conf.avoidHighways,
avoidTolls: this.direction_conf.avoidTolls,
region: this.direction_conf.region,
travelMode: google.maps.DirectionsTravelMode[this.direction_conf.travelMode],
language: "fr"
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
},
//Loops through all circles
create_circles: function(){
for (var i = 0; i < this.circles.length; ++i) {
//by convention, default style configuration could be integrated in the first element
if ( i === 0 )
{
if (this.exists(this.circles[i].strokeColor )) { this.circles_conf.strokeColor = this.circles[i].strokeColor; }
if (this.exists(this.circles[i].strokeOpacity)) { this.circles_conf.strokeOpacity = this.circles[i].strokeOpacity; }
if (this.exists(this.circles[i].strokeWeight )) { this.circles_conf.strokeWeight = this.circles[i].strokeWeight; }
if (this.exists(this.circles[i].fillColor )) { this.circles_conf.fillColor = this.circles[i].fillColor; }
if (this.exists(this.circles[i].fillOpacity )) { this.circles_conf.fillOpacity = this.circles[i].fillOpacity; }
}
if (this.exists(this.circles[i].latitude) && this.exists(this.circles[i].longitude))
{
center = new google.maps.LatLng(this.circles[i].latitude, this.circles[i].longitude);
//always check if a config is given, if not, use defaults
var circle = new google.maps.Circle({
center: center,
strokeColor: this.circles[i].strokeColor || this.circles_conf.strokeColor,
strokeOpacity: this.circles[i].strokeOpacity || this.circles_conf.strokeOpacity,
strokeWeight: this.circles[i].strokeWeight || this.circles_conf.strokeWeight,
fillOpacity: this.circles[i].fillOpacity || this.circles_conf.fillOpacity,
fillColor: this.circles[i].fillColor || this.circles_conf.fillColor,
radius: this.circles[i].radius,
clickable: false
});
this.circles[i].google_object = circle;
circle.setMap(this.map);
}
}
},
//polygons is an array of arrays. It loops.
create_polygons: function(){
for (var i = 0; i < this.polygons.length; ++i) {
this.create_polygon(i);
}
},
//creates a single polygon, triggered by create_polygons
create_polygon: function(i){
var polygon_coordinates = [];
var strokeColor;
var strokeOpacity;
var strokeWeight;
var fillColor;
var fillOpacity;
//Polygon points are in an Array, that's why looping is necessary
for (var j = 0; j < this.polygons[i].length; ++j) {
var latlng = new google.maps.LatLng(this.polygons[i][j].latitude, this.polygons[i][j].longitude);
polygon_coordinates.push(latlng);
//first element of an Array could contain specific configuration for this particular polygon. If no config given, use default
if (j===0) {
strokeColor = this.polygons[i][j].strokeColor || this.polygons_conf.strokeColor;
strokeOpacity = this.polygons[i][j].strokeOpacity || this.polygons_conf.strokeOpacity;
strokeWeight = this.polygons[i][j].strokeWeight || this.polygons_conf.strokeWeight;
fillColor = this.polygons[i][j].fillColor || this.polygons_conf.fillColor;
fillOpacity = this.polygons[i][j].fillOpacity || this.polygons_conf.fillOpacity;
}
}
// Construct the polygon
var new_poly = new google.maps.Polygon({
paths: polygon_coordinates,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: fillColor,
fillOpacity: fillOpacity,
clickable: false
});
//save polygon in list
this.polygons[i].google_object = new_poly;
new_poly.setMap(this.map);
},
//polylines is an array of arrays. It loops.
create_polylines: function(){
for (var i = 0; i < this.polylines.length; ++i) {
this.create_polyline(i);
}
},
//creates a single polyline, triggered by create_polylines
create_polyline: function(i){
var polyline_coordinates = [];
var strokeColor;
var strokeOpacity;
var strokeWeight;
//2 cases here, either we have a coded array of LatLng or we have an Array of LatLng
for (var j = 0; j < this.polylines[i].length; ++j) {
//if we have a coded array
if (this.exists(this.polylines[i][j].coded_array)){
var decoded_array = new google.maps.geometry.encoding.decodePath(this.polylines[i][j].coded_array);
//loop through every point in the array
for (var k = 0; k < decoded_array.length; ++k) {
polyline_coordinates.push(decoded_array[k]);
polyline_coordinates.push(decoded_array[k]);
}
}
//or we have an array of latlng
else{
//by convention, a single polyline could be customized in the first array or it uses default values
if (j===0){
strokeColor = this.polylines[i][0].strokeColor || this.polylines_conf.strokeColor;
strokeOpacity = this.polylines[i][0].strokeOpacity || this.polylines_conf.strokeOpacity;
strokeWeight = this.polylines[i][0].strokeWeight || this.polylines_conf.strokeWeight;
}
//add latlng if positions provided
if (this.exists(this.polylines[i][j].latitude) && this.exists(this.polylines[i][j].longitude))
{
var latlng = new google.maps.LatLng(this.polylines[i][j].latitude, this.polylines[i][j].longitude);
polyline_coordinates.push(latlng);
}
}
}
// Construct the polyline
var new_poly = new google.maps.Polyline({
path: polyline_coordinates,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
clickable: false
});
//save polyline
this.polylines[i].google_object = new_poly;
new_poly.setMap(this.map);
},
//creates, clusterizes and adjusts map
create_markers: function() {
this.create_google_markers_from_markers();
this.clusterize();
this.adjust_map_to_bounds();
},
//create google.maps Markers from data provided by user
create_google_markers_from_markers: function(){
for (var i = 0; i < this.markers.length; ++i) {
//check if the marker has not already been created
if (!this.exists(this.markers[i].google_object)) {
//test if value passed or use default
var marker_picture = this.exists(this.markers[i].picture) ? this.markers[i].picture : this.markers_conf.picture;
var marker_width = this.exists(this.markers[i].width) ? this.markers[i].width : this.markers_conf.width;
var marker_height = this.exists(this.markers[i].height) ? this.markers[i].height : this.markers_conf.length;
var marker_title = this.exists(this.markers[i].title) ? this.markers[i].title : null;
var Lat = this.markers[i].latitude;
var Lng = this.markers[i].longitude;
//alter coordinates if randomize is true
if ( this.markers_conf.randomize)
{
var LatLng = this.randomize(Lat, Lng);
//retrieve coordinates from the array
Lat = LatLng[0]; Lng = LatLng[1];
}
var myLatLng = new google.maps.LatLng(Lat, Lng);
// Marker sizes are expressed as a Size of X,Y
if (marker_picture === "")
{ var ThisMarker = new google.maps.Marker({position: myLatLng, map: this.map, title: marker_title}); }
else
{
var image = new google.maps.MarkerImage(marker_picture, new google.maps.Size(marker_width, marker_height) );
var ThisMarker = new google.maps.Marker({position: myLatLng, map: this.map, icon: image, title: marker_title});
}
//save object
this.markers[i].google_object = ThisMarker;
//add infowindowstuff if enabled
this.create_info_window(this.markers[i]);
//create sidebar if enabled
this.create_sidebar(this.markers[i]);
}
}
},
// clear markers
clear_markers: function(){
if (this.markerClusterer !== null){
this.markerClusterer.clearMarkers();
}
for (var i = 0; i < this.markers.length; ++i) {
this.markers[i].google_object.setMap(null);
}
},
// replace old markers with new markers on an existing map
replace_markers: function(new_markers){
//reset previous markers
this.markers = new Array;
//reset current bounds
this.google_bounds = new google.maps.LatLngBounds();
//reset sidebar content if exists
this.reset_sidebar_content();
//add new markers
this.add_markers(new_markers);
},
//add new markers to on an existing map
add_markers: function(new_markers){
//clear the whole map
this.clear_markers();
//update the list of markers to take into account
this.markers = this.markers.concat(new_markers);
//put markers on the map
this.create_markers();
},
//creates clusters
clusterize: function()
{
if (this.markers_conf.do_clustering === true)
{
var gmarkers_array = new Array;
for (var i = 0; i < this.markers.length; ++i) {
gmarkers_array.push(this.markers[i].google_object);
}
this.markerClusterer = new MarkerClusterer(this.map, gmarkers_array, { maxZoom: this.markers_conf.clusterer_maxZoom, gridSize: this.markers_conf.clusterer_gridSize });
}
},
// creates infowindows
create_info_window: function(marker_container){
//create the infowindow
var info_window = new google.maps.InfoWindow({content: marker_container.description });
//add the listener associated
google.maps.event.addListener(marker_container.google_object, 'click', this.openInfoWindow(info_window, marker_container.google_object));
},
openInfoWindow: function(infoWindow, marker) {
return function() {
// Close the latest selected marker before opening the current one.
if (Gmaps4Rails.visibleInfoWindow) {
Gmaps4Rails.visibleInfoWindow.close();
}
infoWindow.open(Gmaps4Rails.map, marker);
Gmaps4Rails.visibleInfoWindow = infoWindow;
};
},
//creates sidebar
create_sidebar: function(marker_container){
if (this.markers_conf.list_container)
{
var ul = document.getElementById(this.markers_conf.list_container);
var li = document.createElement('li');
var aSel = document.createElement('a');
aSel.href = 'javascript:void(0);';
var html = this.exists(marker_container.sidebar) ? marker_container.sidebar : "Marker";
aSel.innerHTML = html;
aSel.onclick = this.sidebar_element_handler(marker_container.google_object, 'click');
li.appendChild(aSel);
ul.appendChild(li);
}
},
//moves map to marker clicked + open infowindow
sidebar_element_handler: function(marker, eventType) {
return function() {
Gmaps4Rails.map.panTo(marker.position);
google.maps.event.trigger(marker, eventType);
};
},
reset_sidebar_content: function(){
if (this.markers_conf.list_container !== null ){
var ul = document.getElementById(this.markers_conf.list_container);
ul.innerHTML = "";
}
},
//to make the map fit the different LatLng points
adjust_map_to_bounds: function(latlng) {
//FIRST_STEP: retrieve all bounds
//create the bounds object only if necessary
if (this.map_options.auto_adjust || this.map_options.bounds !== null) {
this.google_bounds = new google.maps.LatLngBounds();
}
//if autodjust is true, must get bounds from markers polylines etc...
if (this.map_options.auto_adjust) {
//from markers
for (var i = 0; i < this.markers.length; ++i) {
this.google_bounds.extend(this.markers[i].google_object.position);
}
//from polygons:
for (var i = 0; i < this.polylines.length; ++i) {
this.polylines[i].google_object.latLngs.forEach(function(obj1){ obj1.forEach(function(obj2){ Gmaps4Rails.google_bounds.extend(obj2);} );})
}
//from polylines:
for (var i = 0; i < this.polygons.length; ++i) {
this.polygons[i].google_object.latLngs.forEach(function(obj1){ obj1.forEach(function(obj2){ Gmaps4Rails.google_bounds.extend(obj2);} );})
}
//from circles
for (var i = 0; i < this.circles.length; ++i) {
this.google_bounds.extend(this.circles[i].google_object.getBounds().getNorthEast());
this.google_bounds.extend(this.circles[i].google_object.getBounds().getSouthWest());
}
}
//in every case, I've to take into account the bounds set up by the user
for (var i = 0; i < this.map_options.bounds.length; ++i) {
//create points from bounds provided
var bound = new google.maps.LatLng(this.map_options.bounds[i].lat, this.map_options.bounds[i].lng);
this.google_bounds.extend(bound);
}
//SECOND_STEP: ajust the map to the bounds
if (this.map_options.auto_adjust || this.map_options.bounds.length > 0) {
//if autozoom is false, take user info into account
if(!this.map_options.auto_zoom) {
var map_center = this.google_bounds.getCenter();
this.map_options.center_longitude = map_center.lat();
this.map_options.center_latitude = map_center.lng();
this.map.setCenter(map_center);
}
else {
this.map.fitBounds(this.google_bounds);
}
}
},
//basic function to check existence of a variable
exists: function(var_name) {
return var_name !== "" && typeof var_name !== "undefined"
},
//randomize
randomize: function(Lat0, Lng0) {
//distance in meters between 0 and max_random_distance (positive or negative)
var dx = this.markers_conf.max_random_distance * this.random();
var dy = this.markers_conf.max_random_distance * this.random();
var Lat = parseFloat(Lat0) + (180/Math.PI)*(dy/6378137);
var Lng = parseFloat(Lng0) + ( 90/Math.PI)*(dx/6378137)/Math.cos(Lat0);
return [Lat, Lng];
},
//gives a value between -1 and 1
random: function() { return ( Math.random() * 2 -1); }
}; |
$(document).ready(imReady);
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, "slow");
return false;
}
}
});
});
function imReady()
{
$("#quotes .avatarBox .avatar").click(function()
{
var idx = $(this).attr('idx');
if( idx =='6')
{
return;
}
if($('#quotes .speechBubble[idx="'+idx+'"]').hasClass('show'))
{
$('#quotes .speechBubble').removeClass('show');
$('#quotes .speechBubble[idx="'+idx+'"]').removeClass('show');
}
else
{
$('#quotes .speechBubble').removeClass('show');
$('#quotes .speechBubble[idx="'+idx+'"]').addClass('show');
}
});
$('#goHome').click(function()
{
$("html, body").animate({ scrollTop: 0 }, "slow");
})
// $("#quotes .avatarBox .avatar").hoverIntent(
// function(elem)
// {
// },
// function(elem)
// {
// console.log(this);
// } );
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createLogger;
var attr = typeof console !== 'undefined' && 'info' in console ? 'info' : 'log';
var pad = function pad(num) {
return ('0' + num).slice(-2);
};
var identity = function identity(obj) {
return obj;
};
function createLogger(_ref) {
var name = _ref.name,
filter = _ref.filter;
filter = typeof filter === 'function' ? filter : identity;
var logInfo = function logInfo(data) {
data = filter(data);
var _data = data,
actionType = _data.actionType,
actionPayload = _data.actionPayload,
previousState = _data.previousState,
currentState = _data.currentState,
_data$start = _data.start,
start = _data$start === undefined ? new Date() : _data$start,
_data$end = _data.end,
end = _data$end === undefined ? new Date() : _data$end,
isAsync = _data.isAsync;
var formattedTime = start.getHours() + ':' + pad(start.getMinutes()) + ':' + pad(start.getSeconds());
var takeTime = end.getTime() - start.getTime();
var message = (name || 'ROOT') + ': action-type [' + actionType + '] @ ' + formattedTime + ' in ' + takeTime + 'ms, ' + (isAsync ? 'async' : 'sync');
try {
console.groupCollapsed(message);
} catch (e) {
try {
console.group(message);
} catch (e) {
console.log(message);
}
}
if (attr === 'log') {
console[attr](actionPayload);
console[attr](previousState);
console[attr](currentState);
} else {
console[attr]('%c action-payload', 'color: #03A9F4; font-weight: bold', actionPayload);
console[attr]('%c prev-state', 'color: #9E9E9E; font-weight: bold', previousState);
console[attr]('%c next-state', 'color: #4CAF50; font-weight: bold', currentState);
}
try {
console.groupEnd();
} catch (e) {
console.log('-- log end --');
}
};
return logInfo;
} |
define(['frame'], function (ngApp) {
'use strict'
ngApp.provider.controller('ctrlMain', [
'$scope',
'http2',
'$uibModal',
function ($scope, http2, $uibModal) {
function createPage(pageType) {
var url = '/rest/pl/be/home/pageCreate?name=' + pageType
url += '&template=basic'
http2.get(url).then(function (rsp) {
$scope.platform[pageType + '_page_name'] = rsp.data.name
location.href = '/rest/pl/fe/code?site=platform&name=' + rsp.data.name
})
}
function resetPage(pageType) {
var name = $scope.platform[pageType + '_page_name'],
url
if (name && name.length) {
url = '/rest/pl/be/home/pageReset?name=' + pageType
url += '&template=basic'
http2.get(url).then(function (rsp) {
location.href = '/rest/pl/fe/code?site=platform&name=' + name
})
} else {
url = '/rest/pl/be/home/pageCreate?name=' + pageType
url += '&template=basic'
http2.get(url).then(function (rsp) {
$scope.platform[pageType + '_page_name'] = rsp.data.name
location.href =
'/rest/pl/fe/code?site=platform&name=' + rsp.data.name
})
}
}
$scope.editPage = function (pageType) {
var name = $scope.platform[pageType + '_page_name']
if (name && name.length) {
location.href = '/rest/pl/fe/code?site=platform&name=' + name
} else {
createPage(pageType)
}
}
$scope.resetPage = function (pageType) {
if (window.confirm('重置操作将覆盖已经做出的修改,确定重置?')) {
resetPage(pageType)
}
}
},
])
ngApp.provider.controller('ctrlHomeCarousel', [
'$scope',
'tmsfinder',
function ($scope, tmsfinder) {
var slides
$scope.add = function () {
tmsfinder.open('platform').then(function (result) {
if (result.url) {
slides.push({
picUrl: result.url + '?_=' + Date.now(),
})
$scope.update('home_carousel')
}
})
}
$scope.remove = function (homeChannel, index) {
slides.splice(index, 1)
$scope.update('home_carousel')
}
$scope.up = function (slide, index) {
if (index === 0) return
slides.splice(index, 1)
slides.splice(--index, 0, slide)
$scope.update('home_carousel')
}
$scope.down = function (slide, index) {
if (index === slides.length - 1) return
slides.splice(index, 1)
slides.splice(++index, 0, slide)
$scope.update('home_carousel')
}
$scope.$watch('platform', function (platform) {
if (platform === undefined) return
if (!platform.home_carousel) platform.home_carousel = []
slides = platform.home_carousel
$scope.slides = slides
})
},
])
ngApp.provider.controller('ctrlHomeNav', [
'$scope',
'$uibModal',
'http2',
function ($scope, $uibModal, http2) {
var navs
$scope.add = function () {
$uibModal
.open({
templateUrl: 'navSites.html',
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
var page,
selected = []
$scope2.page = page = {}
$scope2.listSite = function () {
var url = '/rest/pl/be/home/recommend/listSite'
http2.get(url).then(function (rsp) {
$scope2.sites = rsp.data.sites
$scope2.page.total = rsp.data.total
})
}
$scope2.choose = function (site) {
if (site._selected === 'Y') {
selected.push(site)
} else {
selected.splice(selected.indexOf(site), 1)
}
}
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
$mi.close(selected)
}
$scope2.listSite()
},
],
backdrop: 'static',
})
.result.then(function (sites) {
if (sites && sites.length) {
sites.forEach(function (site) {
navs.push({
title: site.title,
site: {
id: site.siteid,
name: site.title,
},
type: 'site',
})
})
$scope.update('home_nav')
}
})
}
$scope.edit = function (homeNav) {
$uibModal
.open({
templateUrl: 'editNavSite.html',
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
$scope2.homeNav = angular.copy(homeNav)
$scope2.ok = function () {
$mi.close($scope2.homeNav)
}
},
],
backdrop: 'static',
})
.result.then(function (newHomeNav) {
homeNav.title = newHomeNav.title
$scope.update('home_nav')
})
}
$scope.remove = function (homeNav, index) {
navs.splice(index, 1)
$scope.update('home_nav')
}
$scope.up = function (homeNav, index) {
if (index === 0) return
navs.splice(index, 1)
navs.splice(--index, 0, homeNav)
$scope.update('home_nav')
}
$scope.down = function (homeNav, index) {
if (index === navs.length - 1) return
navs.splice(index, 1)
navs.splice(++index, 0, homeNav)
$scope.update('home_nav')
}
$scope.$watch('platform', function (platform) {
if (platform === undefined) return
if (!platform.home_nav) platform.home_nav = []
$scope.navs = navs = platform.home_nav
})
},
])
ngApp.provider.controller('ctrlHomeQrcode', [
'$scope',
'mediagallery',
function ($scope, mediagallery) {
var qrcodes
$scope.add = function () {
var options = {
callback: function (url) {
qrcodes.push({
picUrl: url + '?_=' + new Date() * 1,
})
$scope.update('home_qrcode_group')
},
}
mediagallery.open('platform', options)
}
$scope.doTip = function (tip) {
$scope.update('home_qrcode_group')
}
$scope.remove = function (slide, index) {
qrcodes.splice(index, 1)
$scope.update('home_qrcode_group')
}
$scope.up = function (slide, index) {
if (index === 0) return
qrcodes.splice(index, 1)
qrcodes.splice(--index, 0, slide)
$scope.update('home_qrcode_group')
}
$scope.down = function (slide, index) {
if (index === qrcodes.length - 1) return
qrcodes.splice(index, 1)
qrcodes.splice(++index, 0, slide)
$scope.update('home_qrcode_group')
}
$scope.$watch('platform', function (platform) {
if (platform === undefined) return
if (!platform.home_qrcode_group) platform.home_qrcode_group = []
qrcodes = platform.home_qrcode_group
$scope.qrcodes = qrcodes
})
},
])
})
|
const { AuthenticationError } = require('apollo-server-express');
const jwt = require('jsonwebtoken');
const { APP_SECRET = 'mysecret' } = process.env;
const { MUST_LOGIN, MUST_LOGOUT, WRONG_EMAIL_PASSWORD } = require('./messages');
/**
* Retrieves the cookie and returns the bearer data.
*
* @param {object} req - HTTP request
* @param {object} models - Models provider, must have a User model
* @returns {Promise} Promise object represents the user
*/
const loggedUser = async ({ token }, { User }) => {
if (token) {
// Verify the token
try {
const { userId } = jwt.verify(token, APP_SECRET);
// Get the user
return userId && User.findById(userId);
} catch (e) {
return null;
}
}
return null;
};
/**
* Returns whether a user is logged in or not.
* @param { object } user - logged in user
* @returns {boolean} True of false
*/
const loggedIn = ({ user }) => !!user;
/**
* Ensures that a user is logged in.
* @param {object} ctx - Application context
*/
const ensureLoggedIn = ctx => {
if (!loggedIn(ctx)) {
throw new AuthenticationError(MUST_LOGIN);
}
};
/**
* Ensures that a user is logged out.
* @param {object} ctx - Application context
*/
const ensureLoggedOut = ctx => {
if (loggedIn(ctx)) {
throw new AuthenticationError(MUST_LOGOUT);
}
};
/**
* Handles login attempts, sets the cookie and returns the user.
*
* @param {string} email - email provided by the user
* @param {string} password - password provided by the user
* @param {object} res - HTTP response
* @param {User} User - User model
* @return {object} User
* @throws {AuthenticationError}
*/
const attemptLogin = async (email, password, res, User) => {
const user = await User.findByEmail(email);
// compare provided password against stored password
const isCorrect = user && (await new User(user).rightPassword(password));
if (!isCorrect) {
throw new AuthenticationError(WRONG_EMAIL_PASSWORD);
}
// generate JWT
const token = jwt.sign({ userId: user.id }, APP_SECRET);
// set cookie
res.cookie('token', token, {
httpOnly: true,
maxAge: 60 * 60 * 24 * 1000 // 1d TODO to put inside .env or config
});
return user;
};
/**
* Clears the cookie and returns true.
* @param {*} res - HTTP response
* @returns {boolean} Always true
*/
const attemptLogout = async res => {
res.clearCookie('token');
return true;
};
module.exports = { loggedUser, attemptLogin, attemptLogout, ensureLoggedIn, ensureLoggedOut };
|
// @flow strict
import * as React from 'react';
import { Image } from 'react-native';
import {
StyleSheet,
AppleWalletBackground,
AppleWalletBackgroundTablet,
AdaptableLayout,
} from '@kiwicom/mobile-shared';
export default function HeaderImage() {
return (
<AdaptableLayout
renderOnNarrow={
<Image
source={AppleWalletBackground}
resizeMode="stretch"
style={styles.image}
/>
}
renderOnWide={
<Image
source={AppleWalletBackgroundTablet}
resizeMode="stretch"
style={styles.image}
/>
}
/>
);
}
const styles = StyleSheet.create({
image: {
flex: 1,
width: '100%',
},
});
|
define(["angular", "xxt-page"], function(angular, codeAssembler) {
'use strict';
var ngApp = angular.module('custom', []);
ngApp.config(['$controllerProvider', function($cp) {
ngApp.provider = {
controller: $cp.register
};
}]);
ngApp.controller('ctrl', ['$scope', '$http', '$q', function($scope, $http, $q) {
var ls, siteId, id, shareby;
ls = location.search;
siteId = ls.match(/[\?&]site=([^&]*)/)[1];
id = ls.match(/[\?&]id=([^&]*)/)[1];
shareby = ls.match(/shareby=([^&]*)/) ? ls.match(/shareby=([^&]*)/)[1] : '';
var setMpShare = function(xxtShare) {
var shareid, sharelink;
//shareid = $scope.user.vid + (new Date()).getTime();
xxtShare.options.logger = function(shareto) {
/*var url = "/rest/mi/matter/logShare";
url += "?shareid=" + shareid;
url += "&site=" + siteId;
url += "&id=" + id;
url += "&type=article";
url += "&title=" + $scope.article.title;
url += "&shareto=" + shareto;
url += "&shareby=" + shareby;
$http.get(url);*/
};
sharelink = location.protocol + '//' + location.hostname + '/rest/site/fe/matter';
sharelink += '?siteId=' + siteId;
sharelink += '&type=custom';
sharelink += '&id=' + id;
//sharelink += "&shareby=" + shareid;
xxtShare.set($scope.article.title, sharelink, $scope.article.summary, $scope.article.pic);
};
var articleLoaded = function() {
/MicroMessenge/i.test(navigator.userAgent) && require(['xxt-share'], function(xxtShare) {
setMpShare(xxtShare);
});
window.loading.finish();
};
var loadArticle = function() {
var deferred = $q.defer();
$http.get('/rest/site/fe/matter/article/get?site=' + siteId + '&id=' + id).success(function(rsp) {
var site = rsp.data.site,
article = rsp.data.article,
channels = article.channels,
page = article.page;
if (article.use_site_header === 'Y' && site && site.header_page) {
codeAssembler.loadCode(ngApp, site.header_page);
}
if (article.use_site_footer === 'Y' && site && site.footer_page) {
codeAssembler.loadCode(ngApp, site.footer_page);
}
codeAssembler.loadCode(ngApp, page).then(function() {
$scope.article = article;
});
if (channels && channels.length) {
for (var i = 0, l = channels.length, channel; i < l; i++) {
channel = channels[i];
if (channel.style_page) {
codeAssembler.loadCode(ngApp, channel.style_page);
}
}
}
$scope.user = rsp.data.user;
$scope.site = site;
$http.post('/rest/site/fe/matter/logAccess?site=' + siteId, {
id: id,
type: 'article',
title: article.title,
shareby: shareby,
search: location.search.replace('?', ''),
referer: document.referrer
});
deferred.resolve();
}).error(function(content, httpCode) {
if (httpCode === 401) {
codeAssembler.openPlugin(content).then(function() {
loadArticle().then(articleLoaded);
});
} else {
alert(content);
}
});
return deferred.promise;
};
loadArticle().then(articleLoaded);
}]);
angular._lazyLoadModule('custom');
return {};
}); |
var mongoose = require('mongoose')
var User = require('./models/User.js');
module.exports = UserList;
function UserList(mongooseUri) {
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'mongoose connection error:'));
db.once('open', function (callback) {
console.log('mongoose connection success');
});
mongoose.connect(mongooseUri);
}
UserList.prototype = {
addUser: function (msg) {
console.log("adduser function")
var newUser = new User({ name: msg});
console.log(newUser.name);
newUser.speak();
newUser.save(function savedUser(err) {
console.log("username: " + msg + " saved.");
if (err) {
console.log("username save error.");
throw err;
}
});
}
} |
const express = require("express");
const app = express();
require('dotenv').config();
const debug = require('debug')('index:');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const router = require('./routes/api');
const PORT = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({extended: true}));
if(process.env.NODE_ENV !== 'test') {
app.use(morgan("combined"));
}
app.use(bodyParser.json());
app.use(cookieParser());
app.use('/api', router);
app.listen(PORT, () => {
debug('Server listening on port ' + PORT);
})
module.exports = app |
const mongoose = require('mongoose');
const bankSchema = mongoose.Schema(
{
bank_name: {
type: String,
trim: true,
unique: 1
}
},
{ timestamps: true }
);
const Bank = mongoose.model('Bank', bankSchema);
module.exports = Bank;
|
var array = [21,13,31,12,21];
console.log("This is an array",array);
var string = "HELLO WORLD";
console.log("This is a string",string);
|
// import * as React from 'react';
// import Box from '@mui/material/Box';
// import Card from '@mui/material/Card';
// import CardActions from '@mui/material/CardActions';
// import CardContent from '@mui/material/CardContent';
// import Button from '@mui/material/Button';
// import Typography from '@mui/material/Typography';
// const bull = (
// <Box
// component="span"
// sx={{ display: 'inline-block', mx: '2px', transform: 'scale(0.8)' }}
// >
// •
// </Box>
// );
// const card = (
// <React.Fragment>
// <CardContent>
// <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom>
// Word of the Day
// </Typography>
// <Typography variant="h5" component="div">
// be{bull}nev{bull}o{bull}lent
// </Typography>
// <Typography sx={{ mb: 1.5 }} color="text.secondary">
// adjective
// </Typography>
// <Typography variant="body2">
// well meaning and kindly.
// <br />
// {'"a benevolent smile"'}
// </Typography>
// </CardContent>
// <CardActions>
// <Button size="small">Learn More</Button>
// </CardActions>
// </React.Fragment>
// );
// export default function OutlinedCard() {
// return (
// <Box sx={{ minWidth: 275 }}>
// <Card variant="outlined">{card}</Card>
// </Box>
// );
// }
|
import * as login from "./action-type"
let defaultState = {
loginType: 0,
username: "",
password: "",
keepAccount: true
}
export const loginData = (state=defaultState, action={}) => {
switch(action.type) {
case login.FORM_SUBMIT:
return {...state, ...action.payload}
default:
return state
}
} |
// @ts-check
class Guest {
constructor() {
// BEGIN (write your solution here)
// END
this.name = 'Guest';
}
getName() {
return this.name;
}
// BEGIN (write your solution here)
isGuest () {
return true;
}
// END
}
export default Guest;
|
document.querySelector("h1").textContent = "Fruits & Vegetables Corp";
let lenkar = document.querySelectorAll("a")[2].textContent = "Vegetables";
let main = document.querySelector('#main');
let about = document.querySelector('#about');
let contact = document.querySelector('#contact');
main.insertBefore(about, contact);
about.textContent ="";
let aboutElement = document.createElement("h2")
aboutElement.textContent="About";
about.appendChild(aboutElement).childNodes[0];
about.replaceChild(aboutElement, about.childNodes[0]);
let contactElement = document.createElement("h2")
contactElement.textContent="Contact";
contact.appendChild(contactElement).childNodes[0];
contact.replaceChild(contactElement, contact.childNodes[0]);
let aboutText = document.createElement("p")
about.appendChild(aboutText);
aboutText.textContent =("We're the best in fruits & vegetables");
let change = document.querySelectorAll("thead td");
for (let td of change) {
let result = document.createElement("th");
result.textContent= td.textContent;
td.replaceWith(result);
}
let head = document.querySelector("head");
let css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("href", "main.css");
head.appendChild(css);
document.querySelector("title").textContent="Fruits & Vegetables Corp";
|
'use strict';
var Thermostat = function () {
this.temp = 20;
this.min_temp = 10;
this.max_temp = 25;
this.power_saving = true;
};
Thermostat.prototype = {
up: function (increase_by) {
if ((this.temp + increase_by) > this.max_temp) {
throw new Error('Unable to set temperature.');
}
this.temp += increase_by;
},
down: function (decrease_by) {
if ((this.temp - decrease_by) < this.min_temp) {
throw new Error('Unable to set temperature.');
}
this.temp -= decrease_by;
},
switch_power_saving: function () {
this.power_saving = !this.power_saving;
this.max_temp = this.power_saving ? 25 : 32;
if (this.temp > this.max_temp) {
this.temp = this.max_temp;
}
},
reset: function () {
this.temp = 20;
},
energy_usage: function () {
if (this.temp < 18) {
return 'low';
} else if (this.temp < 25) {
return 'medium';
} else {
return 'high';
};
},
}; |
// miniprogram/pages/peopleInfo/peopleInfo.js
import province_list from '../../utils/area.js'
import { cloud as CF } from '../../utils/cloudFunction.js'
import Toast from "../../miniprogram_npm/vant-weapp/toast/toast";
Page({
/**
* 页面的初始数据
*/
data: {
areaList: province_list,
show_area: false,
currentPlace:{},
currentPerson: {
province: "",
city: "",
county: "",
name: "",
area: "",
address: "",
idcard: "",
phone: ""
}
},
onLoad: function (options) {
// const scene = decodeURIComponent(options.scene)
var scene;
if(options.scene){
scene = decodeURIComponent(options.scene)
}else{
scene = "1acf1de95e482f37104a16fc5e05ddaf";
}
wx.setNavigationBarTitle({ title: "出入登记" })
if (scene) {
this.queryPeopleByOpenId();
this.queryPalceById(scene);
}else{
Toast.fail('二维码未携带单位信息');
}
},
// 新增或编辑信息
addHistory() {
// 参数完整性校验
console.log(this.data)
var _this = this;
var currentPerson = this.data.currentPerson;
if (currentPerson.address && currentPerson.area && currentPerson.phone && currentPerson.name && currentPerson.idcard) {
// 判断是否有ID信息
if (_this.data.currentPerson._id) {
// 直接新增出入信息
var obj = {
personId: _this.data.currentPerson._id,
placeId: _this.data.currentPlace._id,
personName: _this.data.currentPerson.name,
placeName: _this.data.currentPlace.placename
}
CF.insert("history", obj, function (data) {
wx.navigateTo({
url: '/pages/success/success',
})
})
} else {
// 没有ID信息,先新增PEOPLE信息,再新增出入记录
// 新增时将当前类型添加进去
CF.insert("people", this.data.currentPerson, function (data) {
console.log("insert", data)
_this.data.currentPerson._id = data.result._id
var obj = {
personId: _this.data.currentPerson._id,
placeId: _this.data.currentPlace._id,
personName: _this.data.currentPerson.name,
placeName: _this.data.currentPlace.placename
}
CF.insert("history", obj, function () {
wx.navigateTo({
url: '/pages/success/success',
})
})
})
}
} else {
Toast.fail('请将信息填写完整');
}
},
// 根据ID查询个人信息
queryPeopleByOpenId() {
CF.get("people", { openId: true }, (e) => {
if (e.result.data && e.result.data.length > 0) {
this.setData({
currentPerson: e.result.data[0]
})
}
})
},
// 根据ID查询单位信息
queryPalceById(palceId) {
CF.get("places", { _id: palceId }, (e) => {
console.log(e)
if (e.result.data && e.result.data.length == 1) {
this.setData({
currentPlace: e.result.data[0]
})
} else {
Toast.fail('未找到该单位信息');
setTimeout(() => {
wx.navigateBack()
}, 2000)
}
})
},
// 点击选择地址按钮
selectArea() {
this.setData({
show_area: true
})
},
// 点击遮罩或取消关闭选择器
onCloseArea(event) {
this.setData({
show_area: false
})
},
// 点击确定,存储信息
onConfirmArea(event) {
this.setData({
show_area: false,
"currentPerson.province": event.detail.values[0].name,
"currentPerson.city": event.detail.values[1].name,
"currentPerson.county": event.detail.values[2].name,
"currentPerson.areacode": event.detail.values[2].code,
"currentPerson.area": event.detail.values[0].name + event.detail.values[1].name + event.detail.values[2].name
})
console.log(this.data)
},
// 输入框
onValueChange(e) {
var key = "currentPerson." + e.target.id;
var obj = {};
obj[key] = e.detail;
this.setData(obj)
}
}) |
/***************************************************
* 时间: 8/14/16 08:53
* 作者: zhongxia
* 说明: 生成point点的
* 目前需要支持三种类型的点读点
* 1. 常规点读点
* 2. 创建页面,带有标题的点读点
* 3. 创建页面,自定义图片的点读点
* 4. 展示页面,自定义标题
* 5. 展示页面,自定义图片
***************************************************/
//加载依赖的脚本和样式
(function () {
/**
* 获取当前脚本的目录
* @returns {string}
*/
function getBasePath() {
//兼容Chrome 和 FF
var currentPath = document.currentScript && document.currentScript.src || '';
var paths = currentPath.split('/');
paths.pop();
return paths.join('/');
}
Util.loadCSS(getBasePath() + '/CreatePoint.css');
})()
window.CreatePoint = (function () {
var currentScriptSrc = Util.getBasePath(document.currentScript.src);
//带有标题的点读点类型样式, 音频,视频,图文, 考试
var POINTTITLECLASS = {
audio: 'create-point-title-audio',
video: 'create-point-title-video',
imgtext: 'create-point-title-imgtext',
exam: 'create-point-title-exam'
}
/**
* 生成 point
* @param type 点读点类型
* @param data 点读点的数据
*/
function initPoint(type, data) {
/**
* TODO: 单独把模板抽离出来,后期可以修改成这样
**/
// Util.getTplById(currentScriptSrc + '/tpl.html', 'tpl_show_viewer3d', function (tpl) {
// var tpls = Handlebars.compile(tpl)
// })
var html = "";
var pointId = data.pointId;
var pointIndex = data.pointId && data.pointId.split('_')[1];
var left = data.left || "";
var top = data.top || "";
var scale = data.scale || 1; //缩放的比例, 主要在展示页面用
var className = data.className; //展示页面 添加到点读点的样式
var outHTML = data.outHTML; //[展示页面] 外部传进来的HTML,添加到点读点的div里面
left = typeof (left) === 'number' ? left : left.replace('px', '');
top = typeof (top) === 'number' ? top : top.replace('px', '');
var title = data.title || {};
var pic = data.pic || { src: '', color: '', colorSize: '' }; //自定义图片需要 图片地址,发光颜色,光圈大小
var style = "position:absolute; left:" + left + "px; top :" + top + "px;";
switch (type) {
//常规点读点
case 1:
html = initNormalPoint(pointId, pointIndex, style);
break;
//带有标题的点读点
case 2:
html = initTitlePoint(pointId, style, title);
break;
//自定义图片的点读点
case 3:
html = initCustomImgPoint(pointId, style, pic)
break;
//展示页面 自定义标题[展示页面]
case 4:
html = initMTitlePoint(pointId, style, title, className, outHTML, scale)
break;
//展示页面 自定义图片[展示页面]
case 5:
html = initMCustomImgPoint(pointId, style, pic, className, outHTML, scale)
break;
// 创建页面 自定义绘制区域[展示页面]
case 6:
html = initDrawAreaPoint(pointId, style, data)
break;
default:
html = initCustomImgPoint(pointId, pointIndex, style);
}
return html;
}
/**
* 生成普通Point
* @param pointId 点读点id
* @param index 点读点下标
* @param style 坐标样式
*/
function initNormalPoint(pointId, pointIndex, style) {
var html = [];
html.push('<div data-type="point" id="' + pointId + '" class="radius" style="' + style + '">');
html.push(' <div class="radius-in">' + pointIndex + '</div>');
html.push('</div>');
return html.join('');
}
/**
* 生成带有标题的point
*/
function initTitlePoint(pointId, style, titleObj) {
var title = titleObj.title;
var pointType = titleObj.type || 'audio';
var className = POINTTITLECLASS[pointType]
var id = "";
if (pointId) {
id = 'data-id=' + pointId
}
var html = [];
html.push(' <div id="' + pointId + '" data-type="point" ' + id + ' style="' + style + '" class="create-point-title">')
html.push(' <div class="create-point-title-img ' + className + '"></div>')
html.push(' <div class="create-point-title-line"></div>')
html.push(' <div class="create-point-title-text">' + title + '</div>')
html.push(' </div>')
return html.join('');
}
/**
* 生成自定义图片的point
*/
function initCustomImgPoint(pointId, style, pic) {
var html = [];
var src = pic.src;
var dropFilter = "drop-shadow(0px 0px " + pic.colorSize + "px " + pic.color + ")"
style += 'background: url(' + src + ') no-repeat ;background-size: contain; background-position:center;';
style += 'filter:' + dropFilter + ';-webkit-filter:' + dropFilter + ';';
if (pic.w && pic.h) {
var width = pic.w * 1200 / 1920;
var height = pic.h * 1200 / 1920;
style += 'width:' + width + 'px;height:' + height + 'px';
}
var id = "";
if (pointId) {
id = 'data-id=' + pointId
}
html.push('<div id="' + pointId + '" data-type="point" ' + id + ' style="' + style + '" class="create-point-img"></div>');
return html.join('');
}
/**
* [展示页面,移动端]生成带有标题的point
* @param outClassName 外部传进来的样式
*/
function initMTitlePoint(pointId, style, titleObj, outClassName, outHTML, scale) {
var title = titleObj.title;
var pointType = outClassName.replace('m-', '');
var className = POINTTITLECLASS[pointType]
//缩放,并且使用左上角为缩放的 起始点
if (scale !== 1) {
style += 'transform: scale(' + scale + '); transform-origin:left top;-webkit-transform: scale(' + scale + '); -webkit-transform-origin:left top;';
}
var id = "";
if (pointId) {
id = 'data-id=' + pointId
}
var html = [];
html.push(' <div data-type="point" ' + id + ' style="' + style + '" class="create-point-title ' + outClassName + '">')
html.push(' <div class="create-point-title-img ' + className + '">')
html.push(outHTML)
html.push(' </div>')
html.push(' <div class="create-point-title-line"></div>')
html.push(' <div class="create-point-title-text">' + title + '</div>')
html.push(' </div>')
return html.join('');
}
/**
* [展示页面,移动端]生成自定义图片的point
* @param outClassName 外部传进来的样式
*/
function initMCustomImgPoint(pointId, style, pic, outClassName, outHTML, scale) {
var html = [];
var src = pic.src;
var dynamic = pic.dynamic; //动态图是否只展示第一帧,true 是,false 否
var dynamicAttr = ''
if (dynamic) {
dynamicAttr = 'data-src="' + src + '" data-dynamic="' + dynamic + '"';
}
var dropFilter = "drop-shadow(0px 0px " + pic.colorSize + "px " + pic.color + ")"
style += 'border-radius:0;background: url(' + src + ') no-repeat ;background-size: contain; background-position:center;';
style += 'filter:' + dropFilter + ';-webkit-filter:' + dropFilter + ';';
if (pic.w && pic.h) {
/**
* 1200/1920*scale 按1920的比例缩放计算显示需要多大.
* scale 是 移动端 针对 创建页面 1200 缩放的比例
*/
var width = pic.w * 1200 / 1920 * scale;
var height = pic.h * 1200 / 1920 * scale;
style += 'width:' + width + 'px;height:' + height + 'px';
}
var id = "";
if (pointId) {
id = 'data-id=' + pointId
}
html.push('<div ' + dynamicAttr + ' data-filter="' + dropFilter + '" data-type="pointImg" ' + id + ' style="' + style + '" class="content-center create-point-img ' + outClassName + '">' + outHTML + '</div>');
return html.join('');
}
/**
* 创建页面,自定义绘制区域[and 展示页面没有用到]
*/
function initDrawAreaPoint(pointId, style, data) {
var drawAreaData = data.drawAreaData || {}
if (drawAreaData.w && drawAreaData.h) {
var width = drawAreaData.w * data.w;
var height = drawAreaData.h * data.h;
style += 'width:' + width + 'px;height:' + height + 'px';
}
return '<div id="' + pointId + '" data-type="drawcustomarea" style="' + style + '" class="draw-area-container draw-custom-area__' + drawAreaData.pointType + '"></div>'
}
return {
initPoint: initPoint
}
})();
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Link } from "react-router-dom";
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import AccountCircle from '@material-ui/icons/AccountCircle';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';
import Box from '@material-ui/core/Box';
import Avatar from '@material-ui/core/Avatar';
import clsx from 'clsx';
import Drawer from '@material-ui/core/Drawer';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import DashboardRoundedIcon from '@material-ui/icons/DashboardRounded';
import BlurOnRoundedIcon from '@material-ui/icons/BlurOnRounded';
import SupervisorAccountRoundedIcon from '@material-ui/icons/SupervisorAccountRounded';
import ExitToAppRoundedIcon from '@material-ui/icons/ExitToAppRounded';
import AccountCircleRoundedIcon from '@material-ui/icons/AccountCircleRounded';
import BuildRoundedIcon from '@material-ui/icons/BuildRounded';
import EmailRoundedIcon from '@material-ui/icons/EmailRounded';
import EventRoundedIcon from '@material-ui/icons/EventRounded';
import DoneAllRoundedIcon from '@material-ui/icons/DoneAllRounded';
import HowToRegRoundedIcon from '@material-ui/icons/HowToRegRounded';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import CloseIcon from '@material-ui/icons/Close';
import InboxIcon from '@material-ui/icons/Inbox'
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
display: "flex",
flexGrow: 1,
justifyContent: "center"
},
list: {
width: 250,
},
fullList: {
width: 'auto',
},
avatar: {
margin: theme.spacing(1),
width: theme.spacing(7),
height: theme.spacing(7),
// backgroundColor: theme.palette.secondary.main,
},
avatarDrawer: {
marginLeft: theme.spacing(6),
width: theme.spacing(15),
height: theme.spacing(15),
// backgroundColor: theme.palette.secondary.main,
},
}));
const styles = (theme) => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
const DialogTitle = withStyles(styles)((props) => {
const { children, classes, onClose, ...other } = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles((theme) => ({
root: {
padding: theme.spacing(2),
},
}))(MuiDialogContent);
const DialogActions = withStyles((theme) => ({
root: {
margin: 0,
padding: theme.spacing(1),
},
}))(MuiDialogActions);
export default function AppBarWithDrawer() {
const [opendialog, setOpen] = React.useState(false);
// Handle the open of the about dialog
const handleClickOpen = () => {
setOpen(true);
};
// Handle the close of the about dialog
const handleClose = () => {
setOpen(false);
};
const classes = useStyles();
const [profileAnchor, setProfileAnchor] = React.useState(null);
const open = Boolean(profileAnchor);
// Handle the open of the user profile menu
const handleProfileOpen = (event) => {
setProfileAnchor(event.currentTarget);
};
// Handle the close of the user profile menu
const handleProfileClose = () => {
setProfileAnchor(null);
};
const [openDrawer, setOpenDrawer] = React.useState(false); // Side drawer state
// Handle the open of side drawer
const handleDrawerOpen = () => {
setOpenDrawer(true);
};
// Handle the close of the side drawer
const handleDrawerClose = () => {
setOpenDrawer(false);
};
// Function handle logout click
const handleLogout = (event) => {
localStorage.clear();
};
// Variable containing Side drawer list items
const list = (anchor) => (
<div
className={clsx(classes.list, {
[classes.fullList]: anchor === 'top' || anchor === 'bottom',
})}
role="presentation"
onClick={handleDrawerOpen}
onKeyDown={handleDrawerClose}
>
<List>
<ListItem button key={'Dashboard'} component={Link} to="/Dashboard">
<ListItemIcon><DashboardRoundedIcon /></ListItemIcon>
<ListItemText><Typography>Dashboard</Typography></ListItemText>
</ListItem>
<ListItem button key={'Network Discovery'} component={Link} to="/Network Discovery">
<ListItemIcon><BlurOnRoundedIcon /></ListItemIcon>
<ListItemText><Typography>Network Discovery</Typography></ListItemText>
</ListItem>
<ListItem button key={'Create Users'} component={Link} to="/admins">
<ListItemIcon><SupervisorAccountRoundedIcon /></ListItemIcon>
<ListItemText><Typography>Manage Adminstrators</Typography></ListItemText>
</ListItem>
<ListItem button key={'Settings'} component={Link} to="/settings">
<ListItemIcon><BuildRoundedIcon /></ListItemIcon>
<ListItemText><Typography>Blocklist Settings</Typography></ListItemText>
</ListItem>
<ListItem button key={'About'} onClick={(event) => handleClickOpen()} >
<ListItemIcon><InboxIcon /></ListItemIcon>
<ListItemText><Typography>About</Typography></ListItemText>
</ListItem>
</List>
<Divider />
<List>
<ListItem button key={'Logout'} onClick={(event) => handleLogout(event)} component={Link} to="/">
<ListItemIcon><ExitToAppRoundedIcon /></ListItemIcon>
<ListItemText><Typography>Logout</Typography></ListItemText>
</ListItem>
</List>
</div>
);
return (
<div className={classes.root}>
<AppBar position="absolute" style={{ background: "#616771" }}>
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu" onClick={handleDrawerOpen}>
<MenuIcon />
</IconButton>
<Box className={classes.title}>
<Avatar className={classes.avatar} src="Icons/final_logo.png" />
<Typography variant="h5" style={{ marginLeft: "10px", paddingTop: "20px", fontFamily: "DalekPinpoint" }}>Brother Eye</Typography>
</Box>
<div>
<IconButton
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
onClick={handleProfileOpen}
color="inherit"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={profileAnchor}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={open}
onClose={handleProfileClose}
>
<MenuItem>
<List>
<ListItem style={{ display: "flex" }}>
<Typography variant='h5' style={{ fontFamily: "DalekPinpoint", color: '#079b' }} >
Account Details
</Typography>
</ListItem>
<ListItem>
<ListItemIcon><AccountCircleRoundedIcon /></ListItemIcon>
<ListItemText><Typography>{localStorage.getItem('full_name')}</Typography></ListItemText>
</ListItem>
<ListItem>
<ListItemIcon><EmailRoundedIcon /></ListItemIcon>
<ListItemText><Typography>{localStorage.getItem('email')}</Typography></ListItemText>
</ListItem>
<ListItem>
<ListItemIcon><HowToRegRoundedIcon /></ListItemIcon>
<ListItemText><Typography>{localStorage.getItem('role')}</Typography></ListItemText>
</ListItem>
<ListItem>
<ListItemIcon><DoneAllRoundedIcon /></ListItemIcon>
<ListItemText><Typography>{localStorage.getItem('lastLoginAttempt')}</Typography></ListItemText>
</ListItem>
<ListItem>
<ListItemIcon><EventRoundedIcon /></ListItemIcon>
<ListItemText><Typography>{localStorage.getItem('createdAt')}</Typography></ListItemText>
</ListItem>
</List>
</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
<Drawer anchor="left" open={openDrawer} onClose={handleDrawerClose}>
{list("left")}
</Drawer>
<Dialog onClose={handleClose} aria-labelledby="About" open={opendialog}>
<DialogTitle id="customized-dialog-title" onClose={handleClose}>
<Box className={classes.title} style={{ paddingRight: "30px"}}>
<ListItemIcon><Avatar className={classes.avatarDrawer} src="Icons/final_logo.png" /></ListItemIcon>
</Box>
<Box className={classes.title}>
<Typography variant='h4' style={{ fontFamily: "DalekPinpoint" }} >
Brother Eye
</Typography>
</Box>
</DialogTitle>
<DialogContent dividers>
<Typography style={{ color: '#000' }} gutterBottom>
{'"Can you hear me, father '}
<Link href="https://dc.fandom.com/wiki/Bruce_Wayne_(New*Earth)" style={{ fontFamily: "DalekPinpoint", color: '#079b' }}>
Bruce
</Link>
{'? Eye am no longer a child. Eye have surpassed you, father. Eye have become a world unto myself."'}
</Typography>
<Typography style={{ color: '#079b' }} gutterBottom>
{'-- BrotherEye (When it tries to rule Earth)'}
</Typography>
<Divider />
<Typography style={{ color: '#000' }} gutterBottom>{'\n'}</Typography>
<Typography style={{ color: '#000' }} gutterBottom>{'\n'}</Typography>
<Typography style={{ color: '#000' }} gutterBottom>
{'For now BrotherEye is a network monitoring solution tasked to keep tabs on users in the current network.'}
</Typography>
<Typography style={{ color: '#000' }} gutterBottom>
{'It is SNMP based meaning it uses snmp to try to guess as much about the network topology as possible without going to LLDP or CDP as they are not as much supported in our current test enviroment.'}
</Typography>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleClose} style={{ fontFamily: "DalekPinpoint", color: '#fff', backgroundColor: '#079b' }}>
<Typography style={{ fontFamily: "DalekPinpoint" }}>
Okay
</Typography>
</Button>
</DialogActions>
</Dialog>
</div>
);
} |
import React, {
Component,
PropTypes,
} from 'react'
import {
View,
} from 'react-native'
import Welcome from '@components/Welcome'
export default class WelcomeScreen extends Component {
static defaultProps = {}
static propTypes = {}
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<View style={{ flex: 1 }}>
<Welcome />
</View>
)
}
}
|
function solve() {
let summary = {};
let sortedTypes = [];
for (let i = 0; i < arguments.length; i++) {
var obj = arguments[i];
var type = typeof obj;
console.log(`${type}: ${obj}`);
if (!summary[type]) {
summary[type] = 0;
}
summary[type]++;
}
for (var currType in summary) {
sortedTypes.push([currType, summary[currType]]);
}
for (let [type, occurances] of sortedTypes) {
console.log(`${type} = ${occurances}`);
}
}
//solve('cat', 42, 11, { a: 1, b: 3 }, function () { console.log('Hello world!'); });
solve({ name: 'bob' }, 3.333, 9.999); |
/*
* vscode 中安装prettierrc插件 需要在settings.josn文件中设置如下配置才能生效
* "editor.formatOnSave": true,
*/
module.exports = {
// 一行最多 120 字符
printWidth: 150,
// tab缩进大小
tabWidth: 2,
// 是否使用tab缩进
useTabs: true,
// 使用分号
semi: false,
//是否用单引号 fale 双引号 true 单引号
// 对jsx语法无效
singleQuote: true,
// 末尾需要有逗号
trailingComma: 'none',
// 对象中的空格 默认为true
// true : { foo: bar }
// false: {foo:bar}
bracketSpacing: true,
// 箭头函数参数括号 可选avoid| always
// avoid 能省略时就省略
// always 总是有括号
arrowParens: 'avoid',
// jsx标签闭合位置
// fasle: <div
// className=""
// style={{}}
// >
// true: <div
// className=""
// style={{}} >
jsxBracketSameLine: false,
// elsintIntergration: false
}
|
import { MenuList } from "@material-ui/core";
import React from "react";
import Tab from "./Tab";
function TabList(props) {
return (
<MenuList spacing={1}>
{props.tabList.map((tabName, index) => (
<Tab selectedTab={props.selectedTab} key={index} name={tabName} click={props.click}></Tab>
))}
</MenuList>
);
}
export default TabList;
|
import React from 'react'
import { useForm, FormContext, useFormContext } from 'react-hook-form'
import { useStateMachine } from 'little-state-machine'
import { useNavigate } from 'react-router-dom'
import updateAction from '../updateAction'
function FormControl({ text, name, width, validations, defaultValue }) {
const { errors, register } = useFormContext()
return (
<label style={{ width: width || '100%' }}>
{text}
<input
name={name}
ref={register(validations)}
defaultValue={defaultValue}
/>
<div> {errors[name] && <p>{errors[name].message}</p>}</div>
</label>
)
}
export default function NewUser() {
let navigate = useNavigate()
const { action, state } = useStateMachine(updateAction)
function onSubit(data) {
action(data)
navigate('/pagamento')
}
const methods = useForm({
mode: 'onChange'
})
return (
<FormContext {...methods}>
<form onSubmit={methods.handleSubmit(onSubit)}>
<h1>Criar Usúario</h1>
<FormControl
text="Nome:"
name="name"
width="50%"
validations={{
required: 'this is a required',
maxLength: {
value: 30,
message: 'Max length is 30'
}
}}
defaultValue={state.data.name}
/>
<FormControl
text="Sobrenome:"
name="lastName"
width="50%"
defaultValue={state.data.name}
validations={{
required: 'this is a required',
maxLength: {
value: 30,
message: 'Max length is 30'
}
}}
/>
<FormControl
text="Senha"
name="password"
defaultValue={state.data.password}
/>
<p className="diver">Endereço</p>
<FormControl
text="CEP:"
name="cep"
defaultValue={state.data.cep}
ref={{
required: true
}}
/>
<FormControl
text="País:"
name="cuntry"
defaultValue={state.data.contry}
ref={{
required: true
}}
/>
<FormControl
text="Estado:"
name="state"
defaultValue={state.data.state}
ref={{
required: true
}}
/>
<FormControl
text="Cidade:"
name="city"
defaultValue={state.data.city}
ref={{
required: true
}}
/>
<FormControl
text="Bairro:"
name="district"
defaultValue={state.data.district}
ref={{
required: true
}}
/>
<FormControl
text="Numero:"
name="number"
defaultValue={state.data.number}
ref={{
required: true
}}
/>
<p className="diver">Contato</p>
<FormControl
text="Email:"
name="email"
defaultValue={state.data.password}
ref={{
required: 'this is required',
pattern: {
value: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
message: 'Invalid email address'
}
}}
/>
<FormControl
text="Telefone:"
name="phoneNumber"
ref={{
required: 'this is required'
}}
defaultValue={state.data.password}
/>
<FormControl
text="Celular:"
name="email"
ref={{
required: 'this is required'
}}
defaultValue={state.data.password}
/>
<button type="submit">Criar Usuário</button>
</form>
</FormContext>
)
}
|
/**
* Created by Njoku on 02.09.2014.
*/
Package.describe({
summary: "Eine Klasse die einfache arithmetische Operationen anbietet",
version: "1.0.0"
});
Package.on_use(function (api, where) {
api.use([], 'client');
//api.add_files(['berechnung.js'], 'client');
api.add_files(['berechnung.js']);
if (api.export)
api.export('Berechnung');
}); |
import {put} from '../../../utils/http';
import {REDUCERS_GROUP_PREFIX, ENDPOINT_CHANGE_EMAIL} from './constants';
const REDUCER_NAME = `${REDUCERS_GROUP_PREFIX}/change-email`;
const CHANGE_EMAIL_SUCCESS = `${REDUCER_NAME}/CHANGE_EMAIL_SUCCESS`;
const CHANGE_EMAIL_ERROR = `${REDUCER_NAME}/CHANGE_EMAIL_ERROR`;
const initState = {
confirmed: false
};
export default (state = initState, action) => {
switch (action.type) {
case CHANGE_EMAIL_SUCCESS:
return {...state, confirmed: true, successMessage: action.message};
case CHANGE_EMAIL_ERROR:
return {...state, errorMessage: action.error};
default:
return state;
}
};
export const confirmChangeEmail = token => {
return dispatch => {
put(`${ENDPOINT_CHANGE_EMAIL}/${token}`, null, null).then(response => {
dispatch({type: CHANGE_EMAIL_SUCCESS, message: response.data.message});
}).catch(response => {
dispatch({type: CHANGE_EMAIL_ERROR, error: response.message});
});
}
};
|
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
`;
export const PokemonName = styled.span`
width: 100%;
height: 40px;
background-image: linear-gradient(to right, #e2f3ff 50%, #9dd8ff);
box-shadow: inset 0 0 10px #000000;
color: #000000;
border-radius: 10px;
font-weight: 700;
font-size: 25px;
display: grid;
place-content: center;
`;
export const PokemonDisplay = styled.div`
width: 100%;
height: 300px;
background-image: linear-gradient(to right, #e2f3ff 50%, #9dd8ff);
box-shadow: inset 0 0 10px #000000;
color: #000000;
border-radius: 10px;
display: grid;
place-content: center;
`;
export const Pokemon = styled.img`
width: 250px;
height: 250px;
`;
export const PokemonActions = styled.div`
width: 100%;
height: 40px;
display: flex;
align-items: center;
justify-content: space-around;
`;
export const Button = styled.button`
width: 40px;
height: 40px;
background: #7b0000;
border: 3px solid #7b0000;
border-radius: 100px;
display: grid;
place-content: center;
outline: none;
&:hover {
cursor: pointer;
transform: scale(1.1);
}
&:disabled {
transform: scale(1);
border: 3px solid #9b3838;
background: #9b3838;
cursor: not-allowed;
}
& > svg {
stroke: #eee;
font-size: 10px;
}
`;
export const PokemonDescription = styled.div`
width: 100%;
height: 80px;
background-image: linear-gradient(to right, #e2f3ff 50%, #9dd8ff);
box-shadow: inset 0 0 10px #000000;
color: #000000;
border-radius: 10px;
display: grid;
place-content: center;
padding: 5px;
text-align: center;
`;
|
/**
* Created by 11 on 2016/12/9.
*/
$(".btn").click(function () {
window.parent.document.title=document.title;
window.location.href = "withdrawList.html";
}); |
/*jslint node:false*/
/*jslint loopfunc:true*/
/*jslint browser:true*/
/*jslist jquery:true*/
var topics = [ "Fibonacci spiral", "Finding The North Star", "Shapes in nature", "Malala Yousafzai", "CPR" ];
function createButton( text ) {
var button = $( "<input>" );
button.attr( 'type', 'button' );
button.attr( 'value', text );
button.click( function () {
var giphyGet = $.get( "https://api.giphy.com/v1/gifs/search?q=" + text + "&api_key=dc6zaTOxFJmzC&limit=10&r=pg-13" );
giphyGet.done( function ( responseData ) {
console.log( responseData );
$( '#gallery' ).html( '' );
for ( var i = 0; i < responseData.data.length; i++ ) {
var newImage = $( '<img>' ).attr( 'src', responseData.data[ i ].images.fixed_height_still.url );
newImage.css( 'animation-play-state', 'paused' );
newImage.attr( 'data-still', responseData.data[ i ].images.fixed_height_still.url );
newImage.attr( 'data-animate', responseData.data[ i ].images.fixed_height.url );
newImage.attr( 'data-state', "still" );
newImage.attr( 'alt', 'rating: ' + responseData.data[ i ].rating );
newImage.click( function () {
var state = $( this ).attr( "data-state" );
// If the clicked image's state is still, update its src attribute to what its data-animate value is.
// Then, set the image's data-state to animate
// Else set src to the data-still value
if ( state === "still" ) {
$( this ).attr( "src", $( this ).attr( "data-animate" ) );
$( this ).attr( "data-state", "animate" );
} else {
$( this ).attr( "src", $( this ).attr( "data-still" ) );
$( this ).attr( "data-state", "still" );
}
} );
$( '#gallery' ).append( newImage );
var ratingDiv = $( "<div>" );
ratingDiv.text( newImage.attr( 'alt' ) );
$( "#gallery" ).append( ratingDiv );
//alert( ratingDiv );
}
} );
} );
$( "#buttons" ).append( button );
}
$( document ).ready( function () {
"use strict";
$( '#addbutton' ).click( function () { createButton( $( "#newInput" ).val() ) } );
for ( var i = 0; i < topics.length; i++ ) {
//generic input
var newButton = $( "<input>" );
// assigned an id from the location in the index
newButton.attr( 'id', 'topic-' + i );
// <input id="topic-i"></input>
//input type creates a button in html not text
newButton.attr( 'type', 'button' );
// <input id="topic-i" type="button"></input>
//value is assigned from the items in the array
newButton.attr( 'value', topics[ i ] );
// <input id="topic-i" type="button" value="Value of topics[i]"></input>
//creates a new click handler
newButton.click( function () {
var giphyGet = $.get( "https://api.giphy.com/v1/gifs/search?q=" +
$( this ).val() +
"&api_key=dc6zaTOxFJmzC&limit=10&r=pg-13" );
giphyGet.done( function ( data ) {
console.log( "Yay, got data!", data );
$( '#gallery' ).html( '' );
for ( var i = 0; i < data.data.length; i++ ) {
var newImage = $( '<img>' ).attr( 'src', data.data[ i ].images.fixed_height_still.url );
newImage.css( 'animation-play-state', 'paused' );
newImage.attr( 'data-still', data.data[ i ].images.fixed_height_still.url );
newImage.attr( 'data-animate', data.data[ i ].images.fixed_height.url );
newImage.attr( 'data-state', "still" );
newImage.attr( 'alt', 'rating: ' + data.data[ i ].rating );
newImage.click( function () {
var state = $( this ).attr( "data-state" );
// If the clicked image's state is still, update its src attribute to what its data-animate value is.
// Then, set the image's data-state to animate
// Else set src to the data-still value
if ( state === "still" ) {
$( this ).attr( "src", $( this ).attr( "data-animate" ) );
$( this ).attr( "data-state", "animate" );
} else {
$( this ).attr( "src", $( this ).attr( "data-still" ) );
$( this ).attr( "data-state", "still" );
}
} );
$( '#gallery' ).append( newImage );
var ratingDiv = $( "<div>" );
ratingDiv.text( newImage.attr( 'alt' ) );
$( "#gallery" ).append( ratingDiv );
}
} );
} );
$( "#buttons" ).append( newButton );
}
} ); |
const path = require('path')
const merge = require('webpack-merge')
const webpack = require('webpack')
const base = require('./webpack.base.js')
const config = {
optimization: {
namedModules: true
},
devServer: {
hot: true,
// contentBase: [path.join(__dirname, '../src/public'), path.join(__dirname, '../src/assets')], // 不经过webpack构建,额外的静态文件内容的访问路径
// proxy: { // 代理
// '/api': {
// target: "http://localhost:3000", // 将 URL 中带有 /api 的请求代理到本地的 3000 端口的服务上
// pathRewrite: { '^/api': '' }, // 把 URL 中 path 部分的 `api` 移除掉
// },
// },
}
}
module.exports = merge(base, config)
|
const bcrypt = require('bcrypt');
//Controller untuk user logic
class UserController {
#UserModel;
constructor(UserModel) {
this.#UserModel = UserModel;
}
index = async (req, res) => {
let userSession = req.session.user;
if(!userSession) return res.json({ auth: false });
userSession = await this.#UserModel.findById(userSession._id).populate('carts.product');
if(!userSession) return res.json({ auth: false });
res.json({ auth: true, userSession });
}
//** Register logic */
register = async (req, res) => {
const { username, email, password } = req.body;
//Mencari email atau username yang sama
const user = await this.#UserModel.findOne({ $or: [{ username }, { email }] });
if(user?.email == email) return res.status(409).json({ message: "Email telah terdaftar sebelumnya", success: false });
if(user?.username == username) return res.status(409).json({ message: "Username telah terdaftar sebelumnya", success: false });
//encrypt password
const hash = await bcrypt.hash(password, 10);
const doc = new this.#UserModel({
username,
email,
password: hash,
carts: [],
transactions: []
});
//Simpan doc, lalu mengembalikan document yg tersimpan ke savedDoc
const savedDoc = await doc.save();
if(savedDoc != doc) return res.status(500).json({ message: "Terjadi kesalahan pada server", success: false });
//menyimpan session autentikasi
let userSession = {
id: savedDoc._id,
username: savedDoc.username,
email: savedDoc.email,
carts: savedDoc.carts,
transactions: savedDoc.transactions
};
req.session.user = userSession;
userSession = await this.#UserModel.populate(savedDoc, { path: 'carts.product' });
res.json({ success: true, userSession });
}
//** Login logic */
login = async (req, res) => {
const { email, password } = req.body;
//Response saat login gagal
const failedLogin = () => res.status(401).json({ message: "Email atau password anda salah", success: false });
//Mencari user dengan inputan email
const user = await this.#UserModel.findOne({ email }).populate('carts.product');
if(!user) return failedLogin();
//Menyocokkan password yang terenkripsi dengan inputan password
const match = await bcrypt.compare(password, user.password);
if(!match) return failedLogin();
//Menyimpan session dari user
const userSession = {
_id: user._id,
username: user.username,
email: user.email,
carts: user.carts,
transactions: user.transactions
};
req.session.user = userSession;
res.json({ success: true, userSession: user});
}
//**Logout logic */
logout = async (req, res) => {
//Hapus user session
const loggedOut = await req.session.destroy();
if(!loggedOut) return res.status(500).json({ message: "Terjadi kesalahan pada server", success: false });
//Hapus cookie
res.clearCookie('session-id');
res.json({ success: true });
}
addCart = async (req, res) => {
const { userID, quantity, status, productID, discount } = req.body;
//Mencari user lalu push data keranjang ke field carts
const updatedUser = await this.#UserModel.findByIdAndUpdate(userID, {
$push: {
carts: {
quantity,
status,
discount,
product: productID
}
}
},
{ new: true })
.populate('carts.product');
res.json({ success: true, userSession: updatedUser });
}
removeItemFromCart = async (req, res) => {
const { itemID } = req.body;
//mencari item di keranjang
const item = await this.#UserModel.findOne({ 'carts._id': itemID });
if(!item) return res.status(404).json({ success: false, message: "Barang yang dicari tidak ditemukan" });
//menghapus item di keranjang user lalu simpan usernya
await item.carts.id(itemID).remove();
let updatedUser = await item.save();
updatedUser = await this.#UserModel.populate(updatedUser, { path: 'carts.product' });
res.json({ success: true, userSession: updatedUser });
}
removeProductFromCart = async (req, res) => {
const { itemID } = req.body;
const item = await this.#UserModel.findOne({ 'carts.product': itemID });
if(!item) return res.status(404).json({ success: false, message: "Barang yang dicari tidak ditemukan" });
item.carts = await item.carts.filter(data => data.product != itemID);
let updatedUser = await item.save();
updatedUser = await this.#UserModel.populate(updatedUser, { path: 'carts.product' });
res.json({ success: true, userSession: updatedUser });
}
modifyProductQuantity = async (req, res) => {
const { productID } = req.body;
const { q } = req.query || '';
let updatedDoc;
if(q === 'inc') {
updatedDoc = await this.#UserModel.findOneAndUpdate({ 'carts.product': productID },
{ $inc: { 'carts.$.quantity': 1 } },
{ new: true })
.populate('carts.product');
}
if(q === 'dec') {
updatedDoc = await this.#UserModel.findOneAndUpdate({ 'carts.product': productID },
{ $inc: { 'carts.$.quantity': -1 } },
{ new: true })
.populate('carts.product');
}
res.json({ success: true, userSession: updatedDoc });
}
addTransaction = async (req, res) => {
const { userID, carts, address, phone, name, totalPrice, paidVia, boughtDate } = req.body;
const user = await this.#UserModel.findById(userID);
let bought = [];
for(let item in carts) {
if(carts[item].status === 1) {
bought.push({
product: carts[item].product._id,
quantity: carts[item].quantity,
discount: carts[item].discount
});
}
}
await user.transactions.push({
bought,
address,
name,
phone,
totalPrice,
paidVia,
boughtDate
});
const updatedCarts = await user.carts.filter(item => item.status != 1)
user.carts = updatedCarts;
const userSession = await user.save();
res.json({ success: true, userSession });
}
getTransaction = async (req, res) => {
const { q } = req.query || '';
const user = await this.#UserModel.findOne({'transactions._id': q})
.populate('transactions.bought.product');
let transaction = await user.transactions.filter(item => item._id == q);
res.json({ success: true, transaction: transaction[0] });
}
}
module.exports = UserController; |
const path = require('path')
const webpack = require('webpack')
module.exports = {
context: __dirname, // wherever webpack command is run, context is root dir,
devtool: 'sourcemaps', // debug errors refer to source code ln, not bundle ln
resolve: {
extensions: ['.js'],
},
stats: {
colors: true,
reasons: true, // why things fail
chunks: true,
},
entry: {
app: ['babel-polyfill', 'whatwg-fetch', './src/index.js'],
},
output: {
path: path.join(__dirname, '/public'),
filename: '[name].js',
},
devServer: {
contentBase: path.join(__dirname, '/public'),
publicPath: '/',
port: 8000,
historyApiFallback: true,
disableHostCheck: true,
},
plugins: [
new webpack.DefinePlugin({ CONFIG: JSON.stringify(require('config')) })
],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [
/node_modules/,
/config/,
],
loader: 'babel-loader',
},
]
},
} |
import React, {Component} from "react";
export default class Skills extends Component {
constructor() {
super();
this.createProgressBar = this.createProgressBar.bind(this);
}
createProgressBar(item) {
const filledProgressBar = [];
for (let i = 0; i < item.level; i++) {
filledProgressBar.push(<div className="progressBar-with-bg"></div>)
}
for (let i = 0; i < (5-item.level); i++) {
filledProgressBar.push(<div className="progressBar"></div>)
}
return (
<div className="progressBar-wrapper">
{filledProgressBar}
</div>
)
}
render() {
let resumeData = this.props.resumeData;
return (
<section id="skills">
<h1><span>Skills</span></h1>
<div id="skills-section">
<ul className="ul-skills">
{resumeData.skills && resumeData.skills.map((item, index) => {
return (
<div key={index}>
<li>
<div className="skill_logo_container">
<img className="skill_image" src={item.skillogo}/>
</div>
<span className="skillName"> {item.skillname}</span>
{this.createProgressBar(item)}
</li>
</div>
);
})}
</ul>
</div>
</section>
);
}
} |
var mn = mn || {};
mn.components = mn.components || {};
mn.components.MnAuth =
(function (Rx) {
"use strict";
mn.core.extend(MnAuthComponent, mn.core.MnEventableComponent);
MnAuthComponent.annotations = [
new ng.core.Component({
templateUrl: "app-new/mn-auth.html",
})
];
MnAuthComponent.parameters = [
mn.services.MnForm,
mn.services.MnAuth,
window['@uirouter/angular'].UIRouter,
];
return MnAuthComponent;
function MnAuthComponent(mnFormService, mnAuthService, uiRouter) {
mn.core.MnEventableComponent.call(this);
this.focusFieldSubject = new Rx.BehaviorSubject(true);
this.postUILogin = mnAuthService.stream.postUILogin;
this.form = mnFormService.create(this)
.setFormGroup({
user: ['', ng.forms.Validators.required],
password: ['', ng.forms.Validators.required]})
.setPostRequest(this.postUILogin)
.success(uiRouter.urlRouter.sync.bind(uiRouter.urlRouter));
}
})(window.rxjs);
|
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css'
// ReactDOM.render(
// <div className="ml_demo d-flex flex-column justify-content-center align-items-center mt-5 h-50">
// <h1 className="display-3 text-center"><strong>Coming soon</strong></h1>
// </div>,
// document.getElementById('ml_app')
// );
import 'babel-polyfill'
import * as d3 from 'd3';
import * as legend from 'd3-svg-legend';
const protoChart = {
width: 480, // window.innerWidth,
height: 320, // window.innerHeight,
margin: {
left: 10, right: 10, top: 10, bottom: 10,
},
};
function chartFactory(div, opts, proto = protoChart) {
const chart = Object.assign({}, proto, opts);
// console.log(chart)
chart.svg = d3.select(div)
.append('svg')
.attr('width', chart.width)
.attr('height', chart.height);
// .attr('width', chart.width - chart.margin.right)
// .attr('height', chart.height - chart.margin.bottom);
chart.container = chart.svg.append('g')
.attr('id', 'container')
.attr('transform', `translate(${chart.margin.left}, ${chart.margin.top})`);
return chart;
}
function addRoot(data, itemKey, parentKey, joinValue) {
data.forEach((d) => { d[parentKey] = d[parentKey] || joinValue; });
data.push({
[parentKey]: '',
[itemKey]: joinValue,
});
return data;
}
function linkHorizontal(d) {
return "M" + d.source.x + "," + d.source.y
+ "C" + d.source.x + "," + (d.source.y + d.target.y) / 2
+ " " + d.target.x + "," + (d.source.y + d.target.y) / 2
+ " " + d.target.x + "," + d.target.y;
}
function linkVertical(d) {
return "M" + d.source.x + "," + d.source.y
+ "C" + (d.source.x + d.target.x) / 2 + "," + d.source.y
+ " " + (d.source.x + d.target.x) / 2 + "," + d.target.y
+ " " + d.target.x + "," + d.target.y;
}
const uniques = (data, name) => data.reduce(
(uniqueValues, d) => {
uniqueValues.push((uniqueValues.indexOf(name(d)) < 0 ? name(d) : undefined));
return uniqueValues;
}, [])
.filter(i => i); // Filter by identity
function nameId(data, name) {
const uniqueNames = uniques(data, name);
return d3.scaleOrdinal()
.domain(uniqueNames)
.range(d3.range(uniqueNames.length));
}
function binPerName(data, name) {
const nameIds = nameId(data, name);
const histogram = d3.histogram()
.bins(nameIds.range())
.value(d => nameIds(name(d)));
return histogram(data);
}
const colorScale = d3.scaleOrdinal().range(d3.schemeCategory10);
function fixateColors(data, key) {
colorScale.domain(uniques(data, d => d[key]));
}
function tickAngle(d) {
const midAngle = (d.endAngle - d.startAngle) / 2;
return ((midAngle + d.startAngle) / Math.PI) * (180 - 90);
}
function arcLabels(text, radius) {
return (selection) => {
selection.append('text')
.text(text)
.attr('text-anchor', d => (tickAngle(d) > 100 ? 'end' : 'start'))
.attr('transform', (d) => {
const degrees = tickAngle(d);
let turn = `rotate(${degrees}) translate(${radius(d) + 10}, 0)`;
if (degrees > 100) {
turn += 'rotate(180)';
}
return turn;
});
};
}
function tooltip(text, chart) {
return (selection) => {
function mouseover(d) {
const path = d3.select(this);
path.classed('highlighted', true);
const mouse = d3.mouse(chart.node());
const tool = chart.append('g')
.attr('id', 'tooltip')
.attr('transform', `translate(${mouse[0] + 5},${mouse[1] + 10})`);
const textNode = tool.append('text')
.text(text(d))
.attr('fill', 'black')
.node();
tool.append('rect')
.attr('height', textNode.getBBox().height)
.attr('width', textNode.getBBox().width)
.style('fill', 'rgba(255, 255, 255, 0.6)')
.attr('transform', 'translate(0, -16)');
tool.select('text')
.remove();
tool.append('text').text(text(d));
}
function mousemove() {
const mouse = d3.mouse(chart.node());
d3.select('#tooltip')
.attr('transform', `translate(${mouse[0] + 15},${mouse[1] + 20})`);
}
function mouseout() {
const path = d3.select(this);
path.classed('highlighted', false);
d3.select('#tooltip').remove();
}
selection.on('mouseover.tooltip', mouseover)
.on('mousemove.tooltip', mousemove)
.on('mouseout.tooltip', mouseout);
};
}
function allUniqueNames(data, sourceKey = 'source', targetKey = 'target') {
const sources = uniques(data, d => d[sourceKey]);
const targets = uniques(data, d => d[targetKey]);
return uniques(sources.concat(targets), d => d);
}
function connectionMatrix(data, sourceKey = 'source', targetKey = 'target', valueKey = 'value') {
const nameIds = nameId(allUniqueNames(data, 'Source', 'Target'), d => d);
const uniqueIds = nameIds.domain();
const matrix = d3.range(uniqueIds.length).map(() => d3.range(uniqueIds.length).map(() => 1));
data.forEach((d) => {
matrix[nameIds(d[sourceKey])][nameIds(d[targetKey])] += Number(d[valueKey]);
});
return matrix;
}
function makeTree(data, filterByDonor, name1, name2) {
const tree = { name: 'Donations', children: [] };
const uniqueNames = uniques(data, d => d.DonorName);
tree.children = uniqueNames.map((name) => {
const donatedTo = data.filter(d => filterByDonor(d, name));
const donationsValue = donatedTo.reduce((last, curr) => {
const value = Number(curr.Value.replace(/[^\d.]*/g, ''));
return value ? last + value : last;
}, 0);
return {
name,
donated: donationsValue,
children: donatedTo.map(d => ({
name: name2(d),
count: 0,
children: [],
})),
};
});
return tree;
}
const heightOrValueComparator = (a, b) => b.height - a.height || b.value - a.value;
const valueComparator = (a, b) => b.value - a.value;
const descendantsDarker = (d, color, invert = false, dk = 5) =>
d3.color(color(d.ancestors()[d.ancestors().length - 2].id.split(' ').pop()))[invert ? 'brighter' : 'darker'](d.depth / dk);
const getMajorHouses = data => addRoot(data, 'itemLabel', 'fatherLabel', 'Westeros')
.map((d, i, a) => {
if (d.fatherLabel === 'Westeros') {
const childrenLen = a.filter(e => e.fatherLabel === d.itemLabel).length;
return childrenLen > 0 ? d : undefined;
} else {
return d;
}
})
.filter(i => i);
const getHouseName = (d) => {
const ancestors = d.ancestors();
let house;
if (ancestors.length > 1) {
ancestors.pop();
house = ancestors.pop().id.split(' ').pop();
} else {
house = 'Westeros';
}
return house;
};
const houseNames = root => root.ancestors().shift().children.map(getHouseName);
const getHouseColor = d => colorScale(getHouseName(d));
const layoutDemo = ((enabled) => {
if(enabled) {
const westerosChart = chartFactory('div.demo_graph', {
width: parseInt($('div.demo_graph').width() * 0.9),
height: parseInt($('main').height() * 0.6),
// height: parseInt(Math.min($('main').height() * 0.4, $('div.demo_graph').width() * 0.6)),
margin: { left: 50, right: 50, top: 50, bottom: 50 },
padding: { left: 10, right: 10, top: 10, bottom: 10 },
});
westerosChart.loadData = async function loadData(uri) {
if (uri.match(/\.csv$/)) {
this.data = d3.csvParse(await (await fetch(uri)).text());
} else if (uri.match(/\.json$/)) {
this.data = await (await fetch(uri)).json();
}
return this.data;
};
westerosChart.init = function initChart(chartType, dataUri, ...args) {
this.loadData(dataUri).then(data => this[chartType].call(this, data, ...args));
this.innerHeight = this.height - this.margin.top - this.margin.bottom - this.padding.top - this.padding.bottom;
this.innerWidth = this.width - this.margin.left - this.margin.right - this.padding.left - this.padding.right;
};
westerosChart.tree = function Tree(_data) {
const data = getMajorHouses(_data);
const chart = this.container;
const stratify = d3.stratify()
.parentId(d => d.fatherLabel)
.id(d => d.itemLabel);
const root = stratify(data);
const layout = d3.tree()
.size([
this.innerWidth,
this.innerHeight,
]);
fixateColors(houseNames(root), 'id');
const line = d3.line().curve(d3.curveBasis);
// Links
const links = layout(root)
.descendants()
.slice(1);
chart.selectAll('.link')
.data(links)
.enter()
.append('path')
.attr('fill', 'none')
.attr('stroke', 'lightblue')
.attr('d', d => line([
[d.x, d.y],
[d.x, (d.y + d.parent.y) / 2],
[d.parent.x, (d.y + d.parent.y) / 2],
// [(d.x + d.parent.x) / 2, d.y],
// [(d.x + d.parent.y) / 2, d.parent.y],
[d.parent.x, d.parent.y]],
));
// Nodes
const nodes = chart.selectAll('.node')
.data(root.descendants())
.enter()
.append('circle')
.attr('r', 4.5)
.attr('fill', getHouseColor)
.attr('class', 'node')
.attr('cx', d => d.x)
.attr('cy', d => d.y);
const legendGenerator = legend.legendColor()
.scale(colorScale);
this.container
.append('g')
.attr('id', 'legend')
.attr('transform', `translate(0, ${this.innerHeight / 2})`)
.call(legendGenerator);
nodes.call(tooltip(d => d.data.itemLabel, this.container));
};
westerosChart.cluster = function Cluster(_data) {
const data = getMajorHouses(_data);
const stratify = d3.stratify()
.parentId(d => d.fatherLabel)
.id(d => d.itemLabel);
const root = stratify(data);
fixateColors(houseNames(root), 'id');
const layout = d3.cluster()
.size([
this.innerHeight,
this.innerWidth,
// this.innerWidth - 150,
]);
const links = layout(root)
.descendants()
.slice(1);
const line = d3.line().curve(d3.curveBasis);
this.container.selectAll('.link')
.data(links)
.enter()
.append('path')
.attr('fill', 'none')
.attr('stroke', 'lightblue')
.attr('d', d => line([
[d.y, d.x],
// [d.y, (d.x + d.parent.x) / 2],
// [d.parent.y, (d.x + d.parent.x) / 2],
[(d.y + d.parent.y) / 2, d.x],
[(d.y + d.parent.y) / 2, d.parent.x],
[d.parent.y, d.parent.x]],
));
const nodes = this.container.selectAll('.node')
.data(root.descendants())
.enter()
.append('circle')
.classed('node', true)
.attr('r', 5)
.attr('fill', getHouseColor)
.attr('cx', d => d.y)
.attr('cy', d => d.x);
// const l = legend
// .legendColor()
// .scale(color);
// this.container
// .append('g')
// .attr('id', 'legend')
// .attr('transform', `translate(${this.innerWidth - 100}, 0)`)
// .call(l);
// nodes.call(tooltip(d => d.data.itemLabel, this.container));
};
westerosChart.treemap = function Treemap(_data) {
const data = getMajorHouses(_data);
const stratify = d3.stratify()
.parentId(d => d.fatherLabel)
.id(d => d.itemLabel);
const root = stratify(data)
.sum(d => d.screentime)
.sort(heightOrValueComparator);
const cellPadding = 10;
const houseColors = colorScale.copy().domain(houseNames(root));
const layout = d3.treemap()
.size([
this.innerWidth - 100,
this.innerHeight,
])
.padding(cellPadding);
layout(root);
const nodes = this.container.selectAll('.node')
.data(root.descendants().slice(1))
.enter()
.append('g')
.attr('class', 'node');
nodes.append('rect')
.attr('x', d => d.x0)
.attr('y', d => d.y0)
.attr('width', d => d.x1 - d.x0)
.attr('height', d => d.y1 - d.y0)
.attr('fill', d => descendantsDarker(d, colorScale, true));
this.container
.append('g')
.attr('id', 'legend')
.attr('transform', `translate(${this.innerWidth - 100}, ${cellPadding})`)
.call(legend.legendColor().scale(houseColors));
nodes.call(tooltip(d => d.data.itemLabel, this.container));
};
westerosChart.partition = function Partition(_data) {
const data = getMajorHouses(_data);
const stratify = d3.stratify()
.parentId(d => d.fatherLabel)
.id(d => d.itemLabel);
const root = stratify(data)
.sum(d => d.screentime)
.sort(heightOrValueComparator);
const houseColors = colorScale.copy().domain(houseNames(root));
const layout = d3.partition()
.size([
this.innerWidth - 175,
this.innerHeight,
])
.padding(2)
.round(true);
layout(root);
const nodes = this.container.selectAll('.node')
.data(root.descendants().slice(1))
.enter()
.append('g')
.attr('class', 'node');
nodes.append('rect')
.attr('x', d => d.x0)
.attr('y', d => d.y0)
.attr('width', d => d.x1 - d.x0)
.attr('height', d => d.y1 - d.y0)
.attr('fill', d => descendantsDarker(d, colorScale));
this.container
.append('g')
.attr('id', 'legend')
.attr('transform', `translate(${this.innerWidth - 100}, 0)`)
.call(legend.legendColor().scale(houseColors));
nodes.call(tooltip(d => d.data.itemLabel, this.container));
};
westerosChart.radialPartition = function RadialPartition(_data) {
const data = getMajorHouses(_data).map((d, i, a) => Object.assign(d, {
screentime: a.filter(v => v.fatherLabel === d.itemLabel).length ? 0 : d.screentime,
}));
const radius = Math.min(this.innerWidth, this.innerHeight) / 2;
const stratify = d3.stratify()
.parentId(d => d.fatherLabel)
.id(d => d.itemLabel);
const root = stratify(data)
.sum(d => d.screentime)
.sort(null);
const houseColors = colorScale.copy().domain(root.ancestors().shift().children.map(
d => d.id.split(' ')[d.id.split(' ').length - 1])
);
const layout = d3.partition()
.size([
this.innerWidth / 2,
this.innerHeight / 2,
])
.padding(1)
.round(true);
const x = d3.scaleLinear()
.domain([0, radius])
.range([0, Math.PI * 2]);
const arc = d3.arc()
.startAngle(d => x(d.x0))
.endAngle(d => x(d.x1))
.innerRadius(d => d.y0)
.outerRadius(d => d.y1);
layout(root);
const nodes = this.container
.append('g')
.attr('class', 'nodes')
.attr('transform', `translate(${this.innerWidth / 2}, ${this.innerHeight / 2})`)
.selectAll('.node')
.data(root.descendants().slice(1))
.enter()
.append('g')
.attr('class', 'node');
nodes.append('path')
.attr('d', arc)
.attr('fill', d => d3.color(colorScale(d.ancestors()[d.ancestors().length - 2].id.split(' ').pop()))
.darker(d.depth / 5));
this.container
.append('g')
.attr('id', 'legend')
.attr('transform', `translate(${this.innerWidth - 100}, 0)`)
.call(legend.legendColor().scale(houseColors));
nodes.call(tooltip(d => d.data.itemLabel, this.container));
};
westerosChart.pack = function Pack(_data) {
const data = getMajorHouses(_data);
const stratify = d3.stratify()
.parentId(d => d.fatherLabel)
.id(d => d.itemLabel);
const root = stratify(data)
.sum(d => d.screentime)
.sort(valueComparator);
const houseColors = colorScale.copy().domain(houseNames(root));
fixateColors(data, 'itemLabel');
const layout = d3.pack()
.size([
this.innerWidth - 100,
this.innerHeight,
]);
layout(root);
const nodes = this.container.selectAll('.node')
.data(root.descendants().slice(1))
.enter()
.append('circle')
.attr('class', 'node')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', d => d.r)
.attr('fill', d => descendantsDarker(d, colorScale, true, 5));
this.container
.append('g')
.attr('id', 'legend')
.attr('transform', `translate(${this.innerWidth - 100}, ${this.innerHeight / 2})`)
.call(legend.legendColor().scale(houseColors));
nodes.call(tooltip(d => d.data.itemLabel, this.container));
};
westerosChart.init('cluster', '/data/GoT-lineages-screentimes.json');
window.addEventListener("resize", () => {
const w = parseInt($('div.demo_graph').width() * 0.9);
let h = parseInt($('main').height() * 0.6);
// h = parseInt(Math.max(h, w * 0.6));
// westerosChart.rescale(w, h)
westerosChart.width = w
westerosChart.height = h
westerosChart.svg
.attr('width', w)
.attr('height', h)
westerosChart.container.selectAll('path, circle').remove()
westerosChart.init('cluster', '/data/GoT-lineages-screentimes.json');
// chart.container.selectAll('g').remove()
// chart.render()
})
}
})(true)
|
const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
console.log(process.env.DB_URL);
mongoose.connect(process.env.DB_URL,
{useNewUrlParser: true, useUnifiedTopology: true}).then(() => {
console.log('Connected successfully.');
}, err => {
console.log('Connection to db failed: ' + err);
});
module.exports = mongoose.connection; |
import Ember from 'ember';
export default Ember.Controller.extend({
formatter: Ember.inject.service(),
init() {
const prevent = function(event) {
event.preventDefault();
event.stopPropagation();
};
Ember.$('html').on('dragover', function(event) {
prevent(event);
Ember.$('.drop-file-area').css('background-color', '#f0f0f0');
});
Ember.$('html').on('dragleave', function(event) {
prevent(event);
Ember.$('.drop-file-area').css('background-color', 'white');
});
// Ember.$('html').on('dragenter', prevent);
},
// firefox requires event as a parameter to get uploaded file
readAndRedirect(event) {
const file = _.first(event.target.files || event.dataTransfer.files);
if (!_.endsWith(file.name, '.bib')) {
swal({
title: 'Must be a .bib file',
timer: 2000
});
return;
}
const reader = new FileReader();
reader.onload = (e) => {
this.get('formatter').create(e.target.result);
this.transitionToRoute('editor');
};
reader.readAsText(file);
},
actions: {
choose() {
Ember.$('.app-index .body .file-input').trigger('click');
},
select(event) {
this.readAndRedirect(event);
// slow and deprecated for Ember 1.x
Ember.$('.app-index .body .file-input').val("");
},
drop(event) {
event.preventDefault();
event.stopPropagation();
this.readAndRedirect(event);
},
}
});
|
/* @flow */
import React, { Component } from 'react';
import {
Animated,
LayoutAnimation,
} from 'react-native';
import animation, {
enter, leave, reset,
} from './animations';
export default class DynamicListRow extends Component {
constructor(props) {
super(props);
this.state = {
x: null,
y: null,
width: null,
height: null,
};
this._transitionTime = this.props.time || 200;
this._measureView = this._measureView.bind(this);
}
componentWillMount() {
this._controlVar = new Animated.Value(0);
}
componentDidMount() {
enter(this._controlVar, this._transitionTime).start();
}
componentWillReceiveProps(nextProps) {
if (nextProps.remove) {
this.onRemoving(nextProps.onRemoving);
} else {
this._reset();
}
}
componentWillUpdate() {
LayoutAnimation.spring();
}
onRemoving(callback) {
leave(this._controlVar, this._transitionTime).start(callback);
}
_measureView(event) {
this.setState({
x: event.nativeEvent.layout.x,
y: event.nativeEvent.layout.y,
width: event.nativeEvent.layout.width,
height: event.nativeEvent.layout.height,
});
}
_reset() {
reset(this._controlVar);
}
render() {
const { width, height, x, y } = this.state;
const animationFuncParams = { controlVar: this._controlVar, width, height, x, y };
let rowAnimation = animation(this.props.animation, animationFuncParams);
if (this.props.animationFunc) {
rowAnimation = this.props.animationFunc(animationFuncParams);
}
return (
<Animated.View
onLayout={(event) => this._measureView(event)}
style={rowAnimation}
>
{this.props.children}
</Animated.View>
);
}
}
DynamicListRow.propTypes = {
time: React.PropTypes.number,
animation: React.PropTypes.string,
animationFunc: React.PropTypes.func,
children: React.PropTypes.element,
};
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Movie from '../../components/Movie/Movie';
import Spinner from '../../components/UI/Spinner/Spinner';
import Input from '../../components/UI/Input/Input';
import Button from '../../components/UI/Button/Button';
import axios from '../../axios-movie';
import withErrorHandler from '../../hoc/withErrorHandler/withErrorHandler';
import * as action from '../../store/actions/index';
class Movies extends Component {
state = {
controls: {
movieName: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Search Movie'
},
value: ''
}
}
}
componentDidMount(){
this.props.onFetchMovies();
}
editingModeCloseHandler = () => {
this.props.onMovieCancel();
}
editMovieHandler = (id) => {
let movieData = this.props.movies.filter(obj => {
return obj.id === id;
})
this.props.history.push('/film/'+id);
this.props.selectedMovie(movieData[0]);
}
inputChangeHandler = (event, controlName) => {
const updatedControls = {
...this.state.controls,
[controlName]: {
...this.state.controls[controlName],
value: event.target.value,
}
};
this.setState({ controls: updatedControls });
}
submitHandler = (event) => {
event.preventDefault();
this.props.onSearchMovie(this.state.controls.movieName.value);
}
render() {
const formElementsArray = [];
for (let key in this.state.controls){
formElementsArray.push({
id: key,
config: this.state.controls[key]
})
}
let searchForm = formElementsArray.map(formElement => (
<Input key = { formElement.id }
elementType = { formElement.config.elementType }
elementConfig = { formElement.config.elementConfig }
value = { formElement.config.value }
changed = { (event) => this.inputChangeHandler(event, formElement.id)}
/>
));
let movies = <Spinner/>;
if(!this.props.loading){
movies = this.props.error ? <h4>{this.props.error}</h4> : (
this.props.movies.map(movie => (
<Movie
key = { movie.id }
data = { movie.data }
clicked = {() => this.editMovieHandler(movie.id)}
/>
)));
}
return (
<React.Fragment>
<form style={{ display: 'flex', flexDirection: 'row', flexWrap: 'nowrap', justifyContent: 'center' }} >
{ searchForm }
<Button btnType="Success" clicked = { this.submitHandler }>SEARCH</Button>
</form>
<div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center' }}>
{ movies }
</div>
</React.Fragment>
);
}
}
const mapDispatchToProps = dispatch => {
return {
onFetchMovies: () => dispatch(action.fetchMovies()),
onMovieCancel: () => dispatch(action.cancelMovie()),
onSearchMovie: (movieName) => dispatch(action.searchMovie(movieName)),
selectedMovie: (movieData) => dispatch(action.selectedMovie(movieData))
};
};
const mapStateToProps = state => {
return {
movies: state.movies.movies,
loading: state.movies.loading,
token: state.auth.token,
error: state.movies.error
}
}
export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(Movies, axios)); |
let APIURL = '';
switch (window.location.hostname) {
case 'localhost' || '127.0.0.1':
APIURL = 'http://localhost:4000';
break;
case 'dk-like-minds-client.herokuapp.com':
APIURL = 'https://dk-like-minds-server.herokuapp.com'
};
export default APIURL; |
import '../class.css'
import {useDispatch, useSelector} from "react-redux";
import {useEffect, useRef, useState} from "react";
import {
addChapter,
deleteChapter,
fetchLessonsTeacherDetailed,
updateChapter
} from "../../../actions/lessonsTeacherByid";
import SmallModal from "../../../components/modal/smallModal";
function Lessont() {
const dispatch = useDispatch()
let lessonsTeacherById = useSelector(state => state.lessonsTeacherById)
let chapters = lessonsTeacherById.detailed.chapters
const smallRef = useRef()
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [upd, setUpd] = useState(false)
useEffect(() => {
const id = JSON.parse(localStorage.getItem('lessonId'))
dispatch(fetchLessonsTeacherDetailed(id))
}, [])
const handleAddChapter = (e) => {
e.preventDefault()
let lesson = JSON.parse(localStorage.getItem('lessonId'))
dispatch(addChapter(name, description, lesson))
smallRef.current.end()
}
const handleDeleteChapter = (id) => {
dispatch(deleteChapter(id))
}
const handleUpdateChapter = (e) => {
e.preventDefault()
let lesson = JSON.parse(localStorage.getItem('lessonId'))
let id = JSON.parse(localStorage.getItem('reg-id'))
dispatch(updateChapter(lesson, name, description, id))
smallRef.current.end()
setUpd(false)
}
if (!lessonsTeacherById.loading) {
return <>
<div className="modal-chapter">
<SmallModal ref={smallRef}>
<input type={"name"} className={"chapter-input-name"} placeholder={"name"}
onChange={(e) => setName(e.target.value)}/>
<textarea type={"description"} className={"chapter-input-description"} placeholder={"description"}
onChange={(e) => setDescription(e.target.value)}/>
{!upd && <input type={"submit"} value={"Додавання"} className={"submit-add"} onClick={(e) => handleAddChapter(e)}/>}
{upd && <input type={"submit"} className={"submit-upd"} value={"редагувати"} onClick={(e) => handleUpdateChapter(e)}/>}
</SmallModal>
</div>
<div className="container">
<div className="first-section">
{/*{% for i in get_chapter %}*/}
{chapters.map(el => {
return <div className="col" key={el.id}>
<div className="title">
<span>{el.name}</span>
</div>
<div className="description">
<span>{el.description}</span>
</div>
<div className="title pdf">
{/*<a href="{{ i.document.url }}" download>{{i.document.name}}</a>*/}
{/*<img src="../../media/page/pdf.svg" alt="" className="user-png">*/}
</div>
<div className="redaction">
<a onClick={() => handleDeleteChapter(el.id)}>Видалити</a>
<a onClick={() => {
setUpd(true)
localStorage.setItem('reg-id', JSON.stringify(el.id))
smallRef.current.add()
}}>
<span>Редактувати</span>
</a>
</div>
</div>
})}
</div>
<div className="second-section">
<div className="col col-teacher-info">
<div className="title">
<span>
{lessonsTeacherById.detailed.name}
</span>
<hr/>
<span className="subject_description">
{lessonsTeacherById.detailed.description}
</span>
</div>
{/*<div className="teacher-info"><p>{{get_lesson.description}}</p></div>*/}
<div className="whois">
{/*<span>Групи:</span>*/}
{/*{% for i in get_group %}*/}
{/*<span>{{i}}</span>*/}
{/*{% endfor %}*/}
</div>
</div>
<div className="col col-teacher-info add-new-chapter">
<span className="collapsible" onClick={(e) => {
smallRef.current.add()
}}>Додати</span>
<div className="content">
<form encType="multipart/form-data" action="" method="post">
<div className="modal-footer">
<button type="submit" name="button">Add</button>
</div>
</form>
</div>
</div>
</div>
</div>
</>
} else {
}
return (
<div>Loading...</div>
)
}
export default Lessont
|
import FilterBar from "./FilterBar";
const SearchHeader = ({ filters, setFilters }) => {
return (
<div className="search-container">
<div className="col1"></div>
<div className="filters-price">
{/* CHECKBOX ORDER-PRICE */}
<div className="checkbox-orderPrice-container">
<span>Trier par prix : </span>
<span className="checkbox-order-price">
<div
className="btn-price-order-container"
onClick={() => {
const newFilters = { ...filters };
newFilters.checkOrder =
newFilters.checkOrder === "price-asc"
? (newFilters.checkOrder = "price-desc")
: (newFilters.checkOrder = "price-asc");
setFilters(newFilters);
}}
>
<div
className="knob"
style={{
left: filters.checkOrder === "price-asc" ? 2 : 23,
}}
>
{filters.checkOrder === "price-desc" ? (
<span>⇣</span>
) : (
<span>⇡</span>
)}
</div>
</div>
</span>
</div>
{/* PRICE BETWEEN */}
<div className="filters-price-between">
<span>Prix entre : </span>
<span>
<FilterBar filters={filters} setFilters={setFilters} />
</span>
</div>
</div>
<div className="col3"></div>
</div>
);
};
export default SearchHeader;
|
//Check if we don't have the cookie and set it to 0
var $compareBar = $('.compare-hospitals-bar');
var $compareContent = $('.compare-hospitals-content');
var $countSpan = $('#compare_number');
var $heartIcon = $('#compare_heart');
var $svgMapIcon =
`<svg class="map-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33.37 49.61">
<g id="Layer_1" data-name="Layer 1">
<path fill="#037098" d="M26.38 34.66c4.77-8.54 7-14.25 7-18A16.69 16.69 0 000 16.68c0 3.73 2.22 9.44 7 18 2.9 5.2 5.81 9.72 6.63 11l2.37 3.6a.82.82 0 001.33 0l2.36-3.58c.37-.54 3.52-5.36 6.69-11.04zm-9.7 12.75L15 44.83s-3.28-5-6.61-10.93C3.86 25.82 1.58 20 1.58 16.68a15.11 15.11 0 0130.21 0c0 3.35-2.28 9.14-6.79 17.22-2.93 5.24-5.78 9.66-6.59 10.89z"/>
<path fill="#037098" d="M16.68 12.56a4 4 0 104 4 4 4 0 00-4-4z"/>
</g>
</svg>`;
// Where we hold the counts of hospital types
// No of each type of hospital in compare
var nhsCountHolder = $('#nhs-hospital-count');
var privateCountHolder = $('#private-hospital-count');
$body.on('DOMSubtreeModified', privateCountHolder, function () {
// code here
if (parseInt($('#private-hospital-count').text()) > 0) {
$('#multiple_enquiries_button').prop('disabled', false);
} else {
$('#multiple_enquiries_button').prop('disabled', true);
}
});
var multiEnquiryButton = $('#multiple_enquiries_button');
var nhsHospitalCount = 0;
var privateHospitalCount = 0;
var compareHospitalIds = '';
// var privateHospitalIds = '';
// The target for the content to be added
var target = $('#compare_hospitals_grid');
// The content for any empty column in the comparison
var emptyColDesktop = '<div class="col col-empty h-100">\n' +
' <div class="col-inner">\n' +
' <div class="col-header border-bottom-0">\n' +
' <p class="text-center px-2">Selected Hospital<br>\n' +
' will appear here.</p>\n' +
' <p class="text-center px-2"> Add more hospitals to your\n' +
' Shortlist by clicking the <img width="14" height="12" src="/images/icons/heart.svg" alt="Heart icon">\n' +
' </p>\n' +
' </div>\n' +
' </div>\n' +
' </div>';
var emptyColMobile = '<div class="card w-100 rounded-0 border-top-0 border-left-0 border-right-0 border-bottom">\n' +
' <div class="border-bottom">\n' +
' <p class="">Selected Hospital<br>\n' +
' will appear here.</p>\n' +
' <p class=""> Add more hospitals to your\n' +
' Shortlist by clicking the <img width="14" height="12" src="/images/icons/heart.svg" alt="Heart icon">\n' +
' </p>\n' +
' </div>\n' +
' </div>\n';
var emptyCol = ($("body").hasClass("results-page-mobile")) ? emptyColMobile : emptyColDesktop;
if (typeof Cookies.get("compareHospitalsData") === 'undefined') {
Cookies.set("compareHospitalsData", '', {expires: 365});
}
var compareCount = getCompareCount();
var compareData = Cookies.get('compareHospitalsData');
// Check if we need to show the Compare hospitals div (on page load)
if (compareCount > 0 && window.location.href.indexOf("results-page") > '-1') {
// Show the comparison row headings and hide the existing column
$('#compare_hospitals_headings').removeClass('d-none');
$('#no_items_added').addClass('d-none');
// Hide the "you haven't added any items..."
compareHospitalIds = compareData;
// Update the value of the enquiry form
multiEnquiryButton.data('hospital-id', removeTrailingComma(compareHospitalIds));
// Ajax request to retrieve all the Hospitals to compare
getHospitalsByIds(removeTrailingComma(compareHospitalIds));
// Appending the extra empty columns
var remainingColCount = 5 - compareCount;
target.append(repeatStringNumTimes(emptyCol, remainingColCount));
$countSpan.text(compareCount);
$heartIcon.addClass('has-count');
//Add the `active` class that will change the color to pink
$heartIcon.addClass('active');
} else {
$heartIcon.removeClass('active');
target.append(repeatStringNumTimes(emptyCol, 5))
}
/**
* Adds the element to the Comparison Table
*
* @param element
*/
window.addHospitalToCompare = function (element) {
compareHospitalIds = Cookies.get('compareHospitalsData');
// Content for modal trigger button
var circleCheck = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><g><g><g><path fill="#fff" d="M10.002 18.849c-4.878 0-8.846-3.968-8.846-8.847 0-4.878 3.968-8.846 8.846-8.846 4.879 0 8.847 3.968 8.847 8.846 0 4.879-3.968 8.847-8.847 8.847zm0-18.849C4.488 0 0 4.488 0 10.002c0 5.515 4.488 10.003 10.002 10.003 5.515 0 10.003-4.488 10.003-10.003C20.005 4.488 15.517 0 10.002 0z"></path></g><g><path fill="#fff" d="M14.47 5.848l-5.665 6.375-3.34-2.67a.578.578 0 0 0-.811.088c-.2.25-.158.615.091.815l3.769 3.015a.57.57 0 0 0 .361.125c.167 0 .325-.07.433-.196l6.03-6.783a.579.579 0 0 0 .146-.42.588.588 0 0 0-.191-.4.592.592 0 0 0-.824.05z"></path></g></g></g></svg>';
var timesBlack = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10">\n' +
' <g>\n' +
' <g>\n' +
' <path fill="#1b1b1b"\n' +
' d="M5.884 5l3.932-3.932a.626.626 0 0 0-.884-.885L5 4.115 1.068.183a.626.626 0 0 0-.885.885L4.115 5 .183 8.932a.626.626 0 0 0 .883.884L5 5.885l3.932 3.931a.623.623 0 0 0 .883 0 .626.626 0 0 0 0-.884z"/>\n' +
' </g>\n' +
' </g>\n' +
'</svg>\n';
var cancelledOps = null;
var waitingTime = null;
// Content for new hospital added to compare
var hospitalType = element.hospital_type.name === 'Independent' ? 'Private' : 'NHS';
var nhsRating = element.hospital_type.name === 'Independent' ? 1 : 0;
var userRating = 0;
var latestRating = 'No Data';
var friendsAndFamilyRating = null;
var hasNhsEmail = typeof element.email != "undefined" && element.email !== ""; // Email must be not empty string AND not undefined AND be NHS;
if (element.rating !== null && typeof element.rating.friends_family_rating !== "undefined" && element.rating.friends_family_rating !== null) {
friendsAndFamilyRating = element.rating.friends_family_rating;
}
if (element.rating !== null && typeof element.rating.latest_rating !== "undefined" && element.rating.latest_rating !== null) {
latestRating = element.rating.latest_rating;
}
if (element.rating !== null && typeof element.rating.avg_user_rating !== "undefined" && element.rating.avg_user_rating !== null) {
userRating = element.rating.avg_user_rating;
}
if (element.waiting_time.length > 0 && typeof element.waiting_time[0].perc_waiting_weeks !== "undefined" && element.waiting_time[0].perc_waiting_weeks != null) {
waitingTime = element.waiting_time[0].perc_waiting_weeks;
}
if (element.cancelled_op !== null && typeof element.cancelled_op.perc_cancelled_ops !== "undefined" && element.cancelled_op.perc_cancelled_ops != null) {
cancelledOps = element.cancelled_op.perc_cancelled_ops;
// cancelledOps = element.cancelled_op;
}
//NHS Funded work = 1 when private hospital + waiting time OR NHS hospital
var nhsFundedWork = 0;
if (nhsRating === 0 || (nhsRating === 1 && waitingTime !== null)) {
nhsFundedWork = 1;
}
var btnClass = (isDesktop) ? 'btn btn-brand-secondary-3 enquiry font-12 p-2 btn-enquire text-center w-100' : 'btn btn-icon btn-brand-secondary-3 btn-enquire enquiry btn-squared btn-squared_slim font-12 px-5';
var targetModal = hospitalType == 'Private' ? '#hc_modal_enquire_private' : '#hc_modal_contacts_general_shortlist_' + element.id;
var btnContent =
`<a id="${element.id}"
class="${btnClass}"
role="button" data-toggle="modal"
data-hospital-url="${element.url}"
data-hospital-title="${element.display_name}"
data-hospital-id="${element.id}"
data-image="${element.image}"
data-target="${targetModal}">${circleCheck}Enquire</a>`;
// Button content if NHS hospital has a private website url
var urlTwoButton = (element.nhs_private_url != "" && typeof element.nhs_private_url != "undefined") ? `<a id="${element.id}" class="p-0 btn-link col-brand-primary-1 enquiry font-12 mb-4 d-inline-block" target="_blank" href="${element.nhs_private_url}" role="button" data-hospital-type="nhs-hospital"><span>Visit website</span></a>` : '';
// Button to trigger contact form for the private wing of NHS hospital
var nhsPrivateContactBtn = (element.email != "" && typeof element.email != "undefined") ? `<button class="btn btn-squared btn-squared_slim btn-enquire btn-brand-secondary-3 enquiry font-12 text-center mt-5" id="${element.id}" data-hospital-id="${element.id}" data-dismiss="modal" data-hospital-type="nhs-hospital" data-toggle="modal" data-target="#hc_modal_enquire_private" data-hospital-title="${element.display_name}">Make a private treatment enquiry${circleCheck}</button>` : '';
var nhsModalContent =
`<div class="modal modal-enquire fade" id="hc_modal_contacts_general_shortlist_${element.id}" tabindex="-1" role="dialog"
aria-labelledby="" aria-modal="true" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content position-relative">
<div id="hospital_type" class="hospital-type ${hospitalType === 'Private' ? 'private-hospital bg-private' : 'nhs-hospital bg-nhs'}">
<p class="m-0">${hospitalType}</p>
</div>
<div class="modal-body">
<div class="modal-header d-flex justify-content-between">
<button type="button" class="btn-plain ml-auto" data-dismiss="modal" aria-label="Close">
${timesBlack}
</button>
</div>
<div class="container-fluid p-30">
<div class="row">
<div class="col-12 col-md-6">
<div
class="col-inner h-100 col-inner__left text-center d-flex flex-column justify-content-center align-items-center">
<h3 class="modal-title mb-3 w-100">Thanks for Your Interest in <span id="hospital_title">${element.display_name}</span>
</h3>
<div class="d-flex mb-3 w-100">
<div class="modal-copy">
<p class="col-grey p-secondary mb-0">Without a GP referral, this NHS hospital won't respond to direct enquiries regarding
treatments. Please call or check their website to find out more about their services
using the following contact details:</p>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6">
<div
class="col-inner p-30 d-flex flex-column justify-content-center col-inner__right h-100 text-center border rounded">
<h3 class="mb-5">Contact the hospital</h3>
<div class="">
<p class="mb-1">Main switchboard</p>
<p class="col-brand-primary-1 font-20 mb-1" id="hospital_telephone">${element.phone_number}</p>
<a id="${element.id}" class="p-0 btn-link col-brand-primary-1 enquiry font-12 mb-4 d-inline-block" target="_blank" href="${element.url}" role="button" data-hospital-type="${element.hospital_type.name === 'Independent' ? 'private-hospital' : 'nhs-hospital'}">
<span>Visit website</span>
</a>
<p class="mb-1">Private</p>
<!-- Private phone number -->
<p class="col-brand-primary-1 font-20 mb-1" id="hospital_telephone_2">${element.phone_number_2 != "" && typeof element.phone_number_2 != 'undefined' ? element.phone_number_2 : 'No number available'}</p>
<!-- Private web address - only show if nhs_private_url not empty -->
${urlTwoButton}
</div>
<!-- Trigger enquiry form for PRIVATE treatment at NHS hospital -->
${nhsPrivateContactBtn}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>`;
if (hospitalType == 'Private') {
privateHospitalCount += 1;
privateCountHolder.text(privateHospitalCount);
} else {
nhsHospitalCount += 1;
nhsCountHolder.text(nhsHospitalCount);
}
if (isDesktop) {
var newColumn =
'<div class="col text-center" id="compare_hospital_id_' + element.id + '">' +
'<div class="col-inner">' +
'<div class="col-header d-flex flex-column justify-content-between align-items-center px-4 pb-3">' +
// '<div class="image-wrapper" style="background: url(' + element.image + ') no-repeat scroll center center / cover" >' +
'<div class="image-wrapper">' +
'<div class="remove-hospital" id="remove_id_' + element.id + '" data-hospital-type="' + slugify(hospitalType) + '-hospital"></div>' +
'</div>' +
'<div class="w-100 details font-16 SofiaPro-SemiBold"><p class="w-100">' + textTruncate(element.display_name, 30, '...') + '</p></div>' +
btnContent +
'</div>' +
'<div class="cell">' + hospitalType + '</div>' +
'<div class="cell">' + getHtmlDashTickValue(waitingTime, " Weeks") + '</div>' +
'<div class="cell">' + getHtmlStars(userRating) + '</div>' +
'<div class="cell">' + getHtmlDashTickValue(cancelledOps, "%") + '</div>' +
'<div class="cell">' + latestRating + '</div>' +
'<div class="cell">' + getHtmlDashTickValue(friendsAndFamilyRating, "%") + '</div>' +
'<div class="cell">' + getHtmlDashTickValue(nhsFundedWork) + '</div>' +
'<div class="cell">' + getHtmlDashTickValue(nhsRating) + '</div>' +
'<div class="cell column-break"></div>' +
'<div class="cell">' + (element.rating !== null && element.rating.safe !== null ? element.rating.safe : 'No Data') + '</div>' +
'<div class="cell">' + (element.rating !== null && element.rating.effective !== null ? element.rating.effective : 'No Data') + '</div>' +
'<div class="cell">' + (element.rating !== null && element.rating.caring !== null ? element.rating.caring : 'No Data') + '</div>' +
'<div class="cell">' + (element.rating !== null && element.rating.responsive !== null ? element.rating.responsive : 'No Data') + '</div>' +
'<div class="cell">' + (element.rating !== null && element.rating.well_led !== null ? element.rating.well_led : 'No Data') + '</div>' +
'<div class="cell column-break"></div>' +
'<div class="cell">' + (element.place_rating !== null && element.place_rating.cleanliness !== null ? getHtmlDashTickValue(element.place_rating.cleanliness, "%") : 'No data') + '</div>' +
'<div class="cell">' + (element.place_rating !== null && element.place_rating.food_hydration !== null ? getHtmlDashTickValue(element.place_rating.food_hydration, "%") : 'No data') + '</div>' +
'<div class="cell">' + (element.place_rating !== null && element.place_rating.privacy_dignity_wellbeing !== null ? getHtmlDashTickValue(element.place_rating.privacy_dignity_wellbeing, "%") : 'No data') + '</div>' +
'<div class="cell">' + (element.place_rating !== null && element.place_rating.condition_appearance_maintenance !== null ? getHtmlDashTickValue(element.place_rating.condition_appearance_maintenance, "%") : 'No data') + '</div>' +
'<div class="cell">' + (element.place_rating !== null && element.place_rating.dementia !== null ? getHtmlDashTickValue(element.place_rating.dementia, "%") : 'No data') + '</div>' +
'<div class="cell">' + (element.place_rating !== null && element.place_rating.disability !== null ? getHtmlDashTickValue(element.place_rating.disability, "%") : 'No data') + '</div>' +
'</div>' +
'</div>';
// Add new item
target.prepend(newColumn);
} else if (isMobile) {
var newRow =
`<div id="compare_hospital_id_${element.id}" class="card w-100 p-0 border-top-0 border-left-0 border-right-0 border-bottom rounded-0 shadow-none">
<div class="card-header p-0 pb-2 bg-white" id="heading${element.id}">
<button class="btn btn-link collapsed text-decoration-none p-0 rounded-0" data-toggle="collapse" data-target="#collapse${element.id}" aria-expanded="true" aria-controls="collapse${element.id}">
<p class="font-18 SofiaPro-SemiBold mb-2">${textTruncate(element.display_name, 30, '...')}</p>
<p class="col-grey mb-2">${$svgMapIcon}${element.address.city} | ${hospitalType}</p>
<p class="mb-2">${latestRating} | ${getHtmlDashTickValue(waitingTime, " Weeks Average Waiting")}</p>
</button>
<div class="btn-area d-flex align-items-center">
${btnContent}
<span class="remove-hospital col-brand-primary-1 ml-2 font-12" id="remove_id_${element.id}" data-hospital-type="${slugify(hospitalType)}-hospital">Remove</span>
</div>
</div>
<div id="collapse${element.id}" class="collapse" aria-labelledby="heading${element.id}" data-parent="#compare_hospitals_grid">
<div class="card-body p-0 pb-2 pt-3">
<div class="row">
<div class="col-6 border-right">
<div class="col-inner h-100">
<div class="mobile-cell">Hospital Type</div>
<div class="mobile-cell">Average Waiting Time</div>
<div class="mobile-cell">NHS User Rating</div>
<div class="mobile-cell">% Operations cancelled</div>
<div class="mobile-cell">Care Quality Rating</div>
<div class="mobile-cell">Friends & Family Rating</div>
<div class="mobile-cell">NHS Funded Work</div>
<div class="mobile-cell">Private Self Pay</div>
<div class="mobile-cell column-break"></div>
<div class="mobile-cell SofiaPro-SemiBold">Care Quality Rating</div>
<div class="mobile-cell">Safe</div>
<div class="mobile-cell">Effective</div>
<div class="mobile-cell">Caring</div>
<div class="mobile-cell">Responsive</div>
<div class="mobile-cell">Well Led</div>
<div class="mobile-cell column-break"></div>
<div class="mobile-cell SofiaPro-SemiBold">NHS User Rating</div>
<div class="mobile-cell">Cleanliness</div>
<div class="mobile-cell">Food & Hygiene</div>
<div class="mobile-cell">Privacy, Dignity & Wellbeing</div>
<div class="mobile-cell">Dementia Domain</div>
<div class="mobile-cell">Disability Domain</div>
</div>
</div>
<div class="col-6 text-center">
<div class="col-inner">
<div class="mobile-cell">${hospitalType}</div>
<div class="mobile-cell">${getHtmlDashTickValue(waitingTime, " Weeks")}</div>
<div class="mobile-cell">${getHtmlStars(userRating)}</div>
<div class="mobile-cell">${getHtmlDashTickValue(cancelledOps, "%")}</div>
<div class="mobile-cell">${latestRating}</div>
<div class="mobile-cell">${getHtmlDashTickValue(friendsAndFamilyRating, "%")}</div>
<div class="mobile-cell">${getHtmlDashTickValue(nhsFundedWork)}</div>
<div class="mobile-cell">${getHtmlDashTickValue(nhsRating)}</div>
<div class="mobile-cell column-break"></div>
<div class="mobile-cell"></div>
<div class="mobile-cell">${element.rating !== null && element.rating.safe !== null ? element.rating.safe : 'No Data'}</div>
<div class="mobile-cell">${element.rating !== null && element.rating.effective !== null ? element.rating.effective : 'No Data'}</div>
<div class="mobile-cell">${element.rating !== null && element.rating.caring !== null ? element.rating.caring : 'No Data'}</div>
<div class="mobile-cell">${element.rating !== null && element.rating.responsive !== null ? element.rating.responsive : 'No Data'}</div>
<div class="mobile-cell">${element.rating !== null && element.rating.well_led !== null ? element.rating.well_led : 'No Data'}</div>
<div class="mobile-cell column-break"></div>
<div class="mobile-cell"></div>
<div class="mobile-cell">${element.place_rating !== null && element.place_rating.cleanliness !== null ? getHtmlDashTickValue(element.place_rating.cleanliness, "%") : 'No data'}</div>
<div class="mobile-cell">${(element.place_rating !== null && element.place_rating.food_hydration !== null ? getHtmlDashTickValue(element.place_rating.food_hydration, "%") : 'No data')}</div>
<div class="mobile-cell">${(element.place_rating !== null && element.place_rating.privacy_dignity_wellbeing !== null ? getHtmlDashTickValue(element.place_rating.privacy_dignity_wellbeing, "%") : 'No data')}</div>
<div class="mobile-cell">${(element.place_rating !== null && element.place_rating.dementia !== null ? getHtmlDashTickValue(element.place_rating.dementia, "%") : 'No data')}</div>
<div class="mobile-cell">${(element.place_rating !== null && element.place_rating.disability !== null ? getHtmlDashTickValue(element.place_rating.disability, "%") : 'No data')}</div>
</div>
</div>
</div>
</div>
</div>
</div>`;
target.prepend(newRow);
}
// Add corresponding enquiry modal to body
// Add corresponding enquiry modal to body
if (element.hospital_type.name === 'NHS')
$body.append(nhsModalContent);
};
function removeHospitalFromCompare(elementId, data, compareCount, hospitalType) {
var $modalToRemove = $(`#hc_modal_contacts_general_shortlist_${elementId}`);
if ($modalToRemove.length) {
// When removing a hospital from compare, Remove the associated contacts modal from the body - for hospitals in the shortlist
$modalToRemove.remove();
}
// Remove the item from the shortlist
$('#compare_hospital_id_' + elementId).remove();
target.append(emptyCol);
$('button#' + elementId + '.compare').removeClass('selected');
// Filter out the clicked item from the data
var dataArr = data.split(',');
var elementIndex = dataArr.indexOf(elementId);
dataArr.splice(elementIndex, 1);
data = dataArr.join(',');
// Update the ids in the multi enquiry form
multiEnquiryButton.data('hospital-id', removeTrailingComma(data));
compareCount = parseInt(compareCount) - 1;
if (hospitalType == 'private-hospital' || hospitalType == 'private') {
privateHospitalCount -= 1;
privateCountHolder.text(privateHospitalCount)
} else {
nhsHospitalCount -= 1;
nhsCountHolder.text(nhsHospitalCount);
}
// Slide content down when all data removed
if (compareCount === 0) {
// Switch the first column round
$('#compare_hospitals_headings').addClass('d-none');
$('#no_items_added').removeClass('d-none');
// Hide the comparison area
$compareContent.slideUp();
$body.removeClass('shortlist-open');
$compareContent.removeClass('revealed');
}
// Check to see if we need to re-enable the buttons
enableButtons();
// var $countSpan = $('#compare_number');
$countSpan.text(compareCount);
// Set the data cookie
Cookies.set("compareHospitalsData", data, {expires: 365});
}
//Set the OnClick event for the Compare button
$(document).on("click", ".compare", function () {
// Get hospital type of item whose button has been clicked to remove it
var hospitalTypeClicked = $(this).data('hospital-type');
//Get the Data that is already in the Cookies
var compareCount = getCompareCount();
var data = Cookies.get("compareHospitalsData");
//Load the Cookies with the data that we need for the comparison
var elementId = $(this).attr('id');
// Split data string into Array
var dataArr = data.split(',');
// Check if value is in array
var result = false;
for (var i = 0; i < dataArr.length; i++) {
var stringPart = dataArr[i];
if (stringPart != elementId) continue;
result = true;
break;
}
//Check if there are already 5 hospitals for comparison in Cookies
if (compareCount < 5) {
//Check if we don't have the hospital in our comparison and add it - if not true then add to compare - also add the id to the enquiry form
if (!result) {
// Show the headings column when first item added, and it's not already in the
if (compareCount === 0) {
// Toggle the first column of comparison
// Switch the first column round
$('#compare_hospitals_headings').removeClass('d-none');
$('#no_items_added').addClass('d-none');
}
//Add data to Cookies and send the element to populate the table
data += elementId + ',';
// Update the enquiry form
multiEnquiryButton.data('hospital-id', removeTrailingComma(data));
// Remove placeholder column
target.children().last().remove();
// Add to the comparison area
getHospitalsByIds(elementId);
// Update compare count
compareCount = parseInt(compareCount) + 1;
$countSpan.text(compareCount);
}
}
// Check if we have to remove the data of the element that has been clicked - if true, it is already in the data
if (result) {
//Remove the hospital from the comparison table
removeHospitalFromCompare(elementId, data, compareCount, hospitalTypeClicked);
var dataArr = data.split(',');
var elementIndex = dataArr.indexOf(elementId);
dataArr.splice(elementIndex, 1);
data = dataArr.join(',');
compareCount = parseInt(compareCount) - 1;
}
// Pulsate the heart every time there is an action
$heartIcon.removeClass('has-count');
setTimeout(function () {
$heartIcon.addClass('has-count');
}, 100);
if (compareCount > 0) {
$heartIcon.addClass('active');
} else {
$heartIcon.removeClass('active');
}
// Set compareHospitalsData
Cookies.set("compareHospitalsData", data, {expires: 365});
});
//Set the OnClick event for the Remove Hospital on the Comparison table
$(document).on("click", ".remove-hospital", function (e) {
console.log(e);
e.stopPropagation();
var hospitalTypeClicked = $(this).data('hospital-type');
var elementId = $(this).attr('id');
var data = Cookies.get("compareHospitalsData");
var compareCount = getCompareCount();
if (compareCount === 1) {
$heartIcon.removeClass('active');
}
elementId = elementId.replace('remove_id_', '');
removeHospitalFromCompare(elementId, data, compareCount, hospitalTypeClicked);
});
//Set the Onclick event for the Comparison Header - toggle open and closed
$(document).on("click", "#compare_button_title", function (e) {
// Close all open modals
$('.modal').modal('hide');
var compareCount = getCompareCount();
var $openTabs = $('.special-offer-tab.open');
// var solutionsBar = $('.compare-hospitals-bar');
if (compareCount > -1) {
// solutionsBar.toggleClass('open');
$compareContent.slideToggle();
$body.toggleClass('shortlist-open');
// $('.compare-arrow').toggleClass('rotated');
$compareContent.toggleClass('revealed');
// Close the special offer tabs if any are open
$openTabs
.removeClass('open')
.find('.special-offer-body')
.slideUp();
var $isSticky = $('#resultspage_form').hasClass('js-is-sticky');
if ($isSticky) {
stickybits('#resultspage_form').cleanup();
return;
}
stickybits('#resultspage_form', {useStickyClasses: true});
}
});
// Hide shortlist bar if clicking outside it, but only if it is already open, and if you are NOT clicking on the modal eg enquiry modal
$(document).on('click', function (e) {
var isModal = $(e.target).parents('.modal').length || $(e.target).hasClass('modal');
if ($compareBar.has(e.target).length === 0 && $compareContent.hasClass('revealed') && !isModal ) {
$compareContent.slideUp();
$body.removeClass('shortlist-open');
$compareContent.removeClass('revealed');
}
});
// Add custom class to body when mobile special offer tab is open
var $specialOfferMobileTab = $('#hc_modal_mobile_special_offer_tab');
$specialOfferMobileTab.on('show.bs.modal', function () {
$body.addClass('mobile-special-offer-open');
});
$specialOfferMobileTab.on('hidden.bs.modal', function () {
$body.removeClass('mobile-special-offer-open');
});
|
import ConnectionService from "./ConnectionService";
import { has } from "lodash";
const ERROR_CODE_LIST = [400, 401, 403, 404, 500];
class StandardService extends ConnectionService {
constructor() {
super("standard");
}
/**
* Function to format reponse data.
* @type function
* @param {object} response is a response data
* @returns {object} response data:
* {
* status: boolean,
* message: string,
* data: *
* }
* @default ""
* {
* status: false,
* message: ""
* }
* @override
*/
fetchResponse = (response = {}) => {
const result = {
status: false,
message: ""
};
if (
(response.statusCode !== undefined &&
ERROR_CODE_LIST.includes(response.statusCode)) ||
(response.status !== undefined &&
ERROR_CODE_LIST.includes(response.status)) ||
(response.error !== undefined && response.error !== "")
) {
switch (true) {
case has(response, "message"):
result.message = response.message;
break;
case has(response, "error_description"):
result.message = response.error_description;
break;
default:
result.message = response;
}
} else {
result.status = true;
result.data = has(response, "data") ? response.data : response;
}
return result;
};
}
export default StandardService;
|
// On gère l'intensité
let array;
let values;
let length;
let average;
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[0].image + '"/>';
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(function(stream) {
audioContext = new AudioContext();
analyser = audioContext.createAnalyser();
microphone = audioContext.createMediaStreamSource(stream);
javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
analyser.smoothingTimeConstant = 0.8;
analyser.fftSize = 1024;
microphone.connect(analyser);
analyser.connect(javascriptNode);
javascriptNode.connect(audioContext.destination);
javascriptNode.onaudioprocess = function() {
array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
values = 0;
length = array.length;
for (let i = 0; i < length; i++) {
values += (array[i]);
}
average = values / length;
const clos = 1;
const mini = 4;
const maxi = 40;
function neutre() {
if (average < mini) {
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[0].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[1].image + '"/>';
} else if (average > mini + clos && average < mini * 2) {
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[2].image + '"/>';
} else if (average > mini * 2 && average < maxi - (mini * 2)) {
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[3].image + '"/>';
} else if (average > maxi - (mini * 2) && average < maxi - mini) {
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[4].image + '"/>';
} else {
document.getElementById("Emmy0").innerHTML = '<img class="chara" src="' + frame[5].image + '"/>';
}
}
function heureuse() {
if (average < mini) {
document.getElementById("Emmy1").innerHTML = '<img class="chara" src="' + frame[6].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy1").innerHTML = '<img class="chara" src="' + frame[7].image + '"/>';
} else if (average > mini + clos && average < mini * 2) {
document.getElementById("Emmy1").innerHTML = '<img class="chara" src="' + frame[8].image + '"/>';
} else if (average > mini * 2 && average < maxi - (mini * 2)) {
document.getElementById("Emmy1").innerHTML = '<img class="chara" src="' + frame[9].image + '"/>';
} else if (average > maxi - (mini * 2) && average < maxi - mini) {
document.getElementById("Emmy1").innerHTML = '<img class="chara" src="' + frame[10].image + '"/>';
} else {
document.getElementById("Emmy1").innerHTML = '<img class="chara" src="' + frame[11].image + '"/>';
}
}
function doigt() {
if (average < mini) {
document.getElementById("Emmy2").innerHTML = '<img class="chara" src="' + frame[12].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy2").innerHTML = '<img class="chara" src="' + frame[13].image + '"/>';
} else if (average > mini + clos && average < maxi - mini) {
document.getElementById("Emmy2").innerHTML = '<img class="chara" src="' + frame[14].image + '"/>';
} else {
document.getElementById("Emmy2").innerHTML = '<img class="chara" src="' + frame[15].image + '"/>';
}
}
function pense() {
if (average < mini) {
document.getElementById("Emmy3").innerHTML = '<img class="chara" src="' + frame[16].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy3").innerHTML = '<img class="chara" src="' + frame[17].image + '"/>';
} else if (average > mini + clos && average < maxi - mini) {
document.getElementById("Emmy3").innerHTML = '<img class="chara" src="' + frame[18].image + '"/>';
} else {
document.getElementById("Emmy3").innerHTML = '<img class="chara" src="' + frame[19].image + '"/>';
}
}
function note() {
if (average < mini) {
document.getElementById("Emmy4").innerHTML = '<img class="chara" src="' + frame[20].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy4").innerHTML = '<img class="chara" src="' + frame[21].image + '"/>';
} else if (average > mini + clos && average < mini + (clos * 2)) {
document.getElementById("Emmy4").innerHTML = '<img class="chara" src="' + frame[22].image + '"/>';
} else if (average > mini + (clos * 2) && average < maxi - mini) {
document.getElementById("Emmy4").innerHTML = '<img class="chara" src="' + frame[23].image + '"/>';
} else if (average > maxi - mini && average < maxi - clos) {
document.getElementById("Emmy4").innerHTML = '<img class="chara" src="' + frame[24].image + '"/>';
} else {
document.getElementById("Emmy4").innerHTML = '<img class="chara" src="' + frame[25].image + '"/>';
}
}
function taille() {
if (average < mini) {
document.getElementById("Emmy5").innerHTML = '<img class="chara" src="' + frame[26].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy5").innerHTML = '<img class="chara" src="' + frame[27].image + '"/>';
} else if (average > mini - clos && average < mini * 2) {
document.getElementById("Emmy5").innerHTML = '<img class="chara" src="' + frame[28].image + '"/>';
} else if (average > mini * 2 && average < maxi - mini) {
document.getElementById("Emmy5").innerHTML = '<img class="chara" src="' + frame[29].image + '"/>';
} else {
document.getElementById("Emmy5").innerHTML = '<img class="chara" src="' + frame[30].image + '"/>';
}
}
function gratte() {
if (average < mini) {
document.getElementById("Emmy6").innerHTML = '<img class="chara" src="' + frame[31].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy6").innerHTML = '<img class="chara" src="' + frame[32].image + '"/>';
} else if (average > mini + clos && average < mini + (clos * 2)) {
document.getElementById("Emmy6").innerHTML = '<img class="chara" src="' + frame[33].image + '"/>';
} else {
document.getElementById("Emmy6").innerHTML = '<img class="chara" src="' + frame[34].image + '"/>';
}
}
function photo() {
if (average < mini) {
document.getElementById("Emmy7").innerHTML = '<img class="chara" src="' + frame[35].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy7").innerHTML = '<img class="chara" src="' + frame[36].image + '"/>';
} else {
document.getElementById("Emmy7").innerHTML = '<img class="chara" src="' + frame[37].image + '"/>';
}
}
function croise() {
if (average < mini) {
document.getElementById("Emmy8").innerHTML = '<img class="chara" src="' + frame[38].image + '"/>';
} else if (average > mini && average < mini + clos) {
document.getElementById("Emmy8").innerHTML = '<img class="chara" src="' + frame[39].image + '"/>';
} else if (average > mini + clos && average < mini * 2) {
document.getElementById("Emmy8").innerHTML = '<img class="chara" src="' + frame[40].image + '"/>';
} else {
document.getElementById("Emmy8").innerHTML = '<img class="chara" src="' + frame[41].image + '"/>';
}
}
neutre();
heureuse();
doigt();
pense();
note();
taille();
gratte();
photo();
croise();
}
}) |
import io from 'socket.io-client';
const socket = io();
const actions = {
reqUserLocation() {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
},
listenSocketEvents({ commit }) {
socket.on('error', () => commit('catchErrors'));
socket.on('resRandomGif', ({ data }) => commit('storeGifData', data));
socket.on('resWeatherForecast', ({ data }) => commit('storeWeatherForecast', data));
},
emitSocketEvents(context, { latitude, longitude }) {
socket.emit('reqRandomGif', {});
socket.emit('reqWeatherForecast', {
lat: latitude,
lng: longitude,
});
},
restoreUserOptions({ commit }) {
const onStorage = localStorage.getItem('celsius');
if (!onStorage) commit('saveUserOptionsInLocalStorage');
commit('restoreUserCelsiusOption', onStorage);
},
async init({ commit, dispatch }) {
const { coords } = await dispatch('reqUserLocation');
commit('storeUserPosition', coords);
dispatch('restoreUserOptions');
dispatch('listenSocketEvents');
dispatch('emitSocketEvents', coords);
},
};
export default actions;
|
export default ( el, callback ) => {
const touchSurface = el;
let swipedir;
let startX;
let startY;
let distX;
let distY;
const //required min distance traveled to be considered swipe
threshold = 150;
const // maximum distance allowed at the same time in perpendicular direction
restraint = 100;
const // maximum time allowed to travel that distance
allowedTime = 300;
let elapsedTime;
let startTime;
const handleSwipe = callback || ( swipedir => {} );
touchSurface.addEventListener(
'touchstart',
e => {
const touchobj = e.changedTouches[ 0 ];
swipedir = 'none';
dist = 0;
startX = touchobj.pageX;
startY = touchobj.pageY;
startTime = new Date().getTime(); // record time when finger first makes contact with surface
e.preventDefault();
},
false,
);
touchSurface.addEventListener(
'touchmove',
e => {
e.preventDefault(); // prevent scrolling when inside DIV
},
false,
);
touchSurface.addEventListener(
'touchend',
e => {
const touchobj = e.changedTouches[ 0 ];
distX = touchobj.pageX - startX; // get horizontal dist traveled by finger while in contact with surface
distY = touchobj.pageY - startY; // get vertical dist traveled by finger while in contact with surface
elapsedTime = new Date().getTime() - startTime; // get time elapsed
if ( elapsedTime <= allowedTime ) {
// first condition for awipe met
if (
Math.abs( distX ) >= threshold &&
Math.abs( distY ) <= restraint
) {
// 2nd condition for horizontal swipe met
swipedir = distX < 0 ? 'left' : 'right'; // if dist traveled is negative, it indicates left swipe
} else if (
Math.abs( distY ) >= threshold &&
Math.abs( distX ) <= restraint
) {
// 2nd condition for vertical swipe met
swipedir = distY < 0 ? 'up' : 'down'; // if dist traveled is negative, it indicates up swipe
}
}
handleSwipe( swipedir );
e.preventDefault();
},
false,
);
};
|
import React, {Component} from "react";
import "./style.css";
import { Form, FormGroup, Label, Input, Button } from "reactstrap";
import API from '../../utils/API';
import {Link} from "react-router-dom";
class NewAccountForm extends Component {
state = {
userName: "",
userEmail: "",
userPassword: "",
streetAddress: "",
city: "",
state: "",
zipCode: ""
};
handleChange = input => e => {
this.setState({ [input]: e.target.value });
};
// handleSubmit = e => {
// e.preventDefault();
// if (this.state.userName && this.state.userEmail && this.state.userPassword) {
// API.saveUser({
// userName: this.userName,
// userEmail: this.phoneNumber,
// userPassword: this.userPassword,
// streetAddress: this.streetAddress,
// city: this.city,
// state: this.state,
// zipCode: this.zipCode
// })
// .catch(err => console.log);
// }
// };
render(){
return(
<div>
<Form>
<FormGroup>
<Label for="userName">Name</Label>
<Input type="text" name="userName" id="userName"></Input>
</FormGroup>
<FormGroup>
<Label for="userEmail">Email</Label>
<Input type="email" name="userEmail" id="userEmail"></Input>
</FormGroup>
<FormGroup>
<Label for="userPassword">Password</Label>
<Input type="password" name="userPassword" id="userPassword"></Input>
</FormGroup>
<FormGroup>
<Label for="userPasswordVerify">Verify Password</Label>
<Input type="password" name="userPasswordVerify" id="userPasswordVerify"></Input>
</FormGroup>
{/* <FormGroup>
<Label for="streetAddress">Address</Label>
<Input type="text" name="streetAddress" id="streetAddress"></Input>
</FormGroup>
<FormGroup>
<Label for="city">City</Label>
<Input type="text" name="city" id="city"></Input>
</FormGroup>
<FormGroup>
<Label for="state">State</Label>
<Input type="select" name="state" id="state">
<option>1</option>
<option>2</option>
</Input>
</FormGroup>
<FormGroup>
<Label for="zipCode">Zip Code</Label>
<Input type="number" name="zipCode" id="zipCode"></Input>
</FormGroup> */}
<Link to="/Home" ><Button className="formBtn" style={{marginLeft: "53%", marginBottom: "30px"}} onClick={this.handleSubmit}>Submit</Button></Link>
</Form>
</div>
)
}
}
export default NewAccountForm; |
import React from "react";
import { StyleSheet, TouchableOpacity, View } from "react-native";
import { Entypo } from "@expo/vector-icons";
import { FontAwesome } from "@expo/vector-icons";
import { PRIMARY_COLOR } from "../../constants";
const MySendButton = (props) => {
return (
<TouchableOpacity onPress={props.onPress} style={css.border}>
<FontAwesome name={props.iconName} size={18} color="white" />
</TouchableOpacity>
);
};
export default MySendButton;
const css = StyleSheet.create({
border: {
height: 30,
width: 30,
backgroundColor: PRIMARY_COLOR,
borderRadius: 5,
justifyContent: "center",
alignItems: "center",
},
});
|
function verifica() {
const num1 = parseInt(document.getElementById("numero1").value);
const num2 = parseInt(document.getElementById("numero2").value);
if (num1 == num2) {
alert(num1 + ' é igual a ' + num2);
} else if (num1 > num2) {
alert('Número ' + num1 + ' é maior que ' + num2);
} else {
alert('Número ' + num2 + ' é maior que ' + num1);
}
} |
class Player {
constructor(props) {
this.props = props;
this.timeID = null; this.canPlay = false; this.state = "stop"; this.repeat = 0;
this.LRCs = []; this.paragraph = 0; this.lrc = 0; this.block = props.block;
this.currentRange = null; this.isLoop = false;
let self = this;
self.audio = new Audio();
this.audio.autoplay = false;
self.audio.addEventListener("loadstart", function() {
self.onStateChange("loadStart");
}, true);
self.audio.addEventListener("canplay", function() {
// console.log("canplay: " + self.canPlay + "; " + (new Date()))
if(self.canPlay == false) {
self.audio.autoplay = false;
self.onStateChange("canPlay");
self.canPlay = true;
if(self._setting.autoPlay == true) {
setTimeout(()=> {
if(self.audio.src.length > 0 && self.canPlay == true)
self.play()
}, 1000);
}
}
self.audio.removeEventListener("canplay", null)
}, true);
self.audio.addEventListener("durationchange", function() {
if(self.canPlay == false)
self.onStateChange("durationChange", self.audio.duration);
self.audio.removeEventListener("durationchange", null)
}, true);
self.audio.addEventListener("timeupdate", function() {
// console.log("timeupdate: " + self.audio.currentTime)
}, true);
self.audio.addEventListener("ended", function() {
self.onStateChange("sectionChange", -1);
self.state = "pendding";
self.currentRange = null;
self.audio.pause();
self.intervalID = setTimeout(()=>{
if(self.state == "pendding") {
self.beep.play();
self.intervalID = setTimeout(()=>{
self.assignParagraph(0);
}, 5000);
}
}, 1000);
}, true);
this.beep = new Audio("./mp3/beep.mp3");
this.beep.autoplay = false;
this.beep.addEventListener("loadstart", function() {
}, true);
this.beep.addEventListener("canplay", function() {
}, true);
this.beep.volume = 0.7;
}
play(inform){
this.repeat = 0;
if(this.canPlay == false) return;
try {
this.audio.playbackRate = this._setting.rate;
this.audio.play();
this.state = "play";
if(typeof inform == "undefined")
this.onStateChange("play");
this.timing();
} catch (e) {
console.log(e)
}
}
checkLoop() {
this.isLoop = this._setting.range == "paragraph" &&
this.block.length == 2 && this.block[0] == this.block[1] ? true : false;
}
timing(){
clearTimeout(this.timeID);
let self = this;
this.timeID = setInterval(() => {
this.onStateChange("timeUpdate", this.audio.currentTime);
let time = this.audio.currentTime;
let range = this.currentRange;
if(range == null){
if(this.block.length > 0)
this.paragraph = this.block[0];
else
this.paragraph = 0;
let arr = this.LRCs[this.paragraph];
this.currentRange = Object.assign({}, arr[0]);
if(this._setting.range == "paragraph")
this.currentRange.end = arr[arr.length - 1].end;
this.audio.currentTime = this.currentRange.start;
this.lrc = 0;
this.onStateChange("sectionChange", this.paragraph, 0);
} else if(time < range.start || time >= range.end){ // 時間到
if(this._setting.repeat > 0 && time >= range.end) {
let start = this.block.length > 0 ? this.block[0] : 0;
let end = this.block.length > 0 ? this.block[1] : this.LRCs.length - 1;
clearInterval(this.timeID);
this.timeID = null;
this.audio.pause();
// console.log(this.paragraph + "-" + this.lrc + ": " + this.repeat + "/" + this._setting.repeat + ": " + (new Date()).toString("MM:ss.ms"))
// console.log(this._setting.interval)
let _block = this.paragraph, _lrc = this.lrc, beep = 0;
if(this.isLoop == true || this.repeat < this._setting.repeat - 1) {
this.audio.currentTime = range.start;
this.repeat++;
this.onStateChange("repeat", this.repeat);
} else if(this._setting.interrupt == true) {
this.repeat = 0;
this.onStateChange("interrupt");
this.state = "pendding";
this.intervalID = setTimeout(()=>{
if(this.state == "pendding") {
this.beep.play();
}
}, 1000);
this.onStateChange("repeat", this.repeat);
return;
} else if(this._setting.range == "paragraph") {
if(this.isLoop == false) this.repeat = 0;
_lrc = 0;
_block++;
if(_block >= end + 1){
_block = start;
beep = 1;
} else if(this._setting.repeat > 2)
beep = 1;
} else {
this.repeat = 0;
if(_lrc == this.LRCs[_block].length - 1) {
_lrc = 0;
_block++;
if(_block >= end + 1){
_block = start;
beep = 1;
}
} else {
_lrc++;
}
}
if(this.isLoop == true) {
waitToNext();
} else if(beep > 0 || (this.repeat == 0 && this._setting.repeat >= 5)) {
this.intervalID = setTimeout(()=>{
if(this.state == "pendding") {
this.beep.play();
waitToNext();
}
}, 1000);
} else
waitToNext();
function waitToNext() {
let timeout = 1000 * (self._setting.interval > 0
? self._setting.interval
: (range.end - range.start) * Math.abs(self._setting.interval)
);
// console.log("interval: " + (timeout / 1000) + " second")
self.intervalID = setTimeout(()=>{
if(self.state == "pendding") {
self.lrc = _lrc;
self.paragraph = _block;
if(self.repeat == 0) {
self.onStateChange("sectionChange", self.paragraph, self.lrc);
if(self._setting.range == "paragraph"){
let arr = self.LRCs[self.paragraph];
self.currentRange = Object.assign({}, arr[0]);
self.currentRange.end = arr[arr.length - 1].end;
} else {
self.currentRange = self.LRCs[self.paragraph][self.lrc];
}
self.audio.currentTime = self.currentRange.start;
}
self.audio.play();
self.timing();
self.state = "play";
delete self.intervalID;
}
}, timeout);
}
this.state = "pendding";
} else if(time >= range.end && this.paragraph == this.LRCs.length - 1 && this.lrc == this.LRCs[this.paragraph].length - 1) {
clearTimeout(this.timeID);
this.onStateChange("sectionChange", -1);
this.state = "pendding";
this.currentRange = null;
// this.paragraph = this.block.length > 0 ? this.block[0] : 0;
// this.lrc = 0;
this.audio.pause();
this.intervalID = setTimeout(()=>{
if(this.state == "pendding") {
this.beep.play();
this.intervalID = setTimeout(()=>{
// this.intervalID = setTimeout(() => {
this.assignParagraph(this.block.length > 0 ? this.block[0] : 0);
// if(this.state == "pendding") {
// this.play(false);
// }
// }, 1000 * 5);
}, 5000);
}
}, 1000);
return;
} else {
for(let i = 0; i < this.LRCs.length; i++) {
let row = this.LRCs[i];
for(let j = 0; j < row.length; j++) {
if(time >= row[j].start && time <= row[j].end) {
this.currentRange = row[j];
this.paragraph = i;
this.lrc = j;
this.onStateChange("sectionChange", i, j);
return;
}
}
}
}
} else if(this._setting.range == "paragraph") { // 段落模式的字幕
for(let i = 0; i < this.LRCs.length; i++) {
let row = this.LRCs[i];
for(let j = 0; j < row.length; j++) {
if(time >= row[j].start && time <= row[j].end) {
if(j != this.lrc) {
this.paragraph = i;
this.lrc = j;
this.onStateChange("sectionChange", i, j, this.repeat + 1);
}
return;
}
}
}
}
}, 100);
}
stop(beep){
this.audio.pause();
if(this.LRCs.length > 0 && this.LRCs[0].length > 0)
this.audio.currentTime = this.LRCs[0][0].start;
else
this.audio.currentTime = 0;
this.paragraph = 0;
this.lrc = 0;
this.currentRange = null;
this.state = "stop";
this.onStateChange("stop");
this.repeat = 0;
clearInterval(this.timeID);
if(typeof beep =="boolean" && beep == true) {
setTimeout(()=>{
this.beep.play();
}, 1000);
}
}
pause(){
this.audio.pause();
this.state = "pause";
this.onStateChange("pause");
clearInterval(this.timeID);
this.timeID = null;
}
continue(){
console.log("continue");
if(this.intervalID) clearTimeout(this.intervalID);
clearTimeout(this.timeID);
this.audio.currentTime = this.currentRange.start;
this.state = "play";
this.onStateChange("play");
this.audio.play();
this.timing();
}
assignParagraph(value, play) {
this.repeat = 0;
let start = this._setting.repeat > 0 && this.block.length > 0 ? this.block[0] : 0;
let end = this._setting.repeat > 0 && this.block.length > 0 ? this.block[1] : this.LRCs.length - 1;
if(value >= start && value <= end) {
this.restart(value, 0, true);
}
}
gotoParagraph(value){
this.repeat = 0;
let start = this._setting.repeat > 0 && this.block.length > 0 ? this.block[0] : 0;
let end = this._setting.repeat > 0 && this.block.length > 0 ? this.block[1] : this.LRCs.length - 1;
// console.log("value: " + value + ", " + start + " = " + end)
let block = 0;
if(value == "first") {
block = start;
} else if(value == "end") {
block = end;
} else if(!isNaN(value)) {
if(value + this.paragraph < 0)
return;
else if(value + this.paragraph >= end + 1)
block = start;
else {
block = value + this.paragraph;
}
if(block < start)
return;
else if(block > end)
block = start;
}
this.checkLoop();
this.restart(block, 0, true);
}
gotoLRC(value) {
let start = this._setting.repeat > 0 && this.block.length > 0 ? this.block[0] : 0;
let end = this._setting.repeat > 0 && this.block.length > 0 ? this.block[1] : this.LRCs.length - 1;
this.repeat = 0;
let rows = this.LRCs[this.paragraph];
let block = this.paragraph;
let lrc = 0;
if(value == "first") {
lrc = 0;
} else if(value == "end") {
lrc = rows.length - 1;
} else {
lrc = value + this.lrc;
if(lrc < 0) {
block--;
if(block > start - 1) {
rows = this.LRCs[block];
lrc = rows.length - 1;
} else {
return;
}
} else if(lrc >= rows.length) {
block++;
if(block >= end + 1) {
block = start;
}
// rows = this.LRCs[block];
lrc = 0;
}
}
this.restart(block, lrc);
}
restart(paragraph, lrc, first) {
if(paragraph == null)
paragraph = this.paragraph;
else {
let start = this.block.length > 0 ? this.block[0] : 0;
let end = this.block.length > 0 ? this.block[1] : this.LRCs.length - 1;
if(paragraph >= start && paragraph <= end)
this.paragraph = paragraph;
else
return;
}
// console.log("paragraph: " + paragraph + ", lrc: " + lrc + "/" + this.LRCs[paragraph].length)
if(this.LRCs[paragraph].length <= lrc) return;
this.lrc = lrc;
// this.currentRange = this.LRCs[paragraph][lrc];
if(this._setting.range == "paragraph"){ //
if(first == true) {
let arr = this.LRCs[paragraph];
this.currentRange = Object.assign({}, arr[0]);
this.currentRange.end = arr[arr.length - 1].end;
this.audio.currentTime = this.currentRange.start;
} else {
let start = this.LRCs[paragraph][lrc].start;
this.audio.currentTime = start;
}
} else {
this.currentRange = this.LRCs[paragraph][lrc];
this.audio.currentTime = this.currentRange.start;
}
if(this.intervalID) clearTimeout(this.intervalID);
if(this.state == "pendding" || (this.state == "stop" && this.block.length == 2 && this.block[0] == this.block[1])) {
clearTimeout(this.timeID);
this.state = "play";
this.audio.play();
this.timing();
delete this.intervalID;
this.onStateChange("play");
}
this.onStateChange("sectionChange", this.paragraph, this.lrc);
}
get duration() {
return this.audio.duration;
}
get currentTime() {
return this.audio.currentTime;
}
set currentTime(value) {
this.audio.currentTime = value;
}
set src(value) {
this.audio.src = value;
console.log("src: " + this.audio.src)
}
get src() {
return this.audio.src;
}
set setting(value) {
if(this.audio.playbackRate != value.rate) {
this.audio.playbackRate = value.rate;
}
if(this._setting != null && this._setting.repeat != value.repeat) {
this.repeat = 0;
}
this._setting = value;
}
get setting() {
return this._setting;
}
} |
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import ProfilePic from "components/Picture/ProfilePic";
import { WhiteSpace } from "antd-mobile";
import { getInitials } from "utils/userInfo";
import fakePosts from "assets/data/fakePosts"; // feed
import Posts from "components/Feed/Posts"; // feed
import FeedWrapper from "components/Feed/FeedWrapper"; //feed
import CreatePost from "components/CreatePost/CreatePost";
// ICONS
import SvgIcon from "components/Icon/SvgIcon";
import createPost from "assets/icons/create-post.svg"; // feed
import menu from "assets/icons/menu.svg";
import edit from "assets/icons/edit.svg";
import editEmpty from "assets/icons/edit-empty.svg";
import linkedinBlue from "assets/icons/social-linkedin-blue.svg";
import twitterBlue from "assets/icons/social-twitter-blue.svg";
import locationIcon from "assets/icons/location.svg";
import {
ProfileLayout,
BackgroundHeader,
MenuIcon,
UserInfoContainer,
EditIcon,
UserInfoDesktop,
NameDiv,
PlaceholderIcon,
EditEmptyIcon,
DescriptionDesktop,
LocationDesktopDiv,
LocationMobileDiv,
IconsContainer,
HelpContainer,
HelpImage,
LocationIcon,
LinkedinBlueIcon,
TwitterBlueIcon,
DescriptionMobile,
SectionHeader,
CreatePostDiv,
CreatePostIcon,
DrawerHeader,
CustomDrawer,
} from "../components/Profile/ProfileComponents";
const offerHelpInactive = require("assets/help-gesture-unselected.svg");
const needHelpInactive = require("assets/thermometer-unselected.svg");
const Profile = (props) => {
const { firstName, lastName, about, address, country } = props.user;
const needHelp = true;
const [modal, setModal] = useState(false);
const [drawer, setDrawer] = useState(false);
//requires responsive implementation
const renderMyActivities = () => {
return (
<>
<FeedWrapper>
<Posts filteredPosts={fakePosts} />
<SvgIcon
src={createPost}
className="create-post"
onClick={() => setModal(!modal)}
/>
<CreatePost onCancel={() => setModal(false)} visible={modal} />
</FeedWrapper>
</>
);
};
return (
<ProfileLayout>
<BackgroundHeader>
<MenuIcon src={menu} />
</BackgroundHeader>
<UserInfoContainer>
<EditIcon src={edit} onClick={() => setDrawer(true)} />
<ProfilePic noPic={true} initials={getInitials(firstName, lastName)} />
<UserInfoDesktop>
<NameDiv>
{firstName} {lastName}
<PlaceholderIcon />
<EditEmptyIcon src={editEmpty} onClick={() => setDrawer(true)} />
</NameDiv>
<DescriptionDesktop> {about} </DescriptionDesktop>
<LocationMobileDiv>
{address}, {country}
</LocationMobileDiv>
<IconsContainer>
<HelpContainer>
<HelpImage
src={needHelp ? needHelpInactive : offerHelpInactive}
alt="help-type-icon"
/>
{needHelp ? "I need help" : "I want to help"}
</HelpContainer>
<LocationDesktopDiv>
<LocationIcon src={locationIcon} />
{needHelp ? "I need help" : "I want to help"} • {address},{" "}
{country}
</LocationDesktopDiv>
<PlaceholderIcon />
<LinkedinBlueIcon src={linkedinBlue} />
<TwitterBlueIcon src={twitterBlue} />
</IconsContainer>
</UserInfoDesktop>
</UserInfoContainer>
<WhiteSpace />
<div style={{ margin: "0 2.5rem" }}>
<WhiteSpace />
<DescriptionMobile>
<SectionHeader> About</SectionHeader>
{about}
</DescriptionMobile>
<WhiteSpace />
<SectionHeader>
My Activity
<PlaceholderIcon />
<CreatePostDiv>Create post</CreatePostDiv>
<CreatePostIcon src={createPost} onClick={() => setModal(!modal)} />
</SectionHeader>
{renderMyActivities()}
</div>
<CustomDrawer
placement="bottom"
closable={false}
onClose={() => setDrawer(false)}
visible={drawer}
height="150px"
key="bottom"
>
<DrawerHeader>
<Link to="/edit-profile">Edit Account Information</Link>
</DrawerHeader>
<DrawerHeader>
<Link to="/edit-profile">Edit Profile </Link>
</DrawerHeader>
</CustomDrawer>
<WhiteSpace />
</ProfileLayout>
);
};
const mapStateToProps = (state) => {
return {
user: state.user,
};
};
export default connect(mapStateToProps)(Profile);
|
requirejs.config({
baseUrl: "js"
});
requirejs([], function() {
console.log("Success!");
}); |
import mongoose from "mongoose";
const MessageSchema = new mongoose.Schema({
senderName: {
type: String,
trim: true,
required: [true, 'please type your name']
},
email: {
type: String,
trim: true,
required: [true, 'please type your Email']
},
messageBody: {
type: String,
trim: true,
required: [true, 'please type your message']
},
date: {
type: String
}
});
export default mongoose.model('Message', MessageSchema);
|
function javaprg() {
var questions2 = [{
question: " A special method that is used to initialize a class object ?",
choices: ["abstract method","static method","Constructor","overloaded method"],
correctAnswer: 2
}, {
question: "super keyword in Java is used for?",
choices: ["to refer to immediate child class of a class.","to refer to immediate parent class of a class.","to refer to current class object.","to refer to static member of parent class."],
correctAnswer: 1
}, {
question: "Which of the given statement is not true about a Java Package?",
choices: ["A package can be defined as a group of similar types of classes and interface.","Package are used in order to avoid name conflicts and to control access of classes and interface.","A package cannot not have another package inside it.","Java uses file system directory to store package"],
correctAnswer: 2
}, {
question: "What is an immutable object?",
choices: ["an object whose state can be changed after it is created.","an object whose state cannot be changed after it is created.","an object which cannot be casted to another type.","an object which cannot be cloned."],
correctAnswer: 1
}, {
question: " In Java, by default every thread is given a _________ .",
choices: ["MIN_PRIORITY(0)","NORM_PRIORITY(5)","MAX_PRIORITY(10)","HIGH_PRIORITY(7)"],
correctAnswer: 1
}];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var javaquiz = $('#javaquiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#javanext').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(javaquiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#javaprev').on('click', function (e) {
e.preventDefault();
if(javaquiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#javastart').on('click', function (e) {
e.preventDefault();
if(javaquiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#javastart').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<h2>Question ' + (index + 1) + ':</h2>');
qElement.append(header);
var question = $('<p>').append(questions2[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions2[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions2[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
// Displays next requested element
function displayNext() {
javaquiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions2.length){
var nextQuestion = createQuestionElement(questionCounter);
javaquiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#javaprev').show();
} else if(questionCounter === 0){
$('#javaprev').hide();
$('#javanext').show();
}
}else {
var scoreElem = displayScore();
javaquiz.append(scoreElem).fadeIn();
$('#javanext').hide();
$('#javaprev').hide();
$('#javastart').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions2[i].correctAnswer) {
numCorrect++;
}
}
score.append('<br><br><br><br><p align="center">You got ' + numCorrect + ' questions out of ' +
questions2.length + ' right!!!'+"<br><br><br><br><br>");
return score;
}
} |
import DiagramToolbar from './ui.diagram.toolbar';
import DiagramCommandsManager from './diagram.commands_manager';
class DiagramViewToolbar extends DiagramToolbar {
_getCommands() {
return DiagramCommandsManager.getViewToolbarCommands(this.option('commands'), this.option('excludeCommands'));
}
}
export default DiagramViewToolbar; |
import React, { useState } from "react"
import { render } from "react-dom"
import moment from 'moment'
import 'moment/locale/es'
import fotoAvatar from './1.jpg'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/free-solid-svg-icons'
import { Card } from "./src/Card";
import { RandomCat } from "./src/RandomCat";
import { List } from "./src/ejercico1";
import { Half } from "./src/HalfPage";
import { OnionHater } from "./src/odioLaCebolla";
import { PeliInfo } from "./src/pelis";
import CityList from "./src/CityList";
import Ciudades from "./src/ciudades";
import Text from "./src/removeVowels";
import FormText from "./src/formRemoveV";
import { Filtros } from "./src/Directorio";
moment.locale('es')
function App() {
const [text, setText] = useState("")
return <div style={{
width: '100vw',
height: '100vh',
display: "flex"
}}>
<Text>{text}</Text>
<FormText setText={(t) => {
setText(t)
}}></FormText>
</div>
}
render(<App></App>, document.querySelector(`#app`)) |
var sort_8h =
[
[ "SORT_CODE", "sort_8h.html#ad647507b0a28d76364ecafc56fcd2ea5", null ],
[ "sort_t", "sort_8h.html#ae599403f309e9dcfdbf62e63e628a2d8", null ],
[ "mutt_get_sort_func", "sort_8h.html#ae13c0d9d3ffd823955ec4d4653de376d", null ],
[ "mutt_sort_headers", "sort_8h.html#a1584f893fd698002518500ee3139b75d", null ],
[ "perform_auxsort", "sort_8h.html#a1d69cc6b2dfd825821b49d541edf5ca1", null ],
[ "mutt_get_name", "sort_8h.html#a9a230efa9217e987ca1d1adb14b7e235", null ],
[ "C_ReverseAlias", "sort_8h.html#a8d408d0bfffcfd6f6c5f7adea215cfcc", null ],
[ "C_Sort", "sort_8h.html#acfd072fdd89f9029c0bfd4b0a0c8be61", null ],
[ "C_SortAux", "sort_8h.html#aca4b52906acb38c6a150f9ef5a83887a", null ]
]; |
const express = require('express');
const musicOperations = require('../controllers/music');
const songOperations = require('../db/services/songoperations')
const routes = express.Router();
routes.get('/singer',musicOperations.getByArtist);
routes.get('/allsongs',musicOperations.getAllSongs);
routes.post('/addsong',musicOperations.addASong);
routes.post('/removesong', songOperations.removeSong);
module.exports = routes;
|
/* global it */
import supertest from 'supertest'
import chai from 'chai'
import container from '../app/Container';
import { describe } from "mocha";
import { auth, general } from "../app/presentation/core/error/MessageProperties";
const server = container.resolve('server');
const { expect } = chai;
const request = supertest.agent(server.express);
describe('#Auth Service', () => {
let data;
let action;
it('login fail no body', (done) => {
request.post('/api/auth')
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(general.invalidData.httpCode);
expect(res.body.resCode).to.eql(general.invalidData.resCode);
done();
}
});
});
it('login fail empty body', (done) => {
request.post('/api/auth')
.send({})
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(general.invalidData.httpCode);
expect(res.body.resCode).to.eql(general.invalidData.resCode);
done();
}
});
});
it('login fail no username', (done) => {
request.post('/api/auth')
.send({ pwd: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(general.invalidData.httpCode);
expect(res.body.resCode).to.eql(general.invalidData.resCode);
done();
}
});
});
it('login fail no pwd', (done) => {
request.post('/api/auth')
.send({ username: 'test' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(general.invalidData.httpCode);
expect(res.body.resCode).to.eql(general.invalidData.resCode);
done();
}
});
});
it('login fail username', (done) => {
request.post('/api/auth')
.send({ username: 'test', pwd: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.invalidData.httpCode);
expect(res.body.resCode).to.eql(auth.invalidData.resCode);
done();
}
});
});
it('login fail password 1', (done) => {
request.post('/api/auth')
.send({ username: 'wowit', pwd: '5f4dcc3b5aa765d61d8327deb882cf9' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.invalidData.httpCode);
expect(res.body.resCode).to.eql(auth.invalidData.resCode);
done();
}
});
});
it('login fail password 2', (done) => {
request.post('/api/auth')
.send({ username: 'wowit', pwd: '5f4dcc3b5aa765d61d8327deb882cf9' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.invalidData.httpCode);
expect(res.body.resCode).to.eql(auth.invalidData.resCode);
done();
}
});
});
it('login success', (done) => {
request.post('/api/auth')
.send({ username: 'wowit', pwd: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(200);
data = res.body;
done();
}
});
});
it('verify-password fail header', (done) => {
request.post('/api/auth/verify-password')
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.missingAuthorization.httpCode);
expect(res.body.resCode).to.eql(auth.missingAuthorization.resCode);
done();
}
});
});
it('verify-password fail invalid header', (done) => {
request.post('/api/auth/verify-password')
.set('Authorization', 'Bearer 123')
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.unAuthorized.httpCode);
expect(res.body.resCode).to.eql(auth.unAuthorized.resCode);
done();
}
});
});
it('verify-password fail no password', (done) => {
request.post('/api/auth/verify-password')
.set('Authorization', 'Bearer ' + data.accessToken)
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(general.invalidData.httpCode);
expect(res.body.resCode).to.eql(general.invalidData.resCode);
done();
}
});
})
it('verify-password invalid password', (done) => {
request.post('/api/auth/verify-password')
.set('Authorization', 'Bearer ' + data.accessToken)
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf9' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.invalidData.httpCode);
expect(res.body.resCode).to.eql(auth.invalidData.resCode);
done();
}
});
});
it('verify-password', (done) => {
request.post('/api/auth/verify-password')
.set('Authorization', 'Bearer ' + data.accessToken)
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(200);
action = res.body
done();
}
});
});
it('set-password fail header', (done) => {
request.post('/api/auth/set-password')
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.missingAuthorization.httpCode);
expect(res.body.resCode).to.eql(auth.missingAuthorization.resCode);
done();
}
});
});
it('set-password fail invalid header', (done) => {
request.post('/api/auth/set-password')
.set('x-action-token', "1233")
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.unAuthorized.httpCode);
expect(res.body.resCode).to.eql(auth.unAuthorized.resCode);
done();
}
});
});
it('set-password fail no password', (done) => {
request.post('/api/auth/set-password')
.set('x-action-token', action.actionToken)
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(general.invalidData.httpCode);
expect(res.body.resCode).to.eql(general.invalidData.resCode);
done();
}
});
});
it('set-password', (done) => {
request.post('/api/auth/set-password')
.set('x-action-token', action.actionToken)
.send({ password: '5f4dcc3b5aa765d61d8327deb882cf99' })
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(201);
done();
}
});
});
it('logout jwt fail header', (done) => {
request.get('/api/auth/logout')
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.missingAuthorization.httpCode);
expect(res.body.resCode).to.eql(auth.missingAuthorization.resCode);
done();
}
});
});
it('logout jwt fail invalid header', (done) => {
request.get('/api/auth/logout')
.set('Authorization', 'Bearer 1234')
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(auth.unAuthorized.httpCode);
expect(res.body.resCode).to.eql(auth.unAuthorized.resCode);
done();
}
});
});
it('logout jwt success', (done) => {
request.get('/api/auth/logout')
.set('Authorization', 'Bearer ' + data.accessToken)
.end((err, res) => {
if (err) done(err);
else {
expect(res.statusCode).to.eql(200);
done();
}
});
});
});
|
(function () {
angular
.module('loc8rApp')
.controller('homeCtrl', homeCtrl);
homeCtrl.$inject = ['$scope', 'NgTableParams', 'snpediaData'];
function homeCtrl($scope, NgTableParams, snpediaData) {
// Nasty IE9 redirect hack (not recommended)
if (window.location.pathname !== '/') {
window.location.href = '/#' + window.location.pathname;
}
var vm = this;
vm.pageHeader = {
title: 'Applied Biometry',
strapline: ''
};
var self = this;
//Snpedia
vm.wikiTextList = [];
this.getWikiTextList = function callServer(tableState) {
vm.isWikiTextLoading = true;
var pagination = tableState.pagination;
var start = pagination.start || 0; // This is NOT the page number, but the index of item in the list that you want to use to display the table.
var number = pagination.number || 10; // Number of entries showed per page.
snpediaData.getWikiText(start,number,tableState)
.success(function (data) {
tableState.pagination.numberOfPages = 100;//set the number of pages so the pagination can update
vm.wikiTextList = data;
vm.isWikiTextLoading = false;
})
.error(function (e) {
vm.message = "Sorry, something's gone wrong, please try again later";
});
};
self.wikiTagsParams = new NgTableParams({
}, {
counts: [],
getData: function (params) {
vm.wikiTagsList = [];
var offset = params.url().page;
var limit = params.url().count;
snpediaData.getWikiTags(offset, limit)
.success(function (data) {
params.total(data.length);
vm.wikiTagsList = data;
console.log(vm.wikiTagsList);
})
.error(function (e) {
vm.message = "Sorry, something's gone wrong, please try again later";
});
}
});
}
})(); |
import React from 'react'
import logo from '../images/logo.png'
export const QuizselectPage = () => {
return (
<div className="containerquiz">
<div className="row" style={{maxWidth:"50%"}}>
<div className="col s8 s4">
<div className="card">
<div className="card-image">
<img src={logo} alt="logo" />
</div>
<div className="card-content">
<p>Опрос 1</p>
</div>
<div className="card-action">
<a href="/quizselect/quiz">Пройти опрос</a>
</div>
</div>
</div>
</div>
<div className="row" style={{maxWidth: "50%"}}>
<div className="col s8 s4">
<div className="card">
<div className="card-image">
<img src={logo} alt="logo" />
</div>
<div className="card-content">
<p>Опрос 2
</p>
</div>
<div className="card-action">
<a href="/quizselect/quiz">Пройти опрос</a>
</div>
</div>
</div>
</div>
<div className="row" style={{maxWidth: "50%"}}>
<div className="col s8 s4">
<div className="card">
<div className="card-image">
<img src={logo} alt="logo" />
</div>
<div className="card-content">
<p>Опрос 3
</p>
</div>
<div className="card-action">
<a href="/quizselect/quiz">Пройти опрос</a>
</div>
</div>
</div>
</div>
</div>
)
} |
var apiKey,session, publisher;
Template.gameTemplate.rendered = function(){
console.log("gameTemplate rendered");
$("#facebookModal").modal('show');
}
Template.gameboardTemplate.rendered = function(){
tictactoeUI();
}
Template.gameWonModalTemplate.rendered = function(){
if($("#myModal").attr('data-show')=='true')
$("#myModal").modal();
$("#myModal").on('hidden',function(){
var gameId = Session.get('currentGame');
Games.remove(gameId, function(){
Session.set('currentGame', undefined);
window.location = window.location.origin;
});
});
}
Template.waitingForPlayerModalTemplate.rendered = function(){
if($("#waitingForPlayerModal").attr('data-show')=='true')
$("#waitingForPlayerModal").modal();
if($("#waitingForPlayerModal").attr('data-show')=='false'){
$('#waitingForPlayerModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
}
}
window.initOpenTok = function(otSessionId, otToken){
apiKey = 25925352
session = TB.initSession(otSessionId); // Replace with your own session ID. See https://dashboard.tokbox.com/projects
session.addEventListener('sessionConnected', sessionConnectedHandler);
session.addEventListener('sessionDisconnected', sessionDisconnectedHandler);
session.addEventListener('streamCreated', streamCreatedHandler);
session.connect(apiKey, otToken);
}
Template.chatTemplate.rendered=function(){
console.log("chat tempalte rendered");
var $window= $(window);
var $chat= $("#chat");
var chatWidth,chatHeight;
TB.addEventListener("exception", exceptionHandler);
//Replace with your API key and token. See https://dashboard.tokbox.com/projects
function checkDimensions(){
chatHeight=$chat.height();
chatWidth=$chat.width();
//console.log("chat:"+chatWidth+"x"+chatHeight);
var chatWindowWidth= 0.8*chatWidth;
var chatWindowHeight= 3/4*chatWindowWidth;
var chatContentHeight= chatWindowHeight*2+10;
if(chatContentHeight>chatHeight){
//alert("chat height exceeded");
chatWindowHeight= chatHeight*.4;
chatWindowWidth=chatWindowHeight*4/3;
$(".chat-window").width(chatWindowWidth);
$(".chat-window").height(chatWindowHeight);
}
var minWidth= 200;
var minHeight= 150;
if(chatWindowWidth>minWidth && chatWindowHeight>minHeight){
$(".chat-window").width(chatWindowWidth);
$(".chat-window").height(chatWindowHeight);
} else{
$(".chat-window").width(minWidth);
$(".chat-window").height(minHeight);
}
}
checkDimensions();
$window.resize(checkDimensions);
}
function sessionConnectedHandler(event) {
subscribeToStreams(event.streams);
startPublishing();
}
function sessionDisconnectedHandler(event) {
// This signals that the user was disconnected from the Session. Any subscribers and publishers
// will automatically be removed. This default behaviour can be prevented using event.preventDefault()
publisher = null;
}
function addStream(stream) {
// Check if this is the stream that I am publishing, and if so do not publish.
if (stream.connection.connectionId == session.connection.connectionId) {
return;
}
var subscriberDiv = document.createElement('div'); // Create a div for the subscriber to replace
subscriberDiv.setAttribute('id', stream.streamId); // Give the replacement div the id of the stream as its id.
subscriberDiv.setAttribute('class','subscriber_div')
document.getElementById("chat-window-2").appendChild(subscriberDiv);
var vid_width=$(".chat-window").width();
var vid_height=$(".chat-window").height();
var subscriberProps = {width: vid_width, height: vid_height};
session.subscribe(stream, subscriberDiv.id, subscriberProps);
}
function streamCreatedHandler(event) {
subscribeToStreams(event.streams);
}
function startPublishing(){
var parentDiv = document.getElementById("chat-window-1");
var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
publisherDiv.setAttribute('id', 'opentok_publisher');
parentDiv.appendChild(publisherDiv);
var vid_width=$(".chat-window").width();
var vid_height=$(".chat-window").height();
publisher = TB.initPublisher(apiKey, publisherDiv.id); // Pass the replacement div id and properties
session.publish(publisher);
}
function subscribeToStreams(streams) {
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
console.log(stream.connection.connectionId+"&"+session.connection.connectionId);
if (stream.connection.connectionId != session.connection.connectionId) {
addStream(stream);
}
}
}
function exceptionHandler(event) {
alert(event.message);
}
|
import React, {Component} from "react";
import "./baseDatePicker.scss";
import Moment from "moment";
import PropTypes from "prop-types";
import CommonFunc from "components/global/commonFunc";
const TABLE_TYPE = {
YEAR: 0,
MONTH: 1,
DAY: 2,
HOUR: 3,
MIN: 4,
SEC: 5
};
const TOTAL_YEAR = 12;
const TOTAL_MONTH = 12;
const TOTAL_HOURS = 24;
const TOTAL_MINUTES = 60;
const TOTAL_SECONDS = 60;
const WEEK_DAY = 7;
const DATE_TIME_TYPE = {
"YEAR": [true, false, false, false, false, false],
"MONTH": [true, true, false, false, false, false],
"DAY": [true, true, true, false, false, false],
"HOUR": [true, true, true, true, false, false],
"MIN": [true, true, true, true, true, false],
"SEC": [true, true, true, true, true, true],
};
const TIME_TABLE_TITLE = [ "请选择小时", "请选择分钟", "请选择秒钟" ];
const TABLE_CLASS = [ "my-year-table", "my-month-table", "my-date-table", "my-hour-table", "my-min-table", "my-sec-table" ];
const totalValue = [ TOTAL_YEAR, TOTAL_MONTH, 0, TOTAL_HOURS, TOTAL_MINUTES, TOTAL_SECONDS ];
const rouNum = [ 4, 4, 0, 6, 10, 10];
class BaseDatePicker extends Component {
constructor(props) {
super(props);
this.isSetNowTimeEnabled = false;
this.inited = false;
this.state = {
table: null,
header: null,
headerTitle: null,
chooseResult: [],
checkedDate: [],
yearList: {
startYear: (new Date()).getFullYear() - TOTAL_YEAR + 1,
endYear: (new Date()).getFullYear(),
},
timeEnabled: DATE_TIME_TYPE[this.props.type],
}
}
setNextTable = (classIndex) => {
let nextTable = classIndex;
if (classIndex !== TABLE_TYPE.DAY && this.state.timeEnabled[classIndex + 1]) {
nextTable += 1;
} else if (nextTable > TABLE_TYPE.DAY) {
nextTable = TABLE_TYPE.DAY;
}
return nextTable;
};
dealCrossYear = (chooseDate, isPlus = true) => {
let dealDate = [...chooseDate];
dealDate[TABLE_TYPE.MONTH] = isPlus ? (dealDate[TABLE_TYPE.MONTH]+1) : (dealDate[TABLE_TYPE.MONTH]-1);
if (dealDate[TABLE_TYPE.MONTH] <= 0) {
dealDate[TABLE_TYPE.MONTH] = TOTAL_MONTH;
dealDate[TABLE_TYPE.YEAR] -= 1;
} else if (dealDate[TABLE_TYPE.MONTH] > TOTAL_MONTH) {
dealDate[TABLE_TYPE.MONTH] = 1;
dealDate[TABLE_TYPE.YEAR] += 1;
}
return dealDate;
};
setResultByClickValue = (classIndex, className, value) => {
let chooseResult = [...this.state.chooseResult];
let nextTable = this.setNextTable(classIndex);
chooseResult[classIndex] = parseInt(value);
if ( classIndex === TABLE_TYPE.YEAR) {
this.setState({ chooseResult }, ()=>this.changeDate(nextTable));
return;
} else if ( classIndex === TABLE_TYPE.DAY ) {
if ( className === "prev-month" ) {
chooseResult = this.dealCrossYear(chooseResult, false);
}
else if ( className === "next-month" ) {
chooseResult = this.dealCrossYear(chooseResult, true);
}
let compareDate = [...chooseResult];
compareDate[TABLE_TYPE.MONTH] -= 1;
if ( (Moment().startOf("days")).diff(Moment(compareDate).startOf("days"), "days") >= 0) {
if (chooseResult[TABLE_TYPE.HOUR] > (new Date()).getHours()) {
chooseResult[TABLE_TYPE.HOUR] = (new Date()).getHours()
}
chooseResult[TABLE_TYPE.MIN] = 0;
chooseResult[TABLE_TYPE.SEC] = 0;
}
}
this.setState({ chooseResult }, ()=>this.changeDate(nextTable));
};
judgeDisabledDate = (time) => {
const { disableDate } = this.props;
let judgeTime = [...time];
judgeTime[TABLE_TYPE.MONTH] -= 1;
let utc = Moment(judgeTime).utc()._d;
return (typeof disableDate === "function") ? disableDate(utc) : false;
};
judgeTodayItem = (time) => {
let now = new Date();
let nowDate = [ now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0 ];
let judgeTime = [...time.slice(0, 3), 0, 0, 0];
judgeTime[TABLE_TYPE.MONTH] -= 1;
return JSON.stringify(judgeTime) === JSON.stringify(nowDate);
};
chooseDate = (e) => {
let className = e.target.className;
if ( e.target.tagName !== "TD" || className.indexOf("disabled") !== -1 ) return false;
let classIndex = TABLE_CLASS.indexOf(e.currentTarget.className);
this.setResultByClickValue(classIndex, className, e.target.innerHTML);
};
initDayList = (rowNum = 6, rowItemNum = 7) => {
const { chooseResult, checkedDate } = this.state;
let monthDays = [31, (28 + this.isLeapYear(chooseResult[TABLE_TYPE.YEAR])),
31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let selectedYear = chooseResult[TABLE_TYPE.YEAR];
let selectedMonth = chooseResult[TABLE_TYPE.MONTH] - 1;
let prevMonthTotalDate = monthDays[selectedMonth - 1] || 31;
let list = [];
let prevDate = [];
let startDate = 1;
let nextDate = 1;
let utc = Moment([selectedYear, selectedMonth, 1]).utc();
let day = (new Date(utc)).getDay();
if (day === 0) day = WEEK_DAY;
let prevDateTime = this.dealCrossYear(chooseResult, false);
let nowDateTime = [...chooseResult];
let nextDateTime = this.dealCrossYear(chooseResult, true);
for ( let i = 0; i < day; i++) {
prevDate.unshift(prevMonthTotalDate--);
}
list.push(<tr key={rowNum}><th>日</th><th>一</th><th>二</th>
<th>三</th><th>四</th><th>五</th><th>六</th></tr>);
for(let i = 0; i < rowNum; i++) {
let rowList = [];
for(let j = 0; j < rowItemNum; j++) {
if ( prevDate.length > 0 ) {
prevDateTime[TABLE_TYPE.DAY] = prevDate[0];
let className = (this.judgeDisabledDate(prevDateTime) ? "disabled" : "prev-month");
rowList.push(<td key={prevDate[0]} className={className}>{prevDate[0]}</td>);
prevDate.shift();
} else if (startDate <= monthDays[selectedMonth]) {
nowDateTime[TABLE_TYPE.DAY] = startDate;
let className = (this.judgeDisabledDate(nowDateTime) ? "disabled" : "")
+ (JSON.stringify(nowDateTime) === JSON.stringify(checkedDate) ? " checked" : "")
+ (this.judgeTodayItem(nowDateTime) ? " today" : "");
rowList.push(<td key={startDate} className={className}>{startDate}</td>);
startDate++;
} else {
nextDateTime[TABLE_TYPE.DAY] = nextDate;
let className = (this.judgeDisabledDate(nextDateTime) ? "disabled" : "next-month");
rowList.push(<td key={nextDate} className={className}>{nextDate}</td>);
nextDate++;
}
}
list.push(<tr key={i}>{rowList}</tr>);
}
return list
};
initDateTimeList = (total, rowNum, tableType, baseValue = 0) => {
const { chooseResult, checkedDate } = this.state;
let value = tableType === TABLE_TYPE.MONTH ? (baseValue + 1) : baseValue;
let maxValue = total + value;
let rowItemNum = total / rowNum;
let list = [];
let nowDateTime = [...chooseResult];
for(let i = 0; i < rowNum; i++) {
let rowList = [];
for(let j = 0; j < rowItemNum; j++) {
if (value >= maxValue) break;
let show = tableType === TABLE_TYPE.MONTH ? (value + "月") : value;
nowDateTime[tableType] = value;
let className = (this.judgeDisabledDate(nowDateTime) ? "disabled" : "")
+ (JSON.stringify(nowDateTime) === JSON.stringify(checkedDate) ? " checked" : "");
rowList.push(<td key={value} className={className}>{show}</td>);
value++;
}
list.push(<tr key={i}>{rowList}</tr>);
}
return list
};
setTableShow = () => {
this.changeDate(TABLE_TYPE.DAY, false);
};
setNowTime = () => {
if ( this.isSetNowTimeEnabled ) return false;
const { type } = this.props;
let nowDate = new Date();
let chooseResult = [
DATE_TIME_TYPE[type][0] ? nowDate.getFullYear() : 0,
DATE_TIME_TYPE[type][1] ? (nowDate.getMonth() + 1) : 0,
DATE_TIME_TYPE[type][2] ? nowDate.getDate() : 0,
DATE_TIME_TYPE[type][3] ? nowDate.getHours() : 0,
DATE_TIME_TYPE[type][4] ? nowDate.getMinutes() : 0,
DATE_TIME_TYPE[type][5] ? nowDate.getSeconds() : 0
];
let yearList = {
startYear: nowDate.getFullYear() - TOTAL_YEAR + 1,
endYear: nowDate.getFullYear(),
};
let tableType = Math.min(TABLE_TYPE[type], TABLE_TYPE.DAY);
this.setState({ chooseResult, yearList }, ()=>this.changeDate(tableType));
};
setYearByMode = (isPrev = false, nowTable = TABLE_TYPE.DAY, mode = "step") => {
let chooseResult = [...this.state.chooseResult];
let yearList = {...this.state.yearList};
let offset = mode === "step" ? 1 : TOTAL_YEAR;
if ( mode !== "step") chooseResult[TABLE_TYPE.YEAR] = yearList.startYear;
if (isPrev) {
chooseResult[TABLE_TYPE.YEAR] -= offset;
// if (this.judgeDisabledDate(chooseResult)) return;
yearList.startYear -= offset;
yearList.endYear -= offset;
} else {
chooseResult[TABLE_TYPE.YEAR] += offset;
// if (this.judgeDisabledDate(chooseResult)) return;
yearList.startYear += offset;
yearList.endYear += offset;
}
if (mode === "step"){
this.setState({ chooseResult, yearList }, ()=>this.changeDate(nowTable, false));
} else {
this.setState({ yearList }, ()=>this.changeDate(nowTable, false));
}
};
setMonthByOneStep = (isPrev = false) => {
let chooseResult = this.dealCrossYear(this.state.chooseResult, !isPrev);
// if (this.judgeDisabledDate(chooseResult)) return;
this.setState({ chooseResult }, ()=>this.changeDate(TABLE_TYPE.DAY, false))
};
changeDate = (type, isSetDate = true) => {
if (typeof this.props.onChange === "function" && this.inited && isSetDate) {
this.props.onChange(this.state.chooseResult);
this.setState({ checkedDate: this.state.chooseResult}, () => {
this.toggleTable(type);
this.refreshHeader(type);
});
return;
}
this.inited = true;
this.toggleTable(type);
this.refreshHeader(type);
};
isLeapYear = (year) => {
return ((year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0) ? 1 : 0);
};
confirmDate = () => {
if (typeof this.props.onConfirm === "function") {
this.props.onConfirm();
}
};
initTimeArea = () => {
const { type } = this.props;
let initTableIndex = Math.min(TABLE_TYPE[type], TABLE_TYPE.DAY);
this.setState({
timeEnabled: DATE_TIME_TYPE[type],
}, ()=> this.changeDate(initTableIndex, false))
};
componentWillMount () {
const { value, disableDate } = this.props;
let initValue = [0, 0, 0, 0, 0, 0];
this.isSetNowTimeEnabled = (typeof disableDate !== "undefined");
initValue = [...value, ...initValue.slice(value.length, 6)];
this.setState({ chooseResult: initValue, checkedDate: initValue }, this.initTimeArea)
}
refreshHeader = (type) => {
const { chooseResult } = this.state;
let header = null;
switch (type) {
case TABLE_TYPE.YEAR: {
const { yearList } = this.state;
header = <div>
<a className="my-calendar-prev-year-btn" title="上一年" onClick={()=>this.setYearByMode(true, TABLE_TYPE.YEAR, "page")}>{"<<"}</a>
<span>{`${yearList.startYear}年 - ${yearList.endYear}年`}</span>
<a className="my-calendar-next-year-btn" title="下一年" onClick={()=>this.setYearByMode(false, TABLE_TYPE.YEAR, "page")}>{">>"}</a>
</div>;
break;
}
case TABLE_TYPE.MONTH:
header = <div>
<a className="my-calendar-prev-year-btn" title="上一年" onClick={()=>this.setYearByMode(true, TABLE_TYPE.MONTH)}>{"<<"}</a>
<span className="my-year-select" onClick={()=>this.changeDate(TABLE_TYPE.YEAR, false)}>{`${chooseResult[TABLE_TYPE.YEAR]}年`}</span>
<a className="my-calendar-next-year-btn" title="下一年" onClick={()=>this.setYearByMode(false, TABLE_TYPE.MONTH)}>{">>"}</a>
</div>;
break;
case TABLE_TYPE.DAY:
header = <div>
<a className="my-calendar-prev-year-btn" title="上一年" onClick={()=>this.setYearByMode(true)}>{"<<"}</a>
<a className="my-calendar-prev-month-btn" title="上个月" onClick={()=>this.setMonthByOneStep(true)}>{"<"}</a>
<span className="my-calendar-date-select">
<a className="my-year-select" onClick={()=>this.changeDate(TABLE_TYPE.YEAR, false)}>{`${chooseResult[TABLE_TYPE.YEAR]}年 `}</a>
<a className="my-month-select" onClick={()=>this.changeDate(TABLE_TYPE.MONTH, false)}>{`${CommonFunc.dateTimeFormat(chooseResult[TABLE_TYPE.MONTH])}月 `}</a>
<a className="my-day-select" onClick={()=>this.changeDate(TABLE_TYPE.DAY, false)}>{`${CommonFunc.dateTimeFormat(chooseResult[TABLE_TYPE.DAY])}日 `}</a>
</span>
<a className="my-calendar-next-month-btn" title="下个月" onClick={()=>this.setMonthByOneStep(false)}>{">"}</a>
<a className="my-calendar-next-year-btn" title="下一年" onClick={()=>this.setYearByMode(false)}>{">>"}</a>
</div>;
break;
case TABLE_TYPE.HOUR:
case TABLE_TYPE.MIN:
case TABLE_TYPE.SEC:
header = <div>
<span>{TIME_TABLE_TITLE[type - TABLE_TYPE.HOUR]}</span>
<a className="my-calendar-cancel" title="取消" onClick={this.setTableShow}>{"X"}</a>
</div>;
break;
default: break;
}
this.setState({ header });
};
toggleTable = (type) => {
let baseValue = (type === TABLE_TYPE.YEAR) ? this.state.yearList.startYear : 0;
let table = <table className={TABLE_CLASS[type]} onClick={(e) => this.chooseDate(e)}>
<tbody>
{
(type !== TABLE_TYPE.DAY) ?
this.initDateTimeList(totalValue[type], rouNum[type], type, baseValue)
: this.initDayList()
}
</tbody>
</table>;
this.setState({ table });
};
render () {
const { chooseResult, timeEnabled } = this.state;
let timeItem = [ TABLE_TYPE.HOUR, TABLE_TYPE.MIN, TABLE_TYPE.SEC ];
return (
<div className="my-calendar">
<div className="my-calendar-date-panel">
<div className="my-calendar-header">
{this.state.header}
</div>
<div className="my-calendar-body">
{this.state.table}
</div>
<div className="my-calendar-footer">
<span className="my-calendar-time-select">
{
timeItem.map((item) => {
return (
<span key={item}>
<input type="text"
className={(timeEnabled[item] ? "" : "time-disabled")}
value={timeEnabled[item] ? CommonFunc.dateTimeFormat(chooseResult[item]) : "00"}
name={item}
maxLength="2"
readOnly="readonly"
disabled={timeEnabled[item] ? "" : "disabled"}
onClick={()=>this.changeDate(item, false)}
/>
{ (item < TABLE_TYPE.SEC) ? <span>{" : "}</span> : null }
</span>
)
})
}
</span>
<span className="my-calendar-footer-btn">
<a className={(this.isSetNowTimeEnabled ? "hidden" : "")} onClick={this.setNowTime}>此刻</a>
<a className="my-calendar-confirm-btn" onClick={this.confirmDate}>确定</a>
</span>
</div>
</div>
</div>
);
}
}
BaseDatePicker.propTypes = {
value: PropTypes.arrayOf(PropTypes.number),
onChange: PropTypes.func,
type: PropTypes.oneOf(["YEAR", "MONTH", "DAY", "HOUR", "MIN", "SEC"]),
disableDate: PropTypes.func,
};
BaseDatePicker.defaultProps = {
type: "SEC",
value: [
(new Date()).getFullYear(),
(new Date()).getMonth() + 1,
(new Date()).getDate(),
(new Date()).getHours(),
(new Date()).getMinutes(),
(new Date()).getSeconds(),
],
};
export default BaseDatePicker;
|
import { html } from '../../../src/functions/html.function.js';
export const myFirstComponentStyles = html`
<style>
ul {
padding: 0px;
margin: 0px;
}
ul li {
padding: 0px;
margin: 0px;
list-style-type: none;
}
</style>
`; |
"use strict";
document.body.style.backgroundColor = "lightgray";
var idCounter = 0;
var myContent = document.getElementById("content");
myContent.style.height = "300px";
myContent.style.width = "300px";
myContent.style.backgroundColor = "white";
document
.getElementById("greenBtn")
.addEventListener("click", function () {
addColoredBlock("green");
});
function addColoredBlock(colorTo) {
let newBlock = document.createElement("div");
newBlock.classList.add("block");
newBlock.id = ++idCounter;
switch (colorTo) {
case "green":
newBlock.classList.add("green");
break;
case "red":
newBlock.classList.add("red");
break;
case "blue":
newBlock.classList.add("blue");
break;
}
myContent.appendChild(newBlock);
}
function ticTacToc() {
let ticBoard = ["blue", "red", "blue", "red", "blue", "red", "blue", "red", "blue",];
for (let index = 0; index < ticBoard.length; index++) {
addColoredBlock(ticBoard[index]);
}
}
function arrayTestCode2d() {
let array2d = [
["one", "two", "tree"],
["en", "två", "tre"]
];
console.log(array2d);
console.log("only one dim expretion:", array2d[0]);
}
function arrayTestCode3d() {
let array3d = [
[["one"], ["two"], ["tree"]],
[["en"], ["två"], ["tre"]]
];
let expected = "one"
console.log(array3d);
console.log("two dim expretion:", array3d[0][0]);
console.log("Assert", array3d[0][0][0] === expected ? "test passed" : "failed")
} |
// Generated by CoffeeScript 1.8.0
(function() {
var Schema, mongoose, schema;
mongoose = require('mongoose');
Schema = mongoose.Schema;
schema = Schema({
open_id: String,
first_name: String,
last_name: String,
email: String
});
schema.index({
open_id: 1
}, {
unique: true
});
exports.schema = schema;
}).call(this);
|
let imagesArray = [
"./img/turtle-baby.jpg",
"./img/image1.jpg",
"./img/image2.jpg",
"./img/image3.jpg",
"./img/image4.jpg",
"./img/image5.jpg",
"./img/image6.jpg",
"./img/image7.jpg",
"./img/image8.jpg",
];
let switches = document.querySelectorAll(".switch");
for (let i = 0; i < switches.length; i++) {
switches[i].addEventListener("mouseover", function(){
document.querySelector("#display_picture").src = imagesArray[i];
imagesArray[i].classList.add = ("menu_out")
})
}
let Name = document.querySelector("#name")
let email = document.querySelector("#email")
let form = document.querySelector("#form")
let error = document.querySelector ("#error")
let error2 = document.querySelector ("#error2")
form.addEventListener("submit",(e)=> {
let messages = [];
if (Name.value === "" || Name.value == null){
messages.push ("*Mandatory Field")
}
if (messages.length > 0){
e.preventDefault()
error.innerText = messages.join(",")
}
})
form.addEventListener("submit",(e)=> {
let messages = [];
if (email.value === "" || email.value == null){
messages.push ("*Mandatory Field")
}
if (messages.length > 0){
e.preventDefault()
error2.innerText = messages.join(",")
}
})
|
/**
* Created by user on 4/24/15.
*/
'use strict';
angular.module('DeclineSetupService', [])
.factory('DeclineSetup', function(DataStorage, $q, $rootScope) {
//merge with usage below
var fields = function () {
var resultObj = {};
resultObj.activeRLOptions = {
label: $rootScope.t('crm.export.recurring-status'),
data: [{
"id":-1,
"name": $rootScope.t('services.crm.exportsetup.any'),
checked: 'checked'
},
{
"id":1,
"name": $rootScope.t('services.crm.exportsetup.active')
},
{
"id":0,
"name": $rootScope.t('services.crm.exportsetup.inactive')
}]
};
// 2nd select
resultObj.sitesSettings = {
idProp: 'SiteID',
displayProp: 'Name',
enableSearch: true,
scrollableHeight: '163px',
scrollable: true,
searchPlaceholder: $rootScope.t('common.sites-type-here-or-select-from-list'),
selectName: $rootScope.t('common.sites'),
valRequired: true
};
// 3rd select
resultObj.reportOptionsSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '100px',
scrollable: true,
selectName: $rootScope.t('crm.export.report-options'),
};
// 4th select
resultObj.chargeTypeSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '115px',
scrollable: true,
selectName: $rootScope.t('crm.export.charge-type'),
};
// 5th select
resultObj.transactionTypeSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '115px',
scrollable: true,
selectName: $rootScope.t('crm.export.transaction-type'),
};
// 6th select
resultObj.transactionResultSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: true,
scrollableHeight: '108px',
scrollable: true,
searchPlaceholder: $rootScope.t('crm.export.transaction-result.type-transaction-result'),
selectName: $rootScope.t('crm.export.transaction-result'),
};
resultObj.stepTypeSettings = {
idProp: 'id',
displayProp: 'name',
enableSearch: false,
scrollableHeight: '100px',
scrollable: true,
selectName: $rootScope.t('crm.export.last-step'),
selectionLimit: 1
};
resultObj.fromDateOptions = {
//width: 110,
label: $rootScope.t('common.from'),
id: 304,
inline: true
};
resultObj.toDateOptions = {
//width: 110,
label: $rootScope.t('common.to'),
id: 305,
inline: true
};
resultObj.fromDateOptionsSmall = {
label: $rootScope.t('common.from'),
id: 304,
small: true
};
resultObj.toDateOptionsSmall = {
label: $rootScope.t('common.to'),
id: 305,
small: true
};
resultObj.clientsSettings = {
enableSearch: true,
scrollableHeight: '163px',
scrollable: true,
idProp: 'ClientID',
displayProp: 'CompanyName',
selectName: $rootScope.t('common.clients'),
valRequired: true
};
return resultObj;
};
var fieldOptions = function () {
var resultObj = fields();
resultObj.useCurrentDateOptions = {
label: 'SET RECURRENCE TO CURRENT DATE:',
styles: {
"margin-top": "16px",
"margin-bottom": "14px"
},
data: [{"id":"Yes", "name":"Yes"},{"id":"No", "name":"No", checked: true}],
};
resultObj.searchForTxtOptions = {
label: 'SEARCH FOR:',
id: 305
};
resultObj.setRecurrenceRLOptions = {
label: 'SET RECURRENCE TO CURRENT DATE?',
data: [{"id":1,"name":"Yes"},{"id":2,"name":"No", "checked": "checked"}]
};
return resultObj;
};
// Return directly only functions and constants (whiteLabel), other things through function(){return {val: someobject};}
return {
fieldOptions: fieldOptions
};
});
|
let express = require("express");
let router = express.Router();
let sequelize = require("../db");
let LikeFix = sequelize.import("../models/likeFix");
router.post("/fix", (request, response) => {
LikeFix.create({
userId: request.body.userId,
fixId: request.body.fixId,
}).then(
function success(data) {
response.json(data);
},
function error(error) {
response.send(500, error.message);
}
);
});
module.exports = router;
|
var play1=document.getElementById("p1");
var play2=document.getElementById("p2");
var p1score=0;
var p2score=0;
var gamepoint=6;
var gameover=false;
var reset=document.getElementById("rest");
var input=document.querySelector("input");
var play=document.getElementById("play");
play1.addEventListener("click",function(){
if(!gameover){
p1score++;
if(p1score==gamepoint)
{
gameover=true;
}
p1display.textContent=p1score;
}
});
play2.addEventListener("click",function(){
if(!gameover){
p2score++;
if(p2score==gamepoint){
gameover=true;
}
p2display.textContent=p2score;
}
});
reset.addEventListener("click",function(){
var p1score=0;
var p2score=0;
p1display.textContent=0;
p2display.textContent=0;
gameover=false;
});
input.addEventListener("change",function(){
play.textContent=input.value;
gamepoint=Number(input.value);
})
|
import path from 'path';
import GulpGlob from '../src/gulpglob';
import {expect} from 'chai';
describe(`Testing resolve method`, function () {
it(`src/**/*.js`, function () {
const gg = new GulpGlob('src/**/*.js');
return gg.resolve().then(files => {
expect(files).to.eql(['gulpglob.js', 'simple-gulpglob.js'].map(
file => path.join(process.cwd(), 'src', file)));
});
});
it(`['src/**/*.js', '.babelrc']`, function () {
const gg = new GulpGlob('src/**/*.js', '.babelrc');
return gg.resolve().then(files => {
expect(files).to.eql(['.babelrc', 'src/gulpglob.js',
'src/simple-gulpglob.js'].map(file => path.join(process.cwd(), file)));
});
});
});
|
/**
* Created by gullumbroso on 20/09/2016.
*/
angular.module('DealersApp')
/**
* Providing functions for saving default settings for a user.
*/
.factory('Defaults', ['$http', '$rootScope', 'Authentication', function DefaultsFactory($http, $rootScope, Authentication) {
var DEALER_DEFAULTS_PATH = "/dealer_defaults/";
var service = {};
service.updateShippingMethods = updateShippingMethods;
return service;
/**
* Updates the default values of the shipping methods of the dealer in the server.
* @param product - the new product from which the shipping methods should be taken.
* @param dealer - the dealer.
*/
function updateShippingMethods(product, dealer) {
var data = {};
if (product.dealers_delivery) {
data.dealers_delivery = product.dealers_delivery.id;
} else {
data.dealers_delivery = null;
}
if (product.custom_delivery) {
data.custom_delivery = product.custom_delivery.id;
} else {
data.custom_delivery = null;
}
if (product.pickup_delivery) {
data.pickup_delivery = product.pickup_delivery.id;
} else {
data.pickup_delivery = null;
}
$http.patch($rootScope.baseUrl + DEALER_DEFAULTS_PATH + dealer + '/', data)
.then(function (response) {
console.log("Saved the shipping methods as default successfully!");
}, function (err) {
console.log("There was an error while trying to save the shipping methods as defaults: " + err.data);
});
}
}]); |
import localStorage from 'local-storage';
export default class AuthService {
constructor(domain) {
this.domain = process.env.APP_DOMAIN || domain || 'http://localhost:3000'
this.getProfile = this.getProfile.bind(this)
//this.call_profile();
}
getProfileAwait() {
return this.fetch(`${this.domain}/user`, {
method: 'get',
})
}
getMeAwait() {
return this.fetch(`${this.domain}/api/info/me`, {
method: 'get',
})
}
call_profile() {
if(localStorage.get('profile')){
return ;
}
// Get a token
return this.fetch(`${this.domain}/user`, {
method: 'get',
}).then(res => {
if(res.error){
Promise.error(res.error)
return
}
this.setProfile(res)
return Promise.resolve(res)
}).catch(err=>{
})
}
loggedIn(){
// Checks if there is a saved token and it's still valid
const token = this.getToken()
return !!token // handwaiving here
}
setProfile(profile){
// Saves profile data to localStorage
localStorage.set('profile', JSON.stringify(profile))
}
getProfile(){
// Retrieves the profile data from localStorage
const profile = localStorage.get('profile')
return profile ? JSON.parse(profile) : this.call_profile();
}
setToken(idToken){
// Saves user token to localStorage
localStorage.set('id_token', idToken)
}
getToken(){
// Retrieves the user token from localStorage
return localStorage.get('id_token')
}
logout(){
// Clear user token and profile data from localStorage
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
}
_checkStatus(response) {
// raises an error in case response status is not a success
if (response.status >= 200 && response.status < 300) {
return response
} else {
return null
}
}
fetch(url, options){
// performs api calls sending the required authentication headers
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
if (this.loggedIn()){
headers['Authorization'] = 'Bearer ' + this.getToken()
}
return fetch(url, {
headers,
...options
})
.then(response => response.json())
}
} |
w3.includeHTML();
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function formatDate(string) {
const date = new Date(string)
return date.toISOString().split('T')[0]
}
function bindMenubar() {
$('#btn-menu-expand').click(() => {
$('#menu-item-expand').toggle('display')
})
$('#close-menu').click((e) => {
$('#menu-item-expand').toggle('none')
})
$('.menu-item-expand .logged-in').click(() => {
$('.menu-item-expand .member-list-group').toggle('display')
})
$('.menu-item .logged-in').click(() => {
$('.menu-item .member-list-group').toggle('display')
})
$('.member-menu .list-group-item.active').prependTo('.member-menu')
$('.member-menu .list-group-item.active').click(() => {
$('.member-menu .list-group-item:not(.active)').toggle('display')
})
$('#signin-modal .modal-content-signin .btn-register').click(() => {
$('#signin-modal .modal-content-signin').toggle('display')
$('#signin-modal .modal-content-register').toggle('display')
})
$('#signin-modal .modal-content-register .btn-signin').click(() => {
$('#signin-modal .modal-content-signin').toggle('display')
$('#signin-modal .modal-content-register').toggle('display')
})
$('.shop-item-img-group .shop-item-img-thumbnail').click((event) => {
const el = event.currentTarget
$('.shop-item-img-group .shop-item-img-main').attr('src', el.getAttribute('src'))
})
}
$(document).ready(() => {
bindMenubar()
const trainingType = getParameterByName('type')
if (trainingType) {
const trainingUpperCase = trainingType.replace('-', ' ').toUpperCase()
const trainingTypeLine1 = trainingType.split('-')[0].toUpperCase()
const trainingTypeLine2 = trainingType.split('-')[1].toUpperCase()
const academyBookingApp = new Vue({
el: '#academy-booking',
mounted: () => {
bindMenubar()
},
data: {
bookingList: [
],
learner: 2,
type: trainingType,
typeLine1: trainingType.split('-')[0].toUpperCase(),
typeLine2: trainingType.split('-')[1].toUpperCase()
},
methods: {
addTraining() {
const bookingDate = document.querySelector('#booking-date').value
const formatDate = new Date(bookingDate).toISOString().split('T')[0]
this.bookingList.push({
date: formatDate,
dateText: bookingDate,
type: trainingUpperCase,
textLine1: trainingTypeLine1,
textLine2: trainingTypeLine2,
learner: this.learner,
})
},
deleteTraining(index) {
this.bookingList.splice(index, 1)
}
}
})
}
$('#member .input-daterange').datepicker({
format: 'd M yyyy',
weekStart: 1,
autoclose: true,
});
$('#member .input-daterange .end-date').datepicker("setDate", "11-11-2017");
$('#member .input-daterange .end-date').datepicker("setDate", "20-11-2017");
$('#academy-booking #booking-date').datepicker({
format: 'd M yyyy',
weekStart: 1,
autoclose: true,
todayHighlight: true,
});
$("#academy-booking #booking-date").datepicker("setDate", "today");
const formBookingEl = document.querySelector("#form-booking")
if (formBookingEl) {
formBookingEl.addEventListener("submit", function (e) {
document.getElementById('booking-list').value = JSON.stringify(academyBookingApp.bookingList);
e.preventDefault();
this.submit()
});
}
// hotel
$('#hotel #check-in, #hotel #check-out').datepicker({
format: 'd M yyyy',
weekStart: 1,
autoclose: true,
});
//hotel search
$('#form-hotel-search').submit(function(event) {
// event.preventDefault()
const $checkIn = $(this).find("input[name=check-in]")
$checkIn.val(formatDate($checkIn.val()))
const $checkOut = $(this).find("input[name=check-out]")
$checkOut.val(formatDate($checkOut.val()))
})
//hotel book
$('#form-hotel-search .room-list button[type=submit]').click(function(event) {
// event.preventDefault()
const $btn = $(this)
const roomId = $btn.attr('data-room-id')
const $inputRoomId = $("#form-hotel-search input[name=room-id]")
const $formHotel = $('#form-hotel-search')
$formHotel.attr('action', $formHotel.attr('data-booking-action'))
$inputRoomId.val(roomId)
})
// hotel gallery
function changeActiveImage(imgElment) {
$(".gallery .img-thumbnails img.active").removeClass('active')
imgElment.classList.add('active')
const dataImg = imgElment.getAttribute('data-image')
$('.gallery .img-active').attr('src', dataImg)
}
$(".gallery .arrow-right").click(function(event) {
const nextImg = $(".gallery .img-thumbnails img.active").next()[0]
if (nextImg) {
changeActiveImage(nextImg)
} else {
changeActiveImage($(".gallery .img-thumbnails img").first()[0])
}
})
$(".gallery .arrow-left").click(function (event) {
const nextImg = $(".gallery .img-thumbnails img.active").prev()[0]
if (nextImg) {
changeActiveImage(nextImg)
} else {
changeActiveImage($(".gallery .img-thumbnails img").last()[0])
}
})
// copy data to modal when click room image
$('.room-item .room-img').click(function(event) {
$('.hotel-gallery-modal').modal()
//delete exist info
$('.hotel-gallery-modal .text-wrapper').empty()
$('.hotel-gallery-modal .img-thumbnails').empty()
//append new info
$roomItem = $(this).closest('.room-item')
$imgThumbnails = $roomItem.find('.room-info-modal-images img').clone()
let activeImage
$imgThumbnails.each((index, el) => {
if (index === 0) {
el.classList.add('active')
activeImage = el
}
const imgSrc = el.getAttribute('data-thumbnail')
el.setAttribute('src', imgSrc)
$('.hotel-gallery-modal .img-thumbnails').append(el)
})
$('.hotel-gallery-modal .img-active').attr('src', activeImage.getAttribute('src'))
const roomInfo = $roomItem.find('.text-desc-container').clone()
const roomTitle = $roomItem.find('.title').clone()
$('.hotel-gallery-modal .text-wrapper').append(roomInfo)
$('.hotel-gallery-modal .text-desc-container').prepend(roomTitle)
$(".gallery .img-thumbnails img").click(function (event) {
const el = event.currentTarget
changeActiveImage(el)
})
})
})
|
import ViewerService from "../../service/ViewerService";
import ViewerLayerKerken from '../layer/ViewerLayerKerken'
import ViewerLayerKerkenClustered from "../layer/ViewerLayerKerkenClustered";
import {ALLOWED_VIEWER_CRS} from "../../../shared";
class ViewerServiceKerken extends ViewerService {
constructor(props) {
super(props);
}
async getCapabilities() {
return 'skip';
}
setLayers(layers) {
this.layers = [];
for (const l of layers) {
l.available_crs=ALLOWED_VIEWER_CRS; // not set in getCapabilities
if (l.title=='kerken'){
this.layers.push(new ViewerLayerKerken(l));
} else {
this.layers.push(new ViewerLayerKerkenClustered(l));
}
}
}
}
export default ViewerServiceKerken;
|
const mongoose = require("mongoose")
const {ObjectId} =mongoose.Schema;
const loanSchema = new mongoose.Schema({
totalAmount: Number,
numberOfYears: Number,
interestRate: Number,
marginMoney: Number,
paymentStarted: Boolean,
paymentFromBeginning: Boolean,
paymentNotFromBeginning: Boolean,
numberOfYearsLeft: Number,
moratoriumPeriod: Number,
currentYear: Number,
interestPaidDuringMoratorium: Boolean,
emi: Number,
totalDebt: Number,
currentDebt: Number,
user:{
type:ObjectId,
ref:"User",
required:true
}
}, {
collection: "loan"
})
const Loan = mongoose.model("Loan", loanSchema);
module.exports = Loan; |
'use strict';
var options = {
dir: {
src: __dirname + '/src',
tmp: __dirname + '/tmp',
dest: __dirname + '/build',
modules: __dirname + '/node_modules'
},
taskPath: './gulp/',
livereloadPort: 1234,
serverHost: 'localhost',
serverPort: 8080
};
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')({
pattern: ['gulp-*', 'del']
});
var taskList = require('fs').readdirSync(options.taskPath);
taskList.forEach(function (taskFile) {
require(options.taskPath + taskFile)(gulp, plugins, options);
});
gulp.task('null', function (done) {
done();
});
gulp.task(
'default',
gulp.series(
'clean',
'copy',
'less',
'scripts',
'html',
'pdf',
(plugins.util.env.production ? 'gzip' : 'null')
)
);
|
import React from 'react';
// 多个路由切换需要用 Switch
import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom'
import Home from './pages/home/index.js'
import About from './pages/about/index.js'
function App() {
return (
<BrowserRouter >
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About} />
<Redirect to="/" />
{/* <Route component={NoMatch} /> */}
</Switch>
</BrowserRouter>
);
}
export default App;
|
import React,{ memo} from 'react'
import Todo from './Todo'
const TodoList = memo (props =>{
const {todosList,isCheckedAll,checkAllTodos} = props
return (
<section className ="main">
<input
className = "toggle-all"
type="checkbox"
checked={isCheckedAll}
/>
<label htmlFor="toggle-all" onClick={checkAllTodos}></label>
<ul className="todo-list">
{
todosList.map((todo,index) => <Todo key={`todo${todo.id}`}{...{todo}} {...props} index={index}/>)
}
</ul>
</section>
)
})
export default TodoList |
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
require('dotenv').config()
const {
APP_ENV,
HOST,
PORT,
ROOT_URL,
API_KEY
} = process.env
const isDevelopment = APP_ENV === 'development';
const isProduction = APP_ENV === 'production';
const setDevTool = () => {
if (isDevelopment) {
return 'eval'
} else if (isProduction) {
return 'source-map'
} else {
return 'inline-source-map'
}
}
const setPublicPath = () => {
let publicPath
if (isDevelopment) {
publicPath = `http://localhost:${PORT}/`
} else if (isProduction) {
publicPath = `${ROOT_URL}`
}
return publicPath;
}
module.exports = {
entry: [
__dirname + "/client/src/index.jsx",
],
output: {
path: __dirname + "/client/dist",
filename: 'bundle.js',
publicPath: setPublicPath()
},
module: {
rules: [{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(jpg|jpeg|gif|png)?$/,
loader: 'url-loader',
exclude: /node_modules/,
options: {
name: 'images/[name].[ext]'
}
},
{
test: /\.(eot|ttf|otf|svg)(\?.*$|$)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff',
options: {
name: 'fonts/[name].[ext]'
}
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
exclude: /node_modules/
},
{
test: /\.(css)$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: {
loader: 'css-loader',
options: {
minimize: true
}
}
}),
},
{
test: /\.scss$/,
use: [{
loader: 'style-loader',
options: {
sourceMap: true
}
}, {
loader: 'css-loader',
options: {
sourceMap: true
}
}, {
loader: 'sass-loader',
options: {
sourceMap: true
}
}]
}, {
test: /\.html$/,
use: ['html-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + "/client/public/index.html",
inject: 'body'
}),
new ExtractTextPlugin('style.css'),
new webpack.DefinePlugin({
API_KEY: JSON.stringify(API_KEY)
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: [' ', '.js', '.jsx'],
alias: {
Assets: path.resolve(__dirname, './client/src/assets'),
Utils: path.resolve(__dirname, './client/src/utils'),
Actions: path.resolve(__dirname, './client/src/actions'),
Routes: path.resolve(__dirname, './client/src/Routes'),
Public: path.resolve(__dirname, './client/public'),
Components: path.resolve(__dirname, './client/src/components'),
HomePage: path.resolve(__dirname, './client/src/components/homepage'),
Forms: path.resolve(__dirname, './client/src/components/forms'),
General: path.resolve(__dirname, './client/src/components/general'),
Modal: path.resolve(__dirname, './client/src/components/Modal')
}
},
devServer: {
historyApiFallback: true,
hot: true,
compress: true,
inline: true,
host: HOST,
contentBase: '/client/public',
port: PORT,
proxy: {
'api/v1/*': {
target: 'http://localhost:5432',
secure: false,
changeOrigin: true
}
},
},
node: {
fs: "empty"
},
devtool: setDevTool()
} |
import React, { Component } from 'react';
import { Container } from 'semantic-ui-react';
import listContainer from '../hoc/listContainer';
import ListItemStore from '../components/ListItemStore';
class Stores extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
render() {
const EnhancedComponent = listContainer(
ListItemStore,
`Cousine/${this.props.match.params.cousineId}/stores`
);
return (
<Container>
<EnhancedComponent />
</Container>
)
}
}
export default Stores; |
import * as fetch from "./fetch.js"
//----------------------------------------------------------------------------------------------------
// inline HTML file. potrebno je dodat attribut data-inline-html (moze i neki drugi isto) i pozvat ParseForHTMLIncludes(document, 'data-inline-html')
//----------------------------------------------------------------------------------------------------
class CInlineHTMLfileCounter{ constructor(){ this.counter = 0; } }
export function inlineHTMLfile(src, obj, counter, callback){
fetch.fetchTextFileSrc(src, function(txt){
var write_file = null;
write_file = (typeof obj === 'string')? document.getElementById(obj) : obj;
write_file.innerHTML = txt;
--counter.counter;
if(counter.counter == 0){
callback();
}
});
}
function ParseForHTMLIncludes_impl(doc, strAttribute, counter, callback){
//rekurzivna funkcija koja u prvoj for petlji traži <strAttribute> atribut u DOM elementima i povecava counter za svaki takav element
//a zatim prolazi sve te elemente i poziva inlineHTMLfile() za svaki, sa tim da predaje callback funkciju koja rekurzivno poziva ponovno ParseForHTMLIncludes_impl()
//rekurzija se zaustavi jednom kad pri prolazu kroz elemente nije postavljen bHadAttrib na true (tj nije bilo elementa sa <strAttribute> atributom.
var bHadAttrib = false;
{
let elems = [];
let elems_inline_html_file = [];
let allElements = doc.getElementsByTagName("*");
for(let i = 0; i < allElements.length; ++i)
{
let el = allElements[i];
let file_src = el.getAttribute(strAttribute);
if(file_src == null) continue;
el.removeAttribute(strAttribute);
elems[elems.length] = el;
elems_inline_html_file[elems_inline_html_file.length] = file_src;
++counter.counter;
bHadAttrib = true;
}
for(let i = 0; i < elems.length; ++i)
{
let el = elems[i];
let inline_html_file = elems_inline_html_file[i];
inlineHTMLfile(inline_html_file, el, counter,
function(){
ParseForHTMLIncludes_impl(doc, strAttribute, counter, callback); //zove rekurzivno, te ako ne bude novih elemenata zove callback()
}
);
}
if(bHadAttrib == false){ callback(); } //ako nije bilo elemenata, onda zovemo callback()
}
}
export function ParseForHTMLIncludes(doc, strAttribute, callback){
if(strAttribute == undefined || strAttribute == null) strAttribute = "data-inline-html";
var counter = new CInlineHTMLfileCounter();
//poziva rekurzivnu funkciju
ParseForHTMLIncludes_impl(doc, strAttribute, counter, callback);
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
// create DOM element from html
//----------------------------------------------------------------------------------------------------
// https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
export function CreateDOMFromHTML(html){
var template = document.createElement('template');
html = html.trim();
template.innerHTML = html;
return template.content.firstChild;
}
export function CreateDOMFromHTMLFile(callee, src, callback){
fetch.fetchTextFileSrc(src, function(html){
var obj = CreateDOMFromHTML(html);
callback(callee, obj);
});
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
// movable elements
//----------------------------------------------------------------------------------------------------
class CRect{
constructor(el, par){
this.x0 = 0;
this.x1 = 0;
this.y0 = 0;
this.y1 = 0;
this.width = -1;
this.height = -1;
this.el = el;
this.par = par;
}
set(X0,Y0,X1,Y1){
this.x0 = X0;
this.x1 = X1;
this.y0 = Y0;
this.y1 = Y1;
this.width = X1-X0;
this.height = Y1-Y0;
}
isWithin(x,y){
return (x >= this.x0 && x <= this.x1 && y >= this.y0 && y <= this.y1);
}
invalidate(){
if(this.width != -1) return;
let elRect = this.el.getBoundingClientRect();
var objRect = this.par.getBoundingClientRect();
let x0 = elRect.left - objRect.left;
let x1 = x0 + elRect.width;
let y0 = elRect.top - objRect.top;
let y1 = y0 + elRect.height;
if(x0 == 0 && y0 == 0 && x1 == 0 && y1 == 0) return;
this.set(x0,y0,x1,y1);
}
}
function movable_OnMouseDown(e){
e = e || window.event;
this.oldMouseX = e.clientX;
this.oldMouseY = e.clientY;
let thisRect = this.getBoundingClientRect();
let localX = e.clientX - thisRect.left;//this.offsetLeft;
let localY = e.clientY - thisRect.top; //this.offsetTop;
let bInSelectRect = true;
//provjera jeli unutar selection recta
if(this.selectRect != null && this.selectRect.length != 0)
{
bInSelectRect = false;
for(let i = 0; i < this.selectRect.length; ++i){
let rect = this.selectRect[i];
rect.invalidate();
if(rect.isWithin(localX,localY) == true){
bInSelectRect = true; break;
}
}
}
if(bInSelectRect == true){
e.preventDefault();
document.movable_temp_onmouseup = document.onmouseup; //hack kako se nebi izgubio mouse.OnMouseEvent()
document.movable_temp_onmousemove = document.onmousemove; //hack kako se nebi izgubio mouse.OnMouseEvent()
document.onmouseup = movable_StopMovement;
document.onmousemove = movable_DragElement;
document.movable_element = this;
}
}
function movable_DragElement(e){
e = e || window.event;
e.preventDefault();
if(document.movable_element == null) return;
let dX = document.movable_element.oldMouseX - e.clientX;
let dY = document.movable_element.oldMouseY - e.clientY;
document.movable_element.style.top = (document.movable_element.offsetTop - dY) + "px";
document.movable_element.style.left = (document.movable_element.offsetLeft - dX) + "px";
document.movable_element.oldMouseX = e.clientX;
document.movable_element.oldMouseY = e.clientY;
}
function movable_StopMovement(e){
document.onmouseup = document.movable_temp_onmouseup;
document.onmousemove = document.movable_temp_onmousemove;
document.movable_element = null;
}
function movable_findMovableRectFromAttrib(obj, strAttribute){
if(strAttribute == undefined || strAttribute == null) return;
var allElements = obj.getElementsByTagName("*");
//var objRect = obj.getBoundingClientRect();
var Rects = [];
obj.movable_element_handle_attrib = strAttribute;
obj.onresize = function(){
obj.selectRect = movable_findMovableRectFromAttrib(obj, obj.movable_element_handle_attrib);
}
for(let i = 0; i < allElements.length; ++i)
{
let el = allElements[i];
let bHasAttrib = el.getAttribute(strAttribute) != null;
if(bHasAttrib == false){ continue; }
// el.removeAttribute(strAttribute);
// let elRect = el.getBoundingClientRect();
/*let x0 = elRect.left - objRect.left;
let x1 = x0 + elRect.width;
let y0 = elRect.top - objRect.top;
let y1 = y0 + elRect.height;*/
el.onresize = function(){
obj.selectRect = movable_findMovableRectFromAttrib(obj, obj.movable_element_handle_attrib);
}
Rects[Rects.length] = new CRect(el,obj);
}
return Rects;
}
/*
prima element <elem> kojem ce postaviti onmousedown handler za movement.
<handle> je ili attribut DOM elementa unutar <elem>, ili lista rect koordinata (relativno u odnosu na <elem> koje definiraju area koji pomiče element. ako ovaj parametar nije predan onda se element može pomaknut na bilo kojem mjestu
*/
export function MakeElementMovable(elem, handle){
var obj = elem;
if(typeof elem === 'string'){ obj = document.getElementById(elem); }
if(obj == null) return;
obj.onmousedown = movable_OnMouseDown;
obj.oldMouseX = 0;
obj.oldMouseY = 0;
if(handle == null){
obj.selectRect = [];}
else if(typeof handle == 'string'){
obj.selectRect = movable_findMovableRectFromAttrib(obj, handle);}
else if(handle[0].length == undefined){
obj.selectRect = [new CRect(handle[0],handle[1],handle[2],handle[3])];}
else{
obj.selectRect = [];
for(let i = 0; i < handle.length; ++i){
let r = handle[i];
obj.selectRect[i] = new CRect(r[0],r[1],r[2],r[3]);
}
}
}
/*
prima elemente <elems> kojima ce postaviti onmousedown handler za movement.
<handle_attrib> je attribut pomocu kojeg se definira da taj element je handle za movement
*/
export function MakeElementsMovable(elems, handle_attrib){
if(elems == null) return;
if(typeof elems == 'string') MakeElementMovable(elems,handle_attrib);
else{
if(elems.length == undefined) MakeElementMovable(elems,handle_attrib);
for(let i = 0; i < elems.length; ++i) MakeElementMovable(elems[i],handle_attrib);
}
}
//----------------------------------------------------------------------------------------------------
//Check for browser
//https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser/9851769
//https://github.com/arasatasaygin/is.js/blob/master/is.js
var browser = null;
export function CheckWhatBrowser()
{
// cache some methods to call later on
var toString = Object.prototype.toString;
var slice = Array.prototype.slice;
var hasOwnProperty = Object.prototype.hasOwnProperty;
// helper function which compares a version to a range
function compareVersion(version, range) {
var string = (range + '');
var n = +(string.match(/\d+/) || NaN);
var op = string.match(/^[<>]=?|/)[0];
return comparator[op] ? comparator[op](version, n) : (version == n || n !== n);
}
// helper function which extracts params from arguments
function getParams(args) {
var params = slice.call(args);
var length = params.length;
if (length === 1 && is.array(params[0])) { // support array
params = params[0];
}
return params;
}
// helper function which reverses the sense of predicate result
function not(func) {
return function() {
return !func.apply(null, slice.call(arguments));
};
}
// helper function which call predicate function per parameter and return true if all pass
function all(func) {
return function() {
var params = getParams(arguments);
var length = params.length;
for (var i = 0; i < length; i++) {
if (!func.call(null, params[i])) {
return false;
}
}
return true;
};
}
// helper function which call predicate function per parameter and return true if any pass
function any(func) {
return function() {
var params = getParams(arguments);
var length = params.length;
for (var i = 0; i < length; i++) {
if (func.call(null, params[i])) {
return true;
}
}
return false;
};
}
// build a 'comparator' object for various comparison checks
var comparator = {
'<': function(a, b) { return a < b; },
'<=': function(a, b) { return a <= b; },
'>': function(a, b) { return a > b; },
'>=': function(a, b) { return a >= b; }
};
// Environment checks
/* -------------------------------------------------------------------------- */
browser = ["BrowserType"];
// is a given value window?
// setInterval method is only available for window object
browser.windowObject = function(value) {
return value != null && typeof value === 'object' && 'setInterval' in value;
};
var freeGlobal = browser.windowObject(typeof global == 'object' && global) && global;
var freeSelf = browser.windowObject(typeof self == 'object' && self) && self;
var thisGlobal = browser.windowObject(typeof this == 'object' && this) && this;
var root = freeGlobal || freeSelf || thisGlobal || Function('return this')();
var document = freeSelf && freeSelf.document;
var previousIs = root.browser;
// store navigator properties to use later
var navigator = freeSelf && freeSelf.navigator;
var platform = (navigator && navigator.platform || '').toLowerCase();
var userAgent = (navigator && navigator.userAgent || '').toLowerCase();
var vendor = (navigator && navigator.vendor || '').toLowerCase();
// is current device android?
browser.android = function() {
return /android/.test(userAgent);
};
// is current device android phone?
browser.androidPhone = function() {
return /android/.test(userAgent) && /mobile/.test(userAgent);
};
// is current device android tablet?
browser.androidTablet = function() {
return /android/.test(userAgent) && !/mobile/.test(userAgent);
};
// is current device blackberry?
browser.blackberry = function() {
return /blackberry/.test(userAgent) || /bb10/.test(userAgent);
};
// is current browser chrome?
// parameter is optional
browser.chrome = function(range) {
var match = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
return match !== null && !browser.opera() && compareVersion(match[1], range);
};
// is current device desktop?
browser.desktop = function() {
return !browser.mobile() && !browser.tablet();
};
// is current browser edge?
// parameter is optional
browser.edge = function(range) {
var match = userAgent.match(/edge\/(\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current browser firefox?
// parameter is optional
browser.firefox = function(range) {
var match = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current browser internet explorer?
// parameter is optional
browser.ie = function(range) {
var match = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current device ios?
browser.ios = function() {
return browser.iphone() || browser.ipad() || browser.ipod();
};
// is current device ipad?
// parameter is optional
browser.ipad = function(range) {
var match = userAgent.match(/ipad.+?os (\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current device iphone?
// parameter is optional
browser.iphone = function(range) {
// avoid false positive for Facebook in-app browser on ipad;
// original iphone doesn't have the OS portion of the UA
var match = browser.ipad() ? null : userAgent.match(/iphone(?:.+?os (\d+))?/);
return match !== null && compareVersion(match[1] || 1, range);
};
// is current device ipod?
// parameter is optional
browser.ipod = function(range) {
var match = userAgent.match(/ipod.+?os (\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current operating system linux?
browser.linux = function() {
return /linux/.test(platform) && !browser.android();
};
// is current operating system mac?
browser.mac = function() {
return /mac/.test(platform);
};
// is current device mobile?
browser.mobile = function() {
return browser.iphone() || browser.ipod() || browser.androidPhone() || browser.blackberry() || browser.windowsPhone();
};
// is current state online?
browser.online = function() {
return !navigator || navigator.onLine === true;
};
// is current state offline?
browser.offline = !(browser.online());
// is current browser opera?
// parameter is optional
browser.opera = function(range) {
var match = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current browser opera mini?
// parameter is optional
browser.operaMini = function(range) {
var match = userAgent.match(/opera mini\/(\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current browser phantomjs?
// parameter is optional
browser.phantom = function(range) {
var match = userAgent.match(/phantomjs\/(\d+)/);
return match !== null && compareVersion(match[1], range);
};
// is current browser safari?
// parameter is optional
browser.safari = function(range) {
var match = userAgent.match(/version\/(\d+).+?safari/);
return match !== null && compareVersion(match[1], range);
};
// is current device tablet?
browser.tablet = function() {
return browser.ipad() || browser.androidTablet() || browser.windowsTablet();
};
// is current device supports touch?
browser.touchDevice = function() {
return !!document && ('ontouchstart' in freeSelf ||
('DocumentTouch' in freeSelf && document instanceof DocumentTouch));
};
// is current operating system windows?
browser.windows = function() {
return /win/.test(platform);
};
// is current device windows phone?
browser.windowsPhone = function() {
return browser.windows() && /phone/.test(userAgent);
};
// is current device windows tablet?
browser.windowsTablet = function() {
return browser.windows() && !browser.windowsPhone() && /touch/.test(userAgent);
};
// var isOpera = false;
// var isFirefox = false;
// var isSafari = false;
// var isIE = false;
// var isEdge = false;
// var isChrome = false;
// var isBlink = false;
browser.isOpera = browser.opera() || browser.operaMini();
browser.isSafari = browser.safari();
browser.isChrome = browser.chrome();
browser.isFirefox = browser.firefox();
browser.isIE = browser.ie();
browser.isEdge = browser.edge();
}
export {browser};
|
const CartItem = require('../models/Cart-Item');
//---------------------------------------------------- Create Cart Item ----------------------------------------------------------
exports.postAddCartItem = async (req, res, next) => {
const newCartItem = new CartItem({
quantity: req.body.quantity,
cartId: req.body.cartId,
itemId: req.body.itemId
})
try {
const savedCartItem = await newCartItem.save();
res.send({ savedCartItem });
} catch (err) {
res.status(400).send('ERROR', err)
}
};
|
import { CHANGE_SELECTED_MOVIE } from "../constants/selectedMovie";
import { CLOSE_TRAILER } from "../constants/selectedMovie";
import { appLayoutData } from "../utils/myData";
const initialState = {
selectedMovie: {
maPhim: 1329,
tenPhim: "Bố Già",
biDanh: "bo-gia",
trailer: "https://www.youtube.com/embed/jluSu8Rw6YE",
hinhAnh: "http://movie0706.cybersoft.edu.vn/hinhanh/bo-gia_gp01.jpg",
moTa: "Tui Chưa Coi Nên Chưa Biết",
maNhom: appLayoutData.maNhom,
ngayKhoiChieu: "2021-04-03T00:00:00",
danhGia: 10,
},
isOpen: false,
};
function selectedMovieReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_SELECTED_MOVIE: {
return {
// ...state,
selectedMovie: action.payload.data,
isOpen: true,
};
}
case CLOSE_TRAILER: {
console.log(action.payload.isOpen);
return {
...state,
isOpen: action.payload.isOpen,
};
}
default:
return state;
}
}
export default selectedMovieReducer;
|
import React, { useState } from 'react';
import { navigate } from '@reach/router';
import axios from 'axios';
import Form from '../components/Form';
const New = () => {
const [errors, setErrors] = useState([]);
// once updated with the post req, just navigating back to / will add it to DOM
const createAuthor = newAuthor => {
axios
.post('http://localhost:8000/api/authors/create', newAuthor)
.then(() => navigate('/'))
// .then(res => console.log(res))
.catch(err => {
const errorResponse = err.response.data.errors,
errorArr = [];
for (const key of Object.keys(errorResponse)) {
errorArr.push(errorResponse[key].message);
}
setErrors(errorArr);
});
};
return (
<>
<h1>Add a new author:</h1>
<Form onSubmitProp={createAuthor} initialName="" errors={errors} />
</>
);
};
export default New;
|
'use strict';
const Deck = require('./deck');
class Shoe {
constructor(numberOfDecks) {
this.shoe = [];
this.usedShoe = [];
this.numberOfDecks = numberOfDecks;
this.fillShoe();
}
fillShoe() {
//we are creating a brand new shoe, get all the decks and shuffle them
for (let i = 0; i < this.numberOfDecks; i++) {
var deck = new Deck();
this.shoe = [...this.shoe, ...deck.deck];
}
this.shuffle(this.shoe);
}
//shuffle the array provided in place
shuffle(shoe) {
//fisher-yates algorithm for shuffling an array
for (let i = shoe.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * i);
const temp = shoe[i];
shoe[i] = shoe[j];
shoe[j] = temp;
}
}
getOneCard() {
//need to reshuffle if shoe has less than 20% of cards left
//async function so it doesn't stop us from getting the new card?
if (this.shoe.length <= 0.2 * this.numberOfDecks * 52) {
this.refillShoe();
}
var card = this.shoe.shift();
this.usedShoe.push(card);
return card;
//it might be more efficient if we use an actual queue to make this operation O(1) instead of O(n)?
}
async refillShoe() {
//we are reshuffling, so just reshuffle the usedShoe and add it to the current shoe.
this.shuffle(this.usedShoe);
//this way we aren't reshuffling the remaining 20% of cards, we are just adding the used cards to them after reshuffling those.
//using the spread notation to concatenate arrays
this.shoe = [...this.shoe, ...this.usedShoe];
//resetting used shoe as it should now be empty
this.usedShoe = [];
}
}
module.exports = Shoe; |
import {
FETCH_SENTENCES,
SENTENCES_REQUEST,
SENTENCES_RESPONSE,
SENTENCES_ERROR,
} from './types';
let initialState = {
sentencesData: [],
sentencesIsLoading: false,
sentencesIsLoaded: false,
sentencesIsError: false,
};
const sentencesReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_SENTENCES:
return {
...state,
};
case SENTENCES_REQUEST:
return {
...state,
sentencesIsLoading: true,
sentencesIsLoaded: false,
sentencesIsError: false,
};
case SENTENCES_RESPONSE:
return {
...state,
sentencesIsLoading: false,
sentencesIsLoaded: true,
sentencesIsError: false,
sentencesData: action.payload,
};
case SENTENCES_ERROR:
return {
...state,
sentencesIsLoading: false,
sentencesIsLoaded: false,
sentencesIsError: true,
};
default:
return state;
}
};
export default sentencesReducer;
|
import React from 'react';
import {Form,Button,Table,Pagination,Input,Select,Modal,DatePicker,Cascader} from 'antd';
import moment from 'moment';
const FormItem=Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
import {FetchUtil} from '../utils/fetchUtil';
import {trim} from '../utils/validateUtil';
import './ListEvent.less';
export default class DashBoard extends React.Component{
constructor(props){
super(props);
this.state={
modelId:'',
loading:true,
modelList:[],
dashboardUrl:''
}
}
componentDidMount(){
if(!this.props.model.dashboardUrl){
Modal.warning({
title: '信息提醒',
content: '该模型统计报表未初始化!',
});
}
}
componentWillReceiveProps(nextProps){
if(this.props.modelId!=nextProps.modelId&&!nextProps.model.dashboardUrl){
Modal.warning({
title: '信息提醒',
content: '该模型统计报表未初始化!',
});
}
}
render(){
return (
<div className="ant-layout-content">
<iframe ref="dashBoard" name="dashBoard" src={this.props.model.dashboardUrl} style={{minHeight:'800px',width:'100%',border:'0px'}}></iframe>
</div>);
}
} |
import {
takeEvery, put
} from 'redux-saga/effects'
import axios from 'axios'
import { getListAction } from './actionCreators'
import {
GET_MY_LIST
} from './actionTypes'
function* mySaga() {
yield takeEvery(GET_MY_LIST, getList)
}
function* getList() {
// axios.get('https://www.fastmock.site/mock/f54236b7fb320bac2fd44a599897c2f4/redux/api/getlist')
// .then(res => {
// const data = res.data
// const action = getListAction(data)
// put(action)
// })
const res = yield axios.get('https://www.fastmock.site/mock/f54236b7fb320bac2fd44a599897c2f4/redux/api/getlist')
const action = getListAction(res.data)
yield put(action)
}
export default mySaga |
/*!
* Copyright (c) 2018-2023 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
module.exports = class LinkedDataProof {
constructor({type} = {}) {
if(typeof type !== 'string') {
throw new TypeError('A LinkedDataProof must have a "type".');
}
this.type = type;
}
/**
* @param {object} options - The options to use.
* @param {object} options.document - The document to be signed.
* @param {ProofPurpose} options.purpose - The proof purpose instance.
* @param {Array} options.proofSet - Any existing proof set.
* @param {function} options.documentLoader - The document loader to use.
* @param {function} options.expansionMap - NOT SUPPORTED; do not use.
*
* @returns {Promise<object>} Resolves with the created proof object.
*/
async createProof({
/* document, purpose, proofSet, documentLoader, expansionMap */
}) {
throw new Error('"createProof" must be implemented in a derived class.');
}
/**
* @param {object} options - The options to use.
* @param {object} options.document - The document from which to derive
* a new document and proof.
* @param {ProofPurpose} options.purpose - The proof purpose instance.
* @param {Array} options.proofSet - Any existing proof set.
* @param {function} options.documentLoader - The document loader to use.
*
* @returns {Promise<object>} Resolves with the new document with a new
* `proof` field.
*/
async derive({
/* document, purpose, proofSet, documentLoader */
}) {
throw new Error('"deriveProof" must be implemented in a derived class.');
}
/**
* @param {object} options - The options to use.
* @param {object} options.proof - The proof to be verified.
* @param {object} options.document - The document the proof applies to.
* @param {ProofPurpose} options.purpose - The proof purpose instance.
* @param {Array} options.proofSet - Any existing proof set.
* @param {function} options.documentLoader - The document loader to use.
* @param {function} options.expansionMap - NOT SUPPORTED; do not use.
*
* @returns {Promise<{object}>} Resolves with the verification result.
*/
async verifyProof({
/* proof, document, purpose, proofSet, documentLoader, expansionMap */
}) {
throw new Error('"verifyProof" must be implemented in a derived class.');
}
/**
* Checks whether a given proof exists in the document.
*
* @param {object} options - The options to use.
* @param {object} options.proof - The proof to match.
*
* @returns {Promise<boolean>} Whether a match for the proof was found.
*/
async matchProof({
proof /*, document, purpose, documentLoader, expansionMap */
}) {
return proof.type === this.type;
}
};
|
View.extend({
name: 'footer',
el: function() {
return $('footer')[0];
}
}); |
/*
* @lc app=leetcode id=40 lang=javascript
*
* [40] Combination Sum II
*/
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
if (!candidates.length) {
return [];
}
candidates.sort((a, b) => a - b);
const result = [];
let cur = [];
function find(n, index) {
if (index > candidates.length || n < 0) {
return;
}
if (n === 0) {
result.push(cur.join(','));
return;
}
let i = index;
while(i < candidates.length) {
cur.push(candidates[i]);
find(n - candidates[i], i + 1, );
cur.pop();
i++;
}
}
find(target, 0);
return Array.from(new Set(result)).map(i => i.split(','));
};
combinationSum2([10,1,2,7,6,1,5], 8);
|
import React from "react";
import axios from "./axios";
export default class FriendButton extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.renderButton = this.renderButton.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.friendStatus == 0) {
axios
.post(`/send-friend-request/${this.props.match.params.id}`)
.then(resp => {
this.props.setFriendshipStatus(resp.data.status);
});
} else if (this.props.friendStatus == 1) {
if (this.props.match.params.id == this.props.senderId) {
axios
.post(
`/accept-friend-request/${this.props.match.params.id}`
)
.then(resp => {
this.props.setFriendshipStatus(resp.data.status);
});
} else {
axios
.post(
`/cancel-friend-request/${this.props.match.params.id}`
)
.then(resp => {
this.props.setFriendshipStatus(resp.data.status);
});
}
} else if (this.props.friendStatus == 2) {
axios.post(`/unfriend/${this.props.match.params.id}`).then(resp => {
this.props.setFriendshipStatus(resp.data.status);
});
} else if (this.props.friendStatus == 5) {
axios
.post(`/send-friend-request/${this.props.match.params.id}`)
.then(resp => {
this.props.setFriendshipStatus(resp.data.status);
});
}
}
renderButton() {
let text;
if (this.props.friendStatus == 1) {
text = "Pending Request";
if (this.props.match.params.id == this.props.senderId) {
text = "Accept Friend Request";
} else {
text = "Cancel Friend Request";
}
} else if (this.props.friendStatus == 2) {
text = "Unfriend";
} else {
text = "Send Friend Request";
}
return (
<button className="dynamicButton" onClick={this.handleSubmit}>
{text}
</button>
);
}
render() {
return this.renderButton();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.