text
stringlengths 7
3.69M
|
|---|
/*
var mainHeader = document.getElementById('main_h1');
//alert(mainHeader.innerText); for opera, IE
alert(mainHeader.textContent); //for firefox
var myDiv = document.getElementById('div_for_img');
myDiv.innerHTML = "<p><strong>chaging content by new method</strong></p>"
alert(myDiv.innerHTML);
*/
//Lesson 59 - cildNodes, parentNode, nextSibiling, previousSibiling
var myDiv = document.getElementById('div_for_img');
var childDiv = myDiv.childNodes;
for (var i = 0; i < childDiv.length; i++){
//alert(childDiv[i].alt);
}
var parentDiv = myDiv.parentNode;
var brotherDiv = myDiv.nextSibling;
var brother2Div = myDiv.previousSibling;
alert(brother2Div);
/*
Lesson 58 - getElementsById
var moto = document.getElementById('img_1');
alert(moto.alt);
*/
/*
Lesson 57 - getElementsByTagName
var allImg = document.getElementsByTagName('img');
alert("There are " + allImg.length + " images");
*/
|
/* eslint no-console:0 */
import formatFn from 'date-fns/format';
import React from 'react';
import TimePicker from '..';
import '../assets/index.less';
const format = 'h:mm a';
const now = new Date();
now.setHours(0, 0);
function onChange(value) {
console.log(value && formatFn(value, format));
}
const App = () => (
<TimePicker
showSecond={false}
defaultValue={now}
className="xxx"
onChange={onChange}
format={format}
use12Hours
inputReadOnly
/>
);
export default App;
|
import React, { useState, useEffect } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
} from 'react-native';
import { ListItem, Avatar } from 'react-native-elements';
import axios from 'axios';
// const instance = axios.create({});
function SessionsScreen({ navigation, route }) {
const [sessions, setSessions] = useState([]);
useEffect(() => {
async function fetchData() {
let res = await axios
.get(
`https://dumorefitness.himalayantechies.com/programs/view/${route.params.id}.json`,
{
headers: {
'Content-Type': 'application/json',
},
}
)
.then((res) => {
setSessions(res.data.program.sessions);
});
}
fetchData();
}, [route.params.id]);
const renderFunction = (item) => (
<TouchableOpacity onPress={() => navigation.push('Exercises', {id: item.id, name: item.name})}>
<ListItem key={item.id} bottomDivider>
<Avatar
source={{
uri:
'https://dumorefitness.himalayantechies.com/files/' +
item.imageUrl,
}}
style={styles.avatar}/>
<ListItem.Content>
<ListItem.Title>{item.name}</ListItem.Title>
</ListItem.Content>
<ListItem.Chevron/>
</ListItem>
</TouchableOpacity>
);
return (
<View style={styles.homeScreen}>
<View style={styles.homeScreenContainer}>
{sessions.length == 0 ? <View style={{display:"flex", justifyContent: "center", alignItems: "center"}}><Text>Nothing to show</Text></View> : sessions.map((item, i) => renderFunction(item))}
</View>
</View>
);
}
const styles = StyleSheet.create({
homeScreen: {
flex: 1,
},
homeScreenContainer: {},
avatar: {height: 60, width: 60, marginRight: 20}
});
export default SessionsScreen;
|
module.exports = {
plugins: ['wdio', 'jasmine'],
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings',
'prettier',
'plugin:wdio/recommended',
'plugin:jasmine/recommended',
],
env: {
node: true,
es6: true,
jasmine: true,
},
globals: {
chromeBrowserOne: true,
chromeBrowserTwo: true,
},
parser: '@babel/eslint-parser',
parserOptions: {
ecmaVersion: 2016,
requireConfigFile: false,
sourceType: 'module',
},
rules: {
semi: ['error', 'never'],
quotes: ['error', 'single'],
indent: [2, 4],
'import/no-unresolved': [2, { commonjs: true, amd: true }],
'import/named': 2,
'import/namespace': 2,
'import/default': 2,
'import/export': 2,
'wdio/no-pause': 'off',
},
}
|
var editingLocationId;
function GenerateAvailsTable() {
var yearSelected = $("#year").val();
var marketSelected = $("#market").val();
Apollo.ProductionIOService.GetAvails(yearSelected, marketSelected, GenerateAvailsTableCallback, ErrorCallback);
}
function GenerateAvailsTableCallback(results) {
$("#bookingDisplayTable").remove();
//$("#availsDisplay #winterMonthMessage").remove();
$("#availsDisplay").html("");
$("#availsDisplay").append("<table id='bookingDisplayTable' class='featureTable scrollableFixedHeaderTable'></table>");
var prevMarket;
var yearSelected = $("#year").val();
var headerRow = "<thead><tr class='bookingTableHeader'>"
+ ((IsEditUser()) ? "<th colspan='" + (IsAdminUser() ? "3" : "2") + "'> </th>" : "")
+ "<th>Market</th><th>Location</th><th>4-Week Rate Card</th><th>Prod & Install<br/>(must recover<br/>additional creative<br/>cost)</th><th>Prod & Install<br/>(unlimited creatives)</th>"
+ "<th colspan='4'>Jan - " + yearSelected + "</th><th colspan='4'>Feb - " + yearSelected + "</th><th colspan='4'>Mar - " + yearSelected + "</th>"
+ "<th colspan='4'>Apr - " + yearSelected + "</th><th colspan='4'>May - " + yearSelected + "</th><th colspan='4'>Jun - " + yearSelected + "</th>"
+ "<th colspan='4'>Jul - " + yearSelected + "</th><th colspan='4'>Aug - " + yearSelected + "</th><th colspan='4'>Sep - " + yearSelected + "</th>"
+ "<th colspan='4'>Oct - " + yearSelected + "</th><th colspan='4'>Nov - " + yearSelected + "</th><th colspan='4'>Dec - " + yearSelected + "</th>"
+ "</tr></thead>";
$("#bookingDisplayTable").append(headerRow);
headerRow = "<tr class='bookingTableHeader'>"
+ ((IsEditUser()) ? "<td colspan='" + (IsAdminUser() ? "3" : "2") + "'> </td>" : "")
+ "<td>Market</td><td>Location</td><td>4-Week Rate Card</td><td>Prod & Install<br/>(must recover<br/>additional creative<br/>cost)</td><td>Prod & Install<br/>(unlimited creatives)</td>"
+ "<td colspan='4'>Jan - " + yearSelected + "</td><td colspan='4'>Feb - " + yearSelected + "</td><td colspan='4'>Mar - " + yearSelected + "</td>"
+ "<td colspan='4'>Apr - " + yearSelected + "</td><td colspan='4'>May - " + yearSelected + "</td><td colspan='4'>Jun - " + yearSelected + "</td>"
+ "<td colspan='4'>Jul - " + yearSelected + "</td><td colspan='4'>Aug - " + yearSelected + "</td><td colspan='4'>Sep - " + yearSelected + "</td>"
+ "<td colspan='4'>Oct - " + yearSelected + "</td><td colspan='4'>Nov - " + yearSelected + "</td><td colspan='4'>Dec - " + yearSelected + "</td>"
+ "</tr>";
var footerRow = "<tr class='bookingTableFooter'><td colspan='56'>IMPORTANT NOTE:<br/>- All production costs are subject to tax.<br/>- Production cost accounts for (1) art mechanical per media format. Any additional art mechanicals will incur a <u>fee of $100</u>.<br/>- Files are due <u>30 days</u> prior to the starting date to guarantee on-time posting. Titan will not be responsible for late postings if files are delivered after the due date.<br/>- Station Saturation packages will incur additional installation charges. Cost varies with media. Please contact <a href='mailto:production@titan360.com' alt='Mail To: production@titan360.com'>production@titan360.com</a> for quote.</td></tr>";
$("#bookingDisplayTable").append("<tbody>");
var availsRow = "";
prevMarket = results[0].locationMarket;
for (var i = 0; i < results.length; i++) {
if (prevMarket != results[i].locationMarket) {
$("#bookingDisplayTable").append(footerRow);
$("#bookingDisplayTable").append(headerRow);
prevMarket = results[i].locationMarket;
}
availsRow = "<tr class='availRow'>"
+ (IsAdminUser() ? "<td style='text-align:center;'><input type='button' class='button' id='deleteLocation_" + i + "' value='Delete Location' onclick='DeleteLocation(" + results[i].locationId + ");' /></td>" : "")
+ ((IsEditUserForMarket(results[i].locationMarket)) ? "<td style='text-align:center;'><input type='button' class='button' id='editLocation_" + i + "' value='Edit Location' /></td><td style='text-align:center;'><input type='button' class='button' onclick='AddBooking(" + results[i].locationId + ");' value='Add Booking' /></td>" : (IsEditUser() ? "<td colspan='2'> </td>" : ""))
+ "<td style='text-align:center;'>" + results[i].locationMarket + "</td><td class='" + (results[i].locationStatusId != "" ? ("statusClass" + results[i].locationStatusId) : "") + "'>" + results[i].locationDesc + (results[i].locationReserveWinterMonths ? " ***" : "") + "</td>"
+ "<td style='text-align:right;'>" + results[i].fourWeekRate + "</td><td style='text-align:right;'>" + results[i].prodInstallRate + "</td><td style='text-align:right;'>" + results[i].prodInstallRateAdditional + "</td>"
//+ "<td colspan='12'>" + results[i].bookingDesc + "</td>"
+ BuildBookingDisplay(results[i].locationBookings, results[i].locationReserveWinterMonths)
+ "</tr>";
$("#bookingDisplayTable").append(availsRow);
$("#editLocation_" + i).bind("click", results[i], EditLocation);
}
$("#bookingDisplayTable").append(footerRow);
$("#bookingDisplayTable").append("</tbody>");
$(".button").button();
$("#keyDisplay").css({ "display": "block" });
}
function GetColSpan(daysInMonth, daysUsed) {
/*
var perc = parseInt((daysUsed / daysInMonth) * 100);
if (perc >= 75) { return 3; }
if (perc >= 50) { return 2; }
return 1;
*/
if (daysUsed >= 21) { return 3; }
if (daysUsed >= 14) { return 2; }
return 1;
//return 3;
}
function AreDatesEqual(d1, d2) {
return (d1.getFullYear() == d2.getFullYear()
&& d1.getMonth() == d2.getMonth()
&& d1.getDate() == d2.getDate())
}
function GetLastDayOfMonth(month, year) {
switch (month) {
case 3:
case 5:
case 8:
case 10:
return 30;
case 1: return (year % 4 == 0 ? 29 : 28);
default: return 31;
}
}
function DisplayBookings() {
GenerateAvailsTable();
}
function ClearLocation() {
$("#dropDownMarket").val("");
$("#textLocation").val("");
$("#textFourWeekRate").val("");
$("#textProdInstall").val("");
$("#dropDownLocationStatus").val("");
$("#textLocationComments").val("");
}
function ValidateLocation() {
var validationErrors = "Please correct the following error(s):";
var isValid = true;
if ($("#dropDownMarket").val() == "") {
validationErrors += "\n\tPlease choose a Market.";
isValid = false;
}
if ($("#textLocation").val() == "") {
validationErrors += "\n\tPlease enter a Location.";
isValid = false;
}
if ($("#textFourWeekRate").val() == "") {
validationErrors += "\n\tPlease enter a Four Week Rate Card Value.";
isValid = false;
}
if ($("#textProdInstall").val() == "") {
validationErrors += "\n\tPlease enter a Production & Installation Value.";
isValid = false;
}
if (!isValid) { alert(validationErrors); }
return isValid;
}
function AddLocation() {
ClearLocation();
$("#addLocationAdd").removeClass("hiddenButton");
$("#addLocationUpdate").addClass("hiddenButton");
$("#addLocationAdd").unbind("click");
$("#addLocationAdd").click(function () {
if (!ValidateLocation()) { return; }
var updatedLocationObject = { locationId: -1
, locationMarket: $("#dropDownMarket").val()
, locationDesc: $("#textLocation").val()
, fourWeekRate: $("#textFourWeekRate").val()
, prodInstallRate: $("#textProdInstall").val()
, prodInstallRateAdditional: $("#textProdInstallAddtional").val()
, locationStatusId: $("#dropDownLocationStatus").val()
, locationStatus: ""
, locationComments: $("#textLocationComments").val()
, reserveWinterMonths: ($("#radioReserveWinterMonthsYes").attr("checked") !== undefined)
};
Apollo.ProductionIOService.AddUpdateLocation(updatedLocationObject, AddUpdateLocationCallback, ErrorCallback);
});
OpenDialog("addEditLocationDialog");
}
function EditLocation(locationObject) {
ClearLocation();
editingLocationId = locationObject.data.locationId;
$("#addLocationAdd").addClass("hiddenButton");
$("#addLocationUpdate").removeClass("hiddenButton");
$("#dropDownMarket").val(locationObject.data.locationMarket);
$("#dropDownMarket").attr("disabled", !IsEditUserForMarket(locationObject.data.locationMarket));
$("#textLocation").val(locationObject.data.locationDesc);
$("#textFourWeekRate").val(locationObject.data.fourWeekRate);
$("#textProdInstall").val(locationObject.data.prodInstallRate);
$("#textProdInstallAdditional").val(locationObject.data.prodInstallRateAdditional);
$("#dropDownLocationStatus").val(locationObject.data.locationStatusId);
$("#textLocationComments").val(locationObject.data.locationComments);
$("#addLocationUpdate").unbind("click");
$("#addLocationUpdate").click(function () {
if (!ValidateLocation()) { return; }
var updatedLocationObject = { locationId: editingLocationId
, locationMarket: $("#dropDownMarket").val()
, locationDesc: $("#textLocation").val()
, fourWeekRate: $("#textFourWeekRate").val()
, prodInstallRate: $("#textProdInstall").val()
, prodInstallRateAdditional: $("#textProdInstallAdditional").val()
, locationStatusId: $("#dropDownLocationStatus").val()
, locationStatus: ""
, locationComments: $("#textLocationComments").val()
, reserveWinterMonths: ($("#radioReserveWinterMonthsYes").attr("checked") !== undefined)
};
Apollo.ProductionIOService.AddUpdateLocation(updatedLocationObject, AddUpdateLocationCallback, ErrorCallback);
});
OpenDialog("addEditLocationDialog");
}
function DeleteLocation(locationId) {
if (confirm("Are you sure you want to delete this location?")) {
Apollo.ProductionIOService.DeleteLocation(locationId, DeleteLocationCallback, ErrorCallback);
}
}
function DeleteLocationCallback() {
DisplayBookings();
alert("Location deleted.");
}
function AddUpdateLocationCallback() {
DisplayBookings();
alert("Location saved.");
CloseDialog("addEditLocationDialog");
}
function ValidateBooking() {
var validationErrors = "Please correct the following error(s):";
var isValid = true;
if ($("#textBookingDesc").val() == "") {
validationErrors += "\n\tPlease enter a Booking Description.";
isValid = false;
}
if ($("#textStartDate").val() == "") {
validationErrors += "\n\tPlease enter a Start Date.";
isValid = false;
}
if ($("#textEndDate").val() == "") {
validationErrors += "\n\tPlease enter an End Date.";
isValid = false;
}
if ($("#dropDownBookingAE").val() == "" || $("#dropDownBookingAE").val() == "-1") {
validationErrors += "\n\tPlease choose an AE.";
isValid = false;
}
var startDateAsDate = new Date($("#textStartDate").val());
var endDateAsDate = new Date($("#textEndDate").val());
if (AreDatesEqual(startDateAsDate, endDateAsDate)) { validationErrors += "\n\tBooking Dates cannot be equal."; isValid = false; }
if (startDateAsDate > endDateAsDate) { validationErrors += "\n\tEnd Date must be greather than Start Date."; isValid = false; }
if (!isValid) { alert(validationErrors); }
return isValid;
}
function ClearBooking() {
$("#textBookingDesc").val("");
$("#textStartDate").val("");
$("#textEndDate").val("");
$("#dropDownBookingStatus").val("");
$("#textBookingComments").val("");
}
function AddBooking(locationId) {
ClearBooking();
$("#addBookingUpdate").addClass("hiddenButton");
$("#addBookingDelete").addClass("hiddenButton");
$("#addBookingAdd").removeClass("hiddenButton");
$("#addBookingAdd").unbind("click");
$("#addBookingAdd").click(function () {
if (!ValidateBooking()) { return; }
var bookingObject = { locationId: locationId
, bookingId: -1
, bookingDesc: $("#textBookingDesc").val()
, bookingStartDate: $("#textStartDate").val()
, bookingEndDate: $("#textEndDate").val()
, bookingStatusId: $("#dropDownBookingStatus").val()
, bookingComments: $("#textBookingComments").val()
, aeNtId: $("#dropDownBookingAE").val()
};
Apollo.ProductionIOService.AddUpdateBooking(bookingObject, AddUpdateBookingCallback, ErrorCallback);
});
$("#addBookingAdd").bind("click", locationId, SaveNewBooking);
OpenDialog("addEditBookingDialog");
}
function SaveNewBooking(submittedData) {
var locationId = submittedData.data.locationId;
}
function EditBookingById(bookingId) {
Apollo.ProductionIOService.LoadBookingById(bookingId, EditBookingByIdCallback, ErrorCallback);
}
function EditBookingByIdCallback(bookingObject) {
EditBookings(bookingObject);
}
function EditBookings(bookingObject) {
ClearBooking();
$("#addBookingUpdate").removeClass("hiddenButton");
$("#addBookingAdd").addClass("hiddenButton");
$("#addBookingDelete").removeClass("hiddenButton");
OpenDialog("addEditBookingDialog");
$("#textBookingDesc").val(bookingObject.bookingDesc);
//$("#textStartDate").val(bookingObject.bookingStartDate.toDateString());
$("#textStartDate").datepicker("setDate", new Date(bookingObject.bookingStartDateYear, bookingObject.bookingStartDateMonth, bookingObject.bookingStartDateDay));
//$("#textEndDate").val(bookingObject.bookingEndDate.toDateString());
$("#textEndDate").datepicker("setDate", new Date(bookingObject.bookingEndDateYear, bookingObject.bookingEndDateMonth, bookingObject.bookingEndDateDay));
$("#dropDownBookingStatus").val(bookingObject.bookingStatusId);
$("#textBookingComments").val(bookingObject.bookingComments);
$("#dropDownBookingAE").val(bookingObject.aeNtId);
if (IsEditUser()) {
var locationId = bookingObject.locationId;
var bookingId = bookingObject.bookingId;
$("#addBookingUpdate").unbind("click");
$("#addBookingUpdate").click(function () {
if (!ValidateBooking()) { return; }
var bookingObject = { locationId: locationId
, bookingId: bookingId
, bookingDesc: $("#textBookingDesc").val()
, bookingStartDate: $("#textStartDate").val()
, bookingEndDate: $("#textEndDate").val()
, bookingStatusId: $("#dropDownBookingStatus").val()
, bookingComments: $("#textBookingComments").val()
, aeNtId: $("#dropDownBookingAE").val()
};
Apollo.ProductionIOService.AddUpdateBooking(bookingObject, AddUpdateBookingCallback, ErrorCallback);
});
$("#addBookingDelete").unbind("click");
$("#addBookingDelete").click(function () {
if (confirm("Are you sure you want to delete this Booking?")) {
Apollo.ProductionIOService.DeleteBooking(bookingId, DeleteBookingCallback, ErrorCallback);
}
});
} else {
$("#addBookingUpdate").addClass("hiddenButton");
$("#addBookingAdd").addClass("hiddenButton");
$("#addBookingDelete").addClass("hiddenButton");
}
OpenDialog("addEditBookingDialog");
}
function DeleteBookingCallback() {
alert("Booking deleted.");
DisplayBookings();
CloseDialog("addEditBookingDialog");
}
function AddUpdateBookingCallback() {
alert("Booking saved.");
DisplayBookings();
CloseDialog("addEditBookingDialog");
}
function CloseDialog(dialogId) { $('#' + dialogId).dialog("close"); }
function OpenDialog(dialogId) { $('#' + dialogId).dialog("open"); }
function BuildBookingDisplay(bookings, reserveWinterMonths) {
//if (bookings.length == 0) { return "<td colspan='48' style='text-align:center;'>No Bookings</td>"; }
//Each booking area will have 48 cells, 4 for each month
var bookingStartDate, bookingEndDate;
var monthStartDate, monthEndDate;
var row = "";
var monthCell = "";
var cellClass = "";
var monthDisplay = {};
for (var i = 0; i < 12; i++) {
var monthOpen = false;
var monthOpenCols = 0;
var totalOpenCols = 0;
monthStartDate = new Date($("#year").val(), i, 1);
monthEndDate = new Date(monthStartDate);
monthEndDate.setMonth(monthEndDate.getMonth() + 1);
monthEndDate.setDate(monthEndDate.getDate() - 1);
monthCell = "";
for (var j = 0; j < bookings.length; j++) {
//bookingStartDate = bookings[j].bookingStartDate;
bookingStartDate = new Date(bookings[j].bookingStartDateYear, bookings[j].bookingStartDateMonth, bookings[j].bookingStartDateDay);
//bookingEndDate = bookings[j].bookingEndDate;
bookingEndDate = new Date(bookings[j].bookingEndDateYear, bookings[j].bookingEndDateMonth, bookings[j].bookingEndDateDay);
cellClass = (bookings[j].bookingStatusId != "" ? ("statusClass" + bookings[j].bookingStatusId) : "");
//If the booking starts after the current month, break out of the loop
if (bookingStartDate.getMonth() > monthStartDate.getMonth() && bookingStartDate.getYear() >= monthStartDate.getYear()) { break; }
//If the booking ends before the current month, continue to the next booking
if (bookingEndDate.getMonth() < monthEndDate.getMonth() && bookingEndDate.getYear() <= monthEndDate.getYear()) { continue; }
/* Check to see if this booking spans the entire month */
if (AreDatesEqual(bookingStartDate, monthStartDate) && AreDatesEqual(bookingEndDate, monthEndDate)) {
monthCell = "<td colspan='4' style='text-align:center;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
continue;
}
if (AreDatesEqual(bookingStartDate, monthStartDate) && bookingEndDate > monthEndDate) {
monthCell = "<td colspan='4' style='text-align:center;padding-right:none !important;border-right:none !important;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
continue;
}
if (bookingStartDate < monthStartDate && AreDatesEqual(bookingEndDate, monthEndDate)) {
monthCell = "<td colspan='4' style='text-align:center;padding-left:none !important;border-left:none !important;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
continue;
}
if (bookingStartDate < monthStartDate && bookingEndDate > monthEndDate) {
monthCell = "<td colspan='4' style='text-align:center;padding-left:none !important; padding-right:none !important;border-left:none !important;border-right:none !important;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
continue;
}
/* Check to see if this booking only runs during part of the month */
if (bookingStartDate < monthStartDate && bookingEndDate.getMonth() == monthStartDate.getMonth()) {//Partial booking starting in previous month, ending in current
//What percentage of the month is "used" - from the start of the month
monthOpen = true;
monthOpenCols = GetColSpan(monthEndDate.getDate(), (bookingEndDate.getDate() - monthStartDate.getDate()));
totalOpenCols += monthOpenCols;
monthCell = "<td colspan='" + monthOpenCols + "' style='text-align:center;padding-left:none !important; padding-right:none !important;border-left:none !important;border-right:none !important;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
//monthCell += "<td colspan='" + (4 - GetColSpan(monthEndDate.getDate(), bookingEndDate.getDate())) + "'> </td>";
continue;
}
if (bookingStartDate.getMonth() == monthStartDate.getMonth() && (AreDatesEqual(bookingStartDate, monthStartDate) || bookingStartDate > monthStartDate) && bookingEndDate >= monthEndDate) {//Partial booking starting in current month, ending in future month
//What percentage of the month is "used"
monthOpen = false;
monthOpenCols = GetColSpan(monthEndDate.getDate(), (monthEndDate.getDate() - bookingStartDate.getDate()));
totalOpenCols += monthOpenCols;
if (monthCell == "") {
monthCell = "<td colspan='" + (4 - monthOpenCols) + "'> </td>";
} else {
if (totalOpenCols < 4) {
monthCell += "<td colspan='" + (4 - totalOpenCols) + "'> </td>";
}
}
monthCell += "<td colspan='" + monthOpenCols + "' style='text-align:center;padding-left:none !important; padding-right:none !important;border-left:none !important;border-right:none !important;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
//monthOpen = (totalOpenCols < 4);
continue;
}
//if ((AreDatesEqual(bookingStartDate, monthStartDate) && bookingEndDate < monthEndDate) || (bookingStartDate > monthStartDate && AreDatesEqual(bookingEndDate, monthEndDate))) {//Booking starting in current month and ending in current month
if (bookingStartDate >= monthStartDate && bookingEndDate <= monthEndDate) {//Booking starting in current month and ending in current month
monthOpen = true;
monthOpenCols = GetColSpan(monthEndDate.getDate(), (bookingEndDate.getDate() - bookingStartDate.getDate()));
totalOpenCols += monthOpenCols;
monthCell += "<td colspan='" + monthOpenCols + "' style='text-align:center;padding-left:none !important; padding-right:none !important;' class='" + cellClass + "' onclick='EditBookingById(" + bookings[j].bookingId + ");' >" + bookings[j].bookingDesc + "</td>";
monthOpen = (totalOpenCols < 4);
continue;
}
}
//if we get here and still have an open month...close it
if (monthOpen) { monthCell += "<td colspan='" + (4 - totalOpenCols) + "'> </td>"; }
if (monthCell == "" && (i == 0 || i == 1 || i == 10 || i == 11) && reserveWinterMonths) {
row += "<td colspan='4' class='statusClass6'>Cold Weather Restrictions may apply</td>";
} else {
row += (monthCell == "" ? "<td colspan='4'> </td>" : monthCell);
}
}
return row;
}
|
/**
*Client side vote logic. Take a look at the vote.ctp file
*to see all the html.
*/
//No javascript trim function? Puh-leeze
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
//These are the up and down vote arrow images that
//change when the user upvotes or downvotes
up = '/img/up_arrow.gif';
down = '/img/down_arrow.gif';
upred = '/img/up_arrow_red.gif';
downred = '/img/down_arrow_red.gif';
function alreadyVoted(type, id){
voted = type == 'up' && $('#upvoteimg'+id).attr('src') == upred
|| type == 'down'&& $('#downvoteimg'+id).attr('src') == downred;
return voted;
}
function vote(type, model, id){
if(alreadyVoted(type, id))
return;
$.post('/votes/vote/'+type+'/'+model+'/'+id, function(data){
//Nothing here yet
});
}
function getHtmlId(type, id){
var imgid;
if(type == "up"){
imgid = '#upvoteimg';
}
else{
imgid = '#downvoteimg'
}
return imgid += id;
}
function changeVoteDisplay(type, id){
if(alreadyVoted(type,id))
return;
points = $('#points'+id ).html().trim();
points = parseInt(points) + (type == 'up' ? 1 : -1);
$('#points'+id).html(points + " points | by ");
$('#upvoteimg'+id).attr('src', up);
$('#downvoteimg'+id).attr('src', down);
src = type == "up" ? upred : downred;
imgid = getHtmlId(type,id);
$(imgid).attr('src', src);
}
$(document).ready(function(){
//The up/down vote id(s) are in the form 'upvote(N)' or 'downvote(N)' where (N) is the
//id of the model object the user is voting on. This convention is followed for
//points(N) and images so you'll see this type of replace in several places.
$('.upvote').click(function(){
if(bailIfNotLoggedIn())
return;
var modelid = $(this).attr('id').replace("upvote","");
vote("up", model, modelid);
changeVoteDisplay('up', modelid);
});
$('.downvote').click(function(){
if(bailIfNotLoggedIn())
return;
var modelid = $(this).attr('id').replace("downvote","");
vote("down", model, modelid);
changeVoteDisplay('down', modelid);
});
});
|
import React from 'react';
import classes from './NavigationItems.css';
import Aux from '../../../hoc/Aux/Aux';
import NavigationItem from './NavigationItem/NavigationItem';
const navigationItems = (props) =>(
<ul className={classes.NavigationItems}>
<NavigationItem link="/" onClick={props.closeDrawer} exact>Burger Builder</NavigationItem>
{props.isAuthenticated
? <Aux>
<NavigationItem onClick={props.closeDrawer} link="/orders">Orders</NavigationItem>
<NavigationItem onClick={props.closeDrawer} link="/logout"> Logout </NavigationItem>
</Aux>
: <NavigationItem onClick={props.closeDrawer} link="/auth"> Login / Signup </NavigationItem> }
</ul>
);
export default navigationItems;
|
angular.module('app.component2', ['ngRoute', 'app.component2.templates', 'ui.bootstrap'])
.config(function($routeProvider) {
'use strict';
$routeProvider.when('/component-2/dialog-b', {
templateUrl: 'component-2/dialog-b/dialog-b.html',
controller: 'MySecondController'
});
});
|
//The color of the enemy, starts out either red, yellow, or blue
var color : Color = Color.white;var friend : GameObject;
var width : float;
var height : float;
var dirx : int = 1;
var diry : int = 1;
private var size : float = 0.4;
//The speed at which the object rotates around its center
var ROTATE_SPEED : int = 50;
//The sprite renderer component of this object
var sprite : SpriteRenderer;
function Start () {
width = Camera.main.ViewportToWorldPoint(Vector3(1, 1, 10)).x;
height = Camera.main.ViewportToWorldPoint(Vector3(1, 1, 10)).y;
if (Mathf.Round(Random.value) == 1)
dirx = -1;
if (Mathf.Round(Random.value) == 1)
diry = -1;
}
function Update () {
transform.RotateAround(transform.position, transform.forward, ROTATE_SPEED * Time.deltaTime);
if (transform.position.x > width - size) {
dirx *= -1;
transform.position.x = width - size;
}
else if (transform.position.x < -width + size) {
dirx *= -1;
transform.position.x = -width + size;
}
if (transform.position.y > height - size) {
diry *= -1;
transform.position.y = height - size;
}
else if (transform.position.y < -height + size) {
diry *= -1;
transform.position.y = -height + size;
}
transform.position.x += Time.deltaTime * dirx;
transform.position.y += Time.deltaTime * diry;
}
function SetColor (num : int) {
switch (num) {
case 0: color = player_controller.red;
break;
case 1: color = player_controller.yellow;
break;
case 2: color = player_controller.blue;
break;
default: break;
}
sprite.color = color;
}
|
'use strict';
angular.module('spedycjacentralaApp')
.controller('EmployeePersonalDataController', function ($scope, $state, $modal, EmployeePersonalData) {
$scope.employeePersonalDatas = [];
$scope.loadAll = function() {
EmployeePersonalData.query(function(result) {
$scope.employeePersonalDatas = result;
});
};
$scope.loadAll();
$scope.refresh = function () {
$scope.loadAll();
$scope.clear();
};
$scope.clear = function () {
$scope.employeePersonalData = {
startDate: null,
endDate: null,
firstName: null,
lastName: null,
address: null,
id: null
};
};
});
|
/*
* @lc app=leetcode.cn id=34 lang=javascript
*
* [34] 在排序数组中查找元素的第一个和最后一个位置
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
const getLefBorder = () => {
// [left, right]
let left = 0,
right = nums.length - 1;
while (left <= right) {
let mid = Math.ceil(left + (right - left) / 2);
// if mid < left, then left = mid +1
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
// the loop break logic is left > right, so if the mid is the left border
// right = mid - 1 and left will be the correct one
} else if (nums[mid] === target) {
right = mid - 1;
}
}
if (left >= nums.length) return -1;
return nums[left] === target ? left : -1;
};
const getRightBorder = () => {
// [left, right]
let left = 0,
right = nums.length - 1;
while (left <= right) {
let mid = Math.ceil(left + (right - left) / 2);
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] === target) {
left = mid + 1;
}
}
if (left - 1 < 0) return -1;
return nums[left - 1] === target ? left - 1 : -1;
};
return [getLefBorder(), getRightBorder()];
};
// @lc code=end
|
'use strict';
var fs = require('fs');
var turf = require('turf');
var applyFilter = require('../applyFilter.js');
var analytics = JSON.parse(fs.readFileSync(global.mapOptions.analyticsPath));
analytics.experienceFields.forEach(function(field) {
field.filter = applyFilter(field.filter);
});
// Filter features touched by list of users defined by users.json
module.exports = function(tileLayers, tile, writeData, done) {
var layer = tileLayers.osm.osm;
var users = {};
layer.features.forEach(function(val) {
var userId = val.properties['_uid'];
if (!users[userId]) {
var emptyExperienceObject = { objects:0 };
analytics.experienceFields.forEach(function(experience) {
emptyExperienceObject[experience.name] = 0;
});
users[userId] = emptyExperienceObject;
}
users[userId].objects += 1;
analytics.experienceFields.filter(function(field) {
//console.error(field.filter(val), field, val)
return field.filter(val);
}).forEach(function(experience) {
switch (experience.metric) {
case "count":
users[userId][experience.name] += 1;
break;
case "length":
if (val.geometry.type === "LineString" || val.geometry.type === "MultiLineString")
users[userId][experience.name] += turf.lineDistance(val, "kilometers");
break;
case "area":
if (val.geometry.type === "Polygon" || val.geometry.type === "MultiPolygon")
users[userId][experience.name] += turf.area(val);
break;
}
});
});
done(null, users);
};
|
import React from 'react';
const SocialNetworks = ({color}) => {
const icoColor = color === "white" ? "text-white" : "text-dark";
return (
<ul className="list-inline social-networks">
<li className="list-inline-item"><a href=" "><i className={`tf-ion-social-facebook ${icoColor}`}></i></a></li>
<li className="list-inline-item"><a href=" "><i className={`tf-ion-social-twitter ${icoColor}`}></i></a></li>
<li className="list-inline-item"><a href=" "><i className={`tf-ion-social-linkedin ${icoColor}`}></i></a></li>
<li className="list-inline-item"><a href=" "><i className={`tf-ion-social-pinterest ${icoColor}`}></i></a></li>
<li className="list-inline-item"><a href=" "><i className={`tf-ion-social-rss ${icoColor}`}></i></a></li>
</ul>
);
};
export default SocialNetworks;
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/gridfstest');
var conn = mongoose.connection;
var multer = require('multer');
var GridFsStorage = require('multer-gridfs-storage');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs = Grid(conn.db);
var ursa = require('ursa');
var fs = require('fs');
var encoding = 'base64';
//Private key of this node is inside the keys folder, generated by keygen.js
var priv = ursa.createPrivateKey(fs.readFileSync('./keys/privkey.pem'));
/*encryption variables*/
var fs = require('fs');
var crypto = require('crypto');
var algorithm = 'aes-256-cbc';
function encrypt(name, res) {
//key to encode the original file
var key = '14189dc35ae35e75ff31d7502e245cd9bc7803838fbfd5c773cdcd79b8a28bbd';
var sha_hash;
var id;
var cipher = crypto.createCipher(algorithm, key);
var file;
gfs.collection('ctFiles');
//fetching the original uploaded file
gfs.files.find({"filename" : name }).toArray(function(err, files) {
if(!files || files.length === 0) {
console.log("File not correctly uploaded");
}
var input = gfs.createReadStream({
filename: files[0].filename,
root: "ctFiles"
});
var output = fs.createWriteStream(files[0].filename+'.enc');
//encoding the original file
input.pipe(cipher).pipe(output);
output.on('finish', function() {
console.log('Encrypted file written to disk!');
/*var key_cipher = crypto.createCipher(algorithm, private_key);
var input_key = key;
var encrypted_key = key_cipher.update(input_key,'utf8','hex');
encrypted_key += key_cipher.final('hex');*/
//encrypting the key with receiver's public key
var pub = ursa.createPublicKey(fs.readFileSync('./pubkey.pem'));
var data = new Buffer(key, 'ascii');
var encrypted_key = pub.encrypt(data).toString('base64');
//creating sha-hash of the encrypted file
var algo = 'sha256';
var shasum = crypto.createHash(algo);
file = name+'.enc';
var s = fs.ReadStream(file);
s.on('data', function(d) { shasum.update(d); });
s.on('end', function() {
var d = shasum.digest('hex');
console.log(d);
sha_hash = d;
//uploading the encrypted file to database
var read_stream = fs.createReadStream(file);
var writestream = gfs.createWriteStream(
{filename: file,
contentType: "text/plain",
metadata: {originalname: file},
root: 'ctFiles'});
read_stream.pipe(writestream);
console.log(file);
writestream.on("finish",function() {
gfs.collection('ctFiles');
//fetching object-id of the encrypted file form mongodb
gfs.files.find({"filename": file}).toArray(function(err, files){
if(!files || files.length === 0){
console.log("encrypted file not uploaded: "+err);
}
id = files[0]._id;
console.log(files[0]);
//sending the information to response
var array = new Array(3);
array[0]=sha_hash; array[1]=id; array[2]=encrypted_key;
res.json({"error_code":0,"err_desc":null,"hash":array[0],"id":array[1],"key":array[2]});
});
});
});
});
});
}
//View received file and decrypt to display the original file
app.get('/received_file', function(req, res){
gfs.collection('ctFiles'); //set collection name to lookup into
var object = JSON.parse(req.query.object);
console.log(object.id);
var id = new mongoose.mongo.ObjectId(object.id);
/*var key_decipher = crypto.createDecipher(algorithm, public_key);
var input_key = object.key;
var decrypted_key = key_decipher.update(input_key,'hex','utf8');
decrypted_key += key_decipher.final('utf8');*/
//decrypting the received key with own private key
var decrypted_key = priv.decrypt(object.key,'base64').toString('ascii');
// First check if file exists
gfs.files.find({"_id": id}).toArray(function(err, files){
if(!files || files.length === 0){
console.log("File not found");
}
console.log(files[0]);
var read_stream = gfs.createReadStream({_id: id, root: 'ctFiles'});
var decipher = crypto.createDecipher(algorithm, decrypted_key);
//decipher the file and set to response
return read_stream.pipe(decipher).pipe(res);
});
});
/** Seting up server to accept cross-origin browser requests */
app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*"); //to enable CORS
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
/** Setting up storage using multer-gridfs-storage */
var storage = GridFsStorage({
gfs : gfs,
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
},
/** With gridfs we can store aditional meta-data along with the file */
metadata: function(req, file, cb) {
cb(null, { originalname: file.originalname });
},
root: 'ctFiles' //root name for collection to store files into
});
var upload = multer({ //multer settings for single upload
storage: storage
}).single('fil');
//save receiver's Public Key in pubkey.pem file
app.post('/public_key', function(req, res){
// console.log(req.body);
var obj = JSON.parse(JSON.stringify(req.body));
console.log(obj.key);
var temp = obj.key;
fs.writeFile("pubkey.pem", temp, function(err){
if (err) throw err;
console.log("success");
});
});
/** API path that will upload the files */
app.post('/upload', function(req, res) {
// console.log(req);
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
//next(err);
return;
}
var document_name = req.file.filename;
encrypt(document_name, res);
});
});
app.get('/file/:filename', function(req, res){
gfs.collection('ctFiles'); //set collection name to lookup into
/** First check if file exists */
gfs.files.find({filename: req.params.filename}).toArray(function(err, files){
if(!files || files.length === 0){
return res.status(404).json({
responseCode: 1,
responseMessage: "error"
});
}
/** create read stream */
var readstream = gfs.createReadStream({
filename: files[0].filename,
root: "ctFiles"
});
/** set the proper content type */
res.set('Content-Type', files[0].contentType)
/** return response */
return readstream.pipe(res);
});
});
app.listen('3002', function(){
console.log('running on 3002...');
});
|
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Form, Input, Select, Button, AutoComplete, notification, Row, Col } from 'antd';
import { updatePersonalInfo } from '@common/api.js'
import Upload from '@components/upload/index';
import Style from './index.module.less';
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const AutoCompleteOption = AutoComplete.Option;
@inject('rootStore')
@Form.create()
@observer
class EditAccounts extends Component {
state = {
confirmDirty: false,
autoCompleteResult: [],
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll(async (err, values) => {
if (!err) {
let params = {}
Object.keys(values).forEach((index) =>{
if (!!values[index]) params[index] = values[index];
if (index === 'sex' && [0, 1].includes(values[index])) {
params[index] = values[index];
}
});
let response = await updatePersonalInfo(params);
notification['success']({
message: response.message,
});
console.log('Received values of form: ', values, params);
this.props.rootStore.dataStore.changeUserInfo(values);
}
});
}
handleWebsiteChange = (value) => {
let autoCompleteResult;
if (!value) {
autoCompleteResult = [];
} else {
autoCompleteResult = ['.com', '.org', '.net', '.cn'].map(domain => `${value}${domain}`);
}
this.setState({ autoCompleteResult });
}
changeAvatarCb = async (avatarUrl) => {
let info = {
avatarUrl,
};
let response = await updatePersonalInfo(info);
notification.success({
message: response.message,
});
this.props.rootStore.dataStore.changeAvatarUrl(avatarUrl);
}
render() {
const { getFieldDecorator } = this.props.form;
const { autoCompleteResult } = this.state;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
const prefixSelector = getFieldDecorator('prefix', {
initialValue: '86',
})(
<Select style={{ width: 70 }}>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
);
const websiteOptions = autoCompleteResult.map(website => (
<AutoCompleteOption key={website}>{website}</AutoCompleteOption>
));
let { userInfo } = this.props.rootStore.dataStore;
return (
<section className={Style['edit-accounts']}>
<Row className={Style['header']}>
<Col span={8}>
<span className={` ${Style['avatar']} fl-right`} style={{ 'backgroundImage': `url(${userInfo.avatarUrl})`}}></span>
</Col>
<Col span={16}>
<div className={Style['username']}>{userInfo.account}</div>
<div className={Style['notice']}>更换头像<Upload successCb={this.changeAvatarCb} className={Style['notice']} /></div>
</Col>
</Row>
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label={(
<span className={Style['form-item-label']}>姓名</span>
)}
>
{getFieldDecorator('username', {
rules: [{ required: true, message: '请输入用户名', whitespace: true }],
initialValue: userInfo.username
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label={(
<span className={Style['form-item-label']}>网站</span>
)}
>
{getFieldDecorator('website', {
rules: [{ required: false, message: '请输个人网站' }],
initialValue: userInfo.website,
})(
<AutoComplete
dataSource={websiteOptions}
onChange={this.handleWebsiteChange}
>
<Input />
</AutoComplete>
)}
</FormItem>
<FormItem
{...formItemLayout}
label={(
<span className={Style['form-item-label']}>个人简介</span>
)}
>
{getFieldDecorator('abstract', {
rules: [{
required: false, message: '请输入个人简介'
}],
initialValue: userInfo.abstract
})(
<TextArea placeholder="请输入个人简介" autosize={{ minRows: 2, maxRows: 6 }} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label={(
<span className={Style['form-item-label']}>邮箱</span>
)}
>
{getFieldDecorator('email', {
rules: [{
type: 'email', message: '邮件格式不正确',
}],
initialValue: userInfo.email,
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label={(
<span className={Style['form-item-label']}>手机号</span>
)}
>
{getFieldDecorator('mobile', {
rules: [{ required: false, message: '请输入手机号' }],
initialValue: userInfo.mobile
})(
<Input addonBefore={prefixSelector} style={{ width: '100%' }} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label={(
<span className={Style['form-item-label']}>性别</span>
)}
>
{getFieldDecorator('sex', {
rules: [{ required: false, message: '请输入性别' }],
initialValue: [0, 1].includes(userInfo.sex) ? userInfo.sex : '',
})(
<Select>
<Option value={0}>男</Option>
<Option value={1}>女</Option>
</Select>
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit">更新</Button>
</FormItem>
</Form>
</section>
);
}
}
export default EditAccounts;
|
import * as OrderController from "./../controllers/order";
import * as OrderItemController from "./../controllers/order_item";
import { Router } from "express";
const router = new Router();
router.get("/", OrderController.getAllOrders);
router.post("/", OrderController.createOrder);
router.get("/:order_id", OrderItemController.getAllOrderItems);
router.post("/:order_id", OrderItemController.createOrderItems);
router.patch("/:order_id", OrderController.updateOrder);
router.delete("/:order_id", OrderController.deleteOrder);
router.delete("/:order_id/:item_id", OrderItemController.deleteOrderItem);
router.patch("/:order_id/:item_id", OrderItemController.updateOrderItem);
export default router;
|
/*
* @file webpack config for development
* @author nighca <nighca@live.cn>
*/
module.exports = require('./common').then(
config => {
config = require('./addons/sourcemap')(config)
config = require('./addons/define-env')(config, 'development')
return config
}
)
|
class Node {
constructor(key) {
this.key = key;
this.height = 1; // the height of the current node. Each node has a height of at least 1 plus the height of it's tallest child.
this.size = 1; // the number of nodes that are children/grandchildren of the current node. Each node will have a size of at least 1 plus the size of it's children combined.
this.left = null;
this.right = null;
}
insert(key) {
if (key < this.key && this.left) {
this.left.insert(key);
} else if (key < this.key) {
this.left = new Node(key);
}
if (key > this.key && this.right) {
this.right.insert(key);
} else if (key > this.key) {
this.right = new Node(key);
}
}
search(key) {
if (this.key === key) {
return this;
}
if (key < this.key && this.left) {
return this.left.search(key);
} else if (key > this.key && this.right) {
return this.right.search(key);
} else {
return null;
}
}
}
let bst = new Node(10);
bst.insert(9);
bst.insert(6);
bst.insert(12);
console.log(bst);
console.log(bst.find(12));
//console.log(bst.search(16));
|
import * as types from '../actions/actionTypes'
import initialState from '../store/initialState'
export default function reducer(state = initialState, action) {
debugger
switch(action.type) {
case types.UPDATE_RANDOM_GUID :
return {...state, guid: action.guid}
case types.UPDATE_FORM_FIELD:
return {...state, [action.name]: action.value}
default:
return {...state};
}
}
|
/**
* Vuetify theme options.
*/
import { userAdmin, userEditor } from '@/api/mock';
/**
* Login by email and password
*
* @param {String} email user email
* @param {String} password user password
*/
export const loginByEmail = async (email, password) => {
console.log(`[loginByEmail] email ${email}`);
let user = {};
try {
if (userEditor.email === email && userEditor.password === password) {
user = userEditor;
} else if (userAdmin.email === email && userAdmin.password === password) {
user = userAdmin;
}
if (!user || !user.token) {
throw new Error('User is not found');
}
} catch (err) {
console.warn(`[loginByEmail] ${err}`);
}
return { user };
};
/**
* Get user information by token
*
* @param {String} token user token
*/
export const getUserInfo = async (token) => {
console.log(`[getUserInfo] token ${token}`);
let user = {};
try {
if (!token) {
throw new Error('Invalid token');
}
if (token === userAdmin.token) {
user = userAdmin;
} else {
user = userEditor;
}
} catch (err) {
console.warn(`[getUserInfo] ${err}`);
}
return { user };
};
|
(function(){
var HorB=$(document.documentElement);
var title=$(".wraptitle .title");
var floatArea=$(".wraptitle .floatArea");
var fa=$(".floatArea .part2 a");
var pa=$(".previewCatalog dd");
/*左侧章节点击效果类名*/
/* var a=$(".template3 .article .side .previewCatalog dl dd a").eq(0)[0].className;
var arr=a.split(" ");
var changedStyle=arr[1];
*/
/*浮动条显隐*/
$(window).scroll(function()
{
var sTop=document.documentElement.scrollTop || document.body.scrollTop;
if(HorB.width()>1046)
{
if(sTop>=350)
{
title.css("visibility","hidden");
floatArea.slideDown(200);
}
if(sTop<350)
{
title.css("visibility","visible");
floatArea.slideUp(200);
}
}
})
/*浮动章节跳动事件*/
fa.click(function()
{
var index=fa.index(this);
syncStyle(index)
})
/*左侧固定章节跳动*/
pa.click(function()
{
var index=pa.index(this);
pa.removeClass("t3-sideContentCurrent");
pa.eq(index).addClass("t3-sideContentCurrent");
syncStyle(index)
})
/*浮动章节跳动事件*/
function syncStyle(index)
{
pa.removeClass("t3-sideContentCurrent");
pa.eq(index).addClass("t3-sideContentCurrent");
fa.removeClass("current");
fa.eq(index).addClass("current");
ChapterPos(index);
}
/*章节定位到顶部一定位置函数*/
function ChapterPos(index)
{
var obj=$(".chapter").eq(index).offset();
/*标准模式与兼容模式*/
if(document.body.scrollTop)
{
$(document.body).animate({scrollTop:obj.top-90},200);
}
else
{
$(document.documentElement).animate({scrollTop:obj.top-90},200);
}
}
//章节条目收起与展开
var itemx=$(".template3 .article .catalog .paragraph .chapter .item");
var frame=itemx.children(".frame");
var time=200;
itemx.click(function()
{
if($(this).children(".frame").css("display")!="block")
{
frame.slideUp(time);
$(this).children(".frame").slideDown(time);
}
})
/*窗口大小变动浮动显隐*/
$(window).resize(function()
{
var sTop=document.documentElement.scrollTop || document.body.scrollTop;
if(HorB.width()<=1046)
{
title.css("visibility","visible");
floatArea.css("display","none");
}
else
{
if(sTop>=350)
{
title.css("visibility","hidden");
floatArea.css("display","block");
}
else
{
title.css("visibility","visible");
floatArea.css("display","none");
}
}
})
})()
|
import React, {Component} from 'react';
import {Row, Col} from 'reactstrap';
class Footer extends Component {
render() {
return (
<footer className="app-footer">
<div className="container">
<Row>
<Col>
<span> © 2020 ParkZeus | All Rights Reserved</span>
</Col>
<Col className="text-right">
<span> Version 1.0.0</span>
</Col>
</Row>
</div>
</footer>
)
}
}
export default Footer;
|
/**
* Created by nisabhar on 3/11/2016.
*/
define(['jquery', 'pcs/util/pcsUtil'],
function($, pcsUtil) {
'use strict';
function StartformDataService() {
var self = this;
var loggerUtil = require('pcs/util/loggerUtil');
self.paths = {
// For getting the formURL and attachments for a form
'startForm': 'process-definitions/',
// For submitting and saving a process instance
'createProcessInstance': 'processes',
// For getting the start folder name
'startFolderName': 'process-definitions/{0}/startFolderName',
//Excetue PCS form
'executePCSFormRest': 'webforms/{formDefId}/executeRest/{restExecutionId}',
//DP form
'createDPInstance': 'dp-instances?processDefinitionId={processDefinitionId}'
};
// get to array buffer for binary data. Must be used for attachments
var doGetToArrayBuffer = function(url, callback, errorCallback) {
url = url + "&uncache=" + new Date().getTime();
var oReq = new XMLHttpRequest();
oReq.withCredentials = true;
oReq.onload = callback;
oReq.onerror = errorCallback;
oReq.open('GET', url, true);
oReq.responseType = 'arraybuffer';
var authToken = pcsUtil.getAuthInfo();
if(authToken) {
oReq.setRequestHeader('Authorization', authToken);
}
if (pcsUtil.isTestMode()) {
oReq.setRequestHeader('pcs_mode', 'dev');
}
oReq.send();
return oReq;
};
//callback to set authorization request header for every call
var beforeRequestCallback = function(xhr) {
pcsUtil.beforeRequestCallback(xhr,pcsUtil);
};
// wrapper function for HTTP GET
var doGet = function(url, dataType) {
return $.ajax({
type: 'GET',
url: url,
beforeSend: beforeRequestCallback,
xhrFields: {
withCredentials: true
},
contentType: 'multipart/form-data',
dataType: dataType,
cache: false
});
};
// wrapper function for HTTP POST
var doPost = function(url, payload, contentType) {
var bytes = new Uint8Array(payload.length);
for (var i = 0; i < payload.length; i++) {
bytes[i] = payload.charCodeAt(i);
}
return $.ajax({
type: 'POST',
url: url,
cache: false,
processData: false,
data: bytes,
beforeSend: beforeRequestCallback,
xhrFields: {
withCredentials: true
},
contentType: contentType,
});
};
var doRestGet = function(url, params, contentType) {
return $.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: params,
beforeSend: beforeRequestCallback,
xhrFields: {
withCredentials: true
},
contentType: contentType,
cache: false
});
};
// wrapper function for HTTP POST
var doRestPost = function(url, payload, contentType) {
//Dummy ADF call
pcsUtil.adfProxyCall();
loggerUtil.log(payload);
return $.ajax({
type: 'POST',
url: url,
//cache : false,
//processData : false,
data: payload,
contentType: contentType,
dataType: 'json',
beforeSend: function(xhr) {
var authToken = pcsUtil.getAuthInfo();
if(authToken) {
xhr.setRequestHeader('Authorization', authToken);
}
if (pcsUtil.isTestMode()) {
xhr.setRequestHeader('pcs_mode', 'dev');
}
},
xhrFields: {
withCredentials: true
}
});
};
var replacePlaceHolders = function(str, paramsObj) {
return str.replace(/{\w+}/g,
function(placeHolder) {
return paramsObj[placeHolder];
}
);
};
//To get the startForm object to get the list of attachemnts and frevvo form URL
self.getStartFormObject = function(processDefId, serviceName, operation, startType, callback, errorCallback) {
var formType;
if (startType && startType === 'START_PCS_FORM') {
formType = 'webform';
} else {
formType = 'form';
}
var serverPath = pcsUtil.getRestURL() + self.paths.startForm + processDefId + '/' + serviceName + '/' + formType + '?operation=' + operation;
doGetToArrayBuffer(serverPath, callback, errorCallback);
};
self.getFormMetaDataByURL = function(formMetadataUrl) {
return doGet(formMetadataUrl, 'json');
};
self.executePCSFormRest = function(params, payload) {
var serverPath = pcsUtil.getRestURL() + self.paths.executePCSFormRest;
serverPath = replacePlaceHolders(serverPath, params);
return doPost(serverPath, payload, 'application/json');
};
self.executeRest = function(restAPI, payload) {
var serverPath = pcsUtil.getRestURL() + restAPI;
return doRestGet(serverPath, payload, 'application/json');
};
// To get the current payload of the frevvo form
self.getFormPayload = function(processDefId, serviceName, operation, formURL) {
var serverPath = pcsUtil.getRestURL() + self.paths.startForm + processDefId + '/' + serviceName + '/form/payload?operation=' + operation + '&formInstanceURL=' + formURL;
return doGet(serverPath, 'text');
};
// to submit or save a process instance
self.createProcessInstance = function(payload, contentType) {
var serverPath = pcsUtil.getRestURL() + self.paths.createProcessInstance;
return doPost(serverPath, payload, contentType);
};
//To get the startFolderName
self.getStartFolderName = function(processDefId) {
var serverPath = pcsUtil.getRestURL() + self.paths.startFolderName.replace('{0}', processDefId);
return doGet(serverPath, 'text');
};
self.createDPInstance = function(params, payload) {
var serverPath = pcsUtil.getDpRestURL() + self.paths.createDPInstance;
serverPath = replacePlaceHolders(serverPath, params);
return doRestPost(serverPath, payload, 'application/json');
};
}
return new StartformDataService();
}
);
|
define(['apps/system2/docquery/docquery', 'apps/system2/docquery/docquery.service'], function (app) {
app.module.controller("docquery.controller.myarchive", function ($scope, stdApiUrl,stdApiVersion, $uibModal, $filter, docqueryService) {
$scope.downloadUrl = stdApiUrl + stdApiVersion;
docqueryService.getMyArchiveBorrow().then(function (result) {
$scope.myBorrowList = result;
});
$scope.setCurrentItem = function (item) {
$scope.currentItem = item;
$scope.archiveFields = item.ArchiveInfo.HasVolume ? item.ArchiveInfo.VolumeFields : item.ArchiveInfo.BoxFields;
}
$scope.$watch("currentItem", function (newval, oldval) {
if (newval) {
loadArchiveInfo(newval.ArchiveType, newval.Fonds, newval.ArchiveID);
}
})
$scope.giveBack = function (item) {
docqueryService.giveBack(item.BorrowID).then(function () {
item.Status = 4;
})
}
var loadArchiveInfo = function (type, fonds, id) {
docqueryService.getArchiveVolumeData({
ids: id,
fonds: fonds,
archive: type
}).then(function (result) {
if (result.Source && result.Source.length > 0) {
$scope.volumeInfo = result.Source[0];
if ($scope.volumeInfo.ProjectID > 0) {
docqueryService.getProjInfo($scope.volumeInfo.ProjectID).then(function (projInfo) {
$scope.projInfo = projInfo;
});
}
}
});
docqueryService.getArchiveFileData({
volume: id,
fonds: fonds,
archive: type
}).then(function (result) {
$scope.archiveFiles = result.Source;
});
docqueryService.getArchiveLog(fonds, type, id).then(function (datas) {
$scope.currentArchiveLogs = datas;
});
}
$scope.getFiledValue = function (source, field) {
if (source) {
switch (field.DataType) {
case 3: return $filter('TDate')(source["_f" + field.ID]);
case 4: return $filter('enumMap')(source["_f" + field.ID], field.BaseData);
default: return source["_f" + field.ID];
}
}
}
$scope.getMainFileName = function (item) {
var files = $scope.currentItem.ArchiveInfo.FileFields.where(f => f.Main);
if (files.length > 0) {
return files.map(f => item["_f" + f.ID]).join('-');
} else {
return item._f1;
}
}
});
});
|
export const FETCH_HOME = 'FETCH_HOME';
export const REQUEST_LOADING_HOME = 'REQUEST_LOADING_HOME';
export const REQUEST_REJECTED_HOME = 'REQUEST_REJECTED_HOME';
|
import React from 'react';
const TerminatorWars = () => (
<section id="terminator-section">
<span class="green-verbage">Terminator Wars</span>
<span class="white-verbage">Scenario Game</span>
</section>
);
export default TerminatorWars;
|
//style of inputs
$(document).ready(function () {
$('input').blur(function () {
if ($(this).val())
$(this).addClass('used');
else
$(this).removeClass('used');
});
$('textarea').blur(function () {
if ($(this).val())
$(this).addClass('used');
else
$(this).removeClass('used');
});
});
//scroll links
let linkHome = document.querySelector("#linkHome")
let linkPort = document.querySelector("#linkPort")
let linkContact = document.querySelector("#linkContact")
let projetc = document.querySelector("#projects")
let contact = document.querySelector("#contact")
function offset(el) {
var rect = el.getBoundingClientRect()
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return rect.top + scrollTop - 200
}
window.addEventListener("scroll", function (event) {
var scroll = this.scrollY
if (scroll < offset(projetc)) {
linkHome.classList.add("open")
} else {
linkHome.classList.remove("open")
}
if (scroll > offset(projetc) && scroll < offset(contact)) {
linkPort.classList.add("open")
} else {
linkPort.classList.remove("open")
}
if (scroll > offset(contact)) {
linkContact.classList.add("open")
} else {
linkContact.classList.remove("open")
}
})
//snackbar
const Divresult = document.querySelector("#resultado")
function showResult(result, status){
Divresult.innerHTML = result
Divresult.classList.add(status)
Divresult.classList.add("active")
setTimeout(function () {
Divresult.classList.remove('active');
Divresult.classList.remove(status);
}, 3000)
}
//ajax to send email
document.contact__form.onsubmit = async e => {
e.preventDefault()
const form = e.target
const data = new FormData(form)
const options = {
method: form.method,
body: new URLSearchParams(data)
}
/*
fetch(form.action, options)
.then(resp => console.log(resp))
*/
console.log(form.action)
fetch(form.action, options)
.then(response => response.text())
.then(function(result){
console.log(result)
showResult(result, "then")
})
.catch(function(err){
showResult(err, "erro")
console.log(err)
})
}
|
import mongoose from "mongoose";
import Post from "./post.js";
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: { type: String, unique: true },
password: String,
posts: {
type: [{ type: Schema.Types.ObjectId, ref: "Post" }],
default: [],
},
});
/* Remove all posts created by the user in the Post collection */
UserSchema.post("findOneAndDelete", async (doc) => {
if (!doc) return;
try {
for (let postId of doc.posts) {
await Post.findByIdAndDelete(postId);
}
} catch (error) {
console.log(error);
}
});
export default mongoose.model("User", UserSchema);
|
/*
Santa is coming to town and he needs your help finding out who's been naughty or nice. You will be given an entire year of JSON data following this format:
{
January: {
'1': 'Naughty','2': 'Naughty', ..., '31': 'Nice'
},
February: {
'1': 'Nice','2': 'Naughty', ..., '28': 'Nice'
},
...
December: {
'1': 'Nice','2': 'Nice', ..., '31': 'Naughty'
}
}
Your function should return "Naughty!" or "Nice!" depending on the total number of occurrences in a given year (whichever one is greater).
If both are equal, return "Nice!"
*/
function naughtyOrNice(data) {
var year = data;
var naughtyAmount = 0;
var niceAmount = 0;
for (var month in year) {
var dates = year[month];
for (var date in dates) {
var behavior = dates[date];
behavior === "Naughty" ? naughtyAmount += 1 : niceAmount += 1;
}
}
return niceAmount >= naughtyAmount ? "Nice!" : "Naughty!";
}
|
import React, {Component} from 'react'
// import productList from '../components/productlist'
// import Footer from '../components/footer'
import Productlist from '../components/productlist'
class Home extends Component {
render(){
return(
<div>
<section class="banner-area">
<div class="container">
<div class="row fullscreen align-items-center justify-content-start">
<div class="col-lg-12">
<div class="active-banner-slider owl-carousel">
{/* <!-- single-slide --> */}
<div class="row single-slide align-items-center d-flex">
<div class="col-lg-5 col-md-6">
<div class="banner-content">
<h1>Nike New <br/>Collection!</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.</p>
<div class="add-bag d-flex align-items-center">
<a class="add-btn" href="#"><span className="lnr lnr-cross"></span></a>
<span class="add-text text-uppercase">Add to Bag</span>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="banner-img">
<img class="img-fluid" src="img/banner/banner-img.png" alt=""/>
</div>
</div>
</div>
{/* <!-- single-slide --> */}
<div class="row single-slide">
<div class="col-lg-5">
<div class="banner-content">
<h1>Nike New <br/>Collection!</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.</p>
<div class="add-bag d-flex align-items-center">
<a class="add-btn" href="#"><span class="lnr lnr-cross"></span></a>
<span class="add-text text-uppercase">Add to Bag</span>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="banner-img">
<img class="img-fluid" src="img/banner/banner-img.png" alt=""/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{/* <!-- start features Area --> */}
<section class="features-area section_gap">
<div class="container">
<div class="row features-inner">
{/* <!-- single features --> */}
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-features">
<div class="f-icon">
<img src="img/features/f-icon1.png" alt=""/>
</div>
<h6>Free Delivery</h6>
<p>Free Shipping on all order</p>
</div>
</div>
{/* <!-- single features --> */}
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-features">
<div class="f-icon">
<img src="img/features/f-icon2.png" alt=""/>
</div>
<h6>Return Policy</h6>
<p>Free Shipping on all order</p>
</div>
</div>
{/* <!-- single features --> */}
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-features">
<div class="f-icon">
<img src="img/features/f-icon3.png" alt=""/>
</div>
<h6>24/7 Support</h6>
<p>Free Shipping on all order</p>
</div>
</div>
{/* <!-- single features --> */}
<div class="col-lg-3 col-md-6 col-sm-6">
<div class="single-features">
<div class="f-icon">
<img src="img/features/f-icon4.png" alt=""/>
</div>
<h6>Secure Payment</h6>
<p>Free Shipping on all order</p>
</div>
</div>
</div>
</div>
</section>
{/* <!-- end features Area --> */}
{/* <!-- Start category Area --> */}
<section class="category-area">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-12">
<div class="row">
<div class="col-lg-8 col-md-8">
<div class="single-deal">
<div class="overlay"></div>
<img class="img-fluid w-100" src="img/category/c1.png" alt=""/>
<a href="#img/category/c1.jpg" class="img-pop-up" target="_blank">
<div class="deal-details">
<h6 class="deal-title">Analog Camera</h6>
</div>
</a>
</div>
</div>
<div class="col-lg-4 col-md-4">
<div class="single-deal">
<div class="overlay"></div>
<img class="img-fluid w-100" src="img/category/c2.jpg" alt=""/>
<a href="#img/category/c2.jpg" class="img-pop-up" target="_blank">
<div class="deal-details">
<h6 class="deal-title">Roll Film & Accessories</h6>
</div>
</a>
</div>
</div>
<div class="col-lg-4 col-md-4">
<div class="single-deal">
<div class="overlay"></div>
<img class="img-fluid w-100" src="img/category/c3.jpg" alt=""/>
<a href="#img/category/c3.jpg" class="img-pop-up" target="_blank">
<div class="deal-details">
<h6 class="deal-title">Lenses & Accessories</h6>
</div>
</a>
</div>
</div>
<div class="col-lg-8 col-md-8">
<div class="single-deal">
<div class="overlay"></div>
<img class="img-fluid w-100" src="img/category/c4.jpg" alt=""/>
<a href="#img/category/c4.jpg" class="img-pop-up" target="_blank">
<div class="deal-details">
<h6 class="deal-title">Digital Camera</h6>
</div>
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-6">
<div class="single-deal">
<div class="overlay"></div>
<img class="img-fluid w-100" src="img/category/c5.jpg" alt=""/>
<a href="#img/category/c5.jpg" class="img-pop-up" target="_blank">
<div class="deal-details">
<h6 class="deal-title">Video Camera</h6>
</div>
</a>
</div>
</div>
</div>
</div>
</section>
{/* <!-- End category Area --> */}
<Productlist/>
{/* <!-- Start exclusive deal Area --> */}
<section class="exclusive-deal-area">
<div class="container-fluid">
<div class="row justify-content-center align-items-center">
<div class="col-lg-6 no-padding exclusive-left">
<div class="row clock_sec clockdiv" id="clockdiv">
<div class="col-lg-12">
<h1>Exclusive Hot Deal Ends Soon!</h1>
<p>Who are in extremely love with eco friendly system.</p>
</div>
<div class="col-lg-12">
<div class="row clock-wrap">
<div class="col clockinner1 clockinner">
<h1 class="days">150</h1>
<span class="smalltext">Days</span>
</div>
<div class="col clockinner clockinner1">
<h1 class="hours">23</h1>
<span class="smalltext">Hours</span>
</div>
<div class="col clockinner clockinner1">
<h1 class="minutes">47</h1>
<span class="smalltext">Mins</span>
</div>
<div class="col clockinner clockinner1">
<h1 class="seconds">59</h1>
<span class="smalltext">Secs</span>
</div>
</div>
</div>
</div>
<a href="" class="primary-btn">Shop Now</a>
</div>
<div class="col-lg-6 no-padding exclusive-right">
<div class="active-exclusive-product-slider">
{/* <!-- single exclusive carousel --> */}
{/* <div class="single-exclusive-slider">
<img class="img-fluid" src="img/product/e-p1.png" alt=""/>
<div class="product-details">
<div class="price">
<h6>$150.00</h6>
<h6 class="l-through">$210.00</h6>
</div>
<h4>addidas New Hammer sole
for Sports person</h4>
<div class="add-bag d-flex align-items-center justify-content-center">
<a class="add-btn" href=""><span class="ti-bag"></span></a>
<span class="add-text text-uppercase">Add to Bag</span>
</div>
</div>
</div> */}
{/* <!-- single exclusive carousel --> */}
<div class="single-exclusive-slider">
<img class="img-fluid" src="img/product/e-p1.png" alt=""/>
<div class="product-details">
<div class="price">
<h6>$150.00</h6>
<h6 class="l-through">$210.00</h6>
</div>
<h4>addidas New Hammer sole
for Sports person</h4>
<div class="add-bag d-flex align-items-center justify-content-center">
<a class="add-btn" href=""><span class="ti-bag"></span></a>
<span class="add-text text-uppercase">Add to Bag</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{/* <!-- End exclusive deal Area --> */}
{/* <Footer/> */}
</div>
)
}
}
export default Home;
|
/* global EditorTool, Util, translate */
/* exported ListTool */
class ListTool extends EditorTool {
static get toolbox() {
return {
icon: '<i class="list icon"></i>',
title: translate.content.blocks.list,
}
}
// Sanitizer data before saving
static get sanitize() {
return {
items: {},
}
}
constructor({data, _config, api}) {
super({ // Data
id: data.id || Util.generateId(),
items: data.items || [],
style: ['unordered', 'ordered', 'leaf'].includes(data.style) ? data.style : 'unordered',
}, { // Config
id: 'list',
fields: {
items: { input: false }
},
tunes: [
{
name: 'unordered',
icon: 'list ul',
group: 'style',
},
{
name: 'ordered',
icon: 'list ol',
group: 'style',
},
{
name: 'leaf',
icon: 'leaf',
group: 'style',
},
],
}, api)
this.CSS.item = `${this.CSS.container}__item`
}
save(toolElement) {
const itemsData = []
const items = toolElement.querySelectorAll(`.${this.CSS.item}`)
for (let i = 0; i < items.length; i++) {
const value = items[i].innerHTML.replace('<br>', ' ').trim()
if (value) itemsData.push(items[i].innerHTML)
}
return Object.assign(this.data, { items: itemsData })
}
render() {
this.container = Util.make('ul', [this.CSS.baseClass, this.CSS.container], { contentEditable: true })
this.container.addEventListener('keydown', event => this._onItemKeydown(event))
if (this.data.items.length) {
this.data.items.forEach(item => {
Util.make('li', this.CSS.item, { innerHTML: item }, this.container)
})
} else {
Util.make('li', this.CSS.item, {}, this.container)
}
// TODO: Extract this into a function in the super class
this.tunes.forEach(tune => {
this.container.classList.toggle(this.CSS.tunes[tune.name], this.isTuneActive(tune))
})
return this.container
}
_onItemKeydown(event) {
if (event.key == 'Enter' || event.keyCode == 13) { // ENTER
const item = this.currentItem
const items = item.parentNode.children
if (items.length >= 2 && item.nextSibling == null && !item.textContent.trim().length) {
this.api.blocks.insert()
this.api.caret.setToNextBlock('start', 0)
item.remove()
event.preventDefault()
event.stopPropagation()
return false
}
} else if (event.key == 'Backspace' || event.keyCode == 8) { // BACKSPACE
const items = this.container.querySelectorAll(`.${this.CSS.item}`)
const firstItem = items[0]
// Save the last one.
if (items.length < 2 && firstItem && !firstItem.innerHTML.replace('<br>', ' ').trim()) {
event.preventDefault()
}
}
return true
}
// Returns current List item by the caret position
get currentItem() {
let currentNode = window.getSelection().anchorNode
if (currentNode.nodeType !== Node.ELEMENT_NODE) {
currentNode = currentNode.parentNode
}
return currentNode.closest(`.${this.CSS.item}`)
}
onPaste(event) {
const list = event.detail.data
const { tagName: tag } = list
let items = []
if (tag === 'LI') {
items = [list.innerHTML]
} else {
const listItems = Array.from(list.querySelectorAll('LI'))
items = listItems.map(li => li.innerHTML).filter(item => Boolean(item.trim()))
}
this.data = {
style: tag == 'OL' ? 'ordered' : 'unordered',
items: items,
}
}
// Select LI content by CMD+A
selectItem(event) {
event.preventDefault()
const selection = window.getSelection()
const currentNode = selection.anchorNode.parentNode
const currentItem = currentNode.closest('.' + this.CSS.item)
const range = new Range()
range.selectNodeContents(currentItem)
selection.removeAllRanges()
selection.addRange(range)
}
// Define the types of paste that should be handled by this tool.
static get pasteConfig() {
return { tags: ['OL', 'UL', 'LI'] }
}
// Allow native enter behaviour
static get enableLineBreaks() {
return true
}
}
|
function getValues(selector, names) {
const obj = {};
names.forEach((key) => {
const ele = document.querySelector(`${selector}[name=${key}]`);
if (ele == null) {
console.error('missing key: ' + key);
return;
}
if (ele.value.length === 0) {
return;
}
obj[key] = ele.value;
});
return obj;
}
async function callServer(method, url, params = {}) {
method = method.toUpperCase();
const body = method === 'GET' ? null : JSON.stringify(params);
if (method === 'GET') {
url += '?';
for (const key of Object.keys(params)) {
const value = params[key];
url = url + key + '=' + value;
}
}
const response = await fetch(url, {
method,
headers: {
'content-type': 'application/json'
},
body
});
if (response.status >= 400) {
const msg = await response.text();
return alert(msg);
}
return response.text();
}
async function logout() {
callServer('POST', '/user/logout');
window.location = '/user';
}
function tohomepage() {
window.location = '/user/homepage';
}
function fixDates() {
const fullDates = document.getElementsByClassName("displayDate");
Array.from(fullDates).forEach(date => date.innerText = moment.utc(date.innerText).utcOffset("-08:00").format("D MMM YYYY"))
const displayMonthDay = document.getElementsByClassName("displayMonthDay");
Array.from(displayMonthDay).forEach(date => date.innerText = moment.utc(date.innerText).utcOffset("-08:00").format("MMM D"))
const displayMonthDayUpper = document.getElementsByClassName("displayMonthDayUpper");
Array.from(displayMonthDayUpper).forEach(date => date.innerText = moment(date.innerText).format("MMM D").toUpperCase())
const displayTime = document.getElementsByClassName("displayTime");
Array.from(displayTime).forEach(date => date.innerText = moment.utc(date.innerText).utcOffset("-08:00").format("hh:mm a"))
}
fixDates();
|
import React from 'react';
import {Router, Route, IndexRedirect} from 'react-router';
import * as handlers from './handlers';
import App from '../components/App.jsx';
import Chat from '../components/Chat.jsx';
import Login from '../components/Login.jsx';
import Account from '../components/Account.jsx';
function render(history) {
return (
<Router history={history}>
<Route path="/" component={App} onEnter={handlers.getAuth}>
<IndexRedirect to="chat" />
<Route path="account" component={Account} onEnter={handlers.requireAuth} />
<Route path="chat/:channelKey" component={Chat} onEnter={handlers.requireAuth} />
<Route path="chat" component={Chat} onEnter={handlers.requireAuth} />
<Route path="login" component={Login} onEnter={handlers.redirectIfAuth} />
<Route path="logout" onEnter={handlers.logOut} />
</Route>
</Router>
);
}
export default render;
|
const express = require('express');
const app = express();
const mongojs = require('mongojs');
const db = mongojs('todo', [ 'tasks' ]);
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());
app.post('/tasks', function(req, res) {
const name = req.body.name;
const price = req.body.price;
db.tasks.insert({ name, price, status: 0 }, function(err, data) {
return res.json(data);
});
});
app.patch('/tasks/:id', function(req, res) {
const id = req.params.id;
db.tasks.find({ _id: mongojs.ObjectId(id) }, function(err, data) {
const status = +!data[0].status;
db.tasks.update(
{ _id: mongojs.ObjectId(id) },
{ $set: { status } },
{ multi: false },
function(err, data) {
return res.json(data);
}
);
});
});
app.put('/tasks/:id', function(req, res) {
const id = req.params.id;
const name = req.body.name;
const price = req.body.price;
db.tasks.update(
{ _id: mongojs.ObjectId(id) },
{ $set: { name, price } },
{ multi: false },
function(err, data) {
return res.json(data);
}
);
});
app.delete('/tasks', function(req, res) {
db.tasks.remove({ status: 1 }, function(err, data) {
return res.json(data);
});
});
app.delete('/tasks/:id', function(req, res) {
const id = req.params.id;
db.tasks.remove({ _id: mongojs.ObjectId(id) }, function(err, data) {
return res.json(data);
});
});
app.get('/tasks', function(req, res) {
db.tasks.find(function(err, data) {
return res.json(data);
});
});
app.get('/tasks/:id', function(req, res) {
const id = req.params.id;
db.tasks.find({ _id: mongojs.ObjectId(id) }, function(err, data) {
return res.json(data);
});
});
app.listen(8000, function() {
console.log('API running at 8000');
});
|
import React, { useEffect, useState } from "react";
import {
Container,
Content,
Header,
CompanyIcon,
WrapperMenuItem,
WrapperMenu,
} from "./styles";
import NavBar from "../../components/Navbar";
import { registerLocale, setDefaultLocale } from "react-datepicker";
import ptBR from 'date-fns/locale/pt-BR';
import "react-datepicker/dist/react-datepicker.css";
import { useDispatch, useSelector } from "react-redux";
import Taxas from "./Taxas"
import Transporte from "./Transporte"
import { FaBusAlt, FaPercent } from "react-icons/fa";
import { actions } from "../../actions/tableListSettingsActions";
import { selectors } from "../../selector";
export default function Settings() {
const dispatch = useDispatch();
const listTable = useSelector(selectors.getTableSettings);
const countRegister = useSelector(selectors.getCountRegisterSettings);
const [loading, setLoading] = useState(false);
const setTable = (newList) => dispatch(actions.updateTable(newList));
registerLocale('ptBR', ptBR);
const [list, setListaTabela] = useState([]);
const [contentTitle, setContentTitle] = useState(0);
const [content, setContent] = useState(0);
const [startDate, setStartDate] = useState(new Date());
const relatorios = [
{
"title": "Taxas",
"component": <Taxas />,
"icon": <FaPercent/>,
},
{
"title": "Transporte",
"component": <Transporte />,
"icon": <FaBusAlt/>,
}
]
useEffect(() => {
}, []);
return (
<Container>
<NavBar />
<Header>
<CompanyIcon />
<h1>Relatorio</h1>
</Header>
<WrapperMenu>
<ul>
{relatorios.map((item, index) => {
return (
<>
<li
className={content== index ? "ativo":""}
key={index}
onClick={() => setContent(index)}>
{item.icon}
{item.title}
</li>
</>
);
})}
</ul>
</WrapperMenu>
<Content>
{relatorios[content].component}
</Content>
</Container>
);
}
|
$(function () {
//Function that gets the time and displays in the html tag with id = time
function getTime() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$("#time").html(hours + ":" + minutes + ":" + seconds);
}
//Updates the time every 1 second
setInterval(function () {
getTime();
}, 1000);
})
|
const express = require("express");
const axios = require("axios");
const models = require("../models");
const {
getPagingData,
getPagination,
getSort,
} = require("../utils/collection");
const router = express.Router();
router.get("/", async (req, res) => {
const { _page, _limit, _collectionId, _sort } = req.query;
const { limit, offset } = getPagination(_page, _limit);
try {
const collection = await models.Collection.findOne({
where: { id: _collectionId },
});
const _items = await models.Item.findAndCountAll({
where: { collectionId: _collectionId },
order: [getSort(_sort)],
limit,
offset,
});
const items = getPagingData(_items, _page, limit);
return res.status(200).json({ collection, items });
} catch (error) {
return res.status(500).send(error.message);
}
});
module.exports = router;
|
var uiScripts = function () {
var pingTypeSelected = 1;
var init = function () {
supportsSVG();
tooltipHover();
toggleGraphicsPanel();
togglePingBubble();
toggleCreatePing();
runAjaxNotLoggedIn();
};
// fetches the persona content if user is not logged in
var runAjaxNotLoggedIn = function () {
$(".persona-innercontainer").children().detach();
$("#persona-notloggedin").load("notloggedin.html", function () {
toggleOpenPersonaArrows();
runAjaxRegister();
runAjaxForgotPassword();
redeployNanoScrollbars();
});
};
var runAjaxLogin = function () {
$('#loginLink').click(function () {
$(".persona-innercontainer").children().detach();
$("#persona-notloggedin").load("notloggedin.html", function () {
toggleOpenPersonaArrows();
runAjaxRegister();
runAjaxForgotPassword();
redeployNanoScrollbars();
});
});
};
// fetches the persona content if user is not logged in
var runAjaxRegister = function () {
$('#registerLink').click(function () {
$(".persona-innercontainer").children().detach();
$("#persona-register").load("register.html", function () {
toggleOpenPersonaArrows();
runAjaxForgotPassword();
runAjaxLogin();
redeployNanoScrollbars();
});
});
};
// fetches the persona content for forgot password
var runAjaxForgotPassword = function () {
$('#forgotPasswordLink').click(function () {
$(".persona-innercontainer").children().detach();
$("#persona-forgotpassword").load("forgotpassword.html", function () {
toggleOpenPersonaArrows();
runAjaxRegister();
runAjaxLogin();
redeployNanoScrollbars();
});
});
};
var redeployNanoScrollbars = function () {
$(".nano").nanoScroller();
$(".nano").nanoScroller({ destroy: true });
};
var toggleOpenPersonaArrows = function () {
$('.persona-open-tab, #persona-user-container').click(personaPanelOpen);
$('.persona-close-tab').click(personaPanelClose);
};
$('#create-ping-container, .createping-sendping').click(function () {
toggleCreatePing()
});
$('#create-ping-typeofping').click(function () {
togglePingType()
});
// Function for toggling type of pings to be selected
var togglePingType = function () {
if (pingTypeSelected == 1) {
$('#create-ping-typeofping-inner').animate({
top: '-70px'
}, 500);
pingTypeSelected = 2;
} else {
$('#create-ping-typeofping-inner').animate({
top: '0px'
}, 500);
pingTypeSelected = 1;
}
};
var createPingSelection = function () {
// hover and click effects
$('.createping-wheel-image g').hover(function () {
$('.createping-wheel-image g').not(this).stop().animate({
opacity: 0.4
}, 200
);
$(this).animate({
opacity: 1
}, 200
);
}, function () {
$('.createping-wheel-image g:not("createping-wheel-notselected")').stop().animate({
opacity: 1
}, 800
);
}
);
$('.createping-wheel-image g').click(function () {
$('.createping-wheel-image g').attr("class", "createping-wheel-notselected");
$(this).attr("class", "createping-wheel-selected");
});
};
// Function for toggling the create ping on click
var toggleCreatePing = function () {
// CLOSES THE CREATE A PING WHEEL
if ($('#create-ping-container').hasClass('create-ping-open')) {
$('#create-ping-container').removeClass("create-ping-open");
$('#create-ping-question, #create-ping-wheel textarea').animate({
opacity: 0
}, 100);
$('#create-ping-wheel').animate({
top: 0,
height: 180,
width: 180,
marginLeft: '-90px',
marginTop: ''
}, 400);
$('#create-ping-page').animate({
opacity: 0
}, 800, function () {
$('#create-ping-page').hide();
$('#create-ping-question').css({ 'margin-top': '-20px' });
});
// remove field value and hide ping button
$('#create-ping-wheel textarea').val("");
$('.createping-sendping, .createping-wheel-image text').hide();
$('.createping-wheel-image g').attr("class", "");
} else {
// OPENS THE CREATE A PING WHEEL - EMOTIONS DEFAULT
$('#create-ping-page').show().animate({
opacity: 1
}, 800);
$('#create-ping-container').addClass('create-ping-open');
$('#create-ping-wheel').show().delay(800).animate({
top: '50%',
height: 880,
width: 1000,
marginLeft: '-500px',
marginTop: '-400px'
}, 800, function () {
$('#create-ping-question').animate({
opacity: 1
}, 400, function () {
$('.createping-wheel-image text').each(function (index, element) {
$(element).delay(index * 70).fadeIn(600);
});
$('#create-ping-question').delay(2000).animate({
marginTop: '-165px'
}, 400, function () {
$('#create-ping-wheel textarea').delay(100).animate({
opacity: 1
}, 400,
function () {
$("#create-ping-wheel textarea").focus();
})
})
})
});
$("#create-ping-wheel textarea").on("input", function () {
$('.createping-sendping').show();
if (!$("#create-ping-wheel textarea").val()) {
$('.createping-sendping').hide();
}
});
}
createPingSelection();
};
// Function for opening the persona panel on click
var personaPanelOpen = function () {
$('.nav-icon').removeClass('active-tab');
$('#top-nav').addClass('nav-tab-persona');
$('.nav-persona-icon').addClass('active-tab');
$('#persona-container').addClass('persona-open').removeClass('persona-closed');
$('#persona-container').stop().animate({
top: 0
}, 500);
$('#persona-user-container').stop().delay(100).animate({
marginTop: 94
}, 100);
};
// Function for closing the persona panel on click
var personaPanelClose = function () {
$('#top-nav').removeClass('nav-tab-persona');
$('.nav-icon').removeClass('active-tab');
$('#persona-container').addClass('persona-closed').removeClass('persona-open');
$('#persona-container').stop().animate({
top: '100%'
}, 500);
$('#persona-user-container').stop().delay(100).animate({
marginTop: 0
}, 100);
};
// Function for opening the bubble over the star on the map
var togglePingBubble = function () {
$('.ping-emotion-icon').hover(function () {
$(this).find('.map-bubble').show().stop().animate({
opacity: 1
}, 300);
},
function () {
$(this).find('.map-bubble').stop().animate({
opacity: 0
}, 300, function () {
$(this).hide();
});
}
);
};
// Function for toggling the graphic panel on click
var toggleGraphicsPanel = function () {
$('#graphics-panel').click(function () {
if ($(this).hasClass("graphics-open")) {
$(this).removeClass("graphics-open").animate({
width: '300px'
}, 500);
} else {
$(this).addClass('graphics-open').animate({
width: '100%'
}, 500);
}
});
};
// Add tooltip hover delay
var tooltipHover = function () {
$('.tooltip-group').tooltip({
'delay': { show: 1000 }
});
};
// Does this browser/device support SVG? If so add a class to the HTML
var supportsSVG = function () {
return !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
if (supportsSVG()) {
document.documentElement.className += ' svg'; // <html class=" svg">
} else {
document.documentElement.className += ' no-svg'; // <html class=" no-svg">
};
};
$('.nav-persona-icon').click(personaPanelOpen);
return {
init: init
};
}();
|
const express = require('express');
const app = express();
const cors = require('cors');
const PORT = 8000;
app.use(cors())
let rappers = {
'21 savage': {
'age': 28,
'birthName': 'Sheyaa Bin Abraham-Joseph',
'birthLocation': 'London, England'
},
'chance the rapper': {
'age': 27,
'birthName': 'Chancelor Jonathan Bennet',
'birthLocation': 'Chicago, Illinois'
},
'unknown': {
'age': 28,
'birthName': 'unknown',
'birthLocation': 'unknown'
}
}
app.get('/', (request, response) => {
response.sendFile(__dirname + '/index.html')
})
app.get('/api/rappers/:rapperName', (request, response) => {
const rapName = request.params.rapperName.toLocaleLowerCase()
console.log(rapName)
if(rappers[rapName]){
response.json(rappers[rapName])
}else{
response.json(rappers['unknown'])
}
response.json(rappers[rapName])
})
app.listen(process.env.PORT || PORT, () =>{
console.log(`The Server is running on ${PORT} you better catch it`)
})
|
/*
*查看退款列表
*/
import React, { PureComponent } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
Card, Table, Affix, Button
} from 'antd';
import { changeTimeFormat } from '@/utils/changeTimeFormat';
import reqwest from 'reqwest'; //ajax格式的请求函数
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
class RefundList extends PureComponent {
state = {
refundList: [],
pagination: {},
loading: false,
refundDtl: false,
curRecord: {},
}
componentDidMount() {
this.fetch();
}
fetch = (params = {}) => {
this.setState({ loading: true });
reqwest({
url: '/proxy/payorder/getRefundList',
method: 'post',
data: {
page: 1,
size: 10,
...params,
},
type: 'json',
}).then((data) => {
var res = JSON.parse(data.response);
const pagination = {...this.state.pagination};
pagination.total = res.data.total;
this.setState({
loading: false,
refundList: res.data.list,
pagination,
})
})
}
columns = [
{
title: formatMessage({ id: "payorder.user-id" }),
dataIndex: 'userId',
width: '26%',
},
{
title: formatMessage({ id: "payorder.refund.before-expired-time" }),
dataIndex: 'beforeExpiredTime',
width: '18%',
render: text => {
return (<div>{changeTimeFormat(text)}</div>);
},
},
{
title: formatMessage({ id: "payorder.refund.after-expired-time" }),
dataIndex: 'afterExpiredTime',
width: '18%',
render: text => {
return (<div>{changeTimeFormat(text)}</div>);
},
},
{
title: formatMessage({ id: "payorder.refund-status" }),
dataIndex: 'refundStatus',
width: '15%',
render: text => {
var str = formatMessage({ id: (text == 200? "payorder.refund.success-status" : "payorder.refund.fail-status") })
return (<div>{str}</div>);
},
},
{
dataIndex: 'operation',
render: (text, record, index) => {
return (
<a href="#" onClick={this.handleRefundDetails.bind(this, record)}>
<FormattedMessage id="payorder.refund-details" />
</a>
)
}
}
];
handleRefundDetails = (record) => {
this.setState({
refundDtl: true,
curRecord: record,
})
}
handleTableChange = (pagination, filters, sorter) => {
const pager = { ...this.state.pagination };
pager.current = pagination.current;
this.setState({ pagination: pager });
this.fetch({
page: pagination.current,
})
}
renderTable = () => {
return (
<Card bordered={false}>
<Table
bordered
dataSource={this.state.refundList}
columns={this.columns}
pagination={this.state.pagination}
loading={this.state.loading}
onChange={this.handleTableChange}
/>
</Card>
)
}
renderRefundDetails = () => {
var record = this.state.curRecord;
const data = [
{
"title": formatMessage({ id: "payorder.refund-id" }),
"dataIndex": record['refundId'],
},
{
"title": formatMessage({ id: "payorder.refund.order-trade-no" }),
"dataIndex": record['orderTradeNo'],
},
{
"title": formatMessage({ id: "payorder.user-id" }),
"dataIndex": record['userId'],
},
{
"title": formatMessage({ id: "payorder.refund.before-expired-time" }),
"dataIndex": changeTimeFormat(record['beforeExpiredTime']),
},
{
"title": formatMessage({ id: "payorder.refund.after-expired-time" }),
"dataIndex": changeTimeFormat(record['afterExpiredTime']),
},
{
"title": formatMessage({ id: "payorder.refund-status" }),
"dataIndex": formatMessage({ id: (record['refundStatus'] == 200? "payorder.refund.success-status" : "payorder.refund.fail-status") }),
},
{
"title": formatMessage({ id: "payorder.create-time" }),
"dataIndex": changeTimeFormat(record['createTime']),
},
{
"title": formatMessage({ id: "app.cell-operator" }),
"dataIndex": record['cellOperator'],
},
{
"title": formatMessage({ id: "app.remark" }),
"dataIndex": record['remark'],
},
];
const cols = [
{
dataIndex: 'title',
},
{
dataIndex: 'dataIndex',
},
];
return (
<Card bordered={false}>
<Affix offsetTop={10}>
<Button type="primary" onClick={this.handleRefundDetailFinish}>
<FormattedMessage id="app.return" />
</Button>
</Affix>
<Table
bordered
dataSource={data}
columns={cols}
showHeader={false}
pagination={false}
style={{ marginTop: 10 }}
/>
</Card>
)
}
handleRefundDetailFinish = () => {
this.setState({
refundDtl: false,
curRecord: {},
})
}
render() {
return (
<PageHeaderWrapper title={<FormattedMessage id="payorder.refund-list" />}>
{this.state.refundDtl ? this.renderRefundDetails() : this.renderTable()}
</PageHeaderWrapper>
)
}
}
export default RefundList;
|
/**
* Display Map
*
* @param geo_info
*/
function bblog_display_map( geo_info ) {
for ( var i =0; i<geo_info.length; i++ ) {
bblog_init_map(geo_info[i]);
}
}
/**
* Display editable map
*/
function bblog_init_editable_map() {
//create map
//we may be creating or editing post
//in case of editing post, we need to set the location and geo lat lang?
var location = jQuery('#custom-field-_location').val();//based on the key we registered earlier
var lat = jQuery('#custom-field-_geo_lat').val();
var lng = jQuery('#custom-field-_geo_lng').val();
//default position, chandigarh
var position = {lat: 30.7204507, lng: 76.7669704};
if ( lat !='' && lng != '' ) {
//just converting to float
position = {lat: lat - 0 , lng: lng - 0 };
}
var map = new google.maps.Map(document.getElementById('bblog-map-edit-canvas'), {
center: position ,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var input = (document.getElementById('pac-input'));
jQuery(input).val( location );
//var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
if ( lat !='') {
marker.setPosition(position);
}
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible( false );
var place = autocomplete.getPlace();
if ( ! place.geometry ) {
//window.alert("Autocomplete's returned place contains no geometry");
return;
}
map.setCenter(place.geometry.location);
map.setZoom(13); // zoooming it
marker.setPosition( place.geometry.location );
marker.setVisible(true);
var text = jQuery(input).val();
//console.log(text);
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + text);
infowindow.open(map, marker);
jQuery('#custom-field-_location').val(text);
jQuery('#custom-field-_geo_lat').val(place.geometry.location.lat());
jQuery('#custom-field-_geo_lng').val(place.geometry.location.lng());
});
}
function bblog_init_map( info ) {
//create map
var latLang = {lat: info.lat -0 , lng: info.lng-0 };
var map = new google.maps.Map(document.getElementById('bblog-map-canvas-'+info.id), {
zoom: 7,
center: latLang
});
var marker = new google.maps.Marker({
map: map,
position: latLang,
title: info.location
});
//var info_window = new google.maps.InfoWindow();
//infowindow.setContent('<div><strong>' + info.location + '</strong><br>');
//infowindow.open(map, marker);
}
jQuery( document ).ready( function() {
//initialize all maps
//if we are on edit page, let us provide the UI for editing
if ( jQuery('#bblog-map-edit-canvas').get(0) ) {
bblog_init_editable_map();
}
if ( typeof bblog_posts_geo !== 'undefined' ) {
bblog_posts_geo = JSON.parse(bblog_posts_geo);
bblog_display_map( bblog_posts_geo );
}
});
|
var banner = document.querySelector('.banner');
var nav = document.querySelector('nav');
var contacts = document.querySelector('.contacts');
var aboutSection = document.querySelector('.aboutMe');
var footer = document.querySelector('footer');
var openProjects = document.querySelector('.main');
var about = document.querySelector('.about');
var projects = document.querySelector('.projects');
var descriptions = document.getElementsByClassName('description');
var myStory = document.getElementsByClassName('content');
function hasClass(elem, className) {
return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
};
function openBanner() {
banner.classList.add('openBanner');
banner.classList.remove('closedBanner');
};
function closeBanner() {
banner.classList.remove('openBanner');
banner.classList.add('closedBanner');
};
function openContacts() {
footer.classList.add('openContacts');
footer.classList.remove('hiddenContacts');
};
function closeContacts() {
footer.classList.remove('openContacts');
footer.classList.add('hiddenContacts');
};
function openAllProjects() {
openProjects.classList.add('openMain');
openProjects.classList.remove('hiddenMain');
for (var description of descriptions) {
description.tabIndex = 0;
}
};
function closeProjects() {
openProjects.classList.remove('openMain');
openProjects.classList.add('hiddenMain');
for (var description of descriptions) {
description.tabIndex = -1;
}
};
function openAbout() {
aboutSection.classList.add('openAbout');
aboutSection.classList.remove('hiddenAbout');
console.log(myStory);
myStory.tabIndex = 0;
};
function closeAbout() {
aboutSection.classList.remove('openAbout');
aboutSection.classList.add('hiddenAbout');
};
function openNav() {
nav.classList.add('openNav');
nav.classList.remove('closedNav');
};
function closeNav() {
nav.classList.add('closedNav');
nav.classList.remove('openNav');
};
contacts.addEventListener('click', (function(event) {
if(hasClass(banner, 'closedBanner')) {
openContacts();
openBanner();
openNav();
} else if(hasClass(banner, 'openBanner') && hasClass(aboutSection,'openAbout')) {
openContacts();
closeAbout();
} else if(hasClass(banner, 'openBanner') && hasClass(openProjects, 'openMain')) {
openContacts();
closeProjects();
} else if(hasClass(banner, 'openBanner') && hasClass(footer,'openContacts')) {
closeBanner();
closeContacts();
closeNav();
}
}));
about.addEventListener('click', (function(event) {
if(hasClass(banner, 'closedBanner')) {
openAbout();
openBanner();
openNav();
} else if(hasClass(banner, 'openBanner') && hasClass(openProjects, 'openMain')) {
openAbout();
closeProjects();
} else if(hasClass(banner, 'openBanner') && hasClass(footer,'openContacts')) {
openAbout();
closeContacts();
} else if(hasClass(banner, 'openBanner') && hasClass(aboutSection,'openAbout')) {
closeAbout();
closeBanner();
closeNav();
}
}));
projects.addEventListener('click', (function(event) {
if(hasClass(banner, 'closedBanner')) {
openAllProjects();
openBanner();
openNav();
} else if(hasClass(banner, 'openBanner') && hasClass(aboutSection,'openAbout')) {
openAllProjects();
closeAbout();
} else if(hasClass(banner, 'openBanner') && hasClass(openProjects, 'openMain')) {
closeBanner();
closeProjects();
closeNav();
} else if(hasClass(banner, 'openBanner') && hasClass(footer,'openContacts')) {
openAllProjects();
closeContacts();
}
}));
|
/*
* Copyright 2017 PhenixP2P Inc. Confidential and Proprietary. All Rights Reserved.
* Please see the LICENSE file included with this distribution for details.
*/
import React from 'react';
import PropTypes from 'prop-types';
import ChatMessagesContainer from '../containers/ChatMessagesContainer.jsx';
import ChatInputContainer from '../containers/ChatInputContainer.jsx';
import Styles from '../styles/chat.css';
const Chat = ({
messages,
checkIsSelf,
onResize,
isChatNotificationShown,
isMessagesLoading,
changeChatScrollDistance,
roomChatService,
parseScreenName,
isChatInputAnimationEnabled,
isMessagesAnimationEnabled
}) => (
<div className={Styles.container}>
<ChatMessagesContainer
messages={messages}
isMessagesLoading={isMessagesLoading}
isChatNotificationShown={isChatNotificationShown}
checkIsSelf={checkIsSelf}
roomChatService={roomChatService}
changeChatScrollDistance={changeChatScrollDistance}
parseScreenName={parseScreenName}
isChatInputAnimationEnabled={isChatInputAnimationEnabled}
isMessagesAnimationEnabled={isMessagesAnimationEnabled}
/>
<ChatInputContainer roomChatService={roomChatService} onResize={onResize} />
</div>
);
Chat.propTypes = {
checkIsSelf: PropTypes.func.isRequired,
messages: PropTypes.array.isRequired,
onResize: PropTypes.func.isRequired,
isMessagesLoading: PropTypes.bool.isRequired,
isChatNotificationShown: PropTypes.bool,
changeChatScrollDistance: PropTypes.func.isRequired,
roomChatService: PropTypes.object.isRequired,
parseScreenName: PropTypes.func,
isChatInputAnimationEnabled: PropTypes.bool,
isMessagesAnimationEnabled: PropTypes.bool
};
export default Chat;
|
// eslint-disable-line no-console
var genetic;
var pixel = 100;
var gen;
var canvasW = 600;
var stats = new Stats();
stats.setMode( 0 ); // 0 FPS, 1 MS
// align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.right = '0px';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = '999999';
document.addEventListener("DOMContentLoaded", function() {
document.body.appendChild( stats.domElement );
});
function setup() {
var canvas = createCanvas(canvasW, canvasW);
canvas.parent('container');
background(255);
var num_bits = width / pixel * height / pixel;
var p_crossover = 0.98;
var p_mutation = 1.0 / num_bits * 1.5;
genetic = Opal.Genetic.$new(Opal.hash2(["_num_bits", "_p_crossover", "_p_mutation"],
{"_num_bits": num_bits, "_p_crossover": p_crossover, "_p_mutation": p_mutation}));
//noLoop();
}
function draw() {
stats.begin();
var xpos = 0;
var ypos = 0;
gen = genetic.$next_gen();
//draw one row
var bitstring = gen.$fetch('bitstring');
for (var i = 0; i < bitstring.length; i++) {
var bit = bitstring.charAt(i);
//Off / White + grey border
if (bit == '0') {
fill(255);
noStroke();
//stroke(200);
//control
//rect(xpos, ypos, pixel, pixel)
rect(xpos, ypos, random(pixel*2), random(pixel*2), random(7), random(7), random(7), random(7))
} else {
//On / Grey + White border
//Trends this way
fill(50, 1);
//noStroke();
//control
//rect(xpos, ypos, pixel, pixel);
rect(xpos, ypos, pixel*2, pixel*2);
}
if (xpos < width) {
xpos += pixel;
} else {
xpos = 0;
ypos += pixel;
}
}
stats.end();
}
|
// var MINI = require('minified-custom');
// var _=MINI._, $=MINI.$, $$=MINI.$$, EE=MINI.EE, HTML=MINI.HTML;
freebusy.pickatime.enable();
freebusy.pickatime.onclick(callback)
freebusy.pickatime.open(request, query)
// if ('serviceWorker' in navigator) {
// window.addEventListener('load', function() {
// navigator.serviceWorker.register('/sw.js').then(function(reg){
// console.log("SW registration succeeded. Scope is "+reg.scope);
// }).catch(function(err){
// console.error("SW registration failed with error "+err);
// });
// });
// };
// function canUseWebP() {
// var elem = document.createElement('road');
//
// if (!!(elem.getContext && elem.getContext('2d'))) {
// // was able or not to get WebP representation
// return elem.toDataURL('images/webp').indexOf('data:images/webp') == 0;
// }
// else {
// // very old browser like IE 8, canvas not supported
// // return false;
// console.log('loser');
// }
// }
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function() {
console.log("Service Worker Registered");
});
}
// if ('serviceWorker' in navigator) {
// window.addEventListener('load', function() {
// navigator.serviceWorker
// .register('/sw.js', {scope: '/'})
// .then(function(registration) {
// console.log("service worker registered", registration);
// })
// .catch(function(err){
// console.log("Service worker failed to register", err);
// });
// });
// }
// $(function(){
//
// });
// $(".navi").fitText(1.2, { minFontSize: '13px', maxFontSize: '50px' });
// ("h1").fitText(0.6, { minFontSize: '60px', maxFontSize: '174px' });
// ("h4").fitText(1.2, { minFontSize: '50px', maxFontSize: '60px' });
// $("h5").fitText(1.5, { minFontSize: '14px', maxFontSize: '40px' });
// ("h6").fitText(0.8, { minFontSize: '54px', maxFontSize: '140px' });
// $("h5.ello").fitText(1.5, { minFontSize: '18px', maxFontSize: '45px' });
// $("#portfolio").fitText(0.8, { minFontSize: '54px', maxFontSize: '140px' });
//
// $("#contact").fitText(1.2, { minFontSize: '35px', maxFontSize: '80px' });
// $("h5").fitText(2.0);
// ['images/jacker.webp'].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
// img.setAttribute('src', img.getAttribute('data-src'));
// img.onload = function() {
// img.removeAttribute('data-src');
// };
// });
//lazy loading iphone
processScrollMobile = function(){
for(var i = 0; i < images.length; i++) {
loadImage(images[i], function() {
images.splice(i,i);
});
}
};
// if($('h6').has('class','Grid-cell--xs-6')){
// $('.Grid-cell--xs-6').hide();
//
// }
// var userAgent = window.navigator.userAgent;
// if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
// $('#banner').addClass('ios-background');
// }
//
// var winwidth = window.style.width = '';
if(window.innerWidth <600){
document.getElementById('tiles').style.display = 'none';
var tim = document.getElementsByClassName('h6title');
(section).push('h6');
// document.querySelectorAll('h6').style.fontSize = '15em';
// $('h6').after("<img id='tiles' src='/images/tiles1.png' class='last-xs img-responsive'>");
// $('h6').addClass('push-down');
// $('.push-down').css({'margin-top': '6em'});
// $('#tiles').css({
// 'display':'block',
// 'margin': '-4em auto 0 auto',
// 'width': '100%'
// });
}
// else{
// $('#tiles').show();
// }
// });
(function(){
var addEvent = function (el, type, fn) {
if (el.addEventListener)
el.addEventListener(type, fn, false);
else
el.attachEvent('on'+type, fn);
};
removeClass = function( className ) {
this.forEach( function( item ) {
var classList = item.classList;
classList.remove.apply( classList, className.split( /\s/ ) );
});
return this;
};
addClass = function( className ) {
this.forEach( function( item ) {
var classList = item.classList;
classList.add.apply( classList, className.split( /\s/ ) );
});
return this;
};
function after(referenceNode, newNode) {
referenceNode.parentNode.after(newNode, referenceNode.nextSibling);
}
// classList.parentNode.insertBefore(newElement, element.nextSibling);
var extend = function(obj,ext){
for(var key in ext)
if(ext.hasOwnProperty(key))
obj[key] = ext[key];
return obj;
};
window.fitText = function (el, kompressor, options) {
var settings = extend({
'minFontSize' : -1/0,
'maxFontSize' : 1/0
},options);
var fit = function (el) {
var compressor = kompressor || 1;
var resizer = function () {
el.style.fontSize = Math.max(Math.min(el.clientWidth / (compressor*10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)) + 'px';
};
// Call once to set.
resizer();
// Bind events
// If you have any js library which support Events, replace this part
// and remove addEvent function (or use original jQuery version)
addEvent(window, 'resize', resizer);
addEvent(window, 'orientationchange', resizer);
};
if (el.length)
for(var i=0; i<el.length; i++)
fit(el[i]);
else
fit(el);
// return set of elements
return el;
};
})();
document.onscroll = function() {
// console.log(window.pageYOffset);
var nav = document.getElementById('nav');
if ( window.pageYOffset > 4 ) {
nav.style.background = 'rgba(13, 45, 51, 0.95)';
} else {
nav.style.background = 'rgba(21, 71, 76, 0.03)';
}
}
// var needheight= nav.scrollHeight;
// console.log(needheight);
|
function setPropsOnObj(object) {
object.x = 7;
object['y'] = 8;
object.onePlus = function(num) {return num + 1};
}
function setPropsOnArr(arr) {
arr.hello = () => 'Hello!';
arr['full'] = 'stack';
arr[0] = 5;
arr.twoTimes = (num) => num * 2;
}
function setPropsOnFunc(func) {
func.year = '20??';
func.divideByTwo = function(num) {
return num / 2;
};
func.prototype.helloWorld = () => 'Hello World';
}
|
$(function() {
$('pre:not(.hljs)').addClass('hljs');
$(".select-selecter").selecter();
$('#btn-fullscreen').click(function() {
if ($.fullscreen.isFullScreen()) {
$.fullscreen.exit();
} else {
$('.canvas-container').fullscreen({
toggleClass: 'fullscreen'
});
}
});
});
|
class App {
constructor() {
this.landingPage = new LandingPage()
this.navBar = new NavBar()
}
}
|
// search form
// query form, add event, fetch api
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault();
// reset/remove old things
const location = event.target.location.value;
// console.log(location);
// find errors
if (!location) {
document.querySelector(".display").classList.add("error");
// if no location and button is submitted (set main section to add class of error), background turns red and font turns white
} else {
// reset/remove old things
document.querySelector(".history p").classList.add("hidden");
fetch(`https://wttr.in/${location}?format=j1`)
.then((response) => response.json())
.then((weather) => {
// check weather
// console.log(weather);
document.querySelector(
"#textBox"
).innerHTML = `<h2>${weather.nearest_area[0].areaName[0].value}
</h2>
<p><b>Area:</b> ${weather.nearest_area[0].areaName[0].value}</p>
<p><strong>Region:</strong> ${weather.nearest_area[0].region[0].value}</p>
<p><b>Country:</b> ${weather.nearest_area[0].country[0].value}</p>
<p><b>Currently:</b> Feels Like ${weather.current_condition[0].FeelsLikeF}°F</p>`;
document.querySelector("#today").innerHTML = `<h3>Today
</h3>
<p><b>Average Temperature:</b> ${weather.weather[0].avgtempF}°F</p>
<p><strong>Max Temperature:</strong> ${weather.weather[0].maxtempF}°F</p>
<p><b>Min Temperature:</b> ${weather.weather[0].mintempF}°F</p>`;
document.querySelector("#tomorrow").innerHTML = `<h3>Tomorrow
</h3>
<p><b>Average Temperature:</b> ${weather.weather[1].avgtempF}°F</p>
<p><strong>Max Temperature:</strong> ${weather.weather[1].maxtempF}°F</p>
<p><b>Min Temperature:</b> ${weather.weather[1].mintempF}°F</p>`;
document.querySelector("#dayAfter").innerHTML = `<h3>Day After Tomorrow
</h3>
<p><b>Average Temperature:</b> ${weather.weather[2].avgtempF}°F</p>
<p><strong>Max Temperature:</strong> ${weather.weather[2].maxtempF}°F</p>
<p><b>Min Temperature:</b> ${weather.weather[2].mintempF}°F</p>`;
// create 4 articles in the main section (main-info, today, tomorrow, day-after)
const mainInfo = document.createElement("article");
mainInfo.id = "main-info";
const today = document.createElement("article");
today.id = "today";
const tomorrow = document.createElement("article");
tomorrow.id = "tomorrow";
const dayAfter = document.createElement("article");
dayAfter.id = "day-after";
// append all to display section
// document
// .querySelector(".display")
// .append(mainInfo, today, tomorrow, dayAfter);
// previous search
const previousSearches = document.querySelector("ul");
previousSearches.innerHTML += `<li><a href="#">${location}</a> - ${weather.current_condition[0].FeelsLikeF}°F</li>`;
const anchors = document.querySelectorAll("a");
for (let anchor of anchors) {
anchor.addEventListener("click", (event) => {
event.preventDefault();
// click previous
const link = event.target.textContent;
console.log(link);
document.querySelector(".history p").classList.add("hidden");
fetch(`https://wttr.in/${link}?format=j1`)
.then((response) => response.json())
.then((weather) => {
console.log(weather);
document.querySelector(
"#textBox"
).innerHTML = `<h2>${weather.nearest_area[0].areaName[0].value}
</h2>
<p><b>Area:</b> ${weather.nearest_area[0].areaName[0].value}</p>
<p><strong>Region:</strong> ${weather.nearest_area[0].region[0].value}</p>
<p><b>Country:</b> ${weather.nearest_area[0].country[0].value}</p>
<p><b>Currently:</b> Feels Like ${weather.current_condition[0].FeelsLikeF}°F</p>`;
document.querySelector("#today").innerHTML = `<h3>Today
</h3>
<p><b>Average Temperature:</b> ${weather.weather[0].avgtempF}°F</p>
<p><strong>Max Temperature:</strong> ${weather.weather[0].maxtempF}°F</p>
<p><b>Min Temperature:</b> ${weather.weather[0].mintempF}°F</p>`;
document.querySelector("#tomorrow").innerHTML = `<h3>Tomorrow
</h3>
<p><b>Average Temperature:</b> ${weather.weather[1].avgtempF}°F</p>
<p><strong>Max Temperature:</strong> ${weather.weather[1].maxtempF}°F</p>
<p><b>Min Temperature:</b> ${weather.weather[1].mintempF}°F</p>`;
document.querySelector(
"#dayAfter"
).innerHTML = `<h3>Day After Tomorrow
</h3>
<p><b>Average Temperature:</b> ${weather.weather[2].avgtempF}°F</p>
<p><strong>Max Temperature:</strong> ${weather.weather[2].maxtempF}°F</p>
<p><b>Min Temperature:</b> ${weather.weather[2].mintempF}°F</p>`;
});
});
}
});
}
event.target.reset();
});
// previous work
// // main info
// const mainHeading = document.createElement("h2");
// mainHeading.textContent = location;
// const area = document.createElement("p");
// area.textContent = `Area: ${weather.nearest_area[0].areaName[0].value}`;
// const region = document.createElement("p");
// region.textContent = `Region: ${weather.nearest_area[0].region[0].value}`;
// const country = document.createElement("p");
// country.textContent = `Country: ${weather.nearest_area[0].country[0].value}`;
// const currently = document.createElement("p");
// currently.textContent = `Currently: Feels like ${weather.current_condition[0].FeelsLikeF}°F`;
// // add to today
// const todayHeading = document.createElement("h3");
// todayHeading.textContent = "Today";
// const avgTempToday = document.createElement("p");
// avgTempToday.innerHTML = `<span>Average Temperature:</span> ${weather.weather[0].avgtempF}`;
// const maxTempToday = document.createElement("p");
// maxTempToday.textContent = `Max Temperature: ${weather.weather[0].maxtempF}`;
// const minTempToday = document.createElement("p");
// minTempToday.textContent = `Min Temperature: ${weather.weather[0].mintempF}`;
// // add to tomorrow
// const tomorrowHeading = document.createElement("h3");
// tomorrowHeading.textContent = "Tomorrow";
// const avgTempTomorrow = document.createElement("p");
// avgTempTomorrow.innerHTML = `<span>Average Temperature:</span> ${weather.weather[1].avgtempF}`;
// const maxTempTomorrow = document.createElement("p");
// maxTempTomorrow.textContent = `Max Temperature: ${weather.weather[1].maxtempF}`;
// const minTempTomorrow = document.createElement("p");
// minTempTomorrow.textContent = `Min Temperature: ${weather.weather[1].mintempF}`;
// // add to day after
// const dayAfterHeading = document.createElement("h3");
// dayAfterHeading.textContent = "Day After Tomorrow";
// const dayAfterAvg = document.createElement("p");
// dayAfterAvg.innerHTML = `<span>Average Temperature:</span> ${weather.weather[2].avgtempF}°F`;
// const dayAfterMax = document.createElement("p");
// dayAfterMax.innerHTML = `<span>Highest Temperature:</span> ${weather.weather[2].maxtempF}°F`;
// const dayAfterMin = document.createElement("p");
// dayAfterMin.innerHTML = `<span>Lowest Temperature:</span> ${weather.weather[2].mintempF}°F`;
// append items to aside for previous searches
// const searchList = document.querySelector("ul");
// searches.innerHTML += `<li><a href=">${location}</a> - ${weather.current_condition[0].FeelsLikeF}°F</li>`;
// document.querySelector(".history").append;
// // append weather info
// document.querySelector(".display");
// previous searches
// use info from mainHeading to grab the location
// use info from currently to grab the current temp
// const mainHeading = document.createElement("h2");
// mainHeading.textContent = location;
// const area = document.createElement("p");
// const currently = document.createElement("p");
// currently.textContent = `Currently: Feels like ${weather.current_condition[0].FeelsLikeF}°F`;
|
const functions = require("firebase-functions");
const Filter=require('bad-words')
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// functions.logger.info("Hello logs!", {structuredData: true});
// response.send("Hello from Firebase!");
// });
const admin=require('firebase-admin');
const { useCollectionData } = require("react-firebase-hooks/firestore");
admin.initializeApp()
const db=admin.firestore()
exports.detectBadUsers=functions.firestore
.document('messages/{msgId}')
.onCreate(async(doc,ctx)=>{
const filter=new Filter()
const {text,uid}=doc.data()
if (filter.isProfane(text)){
const cleaned=filter.clean(text)
await doc.ref.update({text:`I got blocked for saying ${cleaned}`})
collection('banned').doc(uid).set({});
}
})
|
/*
The background process is responsible for opening Carrot windows in response to
app launches, choosing a file in the Files app on Chrome OS, and external
messages.
*/
var mainWindow = null;
var pending = null;
var files = [];
var commands = [];
var openWindow = function() {
//if window exists, re-use it
if (mainWindow) {
//attach any new files to the window, and re-trigger "open from launch"
mainWindow.contentWindow.launchData = files;
mainWindow.contentWindow.require(["command"], function(c) {
c.fire("session:open-launch");
});
mainWindow.focus();
mainWindow.drawAttention();
files = [];
pending = null;
return;
}
//otherwise, open a new window
var defaults = {
width: 800,
height: 600,
left: 50,
top: 50
};
chrome.app.window.create("main.html", {
bounds: defaults,
id: "caret:main",
frame: "none",
minWidth: 640,
minHeight: 480
}, function(win) {
mainWindow = win;
win.contentWindow.launchData = files;
win.contentWindow.launchCommands = commands;
mainWindow.onClosed.addListener(function() {
mainWindow = null;
chrome.storage.local.remove("isOpen");
});
files = [];
commands = [];
pending = null;
chrome.storage.local.set({isOpen: true});
});
}
var launch = function(launchData) {
if (launchData && launchData.items) files.push.apply(files, launchData.items);
//we delay opening the actual window to give multiple file events time to fire
if (pending !== null) return;
pending = setTimeout(openWindow, 250);
};
chrome.app.runtime.onLaunched.addListener(launch);
var onMessage = function(message, sender, sendResponse) {
//main window will pick up the message, if it's open
//we also allow extensions to suppress launch behavior for spurious messages
if (mainWindow || message.quiet || !message.command) {
//if it is open, and the command is loud enough, flash the window
if (mainWindow && message.command && !message.quiet) {
mainWindow.drawAttention();
}
return;
}
commands.push({
message: message,
sender: sender,
sendResponse: sendResponse
});
//as with files, delay to accumulate multiple messages
if (pending !== null) return;
pending = setTimeout(openWindow, 250);
};
chrome.runtime.onMessageExternal.addListener(onMessage);
//relaunch on reboot, if the window was open at shutdown
var checkRestart = function() {
chrome.storage.local.get("isOpen", function(data) {
if (data.isOpen) launch();
});
};
chrome.app.runtime.onRestarted.addListener(checkRestart);
checkRestart();
// setup for launcher context menus
// currently this is just for emergency reset
chrome.contextMenus.create({
title: "Emergency Reset",
contexts: [ "launcher" ],
id: chrome.runtime.id + ":factory-reset"
}, function() {
if (chrome.runtime.lastError) console.log(chrome.runtime.lastError);
});
window.emergencyReset = function() {
if (mainWindow) mainWindow.close();
var cleared = {
local: false,
sync: false
};
var check = function(storage) {
cleared[storage] = true;
if (cleared.local && cleared.sync) {
chrome.notifications.create("app:factory-reset-complete", {
type: "basic",
iconUrl: "icon-128.png",
title: "Emergency Reset Complete",
message: "Carrot has been reset to the default settings."
}, function() {});
}
};
chrome.storage.local.clear(check.bind(null, "local"));
chrome.storage.sync.clear(check.bind(null, "sync"));
};
chrome.contextMenus.onClicked.addListener(function(data) {
if (data.menuItemId != chrome.runtime.id + ":factory-reset") return;
emergencyReset();
});
var installNotification = "upgraded";
window.showUpdateNotification = function(manifest = chrome.runtime.getManifest()) {
chrome.notifications.create(installNotification, {
type: "basic",
iconUrl: "icon-128.png",
title: chrome.i18n.getMessage("notificationUpdated"),
message: chrome.i18n.getMessage("notificationUpdatedDetail", [manifest.version]),
isClickable: true
}, function(id) { installNotification = id });
};
chrome.runtime.onInstalled.addListener(function(e) {
if (!e.previousVersion) return;
// set a flag for launch updates
window.updateVersion = e.previousVersion;
var manifest = chrome.runtime.getManifest();
// at some point, we should use these.
var [major, minor, build] = e.previousVersion.split(".");
if (e.previousVersion != manifest.version) {
chrome.storage.sync.get("updateNotifications", function(data) {
if (data.updateNotifications && data.updateNotifications != "background") return;
//let the user know
showUpdateNotification(manifest);
});
}
});
chrome.notifications.onClicked.addListener(function(id) {
if (id != installNotification) return;
window.open("https://github.com/Dynamic-Build/Carrot/blob/master/changelog.md", "target=_blank");
});
|
import React from 'react'
import { shallow } from 'enzyme'
import { Button } from '@blueprintjs/core'
import CollectionComponent from '../../CollectionComponent'
import RefreshAction from '../index'
describe('<RefreshAction />', () => {
let dataSource
beforeEach(() => {
dataSource = {
__isCollectionDS__: true,
status: 'ready',
fetch: jest.fn(),
refetch: jest.fn()
}
})
describe('dataSource interactions', () => {
test('ready dataSource', () => {
const comp = shallow(<RefreshAction dataSource={dataSource} />)
const button = comp.renderProp('render')()
expect(dataSource.fetch).not.toHaveBeenCalled()
expect(dataSource.refetch).not.toHaveBeenCalled()
expect(comp.is(CollectionComponent)).toBe(true)
expect(button.is(Button)).toBe(true)
expect(button.prop('disabled')).toBe(false)
button.simulate('click')
expect(dataSource.refetch).toHaveBeenCalled()
})
test('busy dataSource', () => {
dataSource.status = 'busy'
const comp = shallow(<RefreshAction dataSource={dataSource} />)
const button = comp.renderProp('render')()
expect(dataSource.fetch).not.toHaveBeenCalled()
expect(dataSource.refetch).not.toHaveBeenCalled()
expect(comp.is(CollectionComponent)).toBe(true)
expect(button.is(Button)).toBe(true)
expect(button.prop('disabled')).toBe(true)
button.simulate('click')
expect(dataSource.refetch).not.toHaveBeenCalled()
})
})
describe('props', () => {
test('default properties', () => {
const comp = shallow(<RefreshAction dataSource={dataSource} />)
const button = comp.renderProp('render')()
expect(button.prop('text')).toBe('Refresh')
expect(button.prop('icon')).toBe('refresh')
expect(button.prop('intent')).toBeUndefined()
expect(button.prop('large')).toBe(false)
expect(button.prop('small')).toBe(false)
expect(button.prop('minimal')).toBe(false)
})
test('modified properties', () => {
const comp = shallow(
<RefreshAction
dataSource={dataSource}
text="Refresh Data"
icon="server"
intent="primary"
large
small
minimal
/>
)
const button = comp.renderProp('render')()
expect(button.prop('text')).toBe('Refresh Data')
expect(button.prop('icon')).toBe('server')
expect(button.prop('intent')).toBe('primary')
expect(button.prop('large')).toBe(true)
expect(button.prop('small')).toBe(true)
expect(button.prop('minimal')).toBe(true)
})
})
})
|
//公用引入模块
const express = require("express");
const bodyParser = require("body-parser"); //post请求
const session = require("express-session");
const cookieParser = require("cookie-parser");
const path = require("path"); //处理路径
const router = express.Router();
const app = express();
var signature = require('cookie-signature'); //去掉cookies的签名
//app.use(logger("dev"));//日志输出
//=======session and cookie==============================
app.use(cookieParser('Simon'));
app.use(session({
// name: "3project", //cookie名称,默认connect.sid
// secret: "123123", //结合其他加密的方式生成secret
// cookie: {
// maxAge: 3000000
// }, //cookie配置:有效时间
// resave: true, //保存(长度为时间)
// rolling: true, //刷新(刷新之后保存的时间)
// saveUninitialized: false //未初始化cookie要不要保存
}));
//post数据读取
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(router); //使用模块
//通用拦截 放在静态资源之前
app.use("/", (req, resp, next) => {
//进行登录判断
// 1.session.username 有名字
// 2.当前是在login.html
//3.如果资源请求是来源于login.html,也进next
// console.log("通用拦截", req.signedCookies.islogin)
// console.log("req.path当前请求路径",req.path)
// console.log("req.header---",req.headers.referer)
req.headers.referer = req.headers.referer || "" //访问的网址 首次的时候没有referer 这个referer的支持是不统一的,referer这个参数是浏览器自动添加给header中的
if ( req.signedCookies.islogin || req.path == "/login.html" || req.headers.referer.match(/login.html$/)) {
// app.locals.username = req.signedCookies.islogin; //把用户名写到locals.username获取 任何的ejs渲染页面都有这个
// console.log("username",app.locals.username)
next()
} else {
// console.log(req.path) //路径(不带参数)
// console.log(req.url) //完整地址
// req.session.originalURL = req.url; //用户成功登录之后,返回到上一个页面
resp.redirect("/login.html"); //http://localhost:8888/XXXX
}
})
//静态资源
app.use(express.static(__dirname + "/public"));
//domain:cookie在什么域名下有效,类型为String,。默认为网站域名
//expires: cookie过期时间,类型为Date。如果没有设置或者设置为0,那么该cookie只在这个这个session有效,即关闭浏览器后,这个cookie会被浏览器删除。
//httpOnly: 只能被web server访问,类型Boolean。
//maxAge: 实现expires的功能,设置cookie过期的时间,类型为String,指明从现在开始,多少毫秒以后,cookie到期。
//path: cookie在什么路径下有效,默认为'/',类型为String
//secure:只能被HTTPS使用,类型Boolean,默认为false
//signed:使用签名,类型Boolean,默认为false。`express会使用req.secret来完成签名,需要cookie-parser配合使用`
router.post("/newLogin.do", (req, resp) => {
let username = req.body.username;
let password = req.body.password;
if (username === 'admin' && password === 'a123456') {
req.session.username = username;
let data = {
success: 'ok'
}
resp.cookie('islogin', username, {
maxAge: 60 * 1000,
signed: true, //使用签名
httpOnly: true
});
resp.send(data)
} else {
resp.send("登录失败")
}
});
app.listen(9998, () => {
console.log(("服务器9998启动"))
});
|
$(function(){
// 登陆表单
$('#login').click(function(){
$('.sign-box').show();
$('.index-cover').show();
});
$('#close-btn').click(function(){
$('.index-cover').hide();
$('.sign-box').hide();
});
$('.cover').click(function(){
$(this).hide();
// 登陆表单隐藏
$('.sign-box').hide();
// 二维码隐藏
$('#Jqrcode-box').hide();
});
// 导航部分
$('#commit-wrap').hover(
function(){
$('.df-list').show();
},
function(){
$('.df-list').hide();
});
//更多按钮
$('.more-btn').click(function(){
alert('暂无数据!');
})
})
|
import React, { Component } from 'react'
import Axios from 'axios'
import config from '../global/config.json'
const API = config.api_url
export default class Generic extends Component{
constructor(props){
super(props)
this.state = {}
}
render(){
return(
<div>
Project is running!
</div>
)
}
}
|
//
// Waves dApp Magic 8 ball tests
//
describe('8 ball', () => {
const ballAddress = "3N27HUMt4ddx2X7foQwZRmpFzg5PSzLrUgU"
const question = "Test" + Date.now()
const tx = invokeScript({fee: 500000, dApp: ballAddress, call:{function:"tellme", args:[{"type": "string", "value": question}]}, payment: null})
it('Tx is mined in block', async function(){
await broadcast(tx)
await waitForTx(tx.id)
})
it('Question is in ball', async function(){
await accountDataByKey(address()+"_q", ballAddress)
.then(reslove => expect(reslove.value).to.equal(question))
})
})
|
const express = require('express');
const router = express.Router();
const mongoDB = require('mongodb').MongoClient;
const passport = require('passport');
const routes = () => {
router.route('/signUp')
.post((req, res, next) => {
const url = 'mongodb://localhost:27017/libraryApp';
mongoDB.connect(url, (err, db) => {
const collection = db.collection('users');
const user = { username: req.body.userName, password: req.body.password };
collection.insert(user, (err, result) => {
req.login(result, () => {
res.redirect('/auth/profile');
});
});
});
});
router.route('/signIn')
.post(passport.authenticate('local', {
failureRedirect: '/'
}), (req, res, next) => {
res.redirect('/auth/profile');
});
router.route('/profile')
.all((req, res, next) => {
if ( !req.user ) {
res.redirect('/');
}
next();
})
.get((req, res) => {
res.json(req.user);
});
router.route('/signIn');
return router;
};
module.exports = routes;
|
import React, { Component } from 'react'
import { Range } from './components/Range'
export class App extends Component {
state = {
hue: Math.floor(Math.random() * 360),
saturation: Math.floor(Math.random() * 100),
lightness: Math.floor(Math.random() * 100),
alpha: Math.round((Math.random() * (1 - 0) + 0) * 100) / 100,
}
/**
* @param {{ target: { value: any; }; }} event
*/
handleChangeHue = event => {
this.setState({ hue: event.target.value })
}
/**
* @param {{ target: { value: any; }; }} event
*/
handleChangeSaturation = event => {
this.setState({ saturation: event.target.value })
}
/**
* @param {{ target: { value: any; }; }} event
*/
handleChangeLightness = event => {
this.setState({ lightness: event.target.value })
}
/**
* @param {{ target: { value: any; }; }} event
*/
handleChangeAlpha = event => {
this.setState({ alpha: event.target.value })
}
/**
* @param {any} event
*/
handleRandomColor = event => {
this.setState({
hue: Math.floor(Math.random() * 360),
saturation: Math.floor(Math.random() * 100),
lightness: Math.floor(Math.random() * 100),
alpha: Math.round((Math.random() * (1 - 0) + 0) * 100) / 100,
})
}
render() {
return (
<main>
<h1
style={{
textShadow: `0px 5px hsla(${this.state.hue}, ${this.state.saturation}%, ${this.state.lightness}%, ${this.state.alpha})`,
}}
>
Color Picker
</h1>
<div className="first-section">
<section className="color-box">
<div
style={{
backgroundColor: `hsla(
${this.state.hue},
${this.state.saturation}%,
${this.state.lightness}%,
${this.state.alpha}
)`,
}}
></div>
<button onClick={this.handleRandomColor}>Random</button>
</section>
<section className="color-ranges">
<Range
min="0"
max="360"
value={this.state.hue}
onChange={this.handleChangeHue}
/>
<Range
min="0"
max="100"
value={this.state.saturation}
onChange={this.handleChangeSaturation}
/>
<Range
min="0"
max="100"
value={this.state.lightness}
onChange={this.handleChangeLightness}
/>
<Range
min="0"
max="1"
step="0.01"
value={this.state.alpha}
onChange={this.handleChangeAlpha}
/>
</section>
</div>
<section className="color-info">
<div>
<p>
hsla({this.state.hue}, {this.state.saturation}%,{' '}
{this.state.lightness}%, {this.state.alpha})
</p>
</div>
</section>
</main>
)
}
}
|
function returnOrderCtrl($scope, $uibModal, $rootScope, $compile, $state, productService) {
//$scope.products = {};
init();
function init() {
//getAllProducts();
}
//$scope.product = {};
//function getAllProducts() {
// productService.getAllProducts().then(
// function (data) {
// if (data) {
// $scope.products = data;
// }
// });
//};
};
|
import express from 'express';
import { checkSchema } from 'express-validator/check';
import asyncHandler from 'express-async-handler';
import { Stops } from '../config/param-validation';
import stopsCtrl from '../controllers/stops.controller';
import inputsCtrl from '../controllers/inputs.controller';
const router = express.Router();
/** GET /api/stops/search - Search by the stop_id or stop_name */
router.get('/search', checkSchema(Stops.getSearch), stopsCtrl.search);
/** GET /api/stops/proximity - Get the surroundings stops of given location */
router.get(
'/proximity',
checkSchema(Stops.getProximity),
stopsCtrl.getProximity
);
/** POST /api/stops/:stop_id/inputs - Post the new update of a stop */
router.post(
'/:stop_id/inputs',
checkSchema(Stops.postInputs),
asyncHandler(inputsCtrl.saveInputs)
);
/** GET /api/stops/:stop_id/histories - Get All histories of a stop */
router.get('/:stop_id/histories', asyncHandler(stopsCtrl.getHistory));
/** GET /api/stops/:stop_id/:history_id - Get specific history of a stop */
router.get(
'/:stop_id/histor(y|ies)/:history_id?',
asyncHandler(stopsCtrl.getHistory)
);
export default router;
|
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const db = require('../database/database');
const { encryPassword, matchPassword } = require('../controllers/encriptar');
passport.use(
//estategia para autenticar
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password'
},
async (email, password, done) => {
// console.log('email recibido:'+email)
// console.log('password recibido:'+password)
var validar_email;
//confirmar si existe el email del usuario
const usuario_ = await db.query('SELECT * FROM usuario WHERE email = $1', [email]);
const usuario = usuario_.rows[0];
if(usuario){
validar_email = usuario.email;
}
// console.log('Email de la DB: ' + validar_email)
if (!validar_email) {
// console.log('Este Email: '+email+' no existe en la BD');
return done(null, false, { message: 'Usuario no encontrado' });
} else {
// console.log('-Iniciando verificacion de contraseña')
//matchPassword devuelve true si conicide la contraseña con la DB
const validar_password = await matchPassword(password, usuario.id);
// console.log('ya se valido la contraseña')
if (validar_password) {
return done(null, usuario)
} else {
return done(null, false, {message:'Contraseña incorrecta'})
}
}
}
)
);
//metodo que recibe una funcion y esta funcion recibe un usuario y done(funcion callback para terminar)
//la funcion done recibe un error y un usuario
passport.serializeUser((usuario, done) => {
done(null, usuario.id);
});
//mientras navega el usuario permite verificar si el id tiene los permisos o existe
passport.deserializeUser(async(id, done) => {
var usuario_;
var error;
try{
//verifica si el id existe en la base de datos
usuario_ = await (await (db.query('SELECT * FROM usuario WHERE id = $1', [id]))).rows[0];
}catch(e){
error = e;
}
done(error, usuario_);
})
|
/*
Copyright 2016-2018 Stratumn SAS. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { sign as nacl } from 'tweetnacl';
import { stringify } from 'canonicaljson';
import { runTestsWithDataAndAgent } from './utils/testSetUp';
import { sign, signedProperties, signatureAlgorithms } from '../src/sign';
import { withKey } from '../src/withKey';
import { decodeSignatureFromPEM, decodePKFromPEM } from '../src/encoding';
const testPrivateKey = `-----BEGIN ED25519 PRIVATE KEY-----
BEAu3UcG9B1K7E7YbzeVUJPbU9v62rSQPSr87rCbPkwCg+JRhN20fmXhDtzfHTow
BFVsvHaVt+putNZGntbUraRS
-----END ED25519 PRIVATE KEY-----`;
const testPublicKey = `-----BEGIN ED25519 PUBLIC KEY-----
MCowBQYDK2VwAyEA4lGE3bR+ZeEO3N8dOjAEVWy8dpW36m601kae1tStpFI=
-----END ED25519 PUBLIC KEY-----`;
describe('#signedProperties', () => {
runTestsWithDataAndAgent(processCb => {
it('assigns the passed properties to a process', () =>
processCb()
.sign({ inputs: true })
.signed.should.deepEqual({ inputs: true }));
it('assigns the passed properties to a segment', () =>
processCb()
.createMap('test')
.then(s1 =>
s1.sign({ inputs: true }).signed.should.deepEqual({ inputs: true })
));
it('assigns default properties to sign when called without argument on a segment', () =>
signedProperties({ meta: { linkHash: 'test' } }).signed.should.deepEqual({
inputs: true,
action: true,
prevLinkHash: true,
refs: true
}));
it('does not enable signing prevLinkHash by default when called on a process', () =>
signedProperties({}).signed.should.deepEqual({
inputs: true,
action: true,
prevLinkHash: false,
refs: true
}));
it('fails if trying to add a invalid propery to be signed', () =>
(() => signedProperties({}, { unknown: true })).should.throw(
'Cannot sign property unknown, it has to be one of inputs,action,prevLinkHash,refs'
));
});
});
describe('#sign', () => {
const testKey = withKey({}, testPrivateKey).key;
const testData = {
refs: [{ test: 'test' }],
action: 'test',
prevLinkHash: 'test',
inputs: ['1', '2']
};
it('outputs a signature given a key and data to sign', () =>
sign(testKey, testData).then(sig => {
sig.payload.should.be.exactly(
'[meta.refs[*].linkHash,meta.action,meta.prevLinkHash,meta.inputs]'
);
sig.publicKey.should.be.exactly(testPublicKey);
}));
it('build the payload accordingly to the provided data', () =>
sign(testKey, { ...testData, inputs: false }).then(sig =>
sig.payload.should.be.exactly(
'[meta.refs[*].linkHash,meta.action,meta.prevLinkHash]'
)
));
it('outputs a valid signature', () =>
sign(testKey, { ...testData, inputs: false }).then(sig => {
const { signature, publicKey, type } = sig;
type.should.be.exactly(signatureAlgorithms[testKey.type]);
const publicKeyBytes = decodePKFromPEM(publicKey).publicKey;
const signatureBytes = decodeSignatureFromPEM(signature).signature;
const payloadBytes = Buffer.from(
stringify([
testData.refs.map(r => r.linkHash).filter(Boolean),
testData.action,
testData.prevLinkHash
])
);
const verif = nacl.detached.verify(
payloadBytes,
signatureBytes,
publicKeyBytes
);
verif.should.be.true();
}));
it('fails if the provided data does not match [inputs, action, refs, prevLinkHash]', () =>
sign(testKey, { ...testData, unknown: 'test' })
.then(() => {
throw new Error('should have failed');
})
.catch(err =>
err.message.should.be.exactly(
'Cannot sign property unknown, it has to be one of inputs,action,prevLinkHash,refs'
)
));
it('fails the provided data to sign is null', () =>
sign(testKey, null)
.then(() => {
throw new Error('should have failed');
})
.catch(err =>
err.message.should.be.exactly('trying to sign an emtpy payload')
));
it('fails the provided data to sign is empty', () =>
sign(testKey, {})
.then(() => {
throw new Error('should have failed');
})
.catch(err =>
err.message.should.be.exactly(
'jmespath query [] did not match any data'
)
));
it('fails when the key is ill-formatted ', () =>
sign({ type: 'ed25519' }, testData)
.then(() => {
throw new Error('should have failed');
})
.catch(err =>
err.message.should.be.exactly(
'key is not defined (use: segment.withKey(key)'
)
));
it('fails when the key type does not match any signature algorithm ', () =>
sign({ ...testKey, ...{ type: 'unknown' } }, testData)
.then(() => {
throw new Error('should have failed');
})
.catch(err =>
err.message.should.be.exactly(
'signing is not supported for this type of key [unknown]'
)
));
});
|
angular.module('starter.controllers', ['ionic.cloud'])
.config(function ($ionicCloudProvider) {
$ionicCloudProvider.init({
"core": {
"app_id": "ff9c7a36"
},
"push": {
"sender_id": "972141839894",
"pluginConfig": {
"ios": {
"badge": true,
"sound": true
},
"android": {
"iconColor": "#343434"
}
}
}
});
})
.controller('DashCtrl', function ($scope, $ionicPush) {
$scope.text='';
$ionicPush.register().then(function (t) {
$scope.text=JSON.stringify(t);
t.type='android';
t.saved=true;
return $ionicPush.saveToken(t);
},function (t) {
alert(JSON.stringify(t));
return;
}).then(function (t) {
alert('Token saved:', JSON.stringify(t));
},function (t) {
alert(JSON.stringify(t));
return;
});
$scope.$on('cloud:push:notification', function (event, data) {
alert(JSON.stringify(data));
var msg = data.message;
alert(msg.title + ': ' + msg.text);
});
alert("hi");
})
.controller('ChatsCtrl', function ($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function (chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function ($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function ($scope) {
$scope.settings = {
enableFriends: true
};
});
|
const AWS = require('aws-sdk');
const request = require('request');
const _ = require('lodash');
const BigQuery = require('@google-cloud/bigquery');
const bigquery = BigQuery();
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
Date.prototype.addDays = function(days)
{
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
}
const doRegion = function(startTime, endTime) { return function(region) {
const ec2 = new AWS.EC2({
region: region
});
queryAndInsert(ec2, region, startTime, endTime, {
StartTime: startTime.toISOString(),
EndTime: endTime.toISOString()
}, null);
}}
const queryAndInsert = function(ec2, region, startTime, endTime, params, nextToken) {
const query = _.assign(params, {NextToken: nextToken});
const date_str = startTime.yyyymmdd();
const bqTable = bigquery.dataset('aws_cost').table('spot_price_history$' + date_str);
ec2.describeSpotPriceHistory(query, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
if (data['NextToken']) {
queryAndInsert(ec2, region, startTime, endTime, params, data['NextToken']);
}
rows = data['SpotPriceHistory'].map((x) =>
_.assign(x, {'Region': region}))
.filter((x) =>
(startTime <= x['Timestamp']) && (x['Timestamp'] <= endTime));
bqTable.insert(rows)
.then((data) => {
console.log(data[0], data[1])
});
}
});
}
exports.run = function() { //event, context) {
//console.log(event);
const date = process.env.DATE; //event['date'];
const startTime = new Date(date);
const endTime = new Date(date).addDays(1)
new AWS.EC2({
region: 'us-east-1'
}).describeRegions({}, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
_.map(data['Regions'], 'RegionName').map(doRegion(startTime, endTime));
}
});
}
exports.run();
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Header from './components/Header.js'
import Footer from './components/Footer.js'
class App extends Component {
constructor(props) {
super(props);
this.state = {
hobbies: ["flying kites", "skipping to my lou", "eating", "higher-order functions", "reading", "zelda", "running"],
inputText: ''
}
}
handleInputChange(e) {
this.setState({ inputText: e.target.value })
}
addHobby() {
// let newHobbies = this.state.hobbies;
// newHobbies.push(this.state.inputText);
this.setState({
hobbies: [...this.state.hobbies, this.state.inputText],
inputText: ''
})
}
render() {
let list = this.state.hobbies.map((hobby, index) => {
return (
<p key={index}>{hobby}</p>
)
})
var myName = "Andrew Semle";
return (
<div className="App">
< Header />
<h1>My First React App</h1>
<h5>My List of Hobbies</h5>
<input type="text" value={this.state.inputText} onChange={(e) => this.handleInputChange(e)}/>
<button onClick={() => this.addHobby()}>Add Hobby</button>
<div>{list}</div>
<Footer />
</div>
);
}
}
export default App;
|
//1. fs.stat 检索是文件还是目录
//2. fs.mkdir 创建目录
//3. fs.writeFile 创建写入目录
//4. fs.appendFile 追加目录
//5. fs.readFile 读取文件 .toString()
//6. fs.readdir 读取目录
//7. fs.rename 重命名 移动文件
//8. fs.rmdir 删除目录
//9. fs.unlink 删除文件
//10. fs.createReadSteam 从文件流中读取数据
//11. fs.createWriteStream 写入文件 //58
const fs = require("fs");
// fs.stat('./www',(err,data)=> {
// if(err){
// console.log(err);
// return ;
// }
// console.log(`是文件:${data.isFile()}`);
// console.log(`是目录:${data.isDirectory()}`)
// })
// fs.writeFile('./www/hello.html',"你好node js 哈哈哈",(err)=>{
// console.log(err);
// })
// fs.readdir('../node',function(err,data){
// if(err){
// console.log(err);
// }else{
// console.log(data);
// }
// })
// var readSteam = fs.createReadStream('./www/index.txt');
// let count = 0;
// let str = '';
// //数据过多的话 会读取多次
// readSteam.on('data',(data)=>{
// str += data;
// count++;
// })
// readSteam.on('end',()=>{
// console.log(count);
// console.log(str);
// })
// readSteam.on('error',(err)=>{
// console.log(str);
// console.log(count);
// })
// var str = '';
// for(var i = 0;i < 500;i++){
// str+='我是从数据库获取的数据,我要保存起来\n'
// }
// const writeStream = fs.createWriteStream('./www/index.txt');
// writeStream.write(str);
// //是一个异步 需要标记写入完成
// writeStream.end();
// //只有标记写入完成 才能 触发finish事件
// writeStream.on('finish',()=>{
// console.log('写入完成');
// })
//创建一个读取流
var readSteam = fs.createReadStream('./www/pic1.jpg');
//创建一个写入流
var writeStream = fs.createWriteStream('./study1/copy1.jpg');
//以流的方式写入 一个写入一个写出 一个管子 //文件上传和图片上传会使用文件流的方式
readSteam.pipe(writeStream);
|
import React, {useState} from "react";
import {View, StyleSheet, Image, ScrollView} from 'react-native'
import {BigTitle} from "../ui/BigTitle";
import StrainInput from "../components/StrainInput";
import CultureSelector from "../components/CultureSelector";
import {AppButton} from "../ui/AppButton";
import {useDispatch, useSelector} from "react-redux";
import {chooseAvgPlantGrow, chooseProjectPok, chooseUnit} from "../store/actions/fieldsInfo";
import Toast from "react-native-root-toast";
const options = ["Г/м^2", "Кг/Га", "Т/Га", "Г/м^3"];
export const LastInfoScreen = ({navigation}) => {
const [avgPlantGrow, setAvgPlantGrow] = useState('')
const [projectPok, setProjectPok] = useState('')
const [unit, setUnit] = useState('')
const dispatch = useDispatch()
return (
<View style={styles.container}>
<ScrollView style={styles.scrollContainer} contentContainerStyle={{ alignItems: 'center' }}>
<BigTitle text='Введите информацию' />
<Image source={require('../../assets/img/agro5.png')} style={styles.promo} />
<View style={styles.card}>
<StrainInput
label='Введите средний рост растений по полю (в см)'
placeholder='Впишите числовое значение'
value={avgPlantGrow}
typeKeyBoard='numeric'
onInputTextChange={setAvgPlantGrow}
/>
</View>
<View style={styles.card}>
<StrainInput
label='Введите процент проективного покрытия'
placeholder='Впишите числовое значение'
value={projectPok}
typeKeyBoard='numeric'
onInputTextChange={(text) => {
if (text > 100 || text < 0) {
let toast = Toast.show('Укажите корректное значение процента', {
duration: Toast.durations.SHORT,
});
} else {
setProjectPok(text)
}
}}
/>
</View>
<View style={styles.card}>
<CultureSelector
options={options}
placeholder={'Единица измерения'}
label='Выберите единицу измерения фитомассы'
value={unit}
onSelectOptionChange={option => {
setUnit(option)
}}
/>
</View>
<View style={styles.buttonWrap}>
<AppButton
text={'Далее'}
onPress={() => {
dispatch(chooseAvgPlantGrow(avgPlantGrow))
dispatch(chooseProjectPok(projectPok))
dispatch(chooseUnit(unit))
navigation.navigate('Comment')
}}
disabled={!(!!avgPlantGrow && !!projectPok && !!unit)}
/>
</View>
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
container: {
flexGrow: 1,
alignItems: 'center'
},
scrollContainer: {
paddingHorizontal: 20,
backgroundColor: 'white',
},
buttonWrap: {
width: '100%',
alignItems: 'center',
marginVertical: 10,
},
promo: {
resizeMode: 'contain',
width: '100%',
height: 220,
zIndex: -100,
},
card: {
width: '99%',
overflow: 'hidden',
maxWidth: '100%',
maxHeight: 500,
marginVertical: 10,
borderColor: 'rgba(0, 0, 0, 0.05)',
borderRadius: 17,
backgroundColor: '#fff',
shadowColor: "#000",
paddingHorizontal: 10,
paddingVertical: 10,
shadowOffset: {
width: 0,
height: 5,
},
shadowOpacity: 0.20,
shadowRadius: 2.25,
elevation: 5,
flexDirection: 'column',
justifyContent: 'space-between'
},
})
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/_components/_plate" ], {
5734: function(e, n, t) {},
7649: function(e, n, t) {
t.r(n);
var a = t("d4fe"), o = t("d3e2");
for (var c in o) [ "default" ].indexOf(c) < 0 && function(e) {
t.d(n, e, function() {
return o[e];
});
}(c);
t("be6a");
var i = t("f0c5"), u = Object(i.a)(o.default, a.b, a.c, !1, null, "0e1938e6", null, !1, a.a, void 0);
n.default = u.exports;
},
be6a: function(e, n, t) {
var a = t("5734");
t.n(a).a;
},
bf64: function(e, n, t) {
Object.defineProperty(n, "__esModule", {
value: !0
}), n.default = void 0;
var a = {
props: {
plate: {
type: Object
}
},
methods: {
openDetail: function() {
this.$sendCtmEvtLog("楼盘详情页板块入口点击"), wx.navigateTo({
url: "/pages/packageB/plates/main?id=".concat(this.plate.id)
});
}
}
};
n.default = a;
},
d3e2: function(e, n, t) {
t.r(n);
var a = t("bf64"), o = t.n(a);
for (var c in a) [ "default" ].indexOf(c) < 0 && function(e) {
t.d(n, e, function() {
return a[e];
});
}(c);
n.default = o.a;
},
d4fe: function(e, n, t) {
t.d(n, "b", function() {
return a;
}), t.d(n, "c", function() {
return o;
}), t.d(n, "a", function() {});
var a = function() {
var e = this;
e.$createElement;
e._self._c;
}, o = [];
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/building/_components/_plate-create-component", {
"pages/building/_components/_plate-create-component": function(e, n, t) {
t("543d").createComponent(t("7649"));
}
}, [ [ "pages/building/_components/_plate-create-component" ] ] ]);
|
import React from 'react'
import {View} from 'react-native'
import MovieDetail from '../componets/MovieDetail'
const Details = ({route})=>{
return(
<View>
<MovieDetail movieid={route.params.movieid}/>
</View>
);
}
export default Details;
|
window.onload = btnon;
function btnon(){
var input = document.getElementsByTagName("input");
var btn = document.getElementsByTagName("button");
btn[0].onclick = function(){
ale(input[0],input[1]);
}
}
function ale(x,y){
alert(x.value);
alert(y.value);
}
|
import React from 'react';
import UserInfo from './UserInfo';
import { Row, Col } from 'react-flexbox-grid';
import { Link } from 'react-router-dom';
import logo from '../img/logo.png';
const Header = () => (
<Row className="header">
<Col xs={6}>
<Link to="/">
<img className="img-logo" src={logo} alt="logo"/>
</Link>
</Col>
<Col xs={6}>
<UserInfo />
</Col>
</Row>
);
export default Header;
|
describe('Poll Model', () => {
describe('create()', () => {
it('creates a poll with an owner', (done) => {
Poll
.create({
guid: GUID.v4(),
owner_guid: 'f03ede7c-b131-4112-bcc7-130a3e87988c',
title: "If you had a million dollars?",
isPublic: true,
})
.then(([poll]) => {
expect(poll.id).to.equal(3)
expect(poll.owner_guid).to.equal('f03ede7c-b131-4112-bcc7-130a3e87988c')
expect(poll.title).to.equal('If you had a million dollars?')
expect(poll.isPublic).to.equal(true)
expect(poll.created_at).to.exist()
expect(poll.created_at).to.be.a.date()
expect(poll.updated_at).to.exist()
expect(poll.updated_at).to.be.a.date()
done();
})
})
it('sets attribute isPublic to false by default if not set', (done) => {
Poll
.create({
guid: GUID.v4(),
owner_guid: 'f03ede7c-b131-4112-bcc7-130a3e87988c',
title: "If you had a million dollars?",
isPublic: undefined,
})
.then(([poll]) => {
expect(poll.isPublic).to.equal(false)
done();
})
})
})
describe('getAll()', () => {
it('returns all polls with no passed in options', (done) => {
Poll
.getAll()
.then((polls) => {
expect(polls.length).to.equal(2)
done()
})
.catch(err => done(err))
})
it('returns only public polls when an option object of { isPublic: true } is passed in', (done) => {
Poll
.getAll({ isPublic: true })
.then((polls) => {
expect(polls.length).to.equal(1)
done()
})
.catch(err => done(err))
})
})
describe('findBy()', (done) => {
it('returns a poll with passed in options', (done) => {
Poll
.findBy({ guid: '4c8d84f1-9e41-4e78-a254-0a5680cd19d5' })
.then((poll) => {
expect(poll.title).to.equal('What is your favorite JS framework?')
expect(poll.isPublic).to.equal(true)
done()
})
.catch(err => done(err))
})
})
describe('update()', (done) => {
it('find a poll by guid and updates with passed in values', (done) => {
Poll
.update({ guid: '4c8d84f1-9e41-4e78-a254-0a5680cd19d5' }, {
title: "What is the best time to study?",
isPublic: false,
})
.then(([poll]) => {
expect(poll.id).to.equal(1)
expect(poll.owner_guid).to.equal('f03ede7c-b131-4112-bcc7-130a3e87988c')
expect(poll.title).to.equal('What is the best time to study?')
expect(poll.guid).to.equal('4c8d84f1-9e41-4e78-a254-0a5680cd19d5')
expect(poll.isPublic).to.equal(false)
done()
})
.catch(err => done(err))
})
})
describe('Relations', (done) => {
describe('owner()', () => {
it('returns the owner', (done) => {
User
.findBy({username: 'lukeghenco'})
.then(user => {
Poll
.listOwner('4c8d84f1-9e41-4e78-a254-0a5680cd19d5')
.then(owner => {
expect(owner).to.equal({
name: 'Luke Ghenco',
username: 'lukeghenco',
email: 'luke@gmail.com'
})
done()
})
})
})
})
describe('has many', () => {
it('listPollOpinions', (done) => {
Poll
.listPollOpinions('4c8d84f1-9e41-4e78-a254-0a5680cd19d5', ['poll_opinions.content'])
.then(opinions => {
const [opinion1, opinion2] = opinions
expect(opinions.length).to.equal(2)
expect(opinion1.content).to.equal('React')
expect(opinion2.content).to.equal('Angular')
done()
})
})
})
})
})
|
(function() {
// 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释
var imports = [
'rd.controls.Table'
];
var extraModules = [ ];
var controllerDefination = ['$scope', 'EventService','EventTypes',main];
function main($scope,EventService,EventTypes ) {
$scope.tableSetCurrentPage = function(){//
rdk.tableID.setCurrentPage(1);//设置当前页
}
$scope.tableResetCurrentPage = function(){
rdk.tableID.resetCurrentPage();//重置当前页
}
$scope.tableGetTablePageNumber = function(){
alert( "当前分页类型的数字代号:"+rdk.tableID.getTablePageNumber());
}
$scope.tableSetPageSize = function(){
rdk.tableID.setPageSize(2);//重新定义列表每页要展现的行数
}
$scope.tableSetChecked = function(){
var item =[{//对象里写的属性全可以匹配到才会勾选
"name":"Tiger Nixon1",
"office":"Edinburgh"
}];
rdk.tableID.setChecked(item);
}
$scope.tableSetGlobalSearch = function(){//过滤
rdk.tableID.setGlobalSearch('Tokyo');
}
$scope.tableGetSearchInfo = function(){//得其过滤的值
alert(rdk.tableID.getSearchInfo().searchKey);
}
}
var controllerName = 'DemoController';
//==========================================================================
// 从这里开始的代码、注释请不要随意修改
//==========================================================================
define(/*fix-from*/application.import(imports)/*fix-to*/, start);
function start() {
application.initImports(imports, arguments);
rdk.$injectDependency(application.getComponents(extraModules, imports));
rdk.$ngModule.controller(controllerName, controllerDefination);
}
})();
|
// https://codepen.io/chrisbridges/pen/YJXzPZ?editors=0012
// What used to be this
let name = 'Chris'
let activity = 'learning about template strings!'
// need to remember to include proper spaces before adding
let sayHello = 'Hello, ' + name + '. I hope you are having a fun time ' + activity
console.log(sayHello)
// Can now be this!
let newName = 'Jason'
let newActivity = 'conquering ES6!'
// Notice the back ticks - these are not standard quotation marks
let newSayHello = `Hello, ${newName}. I hope you are having a fun time ${newActivity}`
console.log(newSayHello)
|
import { lazy, Suspense } from 'react';
import { NavLink, Route, useRouteMatch } from "react-router-dom";
import { useLocation } from 'react-router';
// import CastView from "../CastView/CastView";
// import ReviewsView from "../ReviewsView/ReviewsView";
import styles from './styles.module.scss';
const CastView = lazy(() => import("../CastView/CastView"));
const ReviewsView = lazy(() => import("../ReviewsView/ReviewsView"));
const AdditionalInformation = () => {
const { url, path } = useRouteMatch();
const location = useLocation();
return (
<div className={styles.info}>
<div>
<h4>Additional Information</h4>
<div className={styles.navigation}>
<NavLink
to={{
pathname: `${url}/cast`,
state: {from: location?.state?.from}
}}
className={styles.link}
activeClassName={styles.activeLink}
>
Cast
</NavLink>
<NavLink
to={{
pathname: `${url}/reviews`,
state: {from: location?.state?.from}
}}
className={styles.link}
activeClassName={styles.activeLink}
>
Reviews
</NavLink>
</div>
</div>
<Suspense fallback={<h2>LOADING...</h2>}>
<Route path={`${path}/cast`}>
<CastView/>
</Route>
<Route path={`${path}/reviews`}>
<ReviewsView />
</Route>
</Suspense>
</div>
);
}
export default AdditionalInformation;
|
define([
"controllers/layouts/main",
],
function (Main
) {
var layouts = [
{
id: 'wrapper',
module: function (opt) {
return new Main.View(opt);
}
}
];
return layouts;
});
|
P.views.exercises.priv.Image = P.views.Item.extend({
templateId: 'exercise.priv.image',
tagName: 'span',
className: 'v-image col-xs-4',
events: {
'click .js-delete': 'del',
'click .js-rank-top': 'rank'
},
behaviors: {
Img: {
behaviorClass: P.behaviors.exercises.Image
}
},
del: function(event) {
event.stopPropagation();
event.preventDefault();
P.common.forms.Button.disable(this.$('.js-delete'));
this.$el.trigger('delete', [this.model, this]);
},
onDeleteFail: function() {
P.common.forms.Button.reset(this.$('.js-delete'));
},
onRank: function(args) {
this.$el.trigger('rank', [this.model, args.resp.data.sort_rank]);
P.common.forms.Button.reset(this.$('.js-rank-top'));
},
onRankFail: function(args) {
P.errors.ResponseCodes.displayAlert(args.resp);
P.common.forms.Button.reset(this.$('.js-rank-top'));
},
rank: function() {
P.common.forms.Button.disable(this.$('.js-rank-top'));
this.model.url = this.model.get('options');
this.model.pSave({
'sort_rank': '0'
}, {
patch: true
})
.then(this.onRank.bind(this), this.onRankFail.bind(this));
},
serializeData: function() {
var ctx = P.views.Item.prototype.serializeData.call(this);
ctx.isDefault = String(this.model.get('sort_rank')) === '0';
return ctx;
}
});
|
'use strict';
function solve(params){
var result = '';
for (var i = 0, len = params.length; i < len; i += 1) {
result += params[i].replace(/\s\s+/g, ' ');
result += '\n';
if (params[i].lastIndexOf('{') !== -1) {
result += ' ';
}
}
console.log(result.trim());
}
var args = [
'.jedi {',
'has: lightsaber;',
'}',
];
var args2 = [
'#the-big-b{',
' color: big-yellow;',
'.little-bs {',
' color: little-yellow;',
' $.male {',
' color: middle-yellow;',
' }',
' }',
'}',
'.muppet {',
' skin : fluffy;',
' $.water-spirit {',
' powers : water;',
' }',
' powers : all-muppet-powers;',
'}'
];
var args3 = [
];
//solve(args);
console.log('--------------------------');
solve(args2);
console.log('--------------------------');
//solve(args3);
|
const log = require('../')('test')
describe('debug-log', () => {
test('log is a method', () => {
log('this is a test', new Date(), { object: 'test'} )
expect(typeof log === 'function').toBeTruthy()
})
})
|
import React, { useState, useEffect } from 'react';
import { Grid, Typography, Link } from '@material-ui/core'
import { axiosInstance, keyApi } from '../api/weather'
import { useSelector, useDispatch } from 'react-redux'
import SearchBar from './SearchBar';
import WeatherDetails from './WeatherDetails';
import WeatherList from './WeatherList';
import WeatherItem from './WeatherItem';
import addToFavorites from '../actions/addAction'
import removeFromFavorites from '../actions/removeAction'
import FavoriteIcon from '@material-ui/icons/Favorite';
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder';
import { IconButton } from '@material-ui/core';
import ErrModal from './ErrModal';
import '../App.css';
export default function Home() {
const [fiveDays, setFiveDays] = React.useState([]);
const [currDay, setCurrDay] = React.useState(null);
const [showErr, setShowErr] = React.useState(false);
const dispatch = useDispatch();
const _favorites = useSelector(state => state.favoritesState.favorits)
const handleClose = () => {
setShowErr(false);
};
async function handleSubmit(searchTerm) {
const _url = `/currentconditions/v1/${searchTerm.key}`;
try {
const res = await axiosInstance.get(_url, {
params: {
apikey: keyApi,
}
});
if (res && res.data && res.data.length > 0) {
let _currDay = res.data.shift();
let isFavorite = false
if (_currDay != null) {
if (_favorites && _favorites.length > 0) {
let _isFavorite = _favorites.filter((obj) => { return obj.key === searchTerm.key });
if (_isFavorite.length > 0) {
isFavorite = true
}
}
setCurrDay({ title: searchTerm.title, key: searchTerm.key, WeatherIcon: _currDay.WeatherIcon, WeatherText: _currDay.WeatherText, Temperature: _currDay.Temperature.Metric, isFavorites: isFavorite });
};
findNextDays(searchTerm);
};
} catch (e) {
setShowErr(true);
};
}
async function findNextDays(searchTerm) {
const _url = `/forecasts/v1/daily/5day/${searchTerm.key}`;
const res = await axiosInstance.get(_url, {
params: {
apikey: keyApi,
}
});
if (res && res.data && res.data.DailyForecasts && res.data.DailyForecasts.length > 0) {
let _nextDays = res.data.DailyForecasts;
if (_nextDays != null) {
setFiveDays(_nextDays.map((obj) => { return <WeatherItem weatherItem={obj} key={obj.EpochDate} temp={(Math.floor(5 / 9 * (obj.Temperature.Maximum.Value - 32) * 100) / 100) + 'C'} day={new Date(obj.Date).getDay()} /> }));
}
}
}
return (
<Grid justify="center" container spacing={10}>
<Grid item xs={12}>
<Grid justify="center" container spacing={10}>
<Grid className="searchBar-grid" item md={6} xs={12}>
<SearchBar onFormSubmit={handleSubmit} />
</Grid>
{currDay != null &&
<Grid item md={8} xs={12}>
<Grid style={{ display: 'flex', float: 'right' }}>
{currDay != null && currDay.isFavorites ?
< FavoriteIcon /> : < FavoriteBorderIcon />
}
{currDay != null && !currDay.isFavorites ?
<IconButton className="add-to-favorites-text" onClick={() => { dispatch(addToFavorites(currDay)) }}>Add To Favorites</IconButton>:
<IconButton className="add-to-favorites-text" onClick={() => { dispatch(removeFromFavorites(currDay)) }}>Remove from Favorites</IconButton>
}
</Grid>
<Grid item md={8} xs={12}>
<WeatherDetails weather={currDay} />
</Grid>
</Grid>
}
{fiveDays.length > 0 &&
<Grid item xs={8}>
<WeatherList listItems={fiveDays} />
</Grid>
}
</Grid>
</Grid>
{showErr && <ErrModal showModal={showErr} handleClosePar={handleClose} />}
</Grid>
);
}
|
import { Router } from 'express'
import moment from 'moment'
import consola from 'consola'
import nodemailer from 'nodemailer'
import xss from 'xss'
import hasher from 'wordpress-hash-node'
import connection from '../mysqlConnect'
const config = require('../config').default
const router = Router()
// eslint-disable-next-line no-unused-vars
let arrResponse = {}
router.post('/register', function (req, res, next) {
const name = xss(req.body.name)
const email = xss(req.body.email)
const password = hasher.HashPassword(xss(req.body.password))
const permission = xss(req.body.permission)
const createdAt = moment().format('YYYY-MM-DD HH:mm:ss')
const emailQuery = `SELECT * FROM date_users WHERE user_mail = "${email}" LIMIT 1`
const registerQuery = `INSERT INTO date_users (user_name, user_mail, user_password, permission, created_at) VALUES("${name}", "${email}", "${password}", "${permission}", "${createdAt}")`
const output = `dates事務局
${name}様が登録いたしました。
ログインID:${email}
登録日時:${createdAt}
----------------------------------------------------------------
dates事務局
Email: support@dates.jp
URL: https://dates.jp
----------------------------------------------------------------`
const reverse = `dates事務局
${name}様
datesへのご登録ありがとうございます。
下記URLよりサイトをご利用いただけます。
https://dates.jp/
この返信は自動返信メールです。
その他、ご質問、ご要望があれば、下記URLより
お問い合わせください。
https://dates.jp/contact
----------------------------------------------------------------
dates事務局
Email: support@dates.jp
URL: https://dates.jp
----------------------------------------------------------------`
const transporter = nodemailer.createTransport(config.transporter)
const mailOptions = {
from: 'sauzar18@gmail.com',
to: 'sauzar18@gmail.com',
subject: `【dates事務局】${name}様にご登録いただきました。`,
text: output
}
const autoSend = {
from: 'sauzar18@gmail.com',
to: email,
subject: `【dates事務局】${name}様ご登録ありがとうございます。`,
text: reverse
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
arrResponse = {
'status': 'error',
'error': error
}
res.status(500)
} else {
arrResponse = {
'status': 'success',
'data': info.accepted
}
transporter.sendMail(autoSend, (error, info) => {
if (error) consola.ready(error)
else consola.ready(info.accepted)
})
}
res.end()
})
connection.query(emailQuery, function (err, email) {
const emailExists = email.length
if (emailExists) {
res.status(401).json({
error: '既にメールアドレスが登録されています'
})
} else if (err) {
consola.ready(err)
} else {
connection.query(registerQuery, function (err, rows) {
if (rows) {
res.json({
ok: true
})
} else if (err) {
consola.ready(err)
res.json({
ok: false
})
}
})
}
})
})
export default router
|
// ==UserScript==
// @name find_all_ed2k_or_magnet
// @namespace NULL
// @version 0.1
// @description find all ed2k,magnet links
// @author Simon Shi
// @include *
// @match *
// @grant unsafeWindow
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
// Your code here...
console.log("find_all_ed2k_or_magnet loaded")
var herf_list = document.getElementsByTagName("A")
var i = 0
var results = new Array()
var results_text = ""
var split_count = 0
var last_text = ""
var last_type = ""
var type_ed2k = false
var type_magnet = false
var current_type = ""
for(i in herf_list){
var url_text = herf_list[i].href
if(url_text == null){
continue
}
if(url_text == last_text){
continue
}
last_text = url_text
type_ed2k = url_text.startsWith("ed2k:")
type_magnet = url_text.startsWith("magnet")
if(type_ed2k){
current_type = "type_ed2k"
}else if(type_magnet){
current_type = "type_magnet"
}else{
current_type = last_type
}
if(url_text.startsWith("ed2k:") || url_text.startsWith("magnet")){
split_count = split_count + 1
results.push(url_text)
try{
if(split_count == 1){
results_text = decodeURI(url_text)
}else if(current_type != last_type){
results_text = results_text + "\n\n\n\n" + decodeURI(url_text)
}else{
results_text = results_text + "\n" + decodeURI(url_text)
}
}catch(err){
console.log(err)
console.log(url_text)
results_text = results_text + "\n" + url_text
}
}
last_type = current_type
}
if(split_count<=0){
console.log("No ed2k or magnet found. return.")
return;
}
console.log(results)
var newDiv = document.createElement("div");
newDiv.style.backgroundColor= "#c0ffc0"
newDiv.innerText=(results_text)
document.body.appendChild(newDiv)
})();
|
var Vue = require('vue');
var VueRouter = require('vue-router');
var configRouter = require('./route.config.js');
Vue.use(VueRouter);
var router = new VueRouter({});
configRouter(router)
var App = Vue.extend(require('./app.vue'));
router.start(App, 'body div');
window.router = router;
|
import ResultsItem from '../../client/components/results__item';
const FLIGHT = {
"airline": {
"code": "SU",
"name": "Aeroflot"
},
"flightNum": 182,
"start": {
"dateTime": "2016-09-03T09:59:00+10:00",
"airportCode": "SYD",
"airportName": "Kingsford Smith",
"cityCode": "SYD",
"cityName": "Sydney",
"countryCode": "AU",
"countryName": "Australia",
"latitude": -33.946111,
"longitude": 151.177222,
"stateCode": "NS",
"timeZone": "Australia/Sydney"
},
"finish": {
"dateTime": "2016-09-03T16:00:00-04:00",
"airportCode": "JFK",
"airportName": "John F Kennedy Intl",
"cityCode": "NYC",
"cityName": "New York",
"countryCode": "US",
"countryName": "United States",
"latitude": 40.639751,
"longitude": -73.778925,
"stateCode": "NY",
"timeZone": "America/New_York"
},
"plane": {
"code": "333",
"shortName": "Airbus A330-300",
"fullName": "Airbus Industrie A330-300",
"manufacturer": "Airbus",
"model": "A330-300"
},
"distance": 16014,
"durationMin": 1201,
"price": 1590.82
};
describe('Results Item', function() {
it('it renders correct markup', function() {
expect(ResultsItem(FLIGHT)).to.be.eql(`
<div class=undefined>
<h4 class=undefined>
$1590.82
</h4>
<div class=undefined>
<div class=undefined>
<strong>SU182</strong>
Aeroflot
</div>
<div>
<strong>23:59</strong>
Kingsford Smith
</div>
<div>
<strong>20:00</strong>
John F Kennedy Intl
</div>
</div>
<div class=undefined>
20h 1m
</div>
</div>
`);
});
});
|
/**
* Represents a playing card.
* @TODO Add support for blank cards, use '00' as the code.
* @author Rajitha Wannigama
*/
var Card = {
/**
* @type {Rank}
* @private
*/
rank: undefined,
/**
* @type {Suit}
* @private
*/
suit: undefined,
/**
* Create a new card.
* Card.create('2C'); // Two of Clubs
* Card.create('WC'); // The Joker - suit lets you identify each joker.
* @constructor
* @this {Card}
* @param {String} value '2c' for Two of Clubs. Case does not matter, e.g. '2c' == '2C'
* @returns {Card}
* @throws {Error}
*/
create: function(value) {
var obj, rank, suit;
// Value must be a string of length 2.
if ( (typeof value != 'string') || (value.length != 2) ) {
throw new Error('cards.Card.create: Invalid value for a card. value = ' + value);
}
value = value.toLowerCase();
rank = Rank.create(value[0]);
suit = Suit.create(value[1]);
obj = Object.create(this);
obj.rank = rank;
obj.suit = suit;
return obj;
},
/**
* Get the HTML code that displays this card.
* @param {Object} [options] an object that defines how this card is displayed
* {
* faceup: true,
* size: 'poker','bridge','jumbo','mini', 'custom' // if custom, define width and height
* scale: '5:2', '1:1' // the scale used to draw the card on the screen.
* poker size (2.5×3.5 inches (64×89 mm), or B8 size according to ISO 216)
* bridge size (2.25×3.5 inches (57×89 mm))
* smaller size (usually 1.75×2.625 inches (44×66.7 mm)) for solitaire
*
* }
* @returns {Object #<HTMLDivElement>}
*/
html: function(options) {
if ( typeof options === 'undefined' ) {
// Use default options
options = {
faceup: true,
size: 'poker',
scale: '',
selectable: false,
hover_effect: 'zoom', // 'push', 'highlight'
zoom_on_hover: false
}
}
var div = document.createElement('div');
var divTop = document.createElement('div');
var divBottom = document.createElement('div');
var sRank = document.createElement('span');
var sSuit = document.createElement('span');
div.setAttribute('data-cards','card');
div.style.position = 'relative';
div.style.border = '1px solid #000000';
div.style.backgroundColor = '#ffffff';
div.style.borderRadius = '10px';
div.style.fontFamily = '"Trebuchet MS", Helvetica, sans-serif';
div.style.display = 'inline-block';
div.style.width = '80px';
div.style.height = '111.25px';
//div.style.paddingLeft = '4px';
//div.style.paddingRight = '4px';
sRank.innerHTML = this.rank.html();
sSuit.innerHTML = this.suit.html();
if ( /^(h|d)$/.test(this.suit.value) ) {
sSuit.style.color = 'red';
}
sRank.style.fontSize = '16px';
if ( this.rank.value === '0' ) {
sRank.style.fontSize = '14px';
}
sSuit.style.fontSize = '22px';
divTop.appendChild(sRank);
divTop.appendChild(sSuit);
divTop.style.position = 'absolute';
divTop.style.top = '0px';
divTop.style.left = '4px';
div.appendChild(divTop);
divBottom.appendChild(sSuit.cloneNode(true));
divBottom.appendChild(sRank.cloneNode(true));
divBottom.style.transform = 'rotate(180deg)';
divBottom.style.webkitTransform = 'rotate(180deg)';
divBottom.style.MozTransform = 'rotate(180deg)';
divBottom.style.msTransform = 'rotate(180deg)';
divBottom.style.OTransform = 'rotate(180deg)';
divBottom.style.position = 'absolute';
divBottom.style.bottom = '0px';
divBottom.style.right = '4px';
div.appendChild(divBottom);
return div;
},
/**
*
* @param {Object} obj
* @returns {Boolean}
*/
isCard: function(obj) {
return typeof obj === 'object';
},
/**
*
* @param {RegExp}
* @returns {Boolean}
*/
is: function() {
}
};
|
import React, {useState} from 'react';
import {Button, Form, FormGroup, Label, Input, Row} from 'reactstrap';
import './SkiLengthForm.css'
function SkiLengthFormAdult() {
const [type, setType] = useState("Klassisk")
const [bodyLength, setBodyLength] = useState(0);
const [skiLength, setSkiLength] = useState(0);
function submitForm() {
let urlAPI = ""
if (type === "Klassisk") {
urlAPI = `https://localhost:5001/Ski/GetSkiLengthClassic/${bodyLength}`
} else {
urlAPI = `https://localhost:5001/Ski/GetSkiLengthFreestyle/${bodyLength}`
}
fetch(urlAPI, {
method: 'get',
})
.then(res => res.json())
.then(length => {
setSkiLength(length)
})
.catch(err => console.log(err));
}
let message = skiLength > 0 ? `Vi rekommenderar skidlängden: ${skiLength} cm` : "Fyll i värden och klicka på beräkna"
return (
<div>
<Form>
<Row form className={"formRow"}>
<FormGroup>
<Label for="type">Typ</Label>
<Input type="select" name="type" id="type" value={type}
onChange={(e) => setType(e.target.value)}>
<option>Klassisk</option>
<option>Fristil</option>
</Input>
</FormGroup>
<FormGroup>
<Label for="length">Kroppslängd (cm)</Label>
<Input type="number" name="Kroppslängd" id="length" value={bodyLength}
onChange={(e) => setBodyLength(e.target.value)}/>
</FormGroup>
</Row>
</Form>
<Button color={"primary"} className={"button"} onClick={submitForm}>Beräkna!</Button>
<div className={"padding"}>
<p>
{message}
</p>
</div>
</div>
);
}
export default SkiLengthFormAdult;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// 空禁止
function validator(v) {return v.length > 0;}
var Chat = new Schema({
roomId : { type: Number }
, userId : { type: String }
, userImageUri : { type: String }
, message : { type: String, validate: [validator, "Empty Error"] }
, createdDate : { type: String }
});
mongoose.connect('mongodb://localhost/ruura');
exports.Chat = mongoose.model('Chat', Chat);
|
// New York Times API
//
// http://developer.nytimes.com/
//
// Ask your local mentor for the API key or request your own. Use localhost as the website.
//
// - Use the Article Search API
// - Find articles about the moon landing by Apollo 11
// - Display the following fields in a list
// - Headline
// - Snippet
// - Publication date
// - Create a permalink to that article
var heading = document.createElement('h1');
document.body.appendChild(heading);
heading.setAttribute('class', 'heading');
heading.innerHTML = "Apollo 11";
var button = document.createElement('button');
document.body.appendChild(button);
button.setAttribute('class', 'button');
button.innerHTML = "Next";
var headline = document.createElement('p');
document.body.appendChild(headline);
headline.setAttribute('class', 'headline');
var link = document.createElement('a');
document.body.appendChild(link);
link.setAttribute('class', 'link');
link.setAttribute('href', '#')
link.innerHTML = "Go to the article!";
var snippet = document.createElement('p');
document.body.appendChild(snippet);
snippet.setAttribute('class', 'snippet');
var date = document.createElement('p');
document.body.appendChild(date);
date.setAttribute('class', 'date');
var request = new XMLHttpRequest();
var articleData = [];
request.open('GET', 'https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=ecf5a7de7cc04cb2b96621ac0933ae26&q=apollo+11+moon', true);
request.send(null);
request.onreadystatechange = function (response) {
var apolloData;
if (request.readyState === XMLHttpRequest.DONE) {
apolloData = JSON.parse(request.response);
getData(apolloData);
console.log(apolloData);
}
};
function getData (article) {
var index = 0;
article.response.docs.forEach( function (e) {
console.log(e);
articleData.push({'headline': e.headline.main, 'snippet': e.snippet, 'date': e.pub_date, 'link': e.web_url, 'index': index });
index++;
})
}
var counter = 0;
function changeArticle () {
headline.innerHTML = articleData[counter].headline;
link.setAttribute('href', articleData[counter].link);
snippet.innerHTML = articleData[counter].snippet;
date.innerHTML = articleData[counter].date;
counter++;
if (counter >= articleData.length) {
counter = 0;
}
}
button.addEventListener('click', changeArticle);
|
import Grid from "@material-ui/core/Grid";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";
import React from "react";
export default function SizeSelector() {
const [alignment, setAlignment] = React.useState("left");
const handleChange = (event, newAlignment) => {
setAlignment(newAlignment);
};
return (
<Grid container spacing={2} direction="column" alignItems="left">
<Grid item>
<ToggleButtonGroup
size="medium"
value={alignment}
exclusive
onChange={handleChange}
>
<ToggleButton value="left"> S</ToggleButton>
<ToggleButton value="center">M</ToggleButton>
<ToggleButton value="right">L</ToggleButton>
<ToggleButton value="justify">XL</ToggleButton>
</ToggleButtonGroup>
</Grid>
</Grid>
);
}
|
var spawn = require("child_process").spawn;
var spawnSync = require("child_process").spawnSync;
var exec = require("child_process").exec;
var readline = require('readline');
var binaryFile = 'test';
var gdb = spawn('lldb',[binaryFile]);
var cur_ip_port = "192.168.31.169\:1234" //ip:port
var searching_flag = 0;
var search_result = new Array();
gdb.stdout.setEncoding('utf8');
gdb.stderr.setEncoding('utf8');
gdb.stdin.setEncoding('utf8');
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout
});
console.log("开始调试");
var input_command = function(){
rl.question("请输入指令\n",function(answer){
console.log(answer);
if(answer == 'pause'){
answer = 'process\ i';
gdb.stdin.write(answer + '\n');
}else if(answer == 'searching'){
searching_memory();
}else if(answer == 'sr'){
console.log(search_result);
input_command();
}else{
gdb.stdin.write(answer + '\n');
}
// 不加close,则不会结束
// rl.close();
});
}
gdb.stderr.on('data',function(data)
{
console.log(data);
input_command();
});
gdb.stdout.on('data',function(data){
// need = "Current\ executable\ set\ to\ \'test\'\ \(x86_64\)\."
if (searching_flag == 0){
console.log(data);
// console.log(data.match('Current\ executable'));
if(data.match('Current\ executable') != null){
console.log('开启lldb成功,准备连接iphone!')
console.log('process\ connect\ connect\:\/\/' + cur_ip_port);
gdb.stdin.write('process\ connect\ connect\:\/\/' + cur_ip_port + '\n')
}
if(data.match('stop\ reason') != null){
console.log('暂停进程成功!')
input_command();
}
if(data.match('resuming') != null){
console.log('恢复进程运行成功!')
input_command();
}
}
});
var searching_memory = function(){
searching_flag = 1
var start = '10E000000';
var end = '10EFFFFFF';
var now_end_10 = 0
var start_10 = parseInt(start, 16);
var end_10 = parseInt(end, 16);
var keep_searching = function(){
now_end_10 = start_10 + 400;
console.log(end_10 - start_10);
if(end_10 - start_10 > 400){
gdb.stdin.write('memory\ read\ 0x' + start_10.toString(16) + ' 0x' + now_end_10.toString(16) + '\n');
}else{
console.log('搜索完毕!')
searching_flag = 0;
// console.log(search_result);
input_command();
}
}
keep_searching();
gdb.stdout.on('data',function(data){
console.log('outing!!')
if(searching_flag == 1){
console.log('is searching!')
// console.log(data);
need_data = new Array('02','00','00','00');
format_search_result(start_10,data,need_data);
start_10 = now_end_10;
keep_searching();
}else{
console.log('搜索完毕!');
input_command();
}
});
}
var format_search_result = function(base,data,need_data){
var cur_search_result = new Array()
formated = data.split('\ ');
for(var _i = 0,_j = 0;_i <= formated.length - 1;_i++){
if(formated[_i].length == 2){
cur_search_result[base + _j] = formated[_i];
_j++;
}
}
console.log(cur_search_result);
for(var _k = base;_k <= cur_search_result.length - 1;_k++){
if ((cur_search_result[_k] == need_data[0]) && (cur_search_result[_k + 1] == need_data[1]) && (cur_search_result[_k + 2] == need_data[2]) && (cur_search_result[_k + 3] == need_data[3])){
search_result[_k] = cur_search_result[_k];
search_result[_k + 1] = cur_search_result[_k + 1];
search_result[_k + 2] = cur_search_result[_k + 2];
search_result[_k + 3] = cur_search_result[_k + 3];
}
}
}
//command
|
var server = require("./server.js");
var router = require("./router.js");
var processor = require("./requestProcessor");
var process = {};
process["/"] = processor.hello;
process["/start"] = processor.start;
process["/list"] = processor.list;
process["/upload"] = processor.upload;
server.start(router.route, process);
|
/**
* Created by Administrator on 2015/3/26.
*/
var indexPageController = angular.module("indexPageController",[
]);
indexPageController.controller("headDivController",[
"$scope",
"$http",
"$location",
'$timeout',
'checkDuplicateService',
'loginStatusCheckService',
'loginCheckService',
function($scope,$http,$location,$timeout,checkDuplicateService,loginStatusCheckService,loginCheckService){
var login=function(){
this.kick_out=false; //该变量决定是否踢出别处登录的用户
};
$scope.var={};
$scope.var.login={};
$scope.fn={};
$scope.timeout={};
loginStatusCheckService.check($scope);
$scope.fn.toUserPage=function(){
loginStatusCheckService.check($scope);
$location.path("/user"); //ng-view 跳转到用户设置页面
};
$scope.fn.toLoginPage = function(){
$scope.var.hidden_login_page_visible=!$scope.var.hidden_login_page_visible;
};
$scope.fn.LoginPageQuit = function(){
$scope.var.hidden_login_page_visible=false;
$scope.var.login=new login();
};
$scope.fn.toRegisterPage = function(){
$location.path("/register");
$scope.var.hidden_login_page_visible=false;
};
$scope.fn.LoginSubmit=function(){
if($scope.login_form.$valid){
loginCheckService.check($scope);
$scope.var.hidden_login_page_visible=false;
$scope.var.login=new login();
}
};
$scope.fn.logout=function(){
var logoutConfirm=confirm("确定退出?");
if(logoutConfirm){
$http({
method:"POST",
url:"php/logout.php"
}).success(function(result){
$scope.var.user=result;
user=result;
});
}
$location.path("/main");
};
$scope.fn.login_form_enter=function(){
$timeout.cancel($scope.timeout.login_show)
};
$scope.fn.login_form_leave=function(){
$scope.timeout.login_show=$timeout(function(){
$scope.fn.LoginPageQuit();
},3000)
};
}]).controller('navigatorDivController',['$scope','$http','$location','$timeout',function($scope,$http,$location,$timeout){
$http.get("json/navigator.json").success(function(result){
$scope.var=result;
});
$scope.fn={};$scope.timeout={};
$scope.fn.subTitleShow=function(){
$scope.timeout.navigator_subtitle=$timeout(function(){
$scope.var.sub_title_visible=true;
$scope.var.highLightBar.col[0].visible=true;
},500);
};
$scope.fn.subTitleHide=function(){
$scope.var.sub_title_visible=false;
$timeout.cancel($scope.timeout.navigator_subtitle)
};
$scope.fn.showBar=function(dom){
var row_num=dom.row;
var col_num=dom.col;
$scope.var.highLightBar.row[row_num].visible=true;
$scope.var.highLightBar.col[col_num].visible=true;
};
$scope.fn.hideBar=function(dom){
var row_num=dom.row;
var col_num=dom.col;
$scope.var.highLightBar.row[row_num].visible=false;
$scope.var.highLightBar.col[col_num].visible=false;
$timeout.cancel($scope.timeout.navigator_subtitle)
};
$scope.fn.navigatorSwitch=function(obj){
$scope.var.sub_title_visible=false;
var locat="/"+obj.id;
if(obj.need_login){
if(user.loged_in){
if(obj.need_priority!=""){
for(var key in user.priority){
if(key==obj.need_priority){
if(user.priority[key]==1){
$location.path(locat);
return;
}
}
}
alert("没有权限!");
}else{
$location.path(locat);
}
}else{
alert("未登录,请先登录。")
}
}else{
$location.path(locat);
}
};
}]);
var registerPageController=angular.module("registerPageController",[]);
registerPageController.controller("registerController",[
"$scope",
"$http",
"$location",
"$window",
"$timeout",
"$log",
"checkDuplicateService",
'loginStatusCheckService',
'loginCheckService',
function($scope,$http,$location,$window,$timeout,$log,checkDuplicateService,loginStatusCheckService,loginCheckService){
$http.get("json/register_page.json").success(function(result){
$scope.var=result;
});
$scope.fn={};
$scope.fn.RegisterPageHide = function(){
$location.path("/main");
};
$scope.fn.RegisterPageBtnChange=function(){
$scope.var.quit_div_src="media/img/icons/cancel_orange.png";
};
$scope.fn.RegisterPageBtnRestore=function(){
$scope.var.quit_div_src="media/img/icons/cancel_blue.png";
};
$scope.fn.RegisterSubmit=function(){
$scope.var.submitted=true;
$scope.var.password_same=true;
$scope.var.account_duplicate=false;
$scope.var.name_duplicate=false;
$scope.var.phone_number_duplicate=false;
if($scope.var.password!=$scope.var.password2){
$scope.var.password_same=false;
alert("两次密码输入不一致");
return;
}
if($scope.register_form.$invalid){
return;
}
var upload_data={
"user_account":$scope.var.account,
//"user_name":$scope.var.name, //if need to check user name duplication,uncomment it.
"user_phone_number":$scope.var.phone_number
};
checkDuplicateService.check(upload_data).success(function(result){ //check account duplicate
if(result.code===2){
alert("duplicate check params wrong");
$log.log("url:php/duplicate_check.php\n service:checkDuplicateService. \n result: \n");
$log.log(result);
return;
}
$scope.var.account_duplicate=result.account_duplicate;
//$scope.var.name_duplicate=data.name_duplicate; //if need to check user name duplication,uncomment it.
$scope.var.phone_number_duplicate=result.phone_number_duplicate;
$scope.var.error=($scope.var.account_duplicate/*---||$scope.var.name_duplicate---*/||$scope.var.phone_number_duplicate||$scope.register_form.$invalid||(!$scope.var.password_same));
if(!$scope.var.error){
$http({
method:"POST",
url:"php/register_check.php",
data:$scope.var
}).success(function(result){
if(result.code===3){
alert("帐号和密码不能为空");
return;
}
if(result.code===2){
alert("帐号或密码格式不匹配");
return;
}
if(result.code===10){
$scope.var.login={};
$scope.var.login.account=$scope.var.account;
$scope.var.login.password=$scope.var.password;
loginCheckService.check($scope);
$timeout(function(){
$location.path("/main");
$window.location.reload();
},1000);
}
})
}
})
};
}]);
var userPageController=angular.module("userPageController",[]);
userPageController.controller("userPageController",["$scope","$http","readMailContentService","userInfoCacheService",function($scope,$http,readMailContentService,userInfoCacheService){
$scope.fn={};
$scope.var={};
$http.get("json/user_main_page.json").success(function(result){
$scope.var=result;
});
$scope.fn.navigatorLiClick=function(subtitle){
for(var i=0;i!=$scope.var.subtitles.length;i++){
$scope.var.subtitles[i].selected=false;
$scope.var.subtitles[i].css_class="user_page_navigator_origin";
}
subtitle.selected=true;
subtitle.css_class="user_page_navigator_change";
if(subtitle.id=="console"){
$scope.var.user_info_set_selected=true;
}
};
}]);
var mailPageController=angular.module("mailPageController",[]);
mailPageController.controller("mailPageController",["$scope","$http","$log","$timeout","$location","readMailContentService","userInfoCacheService","setMailNoteService","setMailDirectoryService",function($scope,$http,$log,$timeout,$location,readMailContentService,userInfoCacheService,setMailNoteService,setMailDirectoryService){
$scope.fn={};$scope.var={};
if(!user.loged_in){
$location.path("/main");
alert("未登录");
return;
}
$scope.var.mail_directory_index=0;
$scope.var.mail_type=0;
$scope.var.mail_page_index=1;
$http.get("json/mail_page_controller.json").success(function(result){
$scope.var=result;
});
$http.get("php/get_directory.php").success(function(result){
$scope.var.mail_directory=result.content;
for(var p in $scope.var.mail_directory.income){
$scope.var.mail_directory.income[p].chosen=false
}
for(var p in $scope.var.mail_directory.outcome){
$scope.var.mail_directory.outcome[p].chosen=false
}
});
$scope.fn.readMailContent=function(type,page_index,mail_directory){ //type区分邮件类型 0:收件箱;1:发件箱;
$scope.var.mail_content_visible=false;
$scope.var.set_directory_visible=false;
readMailContentService.read(type,page_index,mail_directory).success(function(result){
if(result.code!==10){
alert("read mail content error");
$log.log("url:php/read_mail.php.\n service:readMailContentService.\n result: \n");
$log.log(result);
return;
}
$scope.var.mails=result.mail;
$scope.var.mail_count=result.mail_count;
$scope.var.mail_page_count=Math.ceil(result.mail_count/20);
var user_info=userInfoCacheService.cache.get(0);
if(!user_info){
userInfoCacheService.updata(0).success(function(result2){
if(result2.code!=10){
alert("read user info error");
$log.log("url: php/user_info.php.\n service:userInfoCacheService.\n result:\n");
$log.log(result2);
return;
}
user_info=result2.content;
userInfoCacheService.cache.put(0,result2.content);
for(var p in $scope.var.mails){
var creator_index=$scope.var.mails[p].creator_index;
$scope.var.mails[p].creator=user_info[creator_index-1];
$scope.var.mails[p].receiver_info=[];
for(var q in $scope.var.mails[p].receiver){
var receiver_index=$scope.var.mails[p].receiver[q];
var receiver_info=user_info[receiver_index-1];
$scope.var.mails[p].receiver_info.push(receiver_info)
}
if(typeof($scope.var.mails[p].note)=="undefined"){
$scope.var.mails[p].note={};
}
if($scope.var.mails[p].important=="1"){
$scope.var.mails[p].note.important="media/img/icons/important_red.png";
}else{
$scope.var.mails[p].note.important="media/img/icons/important_grey.png";
}
if($scope.var.mails[p].urgent=="1"){
$scope.var.mails[p].note.urgent="media/img/icons/urgent_yellow.png";
}else{
$scope.var.mails[p].note.urgent="media/img/icons/urgent_grey.png";
}
$scope.var.mails[p].note.selected="media/img/icons/selected_grey.png";
}
})
}else{
for(var p in $scope.var.mails){
var creator_index=$scope.var.mails[p].creator_index;
$scope.var.mails[p].creator=user_info[creator_index-1];
$scope.var.mails[p].receiver_info=[];
for(var q in $scope.var.mails[p].receiver){
var receiver_index=$scope.var.mails[p].receiver[q];
var receiver_info=user_info[receiver_index-1];
$scope.var.mails[p].receiver_info.push(receiver_info)
}
if(typeof($scope.var.mails[p].note)=="undefined"){
$scope.var.mails[p].note={};
}
if($scope.var.mails[p].important=="1"){
$scope.var.mails[p].note.important="media/img/icons/important_red.png";
}else{
$scope.var.mails[p].note.important="media/img/icons/important_grey.png";
}
if($scope.var.mails[p].urgent=="1"){
$scope.var.mails[p].note.urgent="media/img/icons/urgent_yellow.png";
}else{
$scope.var.mails[p].note.urgent="media/img/icons/urgent_grey.png";
}
$scope.var.mails[p].note.selected="media/img/icons/selected_grey.png";
}
}
});
};
$scope.fn.readMailContent(0,1,$scope.var.mail_directory_index);
$scope.fn.writeMail=function(){
$scope.var.write_page_visible=!$scope.var.write_page_visible;
$scope.set_directory_visible=false
};
$scope.fn.allMailChosen=function(){
var mails=$scope.var.mails;
$scope.var.mail_chosen_arr=[];
if(!$scope.var.all_mail_chosen){
for(var p in mails){
$scope.var.mail_chosen_arr.push(mails[p].index);
mails[p].chosen=true;
}
}else{
for(var p in mails){
mails[p].chosen=false;
}
}
$scope.var.all_mail_chosen=!$scope.var.all_mail_chosen;
};
$scope.fn.noteImportant=function(){
setMailNoteService.set($scope.var.mail_chosen_arr,"mail_important",1).success(function(result){
if(result.code!=10){
alert("set note error");
$log.log("url:"+"php/set_mail_note.php \n"+"service: setMailNoteService \n"+"result:");
$log.log(result);
return;
}
for(var p=0;p!=$scope.var.mail_chosen_arr.length;p++){
var index=$scope.var.mail_chosen_arr[p];
for(var x in $scope.var.mails){
if($scope.var.mails[x].index==index){
$scope.var.mails[x].important="1"
}
}
}
})
};
$scope.fn.noteUrgent=function(){
setMailNoteService.set($scope.var.mail_chosen_arr,"mail_urgent",1).success(function(result){
if(result.code!=10){
alert("set note error");
$log.log("url:"+"php/set_mail_note.php \n"+"service: setMailNoteService \n"+"result:");
$log.log(result);
return;
}
for(var p=0;p!=$scope.var.mail_chosen_arr.length;p++){
var index=$scope.var.mail_chosen_arr[p];
for(var x in $scope.var.mails){
if($scope.var.mails[x].index==index){
$scope.var.mails[x].urgent="1"
}
}
}
})
};
$scope.fn.noteRead=function(){
setMailNoteService.set($scope.var.mail_chosen_arr,"mail_read",1).success(function(result){
if(result.code!=10){
alert("set note error");
$log.log("url:"+"php/set_mail_note.php \n"+"service: setMailNoteService \n"+"result:");
$log.log(result);
return;
}
for(var p=0;p!=$scope.var.mail_chosen_arr.length;p++){
var index=$scope.var.mail_chosen_arr[p];
for(var x in $scope.var.mails){
if($scope.var.mails[x].index==index){
$scope.var.mails[x].read="1"
}
}
}
})
};
$scope.fn.mailToTrash=function(){
var cf=confirm("确定删除邮件?");
if(!cf){
$scope.var.mail_chosen_arr=[];
for(var p in $scope.var.mails){
$scope.var.mails[p].chosen=false;
}
return;
}
var data={};
var mail_index_arr=$scope.var.mail_chosen_arr;
data.index=mail_index_arr.join();
console.log(mail_index_arr);
$http({
method:"POST",
url:"php/delete_mail.php",
data:data
}).success(function(result){
if(result.code!=10){
alert("delete mail error");
$log.log("url:delete_mail.php \n function:fn.mailToTrash \n result:");
$log.log(result);
}
$scope.var.mail_content_visible=false;
for(var p in $scope.var.mails){
for(var q in mail_index_arr){
if($scope.var.mails[p].index==mail_index_arr[q]){
$scope.var.mails=ArrayDelValue($scope.var.mails,$scope.var.mails[p])
}
}
}
})
};
$scope.fn.backToMail=function(){
$scope.var.mail_content_visible=false;
$scope.var.set_directory_visible=false;
$scope.var.mail_chosen_arr=[];
for(var p in $scope.var.mails){
$scope.var.mails[p].chosen=false
}
};
$scope.fn.toPage=function(){
$scope.fn.readMailContent($scope.var.mail_type,$scope.var.mail_page_index,$scope.var.mail_directory_index);
};
$scope.fn.toIncomeBox=function(){
if($scope.var.mail_type==0&&!$scope.var.set_directory_visible&&!$scope.var.mail_content_visible){
return;
}
$scope.var.mail_type=0;
$scope.fn.readMailContent($scope.var.mail_type,1,0);
};
$scope.fn.toOutcomeBox=function(){
if($scope.var.mail_type==1&&!$scope.var.set_directory_visible&&!$scope.var.mail_content_visible){
return;
}
$scope.var.mail_type=1;
$scope.fn.readMailContent($scope.var.mail_type,1,0);
};
$scope.fn.mailToDirectory=function(index){
var data=function(){
this.directory_index=index;
this.type=$scope.var.mail_type;
this.mail_index=$scope.var.mail_chosen_arr.join();
};
input=new data;
$http({
method:"POST",
url:"php/mail_move_directory.php",
data:input
}).success(function(result){
if(result.code!=10){
alert("add move directory error");
$log.log("url:"+"php/mail_move_directory.php \n"+"function: fn.moveToDirectory \n"+"result:");
$log.log(result);
return;
}
})
};
$scope.fn.toggleDirectoryInput=function(){
$scope.var.set_directory_visible=!$scope.var.set_directory_visible;
};
$scope.fn.changeMailDirectory=function(type,page_index,mail_directory){
$scope.fn.readMailContent(type,page_index,mail_directory);
$scope.var.mail_directory_index=mail_directory;
};
$scope.fn.addMailDirectory=function(key){
var directory_item=function(index,name){
this.index=index;
this.name=name;
};
var max_index=0;
if(key=="income"){
for(var p in $scope.var.mail_directory.income){
if($scope.var.mail_directory.income[p].index>max_index){
max_index=$scope.var.mail_directory.income[p].index;
}
}
var plus_directory=new directory_item(max_index+1,$scope.var.add_directory_name_income);
$scope.var.mail_directory.income.push(plus_directory);
}
if(key=="outcome"){
for(var p in $scope.var.mail_directory.outcome){
if($scope.var.mail_directory.outcome[p].index>max_index){
max_index=$scope.var.mail_directory.outcome[p].index;
}
}
var plus_directory=new directory_item(max_index+1,$scope.var.add_directory_name_outcome);
$scope.var.mail_directory.outcome.push(plus_directory);
}
setMailDirectoryService.set($scope.var.mail_directory).success(function(result){
if(result.code!=10){
alert("add mail directory error");
$log.log("url:"+"php/set_user_mail_directory.php \n"+"function: fn.addMailDirectory \n"+"result:");
$log.log(result);
return;
}
if(result.code===10){
alert("添加成功");
}
});
$scope.fn.addMailDirectoryCancel();
};
$scope.fn.addMailDirectoryCancel=function(){
$scope.var.add_directory_name_outcome="";
$scope.var.add_directory_name_income="";
$scope.var.add_outcome_directory_clicked=false;
$scope.var.add_income_directory_clicked=false;
};
$scope.fn.mailDirectoryChosen=function(obj){
if(obj.index==0||obj.index==1||obj.index==2){
return;
}
obj.chosen=!obj.chosen;
};
$scope.fn.directoryToTrash=function(){
var cf=confirm("确定要删除么?");
if(!cf){
for(var p in $scope.var.mail_directory.income){
$scope.var.mail_directory.income[p].chosen=false
}
for(var p in $scope.var.mail_directory.outcome){
$scope.var.mail_directory.outcome[p].chosen=false
}
return;
}
var income=[];
var outcome=[];
for(var p in $scope.var.mail_directory.income){
if(!$scope.var.mail_directory.income[p].chosen){
income.push($scope.var.mail_directory.income[p])
}
}
for(var p in $scope.var.mail_directory.outcome){
if(!$scope.var.mail_directory.outcome[p].chosen){
outcome.push($scope.var.mail_directory.outcome[p])
}
}
$scope.var.mail_directory.income=income;
$scope.var.mail_directory.outcome=outcome;
setMailDirectoryService.set($scope.var.mail_directory).success(function(result){
if(result.code!=10){
alert("add mail directory error");
$log.log("url:"+"php/set_user_mail_directory.php \n"+"function: fn.addMailDirectory \n"+"result:");
$log.log(result);
return;
}
if(result.code===10){
alert("删除成功");
}
});
};
$scope.fn.thisDirectoryToTrash=function(key,item){
var cf=confirm("确定删除该文件夹?");
if(cf){
if(key=="income"){
var income=[];
for(var p in $scope.var.mail_directory.income){
if(item.index!=$scope.var.mail_directory.income[p].index){
income.push($scope.var.mail_directory.income[p]);
}
}
$scope.var.mail_directory.income=income;
}
if(key=="outcome"){
var outcome=[];
for(var p in $scope.var.mail_directory.outcome){
if(item.index!=$scope.var.mail_directory.outcome[p].index){
outcome.push($scope.var.mail_directory.outcome[p]);
}
}
$scope.var.mail_directory.outcome=outcome;
}
setMailDirectoryService.set($scope.var.mail_directory).success(function(result){
if(result.code!=10){
alert("add mail directory error");
$log.log("url:"+"php/set_user_mail_directory.php \n"+"function: fn.addMailDirectory \n"+"result:");
$log.log(result);
return;
}
if(result.code===10){
alert("删除成功");
}
});
}
};
$scope.fn.thisDirectoryEdit=function(key,item){
if(key=="income"){
for(var p in $scope.var.mail_directory.income){
if(item.index==$scope.var.mail_directory.income[p].index){
$scope.var.mail_directory.income[p].name=item.tmp_name;
}
}
}
if(key=="outcome"){
for(var p in $scope.var.mail_directory.outcome){
if(item.index==$scope.var.mail_directory.outcome[p].index){
$scope.var.mail_directory.outcome[p].name=item.tmp_name;
}
}
}
setMailDirectoryService.set($scope.var.mail_directory).success(function(result){
if(result.code!=10){
alert("add mail directory error");
$log.log("url:"+"php/set_user_mail_directory.php \n"+"function: fn.addMailDirectory \n"+"result:");
$log.log(result);
}
})
};
$scope.fn.thisDirectoryEditCancel=function(item){
item.change_name=false;
item.tmp_name="";
return item;
};
$scope.$watch("var.mail_chosen_arr.length",function(newval){
newval==0?$scope.var.mail_set_btn_visible=false:$scope.var.mail_set_btn_visible=true;
});
}]).controller("oneMailController",["$scope","$http","$log","noteService",function($scope,$http,$log,noteService){
$scope.$parent.mail.chosen=false;
$scope.$parent.mail.checked_img="media/img/icons/selected_green.png";
$scope.$parent.mail.leave_img="media/img/icons/selected_grey.png";
$scope.fn.mailCreatorClick=function(scope){
scope.creator_visible=!scope.creator_visible;
};
$scope.fn.hideCreatorDiv=function(scope){
scope.creator_visible=false;
};
$scope.fn.showMailContent=function(mail){
$scope.$parent.$parent.var.mail_content={};
$scope.$parent.$parent.var.mail_content_visible=true;
$scope.$parent.$parent.var.mail_content.content=mail.content;
$scope.$parent.$parent.var.mail_content.title=mail.title;
$scope.$parent.$parent.var.mail_content.receiver=mail.receiver_info;
$scope.$parent.$parent.var.mail_content.creator=mail.creator.user_name;
$scope.$parent.$parent.var.mail_content.important=mail.important;
$scope.$parent.$parent.var.mail_content.urgent=mail.urgent;
$scope.$parent.mail.chosen=true;
$scope.$parent.$parent.var.mail_chosen_arr=[];
$scope.$parent.$parent.var.mail_chosen_arr.push(mail.index);
$http({
method:"POST",
url:"php/set_mail_read.php",
data:mail.index
}).success(function(result){
if(result.code!=10){
alert("set mail read error");
$log.log("url:php/set_mail_read.php; \n function:fn.showMailContent() \n result:");
$log.log(result);
}
mail.read=1;
})
};
$scope.fn.selectEnter=function(mail){
noteService.set(mail,"select","enter")
};
$scope.fn.selectLeave=function(mail){
noteService.set(mail,"select","leave")
};
$scope.fn.selectClick=function(mail){
noteService.set(mail,"select","click");
if(mail.chosen){
$scope.$parent.$parent.var.mail_chosen_arr.push(mail.index)
}else{
$scope.$parent.$parent.var.mail_chosen_arr=ArrayDelValue($scope.$parent.$parent.var.mail_chosen_arr,mail.index)
}
};
$scope.fn.noteEnter=function(mail,index){
noteService.set(mail,index,"enter");
};
$scope.fn.noteLeave=function(mail,index){
noteService.set(mail,index,"leave");
};
$scope.fn.noteClick=function(mail,index){
noteService.set(mail,index,"click")
};
$scope.$watch("$parent.mail.chosen",function(){
if(typeof($scope.$parent.mail.note)!="undefined"){
if($scope.$parent.mail.chosen){
if($scope.$parent.mail.note.selected){
$scope.$parent.mail.note.selected="media/img/icons/selected_green.png";
}
}else{
if($scope.$parent.mail.note.selected){
$scope.$parent.mail.note.selected="media/img/icons/selected_grey.png";
}
}
}
});
$scope.$watch("$parent.mail.urgent",function(){
if(typeof($scope.$parent.mail.note)!="undefined"){
if($scope.$parent.mail.urgent=="1"){
$scope.$parent.mail.note.urgent="media/img/icons/urgent_yellow.png";
}else{
$scope.$parent.mail.note.urgent="media/img/icons/urgent_grey.png";
}
}
});
$scope.$watch("$parent.mail.important",function(){
if(typeof($scope.$parent.mail.note)!="undefined"){
if($scope.$parent.mail.important=="1"){
$scope.$parent.mail.note.important="media/img/icons/important_red.png";
}else{
$scope.$parent.mail.note.important="media/img/icons/important_grey.png";
}
}
});
}]).controller("writeMailController",["$scope","$http","$timeout","$log","userInfoCacheService","LDPInfoCacheService",function($scope,$http,$timeout,$log,userInfoCacheService,LDPInfoCacheService){
$scope.var={};
$scope.fn={};
$scope.LDP={};
$scope.receiver_key={};
$scope.receiver_key.page_index=1;
$scope.receiver_selected=[];
$scope.timeout={};
$scope.style={};
$scope.input_width=530;
$scope.receiver_element_style={};
$scope.receiver_stuff_style={};
$scope.receiver_input_style={};
$scope.title_style={};
$scope.content_style={};
$scope.receiver_style={};
$scope.mail_send={};
$scope.mail_send.urgent=0;
$scope.mail_send.important=0;
$scope.LDP=LDPInfoCacheService.cache.get(0);
if(!$scope.LDP){
LDPInfoCacheService.updata(0).success(function(result){
$scope.LDP=result;
LDPInfoCacheService.cache.put(0,result)
})
}
//$scope.all_users=userInfoCacheService.cache.get(0);
//if(!$scope.all_users){
// userInfoCacheService.updata(0).success(function(result){
// if(result.code!=10){
// alert("read user_info error");
// $log.log("url:"+"php/user_info.php \n"+"service: userInfoCacheService \n"+"result:");
// $log.log(result);
// return;
// }
// $scope.all_users=result.content;
// userInfoCacheService.cache.put(0,result.content)
// });
//}
$scope.fn.searchReceiverShow=function(){
$scope.var.search_page_visible=!$scope.var.search_page_visible;
};
$scope.fn.selectAllReceiver=function(){
for(var p in $scope.receivers){
$scope.receiver_selected.push($scope.receivers[p])
}
$scope.var.receiver_element_num=$scope.receiver_selected.length;
};
$scope.fn.searchReceiverHide=function(){
$scope.var.search_page_visible=false;
};
$scope.fn.getReceiverInfo=function(){
$http({
method:"POST",
url:"php/receiver_info.php",
data:$scope.receiver_key
}).success(function(result){
if(result.code!=10){
alert("get receiver_info error");
$log.log("url:"+"php/receiver_info.php \n"+"function: fn.getReceiverInfo \n"+"result:");
$log.log(result);
return;
}
$scope.receivers=result.content;
$scope.var.receiver_count=result.num;
$scope.var.receiver_page_count=Math.ceil(result.num/8);
})
};
$scope.fn.getReceiverInfo();
$scope.fn.writePageInputClick=function(){
$scope.var.search_page_visible=true;
};
$scope.fn.writePageCancel=function(){
var mail_send=function(){
this.important=0;
this.urgent=0;
this.title="";
this.content=""
};
$scope.$parent.var.write_page_visible=false;
$scope.var.search_page_visible=false;
$scope.receiver_selected=[];
$scope.mail_send=new mail_send
console.log($scope)
};
$scope.$watch("receiver_key.location",function(){
if(typeof($scope.receiver_key.location)!="undefined"){
$scope.fn.getReceiverInfo()
}
});
$scope.$watch("receiver_key.department",function(){
if(typeof($scope.receiver_key.department)!="undefined"){
$scope.fn.getReceiverInfo()
}
});
$scope.$watch("receiver_key.position",function(){
if(typeof($scope.receiver_key.position)!="undefined"){
$scope.fn.getReceiverInfo()
}
});
$scope.timeout.receiverName=$timeout(function(){
$scope.fn.getReceiverInfo()
},1000);
$scope.$watch("receiver_key.name",function(){
$timeout.cancel($scope.timeout.receiverName);
if(typeof($scope.receiver_key.name)!="undefined"){
$scope.timeout.receiverName=$timeout(function(){
$scope.fn.getReceiverInfo()
},1000);
}
});
$scope.$watch("receiver_selected.length",function(){
$scope.var.receiver_element_num=$scope.receiver_selected.length;
});
$scope.fn.choseReceiver=function(obj){
$scope.receiver_selected.push(obj);
console.log(obj)
};
$scope.fn.removeReceiver=function(obj){
$scope.receiver_selected=ArrayDelValue($scope.receiver_selected,obj)
};
$scope.fn.send_mail=function(){
var mail_send=function(){
this.urgent=0;
this.important=0
};
var arr=[];
for(var i=0;i!=$scope.receiver_selected.length;i++){
var index=parseInt($scope.receiver_selected[i].user_ID);
arr.push(index);
}
$scope.mail_send.receiver=ArrayDelDuplication(arr); //收件人数组去重
if($scope.mail_send.receiver.length==0||$scope.mail_send.title==""||$scope.mail_send.content==""||typeof($scope.mail_send.title)=="undefined"||typeof($scope.mail_send.content)=="undefined"){
alert("收件人、标题及内容不能为空");
return;
}
$http({
method:"POST",
url:"php/send_mail.php",
data:$scope.mail_send
}).success(function(result){
if(result.code!=10){
alert("send mail error");
$log.log("url:"+"php/send_mail.php \n"+"function: fn.send_mail \n"+"result:");
$log.log(result);
return;
}
$scope.mail_send=new mail_send;
$scope.receiver_selected=[];
}).error(function(result,status){
$log.log("result:"+result+" status:"+status)
})
};
$scope.$watch("var.receiver_element_num",function(){
if($scope.var.receiver_element_num<6||typeof($scope.var.receiver_element_num)=="undefined"){
$scope.receiver_style.height=40;
$scope.title_style.top=80;
$scope.content_style.top=120;
$scope.content_style.height=240;
}else{
$scope.receiver_style.height=80;
$scope.title_style.top=120;
$scope.content_style.top=160;
$scope.content_style.height=200;
if($scope.var.receiver_element_num>11){
document.getElementById("write_page_receiver_stuff").scrollTop=Math.ceil(($scope.var.receiver_element_num-11)/6)*39;
console.log(Math.ceil(($scope.var.receiver_element_num-11)/6)*39);
}
}
if(typeof($scope.var.receiver_element_num)=="undefined"){
$scope.receiver_input_style.width=500;
}else{
$scope.receiver_input_style.width=500-$scope.var.receiver_element_num%6*80;
}
$scope.receiver_stuff_style.height=$scope.receiver_style.height;
});
$scope.style.receiverInput=function(){
return{
"width":$scope.receiver_input_style.width+"px"
}
};
$scope.style.receiverElement=function(){
};
$scope.style.receiverStuff=function(){
return {
"height":$scope.receiver_stuff_style.height+"px",
"width":$scope.receiver_stuff_style.width+"px"
}
};
$scope.style.title=function(){
return{
"top":$scope.title_style.top+"px"
}
};
$scope.style.content=function(){
return{
"top":$scope.content_style.top+"px",
"height":$scope.content_style.height+"px"
}
};
$scope.style.receiver=function(){
return{
"height":$scope.receiver_style.height+"px"
}
}
}]);
|
function Piranha(context) {
this.context = context;
this.goingUp = true;
this.currentLocation = 0;
this.frameCount = 0;
this.waitFrames = 0;
this.leafAngle = 30;
this.colorPalette = {
orange: "rgb(200, 76, 12)",
blue: "rgb(0, 128, 136)",
lightPink: "rgb(252, 188, 176)"
}
}
Piranha.prototype.Draw = function(x, height, scale) {
UpdateState();
this.context.save();
this.context.scale(scale, scale);
DrawLeaves(this.context, this.colorPalette);
DrawLeftPlant(this.context, this.colorPalette);
DrawRightPlant(this.context, this.colorPalette);
this.context.restore();
}
function UpdateState() {
if(this.frameCount == 6) {
this.frameCount = 0;
if(this.currentLocation == 21 && this.waitFrames == 30) {
this.goingUp = false;
this.currentLocation--;
this.waitFrames = 0;
}
else if(this.currentLocation == 0 && this.waitFrames == 30) {
this.goingUp = true;
this.currentLocation++;
this.waitFrames = 0;
}
else if((this.currentLocation == 21 || this.currentLocation == 0) && this.WaitFrames != 30) {
this.waitFrames++;
}
else if(this.goingUp == true) {
this.currentLocation++;
}
else {
this.currentLocation--;
}
}
else {
this.frameCount++;
}
}
function DrawLeaves(context, colorPalette) {
}
function DrawLeftPlant(context, colorPalette) {
}
function DrawRightPlant(context, colorPalette) {
}
|
// globals
var particles;
// constants
var BACKGROUND_COLOR = [15, 5, 5];
var INTERACT_DISTANCE = 60;
var CANVAS_X = 1340;
var CANVAS_Y = 300;
var NUM_PARTICLES = 50;
var V_MAX = 0.7;
/**
* A particle object.
*/
var Particle = function(position) {
this.velocity = createVector(random(-V_MAX,V_MAX), random(-V_MAX,V_MAX));
this.position = position.copy();
}
Particle.prototype.update = function(){
//console.log("x:", this.position.x, "y:", this.position.y)
if ((this.position.x <= 0) || (this.position.x >= CANVAS_X)) {
this.velocity.set(-this.velocity.x, this.velocity.y);
}
if ((this.position.y <= 0) || (this.position.y >= CANVAS_Y)) {
this.velocity.set(this.velocity.x, -this.velocity.y);
}
this.position.add(this.velocity);
};
Particle.prototype.display = function() {
stroke(200, 100);
strokeWeight(1);
fill(80, 100);
ellipse(this.position.x, this.position.y, 3, 3);
};
function drawBackground() {
background(BACKGROUND_COLOR[0], BACKGROUND_COLOR[1], BACKGROUND_COLOR[2]);
}
function setup() {
createCanvas(CANVAS_X, CANVAS_Y);
drawBackground();
particles = [];
for(var i = 1; i < NUM_PARTICLES; i++) {
particles.push(new Particle(createVector(random(0,CANVAS_X),random(0,CANVAS_Y))))
}
}
function draw() {
drawBackground();
for(var i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].display();
// pretty triangles renderer
for(var j = 0; j < particles.length; j++) {
if (i != j) {
var dist12 = particles[i].position.dist(particles[j].position);
if (dist12 <= INTERACT_DISTANCE) {
for(var k = 0; k < particles.length; k++) {
if (i != k && j != k) {
var dist23 = particles[j].position.dist(particles[k].position);
if (dist23 <= INTERACT_DISTANCE) {
//noFill();
strokeWeight(1);
stroke(255,20);
triangle(particles[i].position.x, particles[i].position.y, particles[j].position.x, particles[j].position.y, particles[k].position.x, particles[k].position.y)
}
}
}
}
}
}
}
}
|
/* Import node's http module: */
var express = require('express');
var server = express();
var fs = require('fs');
var _chats = [];
// var handleRequest = require('./request-handler').requestHandler;
var readFile = function(callback) {
fs.readFile('messageData.txt', 'utf-8', (err, chatData) => {
if (err) { throw err; }
callback(chatData);
});
};
var writeFile = function(chatData) {
fs.writeFile('messageData.txt', chatData, function(err) {
if (err) {
return console.log(err);
}
});
};
readFile((chatData) => _chats = JSON.parse(chatData || '[]'));
var defaultCorsHeaders = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-headers': 'content-type, accept',
'access-control-max-age': 10 // Seconds.
};
var headers = defaultCorsHeaders;
headers['Content-Type'] = 'application/json';
// Every server needs to listen on a port with a unique number. The
// standard port for HTTP servers is port 80, but that port is
// normally already claimed by another server and/or not accessible
// so we'll use a standard testing port like 3000, other common development
// ports are 8080 and 1337.
var port = 3000;
// For now, since you're running this server on your local machine,
// we'll have it listen on the IP address 127.0.0.1, which is a
// special address that always refers to localhost.
var ip = '127.0.0.1';
// We use node's http module to create a server.
//
// The function we pass to http.createServer will be used to handle all
// incoming requests.
//
// After creating the server, we will tell it to listen on the given port and IP. */
server.use(express.static('client'));
server.options('/classes/messages', (request, response) => {
response.header(headers);
response.set(200).send();
});
server.get('/classes/messages', (request, response) => {
response.header(headers);
response.send({results: _chats});
});
server.post('/classes/messages', (request, response) => {
request.on('data', chunk => {
var data = JSON.parse(chunk.toString());
data.createdAt = new Date;
_chats.push(data);
if (_chats.length > 100) { _chats.unshift(); }
writeFile(JSON.stringify(_chats));
});
response.header(headers);
response.set(201).send({statusCode: 201, success: 'Message received'});
});
server.listen(port, () => {
console.log('Listening on http://' + ip + ':' + port);
});
// To start this server, run:
//
// node basic-server.js
//
// on the command line.
//
// To connect to the server, load http://127.0.0.1:3000 in your web
// browser.
//
// server.listen() will continue running as long as there is the
// possibility of serving more requests. To stop your server, hit
// Ctrl-C on the command line.
|
// decorator
function cachify(oldFn) {
var cache = {};
var newFn = function() {
var k = Array.prototype.join.call(arguments, ',');
console.log("key", k);
if(cache.hasOwnProperty(k)) {
console.log('cache hit!!!!');
return cache[k];
} else {
var res = oldFn.apply(null, arguments);
cache[k] = res;
return res;
}
};
return newFn;
}
var cacheyParse = cachify(parseInt);
var res1 = cacheyParse("100", 2);
console.log(res1);
var res2 = cacheyParse("100", 2);
console.log(res2);
|
import React from 'react'
import { HashRouter as Router, Switch, Route, Link } from "react-router-dom"
import AddUser from './pages/AddUser.jsx'
import AllUser from './pages/AllUser.jsx'
import EditUser from './pages/EditUser.jsx'
import Page404 from './pages/Page404.jsx'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<Router>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className="navbar-brand">Пользователи</Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item active">
<Link to="/addUser" className="nav-link">Добавить пользователя</Link>
</li>
</ul>
</div>
</nav>
<div>
<Switch>
<Route exact path="/" component={AllUser} />
<Route exact path="/addUser" component={AddUser} />
<Route exact path="/editUser" component={EditUser} />
<Route component={Page404} />
</Switch>
</div>
</Router>
</div>
)
}
}
export default App
|
import map from '../signals/processes/map'
import tail from 'ramda/src/tail'
export default
map((ev) => tail(ev.target.location.hash))
|
/** @see https://drafts.csswg.org/css-grid/ */
export default {
'display': ['grid', 'inline-grid', '-ms-grid'],
'grid': true,
'grid-area': true,
'grid-auto-columns': true,
'grid-auto-flow': true,
'grid-auto-rows': true,
'grid-column': true,
'grid-column-end': true,
'grid-column-start': true,
'grid-row': true,
'grid-row-end': true,
'grid-row-start': true,
'grid-template': true,
'grid-template-areas': true,
'grid-template-columns': true,
'grid-template-rows': true,
};
|
import React, { useState } from "react";
import { MdDehaze, MdClear } from "react-icons/md";
import {
Container,
Nav,
Logo,
MenuButton,
NavRight,
NavMenu,
ButtonOne,
ButtonTwo,
ButtonThree,
} from "./styles";
const style = {
fontSize: 30,
color: "#FFF",
lineHeight: 1.2,
};
function Header() {
const [visible, setVisible] = useState(false);
return (
<Container>
<Nav>
<Logo>At</Logo>
<MenuButton onClick={() => setVisible(!visible)}>
<MdDehaze />
</MenuButton>
<NavRight className={` ${visible ? " responsive" : " "}`}>
<Logo second>At</Logo>
<MenuButton onClick={() => setVisible(!visible)}>
<MdClear style={{ color: "#FFF" }} />
</MenuButton>
<NavMenu>
<span>Why Astatine?</span>
<span>Item 2</span>
<span>Item 3</span>
<span>Item 4</span>
</NavMenu>
<ButtonOne>Sign in</ButtonOne>
<span style={style}>|</span>
<ButtonTwo>GET STARTED</ButtonTwo>
<ButtonThree>Download Astatine App</ButtonThree>
</NavRight>
</Nav>
</Container>
);
}
export default Header;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.