text
stringlengths 7
3.69M
|
|---|
const RecoveryController = function (AuthService) {
const ctrl = this;
ctrl.submitted = false;
ctrl.mail = "";
ctrl.feedback = {
message: "",
showing: false,
type: "error"
};
const showFeedback = (newMessage, type = "error") => {
ctrl.feedback.message = newMessage;
ctrl.feedback.showing = true;
ctrl.feedback.type = type;
};
const handleError = (error) => {
ctrl.loading = false;
if(error.status == 400) {
showFeedback("Esse email ainda não está cadastrado.");
} else {
showFeedback("Ops, tivemos um erro interno, por favor tente novamente mais tarde...");
}
};
const handleSuccess = () => {
ctrl.loading = false;
showFeedback(`Um email com instruções foi enviado para ${ctrl.mail}`, "success");
};
const doRecover = () => {
ctrl.loading = true;
AuthService.recovery(ctrl.mail)
.then(handleSuccess)
.catch(handleError);
};
ctrl.submitForm = (validForm) => {
ctrl.submitted = true;
ctrl.feedback.showing = false;
if (validForm) {
doRecover();
} else {
showFeedback("Preencha os campos em vermelho");
}
};
};
angular.module("myapp").component("recovery", {
templateUrl: "angular/recovery/recovery.html",
controller: RecoveryController,
});
|
import _ from 'lodash';
import reportFrom from '@/data/reportForm';
import places from '@/data/places';
/* eslint-disable import/prefer-default-export */
export const typeName = (type) => {
const typeForm = _.find(reportFrom, data => data.name === 'type');
const typeOption = _.find(typeForm.options, data => data.key === parseInt(type, 10));
if (typeOption) {
return typeOption.label;
}
return '';
};
export const placeName = (place, type) => {
if (type in places) {
const typePlace = _.find(places[type], data => data.key === place);
if (typePlace) {
return typePlace.label;
}
}
return '';
};
|
import React from 'react';
import {storiesOf} from '@storybook/react';
import {Input} from './Input.js';
const story = storiesOf('Input', module);
story.add('Input without any properties', () => {
return <Input name="TestInputField" placeholder="Test Input" />;
});
story.add('Readonly Input', () => {
return <Input name="TestInputField" placeholder="Test Input" readonly={true}/>;
});
|
var post = $(".post");
$(".posted").html("");
post.each(function(){
$(this).appendTo(".posted");
$(".post .row-top .favs").appendTo(".post .row-bottom");
$(".post .row-top .favs").remove();
$(".post .row-top .columns .name").prependTo(".post .row-bottom");
$(".post .row-top .columns .name").remove();
$(".post").toggleClass("post-list");
$(".post").toggleClass("post");
});
var notFound = false;
function ShowNotFound(){
if(!notFound){
document.getElementById("results").style.display = "none";
document.getElementById("not-found-message").style.display = "block";
notFound = true;
}else if(notFound){
document.getElementById("results").style.display = "flex";
document.getElementById("not-found-message").style.display = "none";
notFound = false;
}
}
var showingTypes = false;
function ShowTypes(tipo){
var myLabel = document.getElementById("type-label");
if(!showingTypes){
//tipos.style.display = "flex";
$('.desplegable-list').show();
showingTypes = true;
}else if(showingTypes){
//tipos.style.display = "none";
showingTypes = false;
$('.desplegable-list').hide();
if(tipo != undefined)
myLabel.innerHTML = "Tipo: " + tipo;
}
}
|
exports.seed = function(knex) {
// Deletes ALL existing entries
return knex('ship_specs3')
.truncate()
.then(function () {
// Inserts seed entries
return knex('ship_specs3').insert([
{
id: "63",
afterburner_speed: "0",
beam: "198.0",
cargocapacity: "5400",
height: "72.0",
length: "480.0",
manufacturer_id: "12",
mass: "109860179",
max_crew: "80",
min_crew: "12",
pitch_max: null,
production_note: "Currently being built and tested for implementation in-game.",
production_status: "in-production",
roll_max: null,
scm_speed: "0",
size: "capital",
time_modified: "3 years ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: "0.0",
description: "Designed for use by the UEE military, the Javelin is a massive, modular capital ship that can be appropriated for entrepreneurial use. With a detailed interior, plenty of modular room options and a high crew capacity, the Javelin is a ship that has made a name for itself in a variety of roles.",
url: "/pledge/ships/aegis-javelin/Javelin"
},
{
id: "75",
afterburner_speed: "1115",
beam: "40.0",
cargocapacity: "0",
height: "8.5",
length: "38.5",
manufacturer_id: "12",
mass: "238616",
max_crew: "2",
min_crew: "2",
pitch_max: "80.0",
production_note: null,
production_status: "flight-ready",
roll_max: "120.0",
scm_speed: "225",
size: "medium",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: "51.9",
yaw_max: "80.0",
yaxis_acceleration: "54.5",
zaxis_acceleration: "53.3",
description: "A hard-charging bulldog of a fighter which features extensive forward-mounted weaponry designed to tear through the shields and armor of other spacecraft. So-named because their multiple-jump range allows them to form the vanguard of any military expedition, Vanguards have seen extensive service against the Vanduul.",
url: "/pledge/ships/vanguard/Vanguard-Warden"
},
{
id: "95",
afterburner_speed: "0",
beam: "40.0",
cargocapacity: "0",
height: "8.0",
length: "38.5",
manufacturer_id: "12",
mass: "240092",
max_crew: "2",
min_crew: "2",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "225",
size: "medium",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "The Vanguard Harbinger is Earth’s standard fighter-bomber, converting the standard Warden model’s escape pod into a potent bomb bay. The extended range of the Vanguard and the relatively small profile mean that it can go where carrier-based planes or larger strategic bombers don’t… and then strike hard and make it back to frontier bases. The Vanguard Harbinger is a powerful bomber that can operate out of the roughest forward operating bases.\n",
url: "/pledge/ships/vanguard/Vanguard-Harbinger"
},
{
id: "96",
afterburner_speed: "0",
beam: "40.0",
cargocapacity: "0",
height: "8.5",
length: "38.5",
manufacturer_id: "12",
mass: "238616",
max_crew: "2",
min_crew: "2",
pitch_max: null,
production_note: "Concept complete.",
production_status: "flight-ready",
roll_max: null,
scm_speed: "225",
size: "medium",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "The Vanguard Sentinel is a ship that’s designed to fight smart instead of taking enemies head on. The conversion features an AR cockpit, an external e-War pod, decoy missiles and a set of EMP charges. Vanguard Sentinels often provide necessary combat support for combined operations. A lone Sentinel assigned wild weasel tasks is frequently paired with Harbinger bombers and Warden escorts for large attack missions.",
url: "/pledge/ships/vanguard/Vanguard-Sentinel"
},
{
id: "127",
afterburner_speed: "1020",
beam: "40.0",
cargocapacity: "0",
height: "8.5",
length: "38.5",
manufacturer_id: "12",
mass: "229440",
max_crew: "1",
min_crew: "1",
pitch_max: "80.0",
production_note: "This ship is in game and ready to fly immediately.",
production_status: "flight-ready",
roll_max: "150.0",
scm_speed: "225",
size: "medium",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: "51.8",
yaw_max: "80.0",
yaxis_acceleration: "54.6",
zaxis_acceleration: "53.4",
description: "The Vanguard Hoplite is a cross between the winning Vanguard deep space fighter and a dedicated boarding ship. Adapting the reliable design for amphibious operations, the Hoplite is the perfect tool for inserting an armored strike team with enough firepower to get them out again.",
url: "/pledge/ships/vanguard/Vanguard-Hoplite"
},
{
id: "90",
afterburner_speed: "1150",
beam: "28.5",
cargocapacity: "6",
height: "4.0",
length: "14.5",
manufacturer_id: "4",
mass: "38566",
max_crew: "2",
min_crew: "1",
pitch_max: "80.0",
production_note: "This ship is in game and ready to fly immediately.",
production_status: "flight-ready",
roll_max: "115.0",
scm_speed: "220",
size: "small",
time_modified: "4 months ago",
type: "multi",
xaxis_acceleration: "64.0",
yaw_max: "80.0",
yaxis_acceleration: "71.6",
zaxis_acceleration: "47.3",
description: "Small supply runs from a planet's surface to a nearby orbital station have become commonplace. With bigger ships focusing more on the long-haul, the Reliant's standard 'Kore' loadout gives it enough carrying capacity for starting out with smaller runs while complementing MISC's Hull-series as a long-haul support ship.\t",
url: "/pledge/ships/reliant/Reliant-Kore"
},
{
id: "105",
afterburner_speed: "1150",
beam: "28.5",
cargocapacity: "0",
height: "4.0",
length: "14.5",
manufacturer_id: "4",
mass: "38566",
max_crew: "2",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "166",
size: "small",
time_modified: "2 months ago",
type: "support",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "The Empire depends on up-to-the-second information, which is why reporters need to be able to go where the news is happening: wherever, whenever. Enter the Mako, all the flexibility and dependability of a MISC Reliant combined with a state of the art Image Enhancement suite and turret-mounted optics to capture every moment as it happens with the clarity and accuracy that makes headlines. ",
url: "/pledge/ships/reliant/Reliant-Mako"
},
{
id: "106",
afterburner_speed: "1150",
beam: "28.5",
cargocapacity: "0",
height: "4.0",
length: "14.5",
manufacturer_id: "4",
mass: "38566",
max_crew: "2",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "166",
size: "small",
time_modified: "2 months ago",
type: "industrial",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "Magellan, Pierce, Croshaw, names that echo through history thanks to their adventurous spirit, a curious nature and a reliable ship. The Reliant Sen is a versatile mobile science platform; outfitted with long range capabilities to take you further, longer, and an advanced sensor suite. Perfect for the aspiring explorer who wants to whisper their name into the halls of history.",
url: "/pledge/ships/reliant/Reliant-Sen"
},
{
id: "107",
afterburner_speed: "1150",
beam: "28.5",
cargocapacity: "0",
height: "4.0",
length: "14.5",
manufacturer_id: "4",
mass: "38566",
max_crew: "2",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "166",
size: "small",
time_modified: "2 months ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "With Humanity ever-expanding through the universe, the need for a versatile lightweight fighter has expanded with it. Easy to maintain with a rugged construction, the Reliant Tana makes for an ideal choice for frontier and outpost defense thanks to its custom high-yield power plant, stronger shields and additional weapon mounts.",
url: "/pledge/ships/reliant/Reliant-Tana"
},
{
id: "91",
afterburner_speed: "0",
beam: "90.0",
cargocapacity: "300",
height: "16.0",
length: "85.0",
manufacturer_id: "68",
mass: "3120000",
max_crew: "8",
min_crew: "2",
pitch_max: null,
production_note: "Waiting for resources to start modeling",
production_status: "in-production",
roll_max: null,
scm_speed: "0",
size: "large",
time_modified: "1 year ago",
type: "transport",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "The Genesis is yet another landmark in Crusader Industries’ proud history of transport designs. This ship utilizes award-winning manufacturing techniques and the highest quality parts to create one thing; a next-generation passenger ship at a price that won’t break your budget. Crusader Industries’ proprietary NeoG engine technology offers some of the most efficient flight for a ship of its size.",
url: "/pledge/ships/starliner/Genesis-Starliner"
},
{
id: "93",
afterburner_speed: "1230",
beam: "31.5",
cargocapacity: "0",
height: "8.5",
length: "31.0",
manufacturer_id: "69",
mass: "66013",
max_crew: "1",
min_crew: "1",
pitch_max: "100.0",
production_note: null,
production_status: "flight-ready",
roll_max: "135.0",
scm_speed: "255",
size: "medium",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: "81.4",
yaw_max: "100.0",
yaxis_acceleration: "93.0",
zaxis_acceleration: "76.8",
description: "The Glaive is a symmetrical version of the Scythe. Generally flown by Vanduul with more combat experience, they are better armed and have two huge blades/wings as opposed to one on the standard Scythe.\n\n\nThis model is a human reproduction created by the manufacturer Esperia.\n",
url: "/pledge/ships/esperia-glaive/Glaive"
},
{
id: "97",
afterburner_speed: "0",
beam: "48.0",
cargocapacity: "500",
height: "20.0",
length: "200.0",
manufacturer_id: "4",
mass: "4055000",
max_crew: "5",
min_crew: "3",
pitch_max: null,
production_note: null,
production_status: "in-concept",
roll_max: null,
scm_speed: "0",
size: "capital",
time_modified: "1 year ago",
type: "industrial",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "Musashi Industrial & Starflight Concern is proud to present the Endeavor-class research vessel, a fully modular space platform designed to be adapted for a variety of scientific and medical tasks. Initially developed as a floating laboratory, the MISC Endeavor can be outfitted for everything from spatial telescopy to use as mobile hospital.",
url: "/pledge/ships/misc-endeavor/Endeavor"
},
{
id: "98",
afterburner_speed: "1235",
beam: "26.0",
cargocapacity: "0",
height: "5.0",
length: "24.0",
manufacturer_id: "12",
mass: "78513",
max_crew: "1",
min_crew: "1",
pitch_max: "110.0",
production_note: "Flight Ready",
production_status: "flight-ready",
roll_max: "150.0",
scm_speed: "275",
size: "small",
time_modified: "2 months ago",
type: "combat",
xaxis_acceleration: "81.1",
yaw_max: "110.0",
yaxis_acceleration: "94.1",
zaxis_acceleration: "86.0",
description: "Part of Aegis Dynamics’ Phase Two of new ship models, the Sabre was designed as a space superiority fighter for those situations where you need to leave a lighter footprint. Designed to be a rapid responder, the Sabre is more than capable of establishing battlefield dominance for any number of combat scenarios.",
url: "/pledge/ships/sabre/Sabre"
},
{
id: "120",
afterburner_speed: "1235",
beam: "26.0",
cargocapacity: "0",
height: "5.0",
length: "24.0",
manufacturer_id: "12",
mass: "78513",
max_crew: "1",
min_crew: "1",
pitch_max: "85.0",
production_note: null,
production_status: "flight-ready",
roll_max: "95.0",
scm_speed: "215",
size: "small",
time_modified: "1 year ago",
type: "combat",
xaxis_acceleration: "81.1",
yaw_max: "85.0",
yaxis_acceleration: "94.1",
zaxis_acceleration: "86.0",
description: "Created as part of the ‘Masters of Flight’ series in conjunction with the flight-sim Arena Commander, the Comet pays tribute to famed pilot Captain Kamur Dalion for his work with Aegis to usher in a new era of combat ship design. This Sabre comes equipped with a specialized dogfighting focused loadout and a custom special edition livery honoring this iconic ship.\n",
url: "/pledge/ships/sabre/Sabre-Comet"
},
{
id: "148",
afterburner_speed: "1235",
beam: "20.5",
cargocapacity: "0",
height: "5.0",
length: "24.0",
manufacturer_id: "12",
mass: "69433",
max_crew: "1",
min_crew: "1",
pitch_max: "110.0",
production_note: "Available in 3.0 patch.",
production_status: "flight-ready",
roll_max: "150.0",
scm_speed: "275",
size: "small",
time_modified: "3 years ago",
type: "combat",
xaxis_acceleration: "82.3",
yaw_max: "110.0",
yaxis_acceleration: "95.0",
zaxis_acceleration: "86.7",
description: "Part of Aegis Dynamics’ Phase Two of new ship models, the Sabre was designed as a space superiority fighter for those situations where you need to leave a lighter footprint. They have raised the bar yet again with their Raven variant, maintaining all the speed and maneuverability of its Sabre forebear, but with a lower ship signature, making it a fast, stealthy infiltrator.",
url: "/pledge/ships/sabre/Sabre-Raven"
},
{
id: "103",
afterburner_speed: "0",
beam: "50.0",
cargocapacity: "230",
height: "20.0",
length: "90.0",
manufacturer_id: "3",
mass: "3650500",
max_crew: "8",
min_crew: "3",
pitch_max: null,
production_note: "Concept complete.",
production_status: "in-concept",
roll_max: null,
scm_speed: "0",
size: "large",
time_modified: "1 year ago",
type: "support",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "A so-called “flying toolbox,” the Crucible is Anvil Aerospace’s first dedicated repair ship. Featuring a rotating control bridge and a detachable pressurized workspace, the Crucible is a versatile mobile garage equipped with repair arms, a drone operation center and all the equipment needed to overhaul a damaged craft back into fighting shape.",
url: "/pledge/ships/crucible/Crucible"
},
{
id: "104",
afterburner_speed: "0",
beam: "7.7",
cargocapacity: "0",
height: "2.2",
length: "12.0",
manufacturer_id: "19",
mass: "8290",
max_crew: "1",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "0",
size: "snub",
time_modified: "1 year ago",
type: "competition",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "If you’re looking for something a little more agile, blaze among the stars with Kruger Intergalactic’s P-72 Archimedes. Whether for added security, exploring a system or simply the joy of flying, the Archimedes is the perfect companion snub craft. Featuring an extra intake and a lighter hull than its sister ship, the Archimedes delivers exceptional handling and boost capabilities in a sleek package you’ll want along for the ride.",
url: "/pledge/ships/p72-archimedes/P72-Archimedes"
},
{
id: "207",
afterburner_speed: null,
beam: "7.7",
cargocapacity: "0",
height: "2.2",
length: "12.0",
manufacturer_id: "19",
mass: "8979",
max_crew: "1",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "250",
size: "snub",
time_modified: "3 months ago",
type: "competition",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "Built with exacting precision and styled with urban sophistication in mind, this compact snub isn’t just for show. Fast and responsive, it’s the ideal chaperone for larger ship or the perfect partner for a solo sprint in-atmosphere. The Archimedes Emerald features an exclusive Stellar Fortuna skin, available for a limited time only. ",
url: "/pledge/ships/p72-archimedes/P72-Archimedes-Emerald"
},
{
id: "108",
afterburner_speed: "1240",
beam: "20.0",
cargocapacity: "0",
height: "5.5",
length: "16.5",
manufacturer_id: "69",
mass: "26056",
max_crew: "1",
min_crew: "1",
pitch_max: "115.0",
production_note: null,
production_status: "flight-ready",
roll_max: "140.0",
scm_speed: "290",
size: "small",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: "86.3",
yaw_max: "115.0",
yaxis_acceleration: "116.2",
zaxis_acceleration: "89.5",
description: "Vanduul light fighters, designated 'Blade', are often used as scouts and first wave assault crafts. Over the decades of conflict, they have been increasingly used to take out comm arrays and early warning systems. They have also served well as skirmisher units as their speed allows them to chase down ships attempting to flee. If engaged, expect the Blade to utilize its speed and agility to wear down your defenses.",
url: "/pledge/ships/vanduul-blade/Blade"
},
{
id: "109",
afterburner_speed: "1210",
beam: "15.0",
cargocapacity: "0",
height: "7.0",
length: "24.0",
manufacturer_id: "4",
mass: "116477",
max_crew: "1",
min_crew: "1",
pitch_max: "70.0",
production_note: "Available in Alpha 3.0.",
production_status: "flight-ready",
roll_max: "95.0",
scm_speed: "200",
size: "small",
time_modified: "2 months ago",
type: "industrial",
xaxis_acceleration: "40.6",
yaw_max: "70.0",
yaxis_acceleration: "44.4",
zaxis_acceleration: "42.3",
description: "For years, the Prospector has been the universe’s preferred mining vessel for solo operators. Featuring MISC’s sleek design sensibility and a bevy of upgraded high-tech mining tools, the 2947 Prospector perfectly balances form and functionality.",
url: "/pledge/ships/misc-prospector/Prospector"
},
{
id: "110",
afterburner_speed: "1315",
beam: "16.0",
cargocapacity: "0",
height: "4.5",
length: "15.0",
manufacturer_id: "5",
mass: "40821",
max_crew: "1",
min_crew: "1",
pitch_max: "110.0",
production_note: null,
production_status: "flight-ready",
roll_max: "150.0",
scm_speed: "280",
size: "small",
time_modified: "1 year ago",
type: "combat",
xaxis_acceleration: "92.8",
yaw_max: "110.0",
yaxis_acceleration: "108.7",
zaxis_acceleration: "92.8",
description: "The Buccaneer has been designed from the ground up to fly and fight the way you live. No leather interiors or hyperpillows here: the ‘Bucc is a scrapper designed to maneuver and fight above its weight class. This rough-and-tumble frontier fighter can be maintained in the worst of conditions in order to keep real, working space crews alive.",
url: "/pledge/ships/drake-buccaneer/Buccaneer"
},
{
id: "111",
afterburner_speed: "1100",
beam: "2.5",
cargocapacity: "0",
height: "1.5",
length: "6.0",
manufacturer_id: "5",
mass: "2169",
max_crew: "2",
min_crew: "1",
pitch_max: "90.0",
production_note: "Available in Alpha 3.0.",
production_status: "flight-ready",
roll_max: "110.0",
scm_speed: "155",
size: "snub",
time_modified: "1 year ago",
type: "competition",
xaxis_acceleration: "50.6",
yaw_max: "80.0",
yaxis_acceleration: "67.4",
zaxis_acceleration: "60.8",
description: "The Drake Dragonfly is the perfect snub ship for anyone looking to live on the edge. With nothing separating the pilot from the dangers of space, the Dragonfly is as much an adventure as a ship! Dual-mode conversion allows the Dragonfly to operate on the ground or in space, and a rear-facing second seat means you can even take a passenger! This exclusive Yellowjacket version is available only for the concept sale.\n",
url: "/pledge/ships/drake-dragonfly/Dragonfly-Yellowjacket"
},
{
id: "112",
afterburner_speed: "1100",
beam: "2.5",
cargocapacity: "0",
height: "1.5",
length: "6.0",
manufacturer_id: "5",
mass: "2169",
max_crew: "2",
min_crew: "1",
pitch_max: "115.0",
production_note: "Available in Alpha 3.0.",
production_status: "flight-ready",
roll_max: "175.0",
scm_speed: "255",
size: "snub",
time_modified: "1 year ago",
type: "competition",
xaxis_acceleration: "50.6",
yaw_max: "105.0",
yaxis_acceleration: "67.4",
zaxis_acceleration: "60.8",
description: "The Drake Dragonfly is the perfect snub ship for anyone looking to live on the edge. With nothing separating the pilot from the dangers of space, the Dragonfly is as much an adventure as a ship! Dual-mode conversion allows the Dragonfly to operate on the ground or in space, and a rear-facing second seat means you can even take a passenger! This black model is Drake's standard production version.\n",
url: "/pledge/ships/drake-dragonfly/Dragonfly-Black"
},
{
id: "113",
afterburner_speed: "920",
beam: "8.5",
cargocapacity: "0",
height: "4.3",
length: "9.3",
manufacturer_id: "73",
mass: "12307",
max_crew: "1",
min_crew: "1",
pitch_max: "50.0",
production_note: null,
production_status: "flight-ready",
roll_max: "80.0",
scm_speed: "150",
size: "snub",
time_modified: "1 year ago",
type: "transport",
xaxis_acceleration: "25.8",
yaw_max: "50.0",
yaxis_acceleration: "29.3",
zaxis_acceleration: "27.2",
description: "The ARGO Astronautics MPUV-1P (commonly ‘Argo Personnel.’) is geared towards a simple but incredibly important responsibility: moving groups of people from place to place. The UEE Navy uses MPUV-1Ps extensively, and any new recruit can likely recall those terrifying moments in which such a ship carried them to their first space assignment. In civilian hands, Argo Personnel ships are adapted for everything from standard taxi services to use as makeshift combat dropships. The ARGO is capable of carrying up to eight Humans and their equipment.",
url: "/pledge/ships/argo/MPUV-Personnel"
},
{
id: "114",
afterburner_speed: "900",
beam: "8.5",
cargocapacity: "2",
height: "4.3",
length: "9.5",
manufacturer_id: "73",
mass: "12187",
max_crew: "1",
min_crew: "1",
pitch_max: "50.0",
production_note: null,
production_status: "flight-ready",
roll_max: "80.0",
scm_speed: "150",
size: "snub",
time_modified: "1 year ago",
type: "transport",
xaxis_acceleration: "25.8",
yaw_max: "50.0",
yaxis_acceleration: "29.3",
zaxis_acceleration: "27.2",
description: "The ARGO Astronautics MPUV-1C (commonly ‘Argo Cargo’) is a dedicated merchant transfer ship, a ubiquitous intergalactic stevedore. Vast numbers of Argo Cargos are responsible for loading and unloading goods onto massive long-haul transports and miners that cannot otherwise land on planets or drydocks, such as the Hull D and the Orion. Some captains choose to own and operate their own Argo, while others pay privately owned ships operating as port services a rental fee for performing the unloading process.",
url: "/pledge/ships/argo/MPUV-Cargo"
},
{
id: "115",
afterburner_speed: "1205",
beam: "14.5",
cargocapacity: "0",
height: "6.0",
length: "19.5",
manufacturer_id: "3",
mass: "86454",
max_crew: "1",
min_crew: "1",
pitch_max: "75.0",
production_note: "Currently being built and tested for implementation in-game.",
production_status: "flight-ready",
roll_max: "100.0",
scm_speed: "210",
size: "small",
time_modified: "1 year ago",
type: "exploration",
xaxis_acceleration: "51.9",
yaw_max: "75.0",
yaxis_acceleration: "65.7",
zaxis_acceleration: "58.1",
description: "Presenting the Anvil Aerospace U4A-3 Terrapin-class Scanning/Exploration Ship. The Terrapin was developed near the end of the 28th century to serve as the first ship in the Empire’s defensive restructuring of the Navy. The Terrapin’s watchword is protection, with extensive shield systems and armor layers designed to provide the maximum possible defense for pilot and crew. While it lacks the maneuverability of a dedicated fighter, it does maintain an advanced, hard-hitting array of weapons intended to keep the most fearsome Vanduul raider at bay.",
url: "/pledge/ships/terrapin/Terrapin"
},
{
id: "116",
afterburner_speed: "0",
beam: "82.0",
cargocapacity: "216",
height: "35.0",
length: "155.0",
manufacturer_id: "1",
mass: "17155000",
max_crew: "14",
min_crew: "6",
pitch_max: null,
production_note: null,
production_status: "in-concept",
roll_max: null,
scm_speed: "0",
size: "capital",
time_modified: "4 months ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "The Polaris is a nimble corvette-class capital ship that packs a powerful punch with a full armament of turrets and torpedoes. Intended for use as both a naval patrol ship and to serve as the flagship of militia operations, Polaris has the capacity to perform search and rescue operations, light strike missions and general security patrols. The Polaris includes the facilities to repair, rearm and refuel a single fighter, light bomber or support ship.",
url: "/pledge/ships/polaris/Polaris"
},
{
id: "117",
afterburner_speed: "1116",
beam: "32.0",
cargocapacity: "0",
height: "15.0",
length: "34.0",
manufacturer_id: "69",
mass: "171700",
max_crew: "2",
min_crew: "2",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "178",
size: "medium",
time_modified: "3 months ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "Named after the UPE military designation, the Prowler is a modernized version of the infamous Tevarin armored personnel carrier. Esperia’s astroengineers were given unmitigated access to study original versions of the ship recently discovered in the Kabal system to help meticulously reconstruct the vehicle. Now, the Prowler is the perfect fusion of two cultures: the elegance and effectiveness of the Tevarin war machine combined with the reliability of modern Human technology. \n",
url: "/pledge/ships/prowler/Prowler"
},
{
id: "123",
afterburner_speed: "1185",
beam: "10.0",
cargocapacity: "0",
height: "2.0",
length: "13.0",
manufacturer_id: "6",
mass: "19097",
max_crew: "2",
min_crew: "1",
pitch_max: "100.0",
production_note: null,
production_status: "flight-ready",
roll_max: "135.0",
scm_speed: "255",
size: "snub",
time_modified: "4 months ago",
type: "exploration",
xaxis_acceleration: "59.0",
yaw_max: "100.0",
yaxis_acceleration: "68.2",
zaxis_acceleration: "61.3",
description: "Elegantly styled and meticulously constructed, the 85X is a versatile and comprehensive away-vessel that features precision control in and out of atmosphere. Utilizing much of the same thruster technology as the 300 series, it has the power of a racer with the reliability of a touring ship. Whether descending down to the planet surface or taking in the sights of your system, this runabout continues Origin’s proud tradition of turning heads.\n",
url: "/pledge/ships/85x/85X"
},
{
id: "126",
afterburner_speed: "1345",
beam: "8.2",
cargocapacity: "0",
height: "2.7",
length: "11.5",
manufacturer_id: "4",
mass: "10925",
max_crew: "1",
min_crew: "1",
pitch_max: "127.0",
production_note: null,
production_status: "flight-ready",
roll_max: "172.0",
scm_speed: "335",
size: "small",
time_modified: "2 months ago",
type: "competition",
xaxis_acceleration: "89.7",
yaw_max: "127.0",
yaxis_acceleration: "120.0",
zaxis_acceleration: "98.6",
description: "MISC makes a bid for the next Murray Cup with the all-new Razor. This advanced racer features an advanced composite spaceframe that puts pure speed ahead of everything else... it's the ship for pilots who want to leave the competition in the dust.",
url: "/pledge/ships/razor/Razor"
},
{
id: "157",
afterburner_speed: "1340",
beam: "8.2",
cargocapacity: "0",
height: "2.7",
length: "11.5",
manufacturer_id: "4",
mass: "10925",
max_crew: "1",
min_crew: "1",
pitch_max: "127.0",
production_note: null,
production_status: "flight-ready",
roll_max: "172.0",
scm_speed: "325",
size: "small",
time_modified: "1 year ago",
type: "competition",
xaxis_acceleration: "89.3",
yaw_max: "127.0",
yaxis_acceleration: "119.0",
zaxis_acceleration: "98.1",
description: "Outfitted with signature-reducing materials, the RAZOR-EX was a specialty build for the UEE Advocacy for use in surveillance and extraction operations. Although the EX was ultimately rejected for widespread use, MISC released a variation of the model for the public who were looking to keep a lower profile.",
url: "/pledge/ships/razor/Razor-EX"
},
{
id: "158",
afterburner_speed: "1345",
beam: "8.2",
cargocapacity: "0",
height: "2.7",
length: "11.5",
manufacturer_id: "4",
mass: "10925",
max_crew: "1",
min_crew: "1",
pitch_max: "127.0",
production_note: null,
production_status: "flight-ready",
roll_max: "172.0",
scm_speed: "340",
size: "small",
time_modified: "1 year ago",
type: "competition",
xaxis_acceleration: "89.4",
yaw_max: "127.0",
yaxis_acceleration: "119.1",
zaxis_acceleration: "98.2",
description: "The Razor gets supercharged. The LX features an overclocked engine to unleash blazing top speeds perfect. This power comes at a cost with reduced maneuverability and armaments making it ideal for straight-shot racing. But who needs weapons when you’re leaving your competition in the dust.",
url: "/pledge/ships/razor/Razor-LX"
},
{
id: "128",
afterburner_speed: "1125",
beam: "14.5",
cargocapacity: "0",
height: "6.0",
length: "22.0",
manufacturer_id: "3",
mass: "86454",
max_crew: "2",
min_crew: "2",
pitch_max: "100.0",
production_note: null,
production_status: "flight-ready",
roll_max: "140.0",
scm_speed: "265",
size: "small",
time_modified: "1 year ago",
type: "combat",
xaxis_acceleration: "67.6",
yaw_max: "100.0",
yaxis_acceleration: "84.5",
zaxis_acceleration: "69.6",
description: "Big things do come in small packages: the Hurricane is a fighting spacecraft that packs a deadly punch into a slight fuselage. The spacecraft compensates for its lack of creature comforts with its powerful armament - six guns capable of blasting their way through nearly anything. Hurricane pilots have yet to find an enemy shield they can't knock down.",
url: "/pledge/ships/hurricane/Hurricane"
},
{
id: "129",
afterburner_speed: "0",
beam: "20.0",
cargocapacity: "0",
height: "8.0",
length: "25.5",
manufacturer_id: "21",
mass: "78406",
max_crew: "2",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "0",
size: "small",
time_modified: "2 months ago",
type: "combat",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "Meet the Banu Defender, a multi-crew fighter whose patchwork design highlights technology from a variety of species. Though cargo space is limited, the Defender features modest accommodations for its crew and provides easy access to components. The Defender gets its name from the role it serves: the first line of defense against enemy attacks. That’s why the Defender makes the ideal companion to the Merchantman: one to do the heavy hauling and the other to perform the deadly dogfighting. Every Banu merchant knows an investment in defense is an investment in their livelihood.",
url: "/pledge/ships/defender/Banu-Defender"
},
{
id: "130",
afterburner_speed: "980",
beam: "36.6",
cargocapacity: "0",
height: "4.4",
length: "20.5",
manufacturer_id: "12",
mass: "54216",
max_crew: "1",
min_crew: "1",
pitch_max: "75.0",
production_note: null,
production_status: "flight-ready",
roll_max: "120.0",
scm_speed: "195",
size: "medium",
time_modified: "4 months ago",
type: "combat",
xaxis_acceleration: "47.9",
yaw_max: "75.0",
yaxis_acceleration: "61.1",
zaxis_acceleration: "51.2",
description: "The Aegis Eclipse is a bomber designed to get in and strike before it's even spotted. After extensive service with the UEE, this high-tech military stalwart is making its debut on the civilian market for 2947.",
url: "/pledge/ships/eclipse/Eclipse"
},
{
id: "131",
afterburner_speed: "1105",
beam: "1.5",
cargocapacity: "0",
height: "1.5",
length: "5.5",
manufacturer_id: "81",
mass: "1394",
max_crew: "1",
min_crew: "1",
pitch_max: "125.0",
production_note: "Available in Alpha 3.0.",
production_status: "flight-ready",
roll_max: "175.0",
scm_speed: "275",
size: "snub",
time_modified: "3 months ago",
type: "competition",
xaxis_acceleration: "56.0",
yaw_max: "110.0",
yaxis_acceleration: "70.7",
zaxis_acceleration: "60.6",
description: "Hit the skids with the 2947 Nox. This speedy and maneuverable open-canopy racer from Aopoa is capable of zipping along planet surfaces or deep space. Available for the first time in Human space, the Nox has been specifically redesigned for Human pilots, so grab your ship and head to the racetrack today.\n",
url: "/pledge/ships/nox/Nox"
},
{
id: "132",
afterburner_speed: "1103",
beam: "1.5",
cargocapacity: "0",
height: "1.5",
length: "5.5",
manufacturer_id: "81",
mass: "1394",
max_crew: "1",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "220",
size: "snub",
time_modified: "3 months ago",
type: "competition",
xaxis_acceleration: "56.0",
yaw_max: null,
yaxis_acceleration: "70.7",
zaxis_acceleration: "60.6",
description: "Deriving its name from the Xi’an word for ‘thrust,’ the Nox Kue delivers that and more. This limited version of the open-canopy racer features a stunning brushed-silver finish and was specifically created to celebrate the inaugural sale of the first Nox for Human riders.\n",
url: "/pledge/ships/nox/Nox-Kue"
},
{
id: "134",
afterburner_speed: "0",
beam: "4.0",
cargocapacity: "1",
height: "2.5",
length: "6.0",
manufacturer_id: "83",
mass: "3022",
max_crew: "2",
min_crew: "1",
pitch_max: null,
production_note: null,
production_status: "flight-ready",
roll_max: null,
scm_speed: "0",
size: "vehicle",
time_modified: "1 year ago",
type: "ground",
xaxis_acceleration: null,
yaw_max: null,
yaxis_acceleration: null,
zaxis_acceleration: null,
description: "With a potent combination of speed, maneuverability, and rugged durability, the Cyclone is a perfect choice for local deliveries and transport between planetside homesteads and outposts.",
url: "/pledge/ships/cyclone/Cyclone"
},
]);
});
};
|
import immutable from 'immutable';
import { createStore, compose, applyMiddleware } from 'redux';
const DEFAULT_TYPE = '@@IMSTORE_UPDATE';
function getPath(str) {
return str.split('/');
};
function ImCursor(dispatch, root) {
let rootPath = [];
const actions = [];
return {
setRoot(pathStr) {
rootPath = getPath(pathStr);
},
set(pathStr, value) {
actions.push({
type: 'set',
path: rootPath.concat(getPath(pathStr)),
value,
});
},
update(pathstr, value) {
actions.push({
type: 'update',
path: rootPath.concat(getPath(pathstr)),
value,
});
},
commit() {
dispatch({
type: DEFAULT_TYPE,
data: actions
});
},
get(pathStr) {
const value = root().getIn(getPath(pathStr));
if (value.toJS){
return value.toJS();
}else{
return value;
}
}
}
}
class ImAction {
constructor(args, func) {
this.args = args;
this.func = func;
}
}
export function createImStore(state, otherMiddleWare = []) {
const defaultState = immutable.fromJS(state);
function reducer(state = defaultState, { type, data }) {
if (type == DEFAULT_TYPE) {
let newState = state;
data.forEach((item) => {
if (item.type == 'set') {
newState = state.setIn(item.path, item.value);
} else if (item.type == 'update') {
newState = state.updateIn(item.path, item.value);
}
});
return newState;
} else {
return state;
}
}
const middle = store => next => (action) => {
if (action instanceof ImAction) {
const imCursor = ImCursor(store.dispatch, store.getState)
action.func.apply(imCursor, action.args);
} else {
next(action);
}
}
const enhancer = compose(applyMiddleware(...[...otherMiddleWare, middle]))
return createStore(reducer, defaultState, enhancer);
}
export function bindActions(actions, dispatch) {
const newActions = {};
Object.keys(actions).forEach((key) => {
newActions[key] = function (...args) {
dispatch(new ImAction(args, actions[key]));
}
});
return newActions;
}
|
const getEmailIndex = require("./appointmentUtil");
class Appointment{
constructor(start,end){
this.start = start;
this.end = end;
this.attendees = [];
}
setId(id){
this.id = id;
}
addAttendee(name, email){
let today = new Date();
if(today <= this.start){
this.attendees.push({name,email});
}else{
console.log("Sorry, you should not be able to add an attendee after the appointment `start` datetime");
}
}
removeAttendee(email){
let index = getEmailIndex(this.attendees, email);
if(index != -1){//email is correct
this.attendees.splice(index, 1);
}else{
console.log("Sorry, the email doesn't exist.")
}
}
}
module.exports = Appointment
|
/* global test describe expect */
import { GitRefManager } from '../dist/for-node/managers'
describe('GitRefManager', () => {
test('1e40fdfba1cf17f3c9f9f3d6b392b1865e5147b9', async () => {
let ref = await GitRefManager.resolve({
gitdir: '__tests__/__fixtures__/test-GitRefManager.git',
ref: '1e40fdfba1cf17f3c9f9f3d6b392b1865e5147b9'
})
expect(ref).toMatchSnapshot()
})
test('test-branch', async () => {
let ref = await GitRefManager.resolve({
gitdir: '__tests__/__fixtures__/test-GitRefManager.git',
ref: 'origin/test-branch'
})
expect(ref).toMatchSnapshot()
})
test('test-tag', async () => {
let ref = await GitRefManager.resolve({
gitdir: '__tests__/__fixtures__/test-GitRefManager.git',
ref: 'test-tag'
})
expect(ref).toMatchSnapshot()
})
test('HEAD', async () => {
let ref = await GitRefManager.resolve({
gitdir: '__tests__/__fixtures__/test-GitRefManager.git',
ref: 'HEAD'
})
expect(ref).toMatchSnapshot()
})
test('HEAD depth', async () => {
let ref = await GitRefManager.resolve({
gitdir: '__tests__/__fixtures__/test-GitRefManager.git',
ref: 'HEAD',
depth: 2
})
expect(ref).toMatchSnapshot()
})
test('packed-refs', async () => {
let ref = await GitRefManager.resolve({
gitdir: '__tests__/__fixtures__/test-GitRefManager.git',
ref: 'v0.0.1'
})
expect(ref).toMatchSnapshot()
})
})
|
import styled from "styled-components";
export const SidebarStyle = styled.div`
@keyframes go-left-right{
from{
opacity:0;
transform:translateX(-200px);
}
to{
opacity:1;
transform:translateX(0);
}
}
.layout-sidebar {
animation : go-left-right .4s;
display:inline;
background: #fff;
ul li {
position: relative;
margin-bottom: 38px;
.img {
width: 43px;
height: 43px;
display: inline;
padding-top: 8px;
margin-bottom: 2px;
span {
margin-left:10px;
font-size: 13px;
color: #8e8e8e;
font-weight: 600;
}
img,svg {
width: 25px;
height: 25px;
fill: #8e8e8e;
}
}
.active .img {
span{
font-size:16px;
color: #e9041e;
}
svg {
fill: #e9041e;
}
}
}
padding: 90px 14px ;
text-align: left;
position: fixed;
top: 0px;
left: 0;
width: 240px;
bottom: 0;
}
`
|
$("body").on("propertychange input", "input", function () {
testPhoneNumber();
});
function phoneMobile(phone, callback) {
$(".modelClass").css("display", "block");
var user_type = $("#user_type").val();
var user_id = $("#user_id").val();
$.ajax({
type: "POST",
url: "/index.php/Sdk/WxFlowPayment/GetFlowProtuct",
data: {
phone: phone,
sign: "870d244a38421e6dba1f938e73a44b2e",
user_type: user_type,
user_id: user_id,
product: "1"
},
contentType: "application/x-www-form-urlencoded",
success: function (data) {
callback(data);
$(".modelClass").css("display", "none");
},
error: function (data) { }
});
}
function testPhoneNumber(inputText) {
if (inputText == "" || inputText == null) {
var inputText = $('input').val();
}
if (!/^(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0,0-9])\d{8}$/i.test(inputText)) {
// $('.recharge_list ul li').remove();
// $('.flow_list ul li').remove();
} else {
//$('img').attr("src", "/Application/Sdk/View/WxFlowPayment/images/icon_1.png");
$('.recharge_list ul li').remove();
$('.flow_list ul li').remove();
phoneMobile(inputText, function callback(data) {
var parsedJson = eval('(' + data + ')');
if (parsedJson.msg == 1001) {
var title = "对不起,只允许" + parsedJson.data.province + "内" + parsedJson.data.operator + "号码充值!";
$('#OperatorsName').text(title);
return;
}
//var parsedJson = jQuery.parseJSON(data);
if (inputText != "18507085074") {
$('#OperatorsName').text(parsedJson.data.attribution);
}
else {
$('#OperatorsName').text("号码归属地");
}
$.each(parsedJson.data.packetAll, function (i, item) {
//全国流量折扣价格,显示
if (item.packetS == null) {
//只有省内包
BCratButton(item.packetQ, i, item, inputText);
}
else if (item.packetQ == null) {
//只有全国包
BCratButton(item.packetS, i, item, inputText);
}
else {
if (item.packetQ.price_discount > item.packetS.price_discount) {
BCratButton(item.packetS, i, item, inputText);
}
else {
BCratButton(item.packetQ, i, item, inputText);
}
}
});
//绑定点击效果
selectButton();
});
}
}
//创建按钮
function BCratButton(item, i, data, inputText) {
$(".recharge_list ul").append('' +
'<li class=\"favourable\" >' +
'<div class=\"recharge_item\" >' +
'<span>' + item.size + '</span> ' +
'<p>' + item.price_discount + '元<em> ' + item.price_market + '元</em></p> ' +
'</div>' +
'</li>');
$(".recharge_list ul li").eq(i)[0].jsonData = data;
}
var phone = $('input').val();
if (phone == "") {
//初始化显示联通数据包
testPhoneNumber("18507085074"); //不能删删了会出bug
}
else {
testPhoneNumber();
}
//选择按钮事件
function selectButton() {
jQuery(".recharge_list ul li").each(function (index) {
jQuery(this).click(function () {
// if ($(this)[0].jsonData == null) {
// alert("请输入您的手机号码");
// return;
// }
$('.active').removeClass("active");
$(this).addClass("active");
//清理下列表
$('.flow_list ul li').remove();
var item = $(this)[0].jsonData;
//全国流量折扣价格,显示
if (item.packetS == null) {
//只有全国包
BCratDetailButton(item.packetQ, 0, 1);
}
else if (item.packetQ == null) {
//只有省内包
BCratDetailButton(item.packetS, 0, 0);
}
else {
//省内全国
BCratDetailButton(item.packetS, 0, 0);
BCratDetailButton(item.packetQ, 1, 1);
}
//绑定按钮单机事件
selectDetailButton();
//先设置所有颜色为默认
// $("#tableView li a").css("border-color", "#C0C0C0");
//设置选中元素的CSS颜色
// $("#tableView li a").eq(index).css("border-color", "#D33B3D");
});
});
}
//创建按钮
function BCratDetailButton(item, i, type) {
if (type == 1) {
//全国
var address = "全国";
var addressinfo = "全国可用,即时生效,当月有效";
}
else {
var address = "省内";
var addressinfo = "省内可用,即时生效,当月有效";
}
$(".flow_list ul").append('' +
'<li>' +
'<div class=\"flow_item\" >' +
'<div class=\"flow_left\" >' +
'<p>' + item.price_discount + '元<em>' + address + '</em></p> ' +
'<span>' + addressinfo + '</span> ' +
'</div>' +
'<div class=\"flow_right\" >' +
'<button class=\"btnpay\" type=\"button"\ >购买</button>' +
'</div>' +
'</div>' +
'</li>');
$(".flow_list ul li .btnpay").eq(i)[0].jsonData = item;
}
//全局临时数据存储
var locationData;
//支付方式
//var payType = 0;
//判断是否为微信
function isWeiXin() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
}
$(document).ready(function () {
$(document).click(function () {
//针对所有的点击事件关闭弹出框
$("body").removeClass("ban_scroll");
setTimeout(function () {
$(".mask").hide();
}, 500);
$(".confirm_box").removeClass("open").addClass("close");
});
$(".confirm_header span>i").click(function () {
$("body").removeClass("ban_scroll");
setTimeout(function () {
$(".mask").hide();
}, 500);
$(".confirm_box").removeClass("open").addClass("close");
});
$(".confirm_box").click(function (e) {
e.stopPropagation();
});
$(".payment").click(function (e) {
clickpay(locationData);
});
});
//点击按钮触发事件
function selectDetailButton() {
jQuery(".flow_list ul li .btnpay").each(function (index) {
jQuery(this).click(function (e) {
var inputText = $('.input').val();
if (inputText == null || inputText.length == 0) {
alert("请输入您的手机号码");
inputText = "无";
return;
}
e.stopPropagation();
$("body").addClass("ban_scroll");
$(".confirm_box").removeClass("close").addClass("open");
$(".mask,.confirm_box").show();
if (!isWeiXin()) {
$(".zhifubao").addClass("active");//.siblings().removeClass("active");
$(".weixin").hide();
}
else {
$(".weixin").addClass("active");//.siblings().removeClass("active");
$(".zhifubao").hide();
}
var item = $(this)[0].jsonData;
//中国移动联通电信
var OperatorsName = $('#OperatorsName').val();
var title = OperatorsName + "流量充值" + item.size + "流量包";
var money = "¥" + item.price_discount;
$(".selectinfo").text(title);
$(".teleephonenumber").text(inputText);
$(".paytextinfo").text(money);
locationData = item;
});
});
}
function clickpay(jsonData) {
var user_type = $("#user_type").val();
var user_id = $("#user_id").val();
//当前选择的产品价格
var price_market = jsonData.price_market;
//该流量包来自哪个企业
var user_id = jsonData.productuser_id;
var pid = jsonData.id;
var openid = $("#openid").val();
var phone = $('input').val();
$(".modelClass").css("display", "block");
$.ajax({
type: "POST",
url: "/index.php/Sdk/Api/GetBalance",
data: {
user_type: user_type,
user_id: user_id
},
contentType: "application/x-www-form-urlencoded",
success: function (jsondata) {
//查询当前余额
var lastmoney = parseFloat(jsondata.data);
price_market = parseFloat(price_market);
if (lastmoney < price_market) {
var url = 'http://' + window.location.host + '/index.php/Sdk/WxFlowPayment/limitmoney';
location.href = url;
return;
}
//在微信内。并且选择微信
if (isWeiXin()) {
setTimeout(function () {
$(".modelClass").css("display", "none");
}, 1250);
var url = "/index.php/Sdk/WxFlowPayment/wxpay?pid=" + pid + "&phone=" + phone + "&openid=" + openid + "&user_type=" + user_type + "&user_id=" + user_id;
$("#wxpay").load(url);
}
else {
var url = "/index.php/Sdk/WxFlowPayment/alipay?pid=" + pid + "&phone=" + phone + "&user_type=" + user_type + "&user_id=" + user_id;
location.href = url;
}
// var url = "/index.php/Sdk/WxFlowPayment/appwxpay?pid=" + pid + "&phone=" + phone + "&user_type=" + user_type + "&user_id=" + user_id;
// location.href = url;
//alert(url);
//location.href = url;
},
error: function (data) { }
});
}
/*轮播图*/
var count=0;
var timeId;
var bannerItem=$(".banner_item");
$(".banner_row").css("width",bannerItem.length*100+"vw");
bannerRun();
function bannerRun(){
clearTimeout(timeId);
if(count<bannerItem.length){
$(".banner_row").animate({left:-count*100+"vw"},500);
count++;
timeId=setTimeout(bannerRun,2500);
}else{
var firItem=$(".banner_row .banner_item:last-of-type").clone();
$(".banner_row").css("left",0).prepend(firItem).find(".banner_item:last-of-type").remove();
count=1;
timeId=setTimeout(bannerRun,0);
}
};
|
import { ONEWEEK } from "./constants";
class Api {
constructor({ baseUrl, apiKey }) {
this._baseUrl = baseUrl;
this._apiKey = apiKey;
// this._date = new Date(Date.now() - 604800000); Wed Jan 20 2021 02:53:01 GMT+0500 (Екатеринбург, стандартное время) JSON.stringify()
this._date = new Date(Date.now() - ONEWEEK ).toJSON();
}
search(query) {
return fetch(`${this._baseUrl}?q=${query}&from=${this._date}&sortBy=publishedAt&pageSize=100&apiKey=${this._apiKey}`, {
// return fetch(`https://newsapi.org/v2/everything?q=bitcoin&apiKey=5d60850ecced411db40f614cd2e175ae`, {
headers: {
Authorization: `Client-ID ${this._apiKey}`
}
})
.then(res => res.json());
}
}
const api = new Api({
baseUrl: 'https://nomoreparties.co/news/v2/everything',
// baseUrl: 'https://newsapi.org/v2/everything',
apiKey: '5d60850ecced411db40f614cd2e175ae'
});
export default api;
|
export default class PlainJsFile extends HTMLElement {
}
|
import React, { Component } from 'react';
import HeaderView from './headerView.js'
import MainView from './mainView.js'
import FooterView from './footerView.js'
class TodoView extends Component {
constructor(props) {
super(props);
this.state = {
todoArr: [],
isChecked: false,
IsFooter: false
}
this.addTodo = this.addTodo.bind(this);
this.deleteTodo = this.deleteTodo.bind(this);
this.changeTodoState = this.changeTodoState.bind(this);
this.chearDone = this.chearDone.bind(this);
}
addTodo(newTodolist) {
this.setState(prevState => ({
todoArr: prevState.todoArr.concat(newTodolist)
}))
}
deleteTodo(itemIndex) {
this.state.todoArr.splice(itemIndex, 1);
this.setState({
todoArr: this.state.todoArr
})
}
allChecked() {
let isChecked = false;
if (this.state.todoArr.every(todo => todo.isDone)) {
isChecked = true;
}
this.setState({
todoArr: this.state.todoArr,
isChecked
})
}
changeTodoState(index, isDone, isChecked = false) {
if (isChecked) {
this.setState({
todoArr: this.state.todoArr.map(todo => {
todo.isDone = isDone;
return todo;
}),
isChecked: isDone
})
} else {
this.state.todoArr[index].isDone = isDone;
this.setState({
todoArr: this.state.todoArr
})
this.allChecked();
}
}
chearDone() {
let todos = this.state.todoArr.filter(todo => !todo.isDone);
this.setState({
todoArr: todos,
isChecked: false
})
}
render() {
const props = {
todoCount: this.state.todoArr.length,
todoDoneCount: this.state.todoArr.filter(todo => todo.isDone).length,
isChecked: this.state.isChecked
}
return (
<div className="main">
<HeaderView addTodo={this.addTodo} />
<MainView changeTodoState={this.changeTodoState} deleteTodo={this.deleteTodo} todos={this.state.todoArr} />
<FooterView isChecked={this.state.isChecked} clearDone={this.chearDone} {...props} changeTodoState={this.changeTodoState} />
</div>
)
}
}
export default TodoView;
|
const $firstAttempt = document.querySelectorAll('.first-attempt');
const $dataBorder = document.querySelectorAll('[data-border]');
const $hack = document.querySelectorAll('.hack');
const $hijack = document.querySelectorAll('.hijack');
const $st = document.getElementsByClassName('st1 st2');
const $del = document.querySelectorAll('.del');
const $lastAttempt = document.querySelectorAll('.last-attempt > span');
function addAndSetAttributeForArrayOfElements(elements, attribute, value) {
for (i = 0;i < elements.length;i++) {
elements[i].setAttribute(attribute, value);
}
}
function removeAttributeForArrayOfElements(elements, attribute) {
for (i = 0;i < elements.length;i++) {
elements[i].removeAttribute(attribute);
}
}
function addClassForArrayOfElements(elements, value) {
elements.forEach(function (e) {
e.classList.add(value);
})
}
function addAndSetNewColorAndFontSizeForArrayOfElements(elements, newColor, newFontSize) {
for (i = 0;i < elements.length;i++) {
elements[i].style.color = newColor;
elements[i].style.fontSize = newFontSize;
}
}
function showOrHideElementsForArrayOfElements(elements, hidden_or_visible) {
for (i = 0;i < elements.length;i++) {
$lastAttempt[i].style.visibility = hidden_or_visible;
}
}
addClassForArrayOfElements($firstAttempt,'active');
addAndSetAttributeForArrayOfElements($dataBorder, 'data-el-active', '');
addAndSetAttributeForArrayOfElements($hack, 'title', 'hacking');
removeAttributeForArrayOfElements($hijack, 'title');
addAndSetNewColorAndFontSizeForArrayOfElements($st, 'red', '15px');
removeAttributeForArrayOfElements($del, `data-hack-inactive`);
addAndSetAttributeForArrayOfElements($del, `data-hack-active`, '' );
showOrHideElementsForArrayOfElements($lastAttempt, "hidden");
|
const BetterDB = require('better-sqlite3');
/**
* Get project status by Tasks.projectCode. Sync mode.
* @param {string} projectCode - Project Code
* @returns {Object} Object contains projectStatus
*/
function checkProjectStatusSync(projectCode) {
let resultDb = new BetterDB('./db/projectDB.db');
let stmt = resultDb.prepare(`SELECT Projects.ProjectStatus AS projectStatus
FROM Tasks INNER JOIN Projects ON Tasks.projectCode = Projects.ProjectCode
WHERE Tasks.projectCode = ?;`);
let queryResult = stmt.get(projectCode);
resultDb.close();
return queryResult;
}
module.exports = checkProjectStatusSync;
|
import { Global } from "@emotion/react";
export const fonts = {
heading: "Open Sans",
body: "Poppins",
};
const Fonts = () => (
<Global
styles={`
/* Copied from https://fonts.googleapis.com/css2?family=Open+Sans:wght@700&family=Raleway&display=swap */
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/opensans/v18/mem5YaGs126MiZpBA-UN7rgOXOhpKKSTj5PW.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/opensans/v18/mem5YaGs126MiZpBA-UN7rgOUuhpKKSTjw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 100;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiGyp8kv8JHgFVrLPTucXtAKPY.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 100;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiGyp8kv8JHgFVrLPTufntAKPY.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 100;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiGyp8kv8JHgFVrLPTucHtA.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 200;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLFj_Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 200;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLFj_Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 200;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLFj_Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLDz8Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLDz8Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLDz8Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiEyp8kv8JHgFVrJJbecmNE.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiEyp8kv8JHgFVrJJnecmNE.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiEyp8kv8JHgFVrJJfecg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLGT9Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLGT9Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLGT9Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLEj6Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLEj6Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLEj6Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLCz7Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLCz7Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLCz7Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLDD4Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLDD4Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLDD4Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* devanagari */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLBT5Z11lFc-K.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200C-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLBT5Z1JlFc-K.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v15/pxiByp8kv8JHgFVrLBT5Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
`}
/>
);
export default Fonts;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsSecret = {
name: 'secret',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18 9.5A2.492 2.492 0 0013.511 8H10.49a2.436 2.436 0 10.46 1h2.101a2.5 2.5 0 104.95.5zM20 5h-3V2a2 2 0 00-2-2H9a2 2 0 00-2 2v3H4v1h16zM5 17H4a4 4 0 00-4 4v3h8l-1-1 2-2zM20 17h-1l-4 4 2 2-1 1h8v-3a4 4 0 00-4-4zM11 20h2v4h-2zM12 18l-1 2h2l-1-2z"/></svg>`
};
|
/**
* Exposes a promise and methods to manually resolve or reject it.
*/
class PromiseSource {
/**
* @constructor
* @template T
*/
constructor() {
/**
* @type {!function(result: *) : void}
* @private
*/
this._resolve = undefined;
/**
* @type {!function(error: *) : void}
* @private
*/
this._reject = undefined;
this.promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
/**
* @param {*} result
*/
setResult(result) {
this._resolve(result);
}
/**
* @param {*} error
*/
setError(error) {
this._reject(error);
}
}
export {PromiseSource}
|
var data = "string";
var data_2 = 'string';
// comment
/*
multi-line comment
*/
function myFunction(arg) {
if true {} else { return false }
}
|
var express = require('express');
var cors = require('cors')
var Twitter = require('twitter');
var app = express();
app.use(cors());
var client = new Twitter({
consumer_key: 'iQBlRPcYDqGiTMLslZhlMKP6G',
consumer_secret: 'QbFlWVZpYhYkWvitLtG1Fiwrp7llI9hF9OPql7IoKzMpynP2Rs',
access_token_key: '969939387386560512-OUfTlVcUc0jS54n2KT9ITGMkZYaYhLY',
access_token_secret: 'szAC390M2SRDopeJVwwi8RVNWLr04ZpoXRJkaJH47gZJB'
});
app.get('/tweets', function (req, res) {
client.get('search/tweets', { q: `#${req.query.search}` }, function (error, tweets, response) {
res.send(tweets.statuses.map(tweet => {
return {
'tweetId': tweet.id,
'tweetText': tweet.text,
'hashtags': tweet.entities.hashtags.map(hash => `#${hash.text}`).join(' '),
'userId': tweet.user.id,
'userName': tweet.user.name,
'userImg': tweet.user.profile_image_url
}
}));
// res.send(tweets.statuses);
});
});
app.listen(4000, function () {
console.log('Listening on port 4000!');
});
|
import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import vuecustomElement from 'vue-custom-element'
import UploadButton from 'vuetify-upload-button'
import router from './router'
require('./assets/css/style.css')
Vue.use(vuecustomElement)
Vue.customElement('upload-btn', UploadButton)
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
|
import {FILL_FORM, GET_FORM} from "../constants";
import validation from "../services/validation";
import {getBase} from "../services/baseconverter";
export default function fillForm(name = null, value = null, old = null,) {
if(name === null && value === null && old === null) {
return (dispatch => {
dispatch( {type: GET_FORM, payload: {}} );
});
} else {
return (dispatch => {
const isError = validation(value, old[name].validation);
console.log(isError, "Iseror")
if(old[name].validation === "FILE") {
getBase(value, (new_value)=> {
dispatch( {type: FILL_FORM, payload: {name, value: new_value, isError, old}} );
})
}
else {
dispatch( {type: FILL_FORM, payload: {name, value, isError, old}} );
}
});
}
}
|
export function addTransforms () {
addCodecTransform('Combination', {
rank: 'u32',
high: 'u32'
});
addCodecTransform('WinLossInfo<AccountId>', {
winner: 'AccountId',
win_hand: 'Combination',
loser: 'AccountId',
loss_hand: 'Combination'
});
addCodecTransform('keys::PublicStorage', {});
addCodecTransform('keys::RevealedSecrets', {});
}
|
var myApp = angular.module('principal',['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/inicio', {
templateUrl: 'telas/inicio.html',
controller: 'IndexController'
})
.when('/sobre', {
templateUrl: 'telas/sobre.html',
controller: 'IndexController'
})
.when('/404', {
templateUrl: 'telas/404.html',
})
.otherwise({
redirectTo: '404'
});
}]);
|
async function example6() {
const schema = {
progress: "steps",
pages: [{
legend: "Basics",
fields: [
{
type: "name",
name: "name",
caption: "Enter your name"
},
{
type: "multiline",
caption: "Your comments",
autogrow: true
}
]
},
{
legend: "Interests",
fields: [
{
type: "tags",
name: "tags",
caption: "Add interests",
value: ["Travel", "Reading", "Netflix"]
}
]
},
{
legend: "Final",
fields: [
{
type: "radiobuttonlist",
name: "role",
caption: "Select role",
items: ["Developer", "Product Owner", "Tester", "CTO", "UX"]
}
]
}]
};
return await xo.form.run(schema, {
on: {
post: e => {
alert(JSON.stringify(e.detail.postData, null, 2))
}
}
})
}
export default {n: "Paging & progress", f: example6};
|
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
import '../client/layouts/BuyerMainLayout.html';
import '../client/layouts/BuyerHomeLayout.html';
import '../client/layouts/SellerMainLayout.html';
import '../client/layouts/SellerHomeLayout.html';
import '../client/layouts/HomeLayout.html';
import '../client/Partials/BuyerNavBar.html';
import '../client/Partials/SellerNavBar.html';
import '../client/Partials/NavBar.html';
import '../imports/templateformproducts.html';
import '../imports/templateformcarts.html';
import '../imports/BuyerPolicyPage.html';
import '../imports/SellerPolicyPage.html';
import '../imports/CartPage.html';
import '../imports/buyerhalalsnacks.html';
import '../imports/buyervegansnacks.html';
import '../imports/buyervegetariansnacks.html';
import '../imports/DisplaySearchUsername.html';
import '../imports/DisplaySearchSellerName.html';
import '../imports/MyProductsPage.html';
import '../imports/DisplaySearchPage.html';
import '../imports/SearchPageBuyer.html';
import '../imports/SearchPageSeller.html';
FlowRouter.route('/', {
name: 'home',
action() {
BlazeLayout.render('HomeLayout');
}
});
FlowRouter.route('/Buyer', {
name: 'Buyer',
action() {
BlazeLayout.render('BuyerHomeLayout');
}
});
FlowRouter.route('/Seller', {
name: 'Seller',
action() {
BlazeLayout.render('SellerHomeLayout');
}
});
FlowRouter.route('/Buyer-Home', {
name: 'Buyer-Home',
action() {
BlazeLayout.render('BuyerHomeLayout');
}
});
FlowRouter.route('/Seller-Home', {
name: 'Seller-Home',
action() {
BlazeLayout.render('SellerHomeLayout');
}
});
FlowRouter.route('/buyer-halal-snacks', {
name: 'buyer-halal-snacks',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'Displaybuyerhalalsnacks'});
}
});
FlowRouter.route('/seller-halal-snacks', {
name: 'seller-halal-snacks',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'Displaybuyerhalalsnacks'});
}
});
// FlowRouter.route('/halal-drinks', {
// name: 'halal-drinks',
// action() {
// BlazeLayout.render('MainLayout');
// }
// });
FlowRouter.route('/buyer-vegan-snacks', {
name: 'buyer-vegan-snacks',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'Displaybuyervegansnacks'});
}
});
FlowRouter.route('/seller-vegan-snacks', {
name: 'seller-vegan-snacks',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'Displaybuyervegansnacks'});
}
});
// FlowRouter.route('/vegan-drinks', {
// name: 'vegan-drinks',
// action() {
// BlazeLayout.render('MainLayout');
// }
// });
FlowRouter.route('/buyer-vegetarian-snacks', {
name: 'buyer-vegetarian-snacks',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'Displaybuyervegetariansnacks'});
}
});
FlowRouter.route('/seller-vegetarian-snacks', {
name: 'seller-vegetarian-snacks',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'Displaybuyervegetariansnacks'});
}
});
// FlowRouter.route('/vegetarian-drinks', {
// name: 'vegetarian-drinks',
// action() {
// BlazeLayout.render('MainLayout');
// }
// });
FlowRouter.route('/Add-to-My-Products', {
name: 'Add-to-My-Products',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'templateformproducts'});
}
});
FlowRouter.route('/My-Products', {
name: 'My-Products',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'MyProductsPage'});
}
});
FlowRouter.route('/Buyer-Policy', {
name: 'Buyer-Policy',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'BuyerPolicyPage'});
}
});
FlowRouter.route('/Seller-Policy', {
name: 'Seller-Policy',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'SellerPolicyPage'});
}
});
// FlowRouter.route('/Marketplace', {
// name: 'Marketplace',
// action() {
// BlazeLayout.render('SellerHomeLayout');
// }
// });
FlowRouter.route('/Add-to-Cart', {
name: 'Add-to-Cart',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'templateformcarts'});
}
});
FlowRouter.route('/Cart', {
name: 'Cart',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'CartPage'});
}
});
FlowRouter.route('/display-search-username', {
name: 'display-search-username',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'DisplaySearchUsername'});
}
});
FlowRouter.route('/display-search-seller-name', {
name: 'display-search-seller-name',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'DisplaySearchSellerName'});
}
});
FlowRouter.route('/Search-Buyer', {
name: 'Search-Buyer',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'SearchPageBuyer'});
}
});
FlowRouter.route('/display-search-tags-buyer', {
name: 'display-search-tags-buyer',
action() {
BlazeLayout.render('BuyerMainLayout', {main: 'DisplaySearchPage'});
}
});
FlowRouter.route('/Search-Seller', {
name: 'Search-Seller',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'SearchPageSeller'});
}
});
FlowRouter.route('/display-search-tags-seller', {
name: 'display-search-tags-seller',
action() {
BlazeLayout.render('SellerMainLayout', {main: 'DisplaySearchPage'});
}
});
|
let looper = 0
let j = 0;
let database = firebase.database()
// Checks Username upon registering. Will return either true or false
let checkUserName = () => {
let firstName = $("#registerFirstName").val()
let lastName = $("#registerLastName").val()
let email = $("#registerEmail").val()
let password = $("#registerPassword").val()
let address = $("#registerAddress").val()
let city = $("#registerCity").val()
let state = $("#registerState").val()
let phone = $("#registerPhone").val()
let userName = $("#registerUserName").val()
if (firstName === "" || lastName === "" || email === "" || password === "" || address === "" || city === "" || state === "" || phone === "" || userName === "") {
document.getElementById("submit-button").disabled = true;
$(".container").attr("id", "shake-me")
$("#change-title").text("Please fill all fields")
$("#change-title").css("color", "red")
$("#transfer-button").attr("href", "#")
setTimeout(function () {
// document.getElementById("sign-in").disabled = false
$(".container").attr("id", "")
}, 1000)
setTimeout(function () {
document.getElementById("submit-button").disabled = false;
$("#change-title").css("color", "#1DB954")
$("#change-title").text("Sign Up")
}, 2000)
}
else {
let count = 0;
let looper = 0;
database.ref().on("value", function (data) {
looper++
let value = data.val()
console.log(data.val())
let keysArray = Object.keys(value);
for (var i = 0; i < keysArray.length; i++) {
if (keysArray[i] === userName) {
console.log("checked")
count = 1
}
}
if (count === 0) {
// console.log("pushing")
database.ref(userName).push({
firstName: firstName,
lastName: lastName,
username: userName,
email: email,
password: password,
address: address,
city: city,
state: state,
phone: phone,
driver: "",
license: "",
carMake: "",
carModel: "",
carMileage: "",
MPG: ""
})
window.location.href = "index.html"
// console.log($("#transfer-button")[0])
// console.log("looping")
}
else if (count === 1 && looper === 1) {
// document.getElementById("sign-in").disabled = true
document.getElementById("submit-button").disabled = true;
$(".container").attr("id", "shake-me")
$("#change-title").text("Username is Unavailable")
$("#change-title").css("color", "red")
$("#transfer-button").attr("href", "#")
//Reset all text fields to empty
$("#registerEmail").val('')
$("#registerPassword").val('')
$("#registerAddress").val('')
$("#registerCity").val('')
$("#registerState").val('')
$("#registerPhone").val('')
$("#registerUserName").val('')
$("#registerFirstName").val('')
$("#registerLastName").val('')
setTimeout(function () {
// document.getElementById("sign-in").disabled = false
$(".container").attr("id", "")
}, 1000)
setTimeout(function () {
document.getElementById("submit-button").disabled = false;
$("#change-title").css("color", "#1DB954")
$("#change-title").text("Sign Up")
}, 2000)
}
})
}
}
//main sign in page function
let checkSignIn = () => {
let userSignIn = $("#userName").val().trim()
let userPassword = $("#user-password").val().trim()
database.ref().on("value", function (data) {
let keys = Object.keys(data.val());
for (var i = 0; i < keys.length; i++) {
// console.log(keys)
// console.log(userSignIn)
if (userSignIn == keys[i]) {
database.ref(userSignIn).on("value", function (data) {
let userKeysArray = Object.keys(data.val())
console.log(data.val()[userKeysArray[0]].password)
console.log(userPassword)
if (userPassword == data.val()[userKeysArray[0]].password) {
console.log("loading correctly")
window.location.href = "signedIn.html"
}
})
}
}
setTimeout(function () {
document.getElementById("sign-in").disabled = true;
$(".container").attr("id", "shake-me")
$("#change-title-sign-in").text("Incorrect Username Or Password")
$("#change-title-sign-in").css("color", "red")
$("#transfer-button").attr("href", "#")
$("#userName").val('')
$("#user-password").val('')
setTimeout(function () {
$(".container").attr("id", "")
// document.getElementById("sign-in").disabled = false
}, 1000)
setTimeout(function () {
document.getElementById("sign-in").disabled = false;
$("#change-title-sign-in").css("color", "#1DB954")
$("#change-title-sign-in").text("Sign Up")
}, 2000)
}, 500)
})
}
//start of next part of function, put ins ame function due to asyncrhonous check
$("#submit-button").on("click", function () {
checkUserName()
})
$("#sign-in").on("click", function () {
checkSignIn()
})
let checkedDriver = () => {
if (j === 0) {
$(".input-hidden").css({ "position": "static", "opacity": "1", "transition": "opacity 1s linear" })
j = 1
}
else if (j === 1) {
$(".input-hidden").css({ "position": "absolute", "opacity": "0", "transition": "opacity 0.00001s linear" })
j = 0;
}
}
// function initialize() {
// var input = document.getElementById('search-text-field');
// new google.maps.places.Autocomplete(input);
// }
// google.maps.event.addDomListener(window, 'load', initialize);
|
import {eventChannel, buffers} from 'redux-saga';
import {take, put} from 'redux-saga/effects';
import Immutable from 'immutable';
export const mainViewGeometries = [
{size: 'lg', width: 1140, svgScale: 1.0},
{size: 'md', width: 940, svgScale: 0.9},
{size: 'sm', width: 794, svgScale: 0.75},
];
export default function (bundle, deps) {
bundle.addReducer('init', function (state, _action) {
return state
.set('mainViewGeometry', mainViewGeometries[0])
.set('panes', Immutable.Map());
});
bundle.defineAction('windowResized', 'Window.Resized');
// Event channel for resize events.
// Only the most recent event is kept in the buffer.
const resizeMonitorChannel = eventChannel(function (listener) {
function onResize () {
const width = window.innerWidth;
const height = window.innerHeight;
listener({width, height});
}
window.addEventListener('resize', onResize);
// Add an initial event to the channel.
onResize();
return function () {
window.removeEventListener('resize', onResize);
};
}, buffers.sliding(1));
// Lift resize events into windowResized actions.
bundle.addSaga(function* monitorResize () {
while (true) {
let {width, height} = yield take(resizeMonitorChannel);
yield put({type: deps.windowResized, width, height});
}
});
// Make windowResized update the global state 'size'.
bundle.addReducer('windowResized', function (state, action) {
const {width, height} = action;
return state.set('windowWidth', width).set('windowHeight', height);
});
bundle.addLateReducer(function updateGeometry (state) {
if (!state) return state;
/* Default to the largest geometry, no visible panes. */
let geometry = mainViewGeometries[0];
let panes = state.get('panes');
let viewportTooSmall = false;
const windowWidth = state.get('windowWidth');
if (windowWidth) {
let mainViewWidth = windowWidth;
/* Account for width of enabled panes. */
panes = panes.map(pane => {
if (!pane.get('enabled')) {
return pane.set('visible', false)
}
mainViewWidth -= pane.get('width') + 10;
return pane.set('visible', true);
});
/* Find the largest main-view geometry that fits the available space. */
let geometryIndex = 0;
while (geometry.width > mainViewWidth) {
geometryIndex += 1;
if (geometryIndex === mainViewGeometries.length) {
/* Screen is too small, use the smallest geometry and hide all panes. */
viewportTooSmall = true;
panes = panes.map(pane => pane.set('visible', false));
break;
}
geometry = mainViewGeometries[geometryIndex];
}
}
/* Compute the container width */
/* XXX is this still needed? */
let containerWidth = geometry.width;
panes = panes.map(pane => {
if (pane.get('visible')) {
containerWidth += pane.get('width');
}
return pane;
});
return state
.set('viewportTooSmall', viewportTooSmall)
.set('containerWidth', containerWidth)
.set('mainViewGeometry', geometry)
.set('panes', panes);
});
};
|
function sumArr (arr) {
const sum = arr => arr.reduce((res, el) => res + (Array.isArray(el) ? sum(el) : el), 0);
return sum(arr);
}
|
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';
import autoPopulate from 'mongoose-autopopulate';
const User = mongoose.Schema({
name: String,
company: String,
username: {
type: String,
unique: true,
required: true
},
email: {
type: String,
unique: true,
required: true
},
password: { type: String, select: false },
receipts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'receipt', autopopulate: true }],
categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'category', autopopulate: true }]
});
User.plugin(autoPopulate);
User.statics.findUserByCredentials = function(username, password) {
const User = this;
return User.findOne({ username })
.select('+password')
.then(user => {
if (!user) return Promise.reject();
return bcrypt.compare(password, user.password)
.then(result => {
if (result)
return user;
});
});
};
User.pre('save', function(next) {
const user = this;
if (user.isModified('password')) {
return bcrypt.genSalt(10)
.then(salt =>
bcrypt.hash(user.password, salt)
.then(hash => {
user.password = hash;
next();
})
);
}
next();
});
mongoose.model('user', User);
|
var Buffer = require('buffer').Buffer
console.log('test');
// QmfATQNSR2sbFAQwfgycZyzXqYcAT4TXPSeyyMTjekaUR9
function loadVid(argument) {
let link = document.getElementById("link-box").value.trim();
document.getElementById("vid-frame").style.display = "block";
document.getElementById("vid").src="https://ipfs.io/ipfs/"+link;
document.getElementById("vid-frame").load();
}
function upload_vid() {
const ipfs = new IPFS({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' });
var inputData = document.getElementById('file').files[0];
console.log(new Buffer.alloc(inputData,'binary'));
// ipfs.add(buf, (err, result) => {
// if (err) {
// console.log( 'Hmm.. there was an error: ' + String(err));
// } else {
// // document.getElementById("link-box").value = result;
// console.log(result);
// }
// });
}
|
'use strict';
const block = 'section';
const elems = {
sliderList: block + '__slider-list',
sliderItem: block + '__slider-item',
arrowPrev: block + '__arrow-prev',
arrowNext: block + '__arrow-next'
};
const mods = {
sliderScreen: block + '--slider-screen'
};
$(document).ready(function () {
});
|
System.register(["./configure", "./google-maps"], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function configure(aurelia, configCallback) {
var instance = aurelia.container.get(configure_1.Configure);
// Do we have a callback function?
if (configCallback !== undefined && typeof (configCallback) === 'function') {
configCallback(instance);
}
aurelia.globalResources([
'./google-maps'
]);
}
exports_1("configure", configure);
var configure_1, google_maps_1;
return {
setters: [
function (configure_1_1) {
configure_1 = configure_1_1;
},
function (google_maps_1_1) {
google_maps_1 = google_maps_1_1;
}
],
execute: function () {
exports_1("Configure", configure_1.Configure);
exports_1("GoogleMaps", google_maps_1.GoogleMaps);
}
};
});
|
import { useState } from "react";
import { useDispatch } from "react-redux";
import { createPlayer } from "./playersSlice";
const CreatePlayerForm = ({ clientID, socket }) => {
const dispatch = useDispatch();
const [name, setName] = useState("");
function handleCreatePlayer() {
if (name === "") {
return;
}
const payload = {
name,
clientID,
socket,
};
dispatch(createPlayer(payload));
}
return (
<>
<h1>Add Player</h1>
<label htmlFor="name">Enter name</label>
<input
type="text"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button onClick={handleCreatePlayer}>Create player</button>
</>
);
};
export default CreatePlayerForm;
|
"use strict";
$(document).ready(function () {
var confirmDialog = $("#confirm-dialog")
.dialog({
resizable: false,
height: "auto",
width: 400,
modal: true
})
.dialog("close");
var confirmDialogMessageTag = confirmDialog.find("p");
var inputTextArea = $("#task-input-textarea");
var errorMessage = $("#error-message");
$("#add-button").click(function () {
var taskText = inputTextArea.val();
if ($.trim(taskText).length === 0) {
errorMessage.removeClass("hidden");
inputTextArea.val("");
return;
}
errorMessage.addClass("hidden");
var task = $("<div class='task'></div>");
function setTask() {
task.html(
"<div class='text-section'><ul><li class='text'></li></ul></div>" +
"<div class='buttons-section'><button class='button edit-button' type='button'>Изменить</button>" +
"<button class='button delete-button' type='button'>Удалить</button></div>"
);
task.find(".text").text(taskText);
task.find(".delete-button").click(function () {
confirmDialogMessageTag.text("Вы уверены, что хотите удалить задание?");
confirmDialog.dialog({
buttons: {
"Да": function () {
task.remove();
$(this).dialog("close");
},
"Нет": function () {
$(this).dialog("close");
}
}
});
});
task.find(".edit-button").click(function () {
task.find(".text-section").html("<textarea class='editable-task-textarea' rows='4'></textarea>");
task.find(".buttons-section").html(
"<button class='button save-button' type='button'>Сохранить</button>" +
"<button class='button cancel-button' type='button'>Отменить</button>"
);
task.find(".editable-task-textarea").val(taskText);
task.find(".save-button").click(function () {
if ($.trim(task.find(".editable-task-textarea").val()).length === 0) {
confirmDialogMessageTag.text("У задания нет текста. Удалить его?");
confirmDialog.dialog({
buttons: {
"Да": function () {
task.remove();
$(this).dialog("close");
},
"Нет": function () {
$(this).dialog("close");
}
}
});
return;
}
taskText = task.find(".editable-task-textarea").val();
setTask();
});
task.find(".cancel-button").click(function () {
confirmDialogMessageTag.text("Вы уверены, что хотите отменить внесенные изменения?");
confirmDialog.dialog({
buttons: {
"Да": function () {
setTask();
$(this).dialog("close");
},
"Нет": function () {
$(this).dialog("close");
}
}
});
});
});
}
setTask();
$("#tasks-container").append(task);
inputTextArea.val("");
});
$("#clear-button").click(function () {
if (inputTextArea.val().length !== 0) {
confirmDialogMessageTag.text("Вы уверены, что хотите удалить введенный текст?");
confirmDialog.dialog({
buttons: {
"Да": function () {
inputTextArea.val("");
$(this).dialog("close");
},
"Нет": function () {
$(this).dialog("close");
}
}
});
}
});
});
|
const checkCsrfToken = require('./csrf_token');
const errorPage = require('./error_page');
const requestLog = require('./request_log');
module.exports = {
checkCsrfToken,
errorPage,
requestLog
}
|
/**
* @module Utils
*
*/
export default function launchDarklySdk(id, data, options={}) {
return window.LDClient.initialize(id, data, options);
}
|
lostAndFoundApp.controller('eventLossCtrl',
function ($scope, $routeParams, $http, $location, $rootScope) {
var eventId = $routeParams.eventId;
var retrievedEvent;
$http.get('/pa165/rest/events/' + eventId).then(function (response) {
retrievedEvent = response.data;
console.log(retrievedEvent);
});
var user;
$http.get('/pa165/rest/users/' + $rootScope.currentUser.id).then(function (response) {
user = response.data;
});
console.log($rootScope.currentUser.id);
$scope.event = {
placeOfLoss: "",
dateOfLoss: new Date()
};
$scope.addLoosing = function (event) {
var eventData = {
id: retrievedEvent.id,
item: retrievedEvent.item,
owner: user,
placeOfLoss: event.placeOfLoss,
dateOfLoss: toJSONLocal(event.dateOfLoss)
};
console.log(eventData);
$http({
method: 'POST',
url: '/pa165/rest/events/add_loosing',
data: eventData
})
.then(function success(response) {
$rootScope.successAlert = 'Loosing was reported';
$location.path("/events");
}, function error(response) {
console.log("Error when reporting loosing");
console.log(response);
switch (response.data.code) {
case 'ResourceNotFoundException':
$rootScope.errorAlert = 'Event could not be found';
break;
default:
$rootScope.errorAlert = 'Cannot report loosing: ' + response.data.message;
break;
}
});
};
function toJSONLocal(date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
});
|
module.exports = function(grunt){
// configuration
const sass = require('node-sass');
// require('load-grunt-tasks')(grunt);
// grunt.initConfig({
// });
grunt.registerTask('default', ['sass']);
grunt.initConfig({
// pass in options, plugins, references to files etc
concat: {
js: {
src: ['js/*.js'],
dest: 'app.js'
}
},
sass: {
options: {
implementation: sass,
sourceMap: false
},
dist: {
files: {
'css/styles.css': 'css/sass/styles.scss'
}
}
},
// uglify: {
// build:'app.js',
// dest: 'dest/app.js'
// }
uglify: {
dev: {
options: {
mangle: true
},
files: {
'dest/dest.min.js': 'app.js'
}
}
},
})
// load plugins
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-sass');
grunt.registerTask('default', ['sass']);
// grunt.loadNpmTasks('grant-contrib-concat');
// register task
// grunt.registerTask('run',function(){
// console.log('i am running')
// })
// grunt.registerTask('sleep',function(){
// console.log('i am sleeping')
// })
// grunt.registerTask('all',['sleep','run'])
};
|
Ext.onReady(function() {
var activeTab = parseInt(MODx.request.activeTab);
MODx.load({
xtype: 'sc-certificates-page-home'
,activeTab: activeTab
});
});
StudentCentre.page.CertificatesHome = function(config) {
config = config || {};
Ext.applyIf(config,{
components: [{
xtype: 'sc-certificates-panel-home'
,renderTo: 'sc-certificates-panel-home-div'
,activeTab: config.activeTab
}]
});
StudentCentre.page.CertificatesHome.superclass.constructor.call(this,config);
};
Ext.extend(StudentCentre.page.CertificatesHome,MODx.Component);
Ext.reg('sc-certificates-page-home',StudentCentre.page.CertificatesHome);
|
import React, { useCallback, useEffect, useState, useRef } from 'react';
import './App.css';
export default function App(props) {
// const [urb, setUrb] = useState();
const [sub, setSub] = useState();
const [libraryObject, setLibraryObject] = useState({libraries: {}});
const [selectedLib, setSelectedLib] = useState();
const [selectedBook, setSelectedBook] = useState();
const stateRef = useRef();
stateRef.current = libraryObject;
// Could not figure out how to make urb available by the time UI renders with useEffect. Someone school me please
const urb = props.api;
// atoms of @tas for meta and comments identifiers
const metaId = 1635018093;
const commentsId = 8319395793566789475;
// *** This section populates React state from graph-store scries
// Scry to get graph-store keys
useEffect(() => {
urb.scry({
app: 'graph-store',
path: '/keys'
})
.then(keys => {
keys['graph-update'].keys.forEach(key => {
if(!key.name.includes(" ")){
scryKey(key.name);
}
})
});
}, []);
// Checks keys from useEffect scry to see if they are libraries and adds reduced graph to state object if yes
const scryKey = (key) => {
urb.scry({
app: 'graph-store',
path: `/graph/~zod/${key}`
})
.then(graph => {
// Checks graph for library validator mark
if(graph['graph-update']['add-graph'].mark === "graph-validator-library") {
// Add to library state object
setLibraryObject((prevLibraryObject) => ({
...prevLibraryObject,
libraries: {
...prevLibraryObject.libraries,
[graph['graph-update']['add-graph'].resource.name]: {
name: graph['graph-update']['add-graph'].resource.name,
ship: graph['graph-update']['add-graph'].resource.ship,
}
}
}));
// Then check to see if library has books
if(Object.keys(graph['graph-update']['add-graph'].graph).length > 0) {
addBooksToState(graph);
}
}
})
}
const addBooksToState = (graph) => {
Object.keys(graph['graph-update']['add-graph'].graph).forEach(index => {
// Destructure basic info from book entry
const bookName = graph['graph-update']['add-graph'].graph[index].children[metaId].children[1].post.contents[0].text;
const ISBN = graph['graph-update']['add-graph'].graph[index].children[metaId].children[1].post.contents[1].text;
const destinationLibrary = graph['graph-update']['add-graph'].resource.name;
let comments;
// Check if book has comments and add them to comments object
if(graph['graph-update']['add-graph'].graph[index].children['8319395793566789475'].children){
Object.keys(graph['graph-update']['add-graph'].graph[index].children['8319395793566789475'].children).forEach(
key => (
comments = {
...comments,
[key]:
graph['graph-update']['add-graph'].graph[index].children['8319395793566789475'].children[key].post
}
)
)
} else {
comments = {};
}
// Commit reduced graph info to state
setLibraryObject((prevLibraryObject) => ({
...prevLibraryObject,
libraries: {
...prevLibraryObject.libraries,
[destinationLibrary]: {
...prevLibraryObject.libraries[destinationLibrary],
books: {
...prevLibraryObject.libraries[destinationLibrary].books,
[index]: {
title: bookName,
isbn: ISBN,
comments
}
}
}
}
}))
})
}
// This section monitors updates that happen after page loads
const updateHandler = useCallback(
(update) => {
console.log("New graph", update);
// Check if new graph is a library
if(update['graph-update']['add-graph'] && update['graph-update']['add-graph']['mark'] === "graph-validator-library"){
const newLib = update['graph-update']['add-graph']['resource'];
setLibraryObject((prevLibraryObject) => ({
...prevLibraryObject,
libraries: {
...prevLibraryObject.libraries,
[newLib.name]: {}
}
}))
return
}
// Check if new add-nodes is a book or comment
if(update['graph-update']['add-nodes'] && Object.keys(stateRef.current.libraries).includes(update['graph-update']['add-nodes'].resource.name)){
const nodes = update['graph-update']['add-nodes'].nodes;
const destinationLibrary = update['graph-update']['add-nodes'].resource.name;
console.log("Update is adding nodes to existing library");
Object.keys(nodes).forEach(
node => {
if(node.includes(metaId) && nodes[node].post.contents.length === 2){
console.log("New nodes are a book")
setLibraryObject((prevLibraryObject) => ({
...prevLibraryObject,
libraries: {
...prevLibraryObject.libraries,
[destinationLibrary]: {
...prevLibraryObject.libraries[destinationLibrary],
books: {
...prevLibraryObject.libraries[destinationLibrary].books,
[node.substr(1, 39)]: {
title: nodes[node].post.contents[0].text,
isbn: nodes[node].post.contents[1].text,
comments: {}
}
}
}
}
}))
}
}
)
// Comments only have one node so we use that to check if the nodes are for a comment
if(Object.keys(nodes).length < 4){
const node = Object.keys(nodes)[0];
// console.log("New comments", nodes);
setLibraryObject((prevLibraryObject) => ({
...prevLibraryObject,
libraries: {
...prevLibraryObject.libraries,
[destinationLibrary]: {
...prevLibraryObject.libraries[destinationLibrary],
books: {
...prevLibraryObject.libraries[destinationLibrary].books,
[node.substr(1, 39)]: {
...prevLibraryObject.libraries[destinationLibrary].books[node.substr(1, 39)],
comments: {
...prevLibraryObject.libraries[destinationLibrary].books[node.substr(1, 39)].comments,
[node.substr(61)]:
nodes[node].post
}
}
}
}
}
}))
}
return
}
// Check to see if the update is notifiy of removed-posts
// First compare to library names (graphs), if it matches a library name then delete it from our state
if(update['graph-update']['remove-graph'] && Object.keys(stateRef.current.libraries).includes(update['graph-update']['remove-graph'].name)){
const newState = stateRef.current;
delete newState.libraries[(update['graph-update']['remove-graph'].name)];
setSelectedLib(null);
setLibraryObject(newState);
}
// Then check to see if it is a deleted comment (post)
if(update['graph-update']['remove-posts'] && update['graph-update']['remove-posts'].indices[0].includes("8319395793566789475")){
console.log("Comment removed");
const comIndex = update['graph-update']['remove-posts'].indices[0].substr(61);
// Iterate over keys of each state object until we can check the comment index against the currently selected book
Object.keys(stateRef.current.libraries).forEach(
library => (
Object.keys(stateRef.current.libraries[library].books).forEach(
book => {
Object.keys(stateRef.current.libraries[library].books[book].comments).forEach(
comment => {
if(comment == comIndex){
// Couldn't get setState to re-render without doing it this long hand way. Do I need lodash here?
setLibraryObject(prevLibraryObject => ({
...prevLibraryObject,
libraries: {
...prevLibraryObject.libraries,
[library]: {
...prevLibraryObject.libraries[library],
books: {
...prevLibraryObject.libraries[library].books,
[book]: {
...prevLibraryObject.libraries[library].books[book],
comments: {
...prevLibraryObject.libraries[library].books[book].comments,
[comIndex]: {}
}
}
}
}
}
}));
}
}
)
}
)
)
)
}
},[]);
useEffect(() => {
urb.subscribe({
app: 'graph-store',
path: '/updates',
event: updateHandler,
err: console.log,
quit: console.log,
})
.then((subscriptionId) => {
setSub(subscriptionId);
});
}, []);
useEffect(() => {
urb.subscribe({
app: 'library-proxy',
path: '/libraries',
event: console.log,
err: console.log,
quit: console.log,
})
.then((subscriptionId) => {
setSub(subscriptionId);
});
}, []);
// These functions called by the user to interact with Urbit ship
const createLibrary = (library) => {
urb.poke({
app: 'library-proxy',
mark: 'library-frontend',
json: {
'create-library': {
'library-name': library,
'policy': 'open'
}
}
});
};
const removeLibrary = (library) => {
urb.poke({
app: 'library-proxy',
mark: 'library-frontend',
json: {
'remove-library': {
'library-name': library
}
}
})
}
const addBook = (title, isbn) => {
urb.poke({
app: 'library-proxy',
mark: 'library-frontend',
json: {
'add-book': {
'library-name': selectedLib,
'book': {
title,
isbn
}
}
}
})
}
const addComment = (comment) => {
urb.poke({
app: 'library-proxy',
mark: 'library-frontend',
json: {
'add-comment': {
'library-name': selectedLib,
'top': selectedBook,
'comment': comment
}
}
})
}
const removeComment = (comment) => {
urb.poke({
app: 'library-proxy',
mark: 'library-frontend',
json: {
'remove-comment': {
'library-name': selectedLib,
'index': [selectedBook.toString(), '8319395793566789475', comment.toString()]
}
}
})
}
// Adding this so clear comment section when switching between libraries. Might be a cleaner way to do it?
const changeSelectedLib = (lib) => {
setSelectedBook(null);
setSelectedLib(lib);
}
return (
<div className="App">
<header className="App-header">
<p>
<pre>Connected Ship: {urb.ship}</pre>
</p>
<table width="100%" border="1">
<tr>
<td>
{/* Form to create library */}
<form
onSubmit={(e) => {
e.preventDefault();
const library = e.target.library.value;
createLibrary(library);
}}>
<input
type="library"
name="library"
placeholder="Library Name"/>
<button>
Create Library
</button><br/><br/>
</form>
</td>
<td>
{/* Display selected library over books component */}
<pre>{selectedLib
?
<>
{selectedLib}
<br/>
<button
onClick={() => removeLibrary(selectedLib)}>
Remove
</button><br/>
</>
: "Select a Library"}</pre>
</td>
</tr>
<tr>
<td>
{/* Create a list of existing libraries for user to explore */}
{libraryObject.libraries ? Object.keys(libraryObject.libraries).map(lib =>(
<li>
<button
onClick={() => changeSelectedLib(lib)}
key={lib}>
{lib}
</button>
</li>
))
: "Loading..."}
</td>
<td>
{/* Books component */}
{libraryObject.libraries && selectedLib
? <>
<form
onSubmit={(e) => {
e.preventDefault();
const title = e.target.title.value;
const isbn = e.target.isbn.value;
addBook(title, isbn);
}}>
<input
type="title"
name="title"
placeholder="Title"/><br/>
<input
type="isbn"
name="isbn"
placeholder="ISBN"/><br/>
<button>Add Book</button>
</form>
<br/>
{libraryObject.libraries[selectedLib].books
? Object.keys(libraryObject.libraries[selectedLib].books).map(index => (
<li>
<button
onClick={() => setSelectedBook(index)}>
Title: {libraryObject.libraries[selectedLib].books[index].title}
ISBN: {libraryObject.libraries[selectedLib].books[index].isbn}
</button>
</li>
))
: "No books yet"}
</>
: null}
<br/>
</td>
</tr>
</table>
<table width="100%" border="1">
<tr>
<td>
<pre>
Comments {libraryObject.libraries && selectedLib && selectedBook ? <>for {libraryObject.libraries[selectedLib].books[selectedBook].title}</> : null}
</pre>
</td>
</tr>
<tr>
<td>
{libraryObject.libraries && selectedLib && selectedBook ? <>
<form
onSubmit={(e) => {
e.preventDefault();
const comment = e.target.comment.value;
addComment(comment);
}}
>
<input
type="comment"
name="comment"
placeholder="Comment"
/>
<button>Add Comment</button>
</form>
</> : null}
</td>
</tr>
<tr>
<td>
{selectedLib && selectedBook && Object.keys(libraryObject.libraries[selectedLib].books[selectedBook].comments).length > 0
? Object.keys(libraryObject.libraries[selectedLib].books[selectedBook].comments).map(
key => (
<>
<p>
{libraryObject.libraries[selectedLib].books[selectedBook].comments[key].contents
? <>
{libraryObject.libraries[selectedLib].books[selectedBook].comments[key].author}:
{libraryObject.libraries[selectedLib].books[selectedBook].comments[key].contents[0].text}
<button
onClick={() => removeComment(key)}
>
Remove
</button>
</>
: "Comment Deleted"
}
</p>
</>
)
)
: selectedLib && selectedBook && Object.keys(libraryObject.libraries[selectedLib].books[selectedBook].comments).length === 0
? "No Comments Yet"
: null}
</td>
</tr>
</table>
</header>
</div>
);
}
|
import axios from "axios";
const base = "https://my-nc-knews.herokuapp.com/api";
export const getTopics = async () => {
const {
data: { topics }
} = await axios.get(`${base}/topics`);
return topics;
};
export const getArticlesByTopic = async (topic, query) => {
const {
data: articles
} = await axios.get(`${base}/topics/${topic}/articles${query}`);
return articles;
}
export const getArticles = async (query) => {
const {
data: { articles }
} = await axios.get(`${base}/articles${query}`);
return articles;
}
export const getArticleById = async (article_id) => {
const { data } = await axios.get(`${base}/articles/${article_id}`);
return data;
};
export const getCommentsByArticleId = async (article_id) => {
const {
data: { comments }
} = await axios.get(`${base}/articles/${article_id}/comments`);
return comments;
}
export const submitCommentByArticleId = async (commentBody, article_id, user_id) => {
const { data } = await axios.post(`${base}/articles/${article_id}/comments`, { body: commentBody, user_id: user_id });
return data;
}
// export const voteComment = async (amount, article_id) => {
// const changeVotes = { inc_votes: amount };
// const { data } = await axios.patch(`${base}/articles/${article_id}/comments`, changeVotes);
// return data;
// }
export const deleteComment = async (comment_id, article_id) => {
await axios.delete(`${base}/articles/${article_id}/comments/${comment_id}`)
}
export const voteArticle = async (article_id, amount) => {
const changeVotes = { inc_votes: amount };
const { data } = await axios.patch(`${base}/articles/${article_id}`, changeVotes);
return data;
}
export const submitArticle = async (topicValue, articleBody, titleValue, user_id) => {
const { data: { article } } = await axios.post(`${base}/topics/${topicValue}/articles`, { topic: topicValue, body: articleBody, title: titleValue, user_id: user_id });
return article;
}
export const deleteArticle = async (article_id) => {
await axios.delete(`${base}/articles/${article_id}`);
}
export const getUsers = async () => {
const {
data: { users }
} = await axios.get(`${base}/users`);
return users;
}
export const getUserByUsername = async (username) => {
const {
data
} = await axios.get(`${base}/users/${username}`)
return data;
}
|
const mongoose = require("mongoose")
const supertest = require("supertest")
const helper = require("../utils/test_helper")
const app = require("../app")
const api = supertest(app)
const bcrypt = require("bcrypt")
const Blog = require("../models/blog")
const User = require("../models/user")
describe("When initially saving some notes", () => {
beforeEach(async () => {
await Blog.deleteMany({})
await User.deleteMany({})
const passwordHash = await bcrypt.hash("sekret", 10)
const user = new User({ username: "root", passwordHash })
await user.save()
await Blog.insertMany(helper.initialBlogs)
})
test("Notes are returned as JSON", async () => {
await api
.get("/api/blogs")
.expect(200)
.expect("Content-Type", /application\/json/)
})
test("All notes are returned", async () => {
const response = await api.get("/api/blogs")
expect(response.body).toHaveLength(helper.initialBlogs.length)
})
test("Specified blog is within the returned list", async () => {
const response = await api.get("/api/blogs")
const titles = response.body.map(r => r.title)
expect(titles).toContain("Post test")
})
describe("Viewing a specific note", () => {
test("A specific note can be viewed", async () => {
const blogsAtStart = await helper.blogsInDb()
const blogToView = blogsAtStart[0]
const resultBlog = await api
.get(`/api/blogs/${blogToView.id}`)
.expect(200)
.expect("Content-Type", /application\/json/)
const processedBlogToView = JSON.parse(JSON.stringify(blogToView))
expect(resultBlog.body).toEqual(processedBlogToView)
})
describe("Adding new blogs", () => {
test("A valid note can be added", async () => {
const usersAtStart = await helper.usersInDb()
const userid = usersAtStart[0].id
const newBlog = {
title: "Added through test",
author: "Async/Await",
url: "jest",
likes: 420,
user: userid
}
let token = ""
await api
.post("/api/login")
.send({
username: "root",
password: "sekret"
})
.expect((res) => {
token = res.body.token
})
.expect(200)
await api
.post("/api/blogs")
.set("Authorization", `bearer ${token}`)
.send(newBlog)
.expect(200)
.expect("Content-Type", /application\/json/)
const blogsAtEnd = await helper.blogsInDb()
expect(blogsAtEnd).toHaveLength(helper.initialBlogs.length + 1)
const titles = blogsAtEnd.map(b => b.title)
expect(titles).toContain("Added through test")
})
test("Blog can't be added without authorization header in request", async () => {
const usersAtStart = await helper.usersInDb()
const userid = usersAtStart[0].id
const newBlog = {
author: "Async/Await",
url: "jest",
likes: 420,
user: userid
}
await api
.post("/api/blogs")
.send(newBlog)
.expect(401)
const blogsAtEnd = await helper.blogsInDb()
expect(blogsAtEnd).toHaveLength(helper.initialBlogs.length)
})
test("Blog without title is not added", async () => {
const usersAtStart = await helper.usersInDb()
const userid = usersAtStart[0].id
const newBlog = {
author: "Async/Await",
url: "jest",
likes: 420,
user: userid
}
let token = ""
await api
.post("/api/login")
.send({
username: "root",
password: "sekret"
})
.expect((res) => {
token = res.body.token
})
.expect(200)
await api
.post("/api/blogs")
.set("Authorization", `bearer ${token}`)
.send(newBlog)
.expect(400)
const blogsAtEnd = await helper.blogsInDb()
expect(blogsAtEnd).toHaveLength(helper.initialBlogs.length)
})
test("Blog has identifying \"id\" field", async () => {
const blogsAtStart = await helper.blogsInDb()
const blogToView = blogsAtStart[0]
const resultBlog = await api
.get(`/api/blogs/${blogToView.id}`)
.expect(200)
.expect("Content-Type", /application\/json/)
expect(resultBlog.body.id).toBeDefined()
})
test("Blog with no likes has likes set to 0 on post", async () => {
const usersAtStart = await helper.usersInDb()
const userid = usersAtStart[0].id
const newBlog = {
title: "Added through test",
author: "Async/Await",
url: "jest",
likes: null,
user: userid
}
let token = ""
await api
.post("/api/login")
.send({
username: "root",
password: "sekret"
})
.expect((res) => {
token = res.body.token
})
.expect(200)
await api
.post("/api/blogs")
.set("Authorization", `bearer ${token}`)
.send(newBlog)
.expect(200)
.expect("Content-Type", /application\/json/)
const blogsAtEnd = await helper.blogsInDb()
console.log(blogsAtEnd[blogsAtEnd.length - 1])
expect(blogsAtEnd[blogsAtEnd.length - 1].likes).toBe(0)
})
describe("Deleting blogs", () => {
test("A blog can be deleted", async () => {
const usersAtStart = await helper.usersInDb()
const userid = usersAtStart[0].id
const newBlog = {
title: "Added through test",
author: "Async/Await",
url: "jest",
likes: 420,
user: userid
}
let token = ""
await api
.post("/api/login")
.send({
username: "root",
password: "sekret"
})
.expect((res) => {
token = res.body.token
})
.expect(200)
await api
.post("/api/blogs")
.set("Authorization", `bearer ${token}`)
.send(newBlog)
const tempBlogs = await helper.blogsInDb()
const blog = tempBlogs[tempBlogs.length - 1]
await api
.delete(`/api/blogs/${blog.id}`)
.set("Authorization", `bearer ${token}`)
.expect(204)
const blogsAtEnd = await helper.blogsInDb()
expect(blogsAtEnd).toHaveLength(helper.initialBlogs.length)
const titles = blogsAtEnd.map(r => r.title)
expect(titles).not.toContain(blog.title)
})
})
})
})
})
afterAll(() => {
mongoose.connection.close()
})
|
mainApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider','$httpProvider',
function ($stateProvider, $urlRouterProvider,$locationProvider,$httpProvider) {
$urlRouterProvider.otherwise('/index');
// Home state routing
$stateProvider.
state('home', {
url: '/index',
abstract: true,
templateUrl: 'src/modules/home/views/index.html',
controller: 'HomeController'
}).
state('home.index', {
url: '',
templateUrl: 'src/modules/home/views/home.html'
})
.state('home.my-post', {
url: '/own-post',
templateUrl: 'src/modules/home/views/own-post.html',
controller: 'OwnPostController'
}).state('home.contacted-post', {
url: '/contacted-post',
templateUrl: 'src/modules/home/views/contacted-post.html',
controller:'ContactedPostController'
}).state('home.about', {
url: '/about',
templateUrl: 'src/modules/home/views/about.html'
});
$stateProvider.state('share', {
url: '/share/:id',
templateUrl: 'src/modules/home/views/share.html'
});
}
]);
|
export default () => {
return [
{title: "Javascript", pages: 100},
{title: "Elixir", pages: 350},
{title: "Java", pages: 150},
{title: "Python", pages: 200}
]
}
|
$(function () {
$('#confirm-delete').on('show.bs.modal', function (e) {
var confirmMessage = $(e.relatedTarget).data('message') || 'Are you sure? Do you want to proceed?'
$('#confirm-message').html(confirmMessage)
$(this).find('#delete-form').attr('action', $(e.relatedTarget).data('href'))
})
attachJsDatepicker()
})
function attachJsDatepicker () {
var $elem = $('.js-datepicker')
if ($elem.length > 0) {
$elem.datepicker({
language: 'bg',
todayHighlight: true,
format: 'dd.mm.yyyy',
autoclose: true,
weekStart: 1
})
}
}
function parseAjaxError (err) {
var message = ''
if (err.responseJSON) {
if (err.responseJSON.error) {
message = err.responseJSON.error
} else if (err.responseJSON.errors) {
var key = Object.keys(err.responseJSON.errors)[0]
message = err.responseJSON.errors[key][0]
} else if (err.responseJSON.message) {
message = err.responseJSON.message
}
} else {
message = err.toString()
}
return message
}
|
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Cablagemaster.vue";
const routes = [
{
path: "/",
name: "Cablagemaster",
component: Home
},
{
path: "/cablage",
name: "Cablage",
// route level code-splitting
// this generates a separate chunk (cablage.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "cablage" */ "../views/Cablage.vue")
},
{
path: "/listeaffaire",
name: "Listeaffaire",
// route level code-splitting
// this generates a separate chunk listaffaire.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "listaffaire" */ "../views/Listeaffaire.vue")
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
|
'use strict';
angular
.module('green-board-app', [
'ui.router',
'ui.bootstrap',
'ngStorage',
'GreenBoard'
])
.config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise('/home');
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
//disable IE ajax request caching
/* jshint ignore:start */
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
/* jshint ignore:end */
});
|
/**
* Created by Osvaldo on 21/10/15.
*/
var hub = require('../hub/hub.js');
var Mensagem = require('../util/mensagem.js');
var bdteste = function(){
var me = this;
console.log("iniciei o teste do banco");
me.listeners = {};
me.mapas = [];
me.situacoes = [];
me.modelos = [];
me.wiring();
};
bdteste.prototype.criaUsers = function(){
var me = this;
var users = [];
var userRoot = {
login: 'admin',
senha: 'admin',
tipo: 0,
nome: 'Osvaldo',
setor: 'suporte',
email: 'osvaldo.miguel@grad.ufsc.br',
ramal: '1963',
imagem: '/image/userImagem/osvaldo.JPG'
};
users.push(userRoot);
var userAdmin = {
login: 'tobias',
senha: 'tobias',
tipo: 1,
nome: 'Tobias',
setor: 'Financeiro',
email: 'tobias@tobias.com',
ramal: '1964',
imagem: '/image/userImagem/tobias.JPG'
};
users.push(userAdmin);
var comum1 = {
login: 'basilio',
senha: 'basilio',
tipo: 1,
nome: 'Basilio',
setor: 'Portaria',
email: 'basilio@basilio.com',
ramal: '1965',
imagem: '/image/userImagem/basilio.PNG'
};
users.push(comum1);
var comum2 = {
login: 'artrides',
senha: 'artrides',
tipo: 1,
nome: 'Artrides',
setor: 'Secretaria',
email: 'artrides@artrides.com',
ramal: '1966',
imagem: '/image/userImagem/artrides.PNG'
};
users.push(comum2);
var userMsg = new Mensagem(me, 'banco.usuario.create', {res: users}, 'usuario');
hub.emit(userMsg.getEvento(), userMsg);
console.log('criando usuario teste');
};
bdteste.prototype.retUserCreate = function(msg){
var me = this;
me.criaMapa();
};
bdteste.prototype.criaMapa = function(){
var me = this;
var mapas = [
{
nome: 'meu mapa',
img: '/image/terreo.JPG'
},
{
nome: 'mapa lindo',
img: '/image/pavimento_1_andar.JPG'
},
{
nome: 'mapa locao',
img: '/image/avignon_planta_11_andar.JPG'
}
];
var msg = new Mensagem(me, 'banco.mapa.create', {res: mapas}, 'mapa');
hub.emit(msg.getEvento(), msg);
console.log('criando mapa teste');
};
bdteste.prototype.retMapaCreate = function(msg){
var me = this;
me.mapas = msg.getRes();
me.criaSituacao();
};
bdteste.prototype.criaSituacao = function(){
var me = this;
var situacoes = [
{
nome: 'Em uso'
},
{
nome: 'Com defeito'
},
{
nome: 'Guardado'
},
{
nome: 'Em manutencao'
}
];
var msg = new Mensagem(me, 'banco.situacao.create', {res: situacoes}, 'situacao');
hub.emit(msg.getEvento(), msg);
console.log('criando situacao teste');
};
bdteste.prototype.retSituacaoCreate = function(msg){
var me = this;
me.situacoes = msg.getRes();
me.criaModeloDisp();
};
bdteste.prototype.criaModeloDisp = function(){
var me = this;
var modelos = [
{
tipodisp: 'monitor',
marca: 'samsung',
modelo: 'ss22c300'
},
{
tipodisp: 'micro',
marca: 'sony',
modelo: 'vpcz1'
},
{
tipodisp: 'telefone',
marca: 'intelbras',
modelo: 'advancedtie 103'
}
];
var msg = new Mensagem(me, 'banco.modelodisp.create', {res: modelos}, 'modelodisp');
hub.emit(msg.getEvento(), msg);
console.log('criando modelo disp teste');
};
bdteste.prototype.retModeloDispCrete = function(msg){
var me = this;
me.modelos = msg.getRes();
me.criaDispositivo();
};
bdteste.prototype.criaDispositivo = function(){
var me = this;
var dispositivos = [
{
identificador: 'nute9079',
serialnumber: 'slhijfoa14389',
caminhoimg: 'aquiVaiUmCaminhoValido',
nome: 'dispboladao'
},
{
identificador: 'nute9079',
serialnumber: 'slhijfoa14389',
caminhoimg: 'aquiVaiUmCaminhoValido',
nome: 'dispboladao'
},
{
identificador: 'nute9079',
serialnumber: 'slhijfoa14389',
caminhoimg: 'aquiVaiUmCaminhoValido',
nome: 'dispboladao'
}
];
var diferanca = 1;
var arrDisps = [];
for(var cont = 0; cont<4; cont++){
for(var index in dispositivos){
dispositivos[index].identificador = dispositivos[index].identificador+diferanca;
dispositivos[index].serialnumber = dispositivos[index].serialnumber+diferanca;
dispositivos[index].situacao = me.situacoes[index];
dispositivos[index].modelo = me.modelos[index];
dispositivos[index].mapa = me.mapas[index];
arrDisps.push(dispositivos[index]);
diferanca++;
}
}
var msg = new Mensagem(me, 'banco.dispositivo.create', {res: arrDisps}, 'dispositivo');
hub.emit(msg.getEvento(), msg);
console.log('criando dispositivo teste');
};
bdteste.prototype.retDispCreate = function(msg){
var me = this;
console.log('dispositivo criado com sucesso', msg.getRes());
};
bdteste.prototype.wiring = function(){
var me = this;
me.listeners['banco.ready'] = me.criaUsers.bind(me);
me.listeners['usuario.created'] = me.retUserCreate.bind(me);
me.listeners['mapa.created'] = me.retMapaCreate.bind(me);
me.listeners['situacao.created'] = me.retSituacaoCreate.bind(me);
me.listeners['modelodisp.created'] = me.retModeloDispCrete.bind(me);
me.listeners['dispositivo.created'] = me.retDispCreate.bind(me);
for(var name in me.listeners){
hub.on(name, me.listeners[name]);
}
};
module.exports = new bdteste();
|
import React, {useState, useEffect} from "react";
import { Container } from 'react-bootstrap';
import { Nav } from './components/Nav/Nav'
import { SubmitScore } from './components/SubmitScore/SubmitScore'
import { MainScreen } from './components/MainScreen/MainScreen'
import AimTrainer from './components/AimTrainer/AimTrainer'
import Algebra from './components/Algebra/Algebra'
import { NumberMemory } from './components/NumberMemory/NumberMemory'
import { SeqController }from './components/SeqMemory/SeqController'
import ReactionTime from './components/Reaction-time/ReactionTime'
import './styles/App.scss';
const App = () => {
const [userScore, setUserScore] = useState([])
const [showAnalytics, setShowAnalytics] = useState(false)
const [screen, setScreen] = useState('MainScreen')
useEffect(() => {
setUserScore([])
setShowAnalytics(false)
}, [])
const handleSetScreen = (screen) => {
setScreen(screen)
}
const handleSetUserScore = (score) => {
const newScore = userScore.slice(0)
newScore.push(score)
setUserScore(newScore)
}
return (
<Container fluid className="p-0">
<Nav setScreen={handleSetScreen} setUserScore={setUserScore} setShowAnalytics={setShowAnalytics}/>
{screen === 'SubmitScore' &&
<SubmitScore userScores={userScore} setScreen ={handleSetScreen} skipSubmit={showAnalytics}/>
}
{screen === 'MainScreen' &&
<MainScreen setUserScore={setUserScore} setScreen ={handleSetScreen} setShowAnalytics={setShowAnalytics} nextScreen={'Algebra'}></MainScreen>
}
{screen === 'Algebra' &&
<Algebra setUserScore={handleSetUserScore} setScreen ={handleSetScreen} nextScreen={'SeqController'}></Algebra>
}
{screen === 'SeqController' &&
<SeqController setUserScore={handleSetUserScore} setScreen ={handleSetScreen} nextScreen={'Reaction-Time'}/>
}
{screen === 'Reaction-Time' &&
<ReactionTime setUserScore={handleSetUserScore} setScreen ={handleSetScreen} nextScreen={'NumberMemory'}/>
}
{screen === 'NumberMemory' &&
<NumberMemory setUserScore={handleSetUserScore} setScreen ={handleSetScreen} nextScreen={'AimTrainer'}/>
}
{screen === 'AimTrainer' &&
<AimTrainer setUserScore={handleSetUserScore} setScreen ={handleSetScreen} nextScreen={'SubmitScore'}/>
}
</Container>
);
}
export default App;
|
const {Statistics, Cases, Deadths, Tests} = require('../models/statistics.model');
const {getStatisticsDataFromSource} = require('./CovidService');
const removeStatistcs = async () => {
await Statistics.deleteMany();
}
const setInitialStatisticDataFromSource = () => {
const data = getStatisticsDataFromSource();
data.then(function async (response) {
removeStatistcs();
response.data.response.map(async item => {
await saveItemStatistic(item);
});
}).catch(function (error) {
console.error(error);
});
}
const getAllStatistics = () => {
return Statistics.find({});
}
const getFilteredStatisticsByCountry = (search) => {
const expRegx = new RegExp(search, 'i');
return Statistics.find({'country': expRegx});
}
const saveItemStatistic = async (item) => {
var _cases = new Cases({
new:item['cases'].new,
active:item['cases'].active,
critical:item['cases'].critical,
recovered:item['cases'].recovered,
'1M_pop':item['cases']['1M_pop'],
total:item['cases'].total,
});
var _deaths = new Deadths({
new:item['cases'].new,
'1M_pop':item['cases']['1M_pop'],
total:item['cases'].total,
});
var _test = new Tests({
'1M_pop':item['cases']['1M_pop'],
total:item['cases'].total,
});
var _statistics = new Statistics({
continent:item['continent'],
country:item['country'],
population:item['population'],
cases:_cases,
deaths:_deaths,
tests:_test,
day:item['day'],
time:item['time'],
});
await _statistics.save();
return _statistics;
}
module.exports = {
setInitialStatisticDataFromSource,
getAllStatistics,
getFilteredStatisticsByCountry,
saveItemStatistic,
}
|
import React from "react";
import { Link as RouterLink, Redirect } from "react-router-dom";
//External Library Import
import {
Text,
Image,
Container,
Link,
Heading,
VStack,
Divider,
Flex,
} from "@chakra-ui/react";
import { IoIosSchool } from "react-icons/io";
//Import assets
import Envelop from "../assets/images/mail.png";
import { APP_NAME } from "../utils/Constants";
const EmailConfirmation = (props) => {
const { location } = props;
let state = location.state;
if (state === undefined) {
return (
<Redirect
to={{
pathname: "/signin",
}}
/>
);
}
const email = state.email;
return (
<Container p="8" maxW="lg" mt="4">
<VStack mb="2">
<Flex>
<IoIosSchool fontSize="2.5rem" color="teal" />
<Heading as="h3" letterSpacing="tight" fontWeight="light" ml="2">
{APP_NAME}
</Heading>
</Flex>
<Image height="12rem" width="12rem" src={Envelop} />
<Text fontWeight="bold" fontSize="1.2em">
Email Confirmation
</Text>
<Text fontSize="1.1em" textAlign="center">
An email has been sent to "{email}".
</Text>
<Text fontSize="1.1em">
{" "}
Click on the link to complete registration.
</Text>
<Divider style={{ marginTop: 10 }} />
<Text style={{ marginBottom: 15 }}>
Click{" "}
<Link as={RouterLink} to="/signin" color="teal" fontWeight="bold">
here
</Link>{" "}
to login
</Text>
</VStack>
</Container>
);
};
export default EmailConfirmation;
|
(function() {
return function(req) {
log(req);
if (req.hasOwnProperty('key')) {
//返回懒加载的节点
var key = req.key;
return [
{key: key + '1', name: 'name' + key + '1', isParent: true},
{key: key + '2', name: 'name' + key + '2', isParent: true},
]
} else {
//返回根节点数据
return [
{key: '1', name: 'n1', isParent: true},
{key: '2', name: 'n2', isParent: true},
{key: '3', name: 'n3', isParent: true},
{key: '4', name: 'n4', isParent: true},
]
}
}
})();
|
Ext.define('MyClassic.store.Personnel', {
extend: 'Ext.data.Store',
alias: 'store.personnel',
model : 'MyClassic.model.Account',
pageSize: 5,
autoLoad : {start : 0, limit : 5}
});
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
export default () => (
<nav className="absolute w-full grid grid-cols-header-mobile md:grid-cols-2">
<div className="px-10 lg:px-20 py-5">
<a href="/">
<img
src="/Logo.png"
className="max-w-100 max-h-20 cursor-pointer"
alt="Unisec-Logo"
/>
</a>
</div>
<div className="px-10 lg:px-20 py-5 hidden justify-end items-center">
{/* hidden md:flex */}
<ul className="flex justify-end items-center">
<a href="#" className="mx-5">
<li>Sign up</li>
</a>
<a
href="#"
className="mx-5 bg-black text-white border-black border-2 px-10 py-2 rounded-full duration-500 hover:bg-white hover:text-black">
<li>Sign in</li>
</a>
</ul>
</div>
<div className="hidden justify-center items-center">
{/* flex md:hidden */}
<FontAwesomeIcon icon={["fas", "bars"]} className="w-5 m-2" />
</div>
</nav>
);
|
import React, { useState } from 'react';
import { Button, Card, Container, Divider, Header, Modal } from 'semantic-ui-react';
import "./PriceCalculation.css"
const PriceCalculation = ({totalDiscount, productPrice}) => {
const [open, setOpen] = useState(false)
return (
<Card className={"processCheclOutCalculationContainer"}>
<Container>
<Header> Checkout Summary</Header>
</Container>
<Divider />
<Container style={{marginBottom:20}}>
<Header as={"h4"}> Sub Total : ${productPrice} </Header>
</Container>
<Container>
<Header as={"h4"}> Discount : - ${totalDiscount}</Header>
</Container>
<Divider />
<Container>
<Header> Total : ${productPrice-totalDiscount}</Header>
</Container>
<Container style={{marginTop:20}}>
<Modal
centered={false}
open={open}
onClose={() => setOpen(false)}
onOpen={() => setOpen(true)}
trigger={<Button primary >Process Checkout </Button>}
>
<Modal.Header>Thank you!</Modal.Header>
<Modal.Content>
<Modal.Description>
Your order has
been placed!.
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<Button primary onClick={() => setOpen(false)}>OK</Button>
</Modal.Actions>
</Modal>
</Container>
</Card>
);
};
export default PriceCalculation;
|
import { expect } from 'chai'
import Validator from 'src/validator'
import object from 'src/object'
import string from 'src/string'
import number from 'src/number'
import array from 'src/array'
import shape from 'src/object/shape'
export default function testShape() {
const validator = new Validator('test')
validator.use('object', object)
validator.use('string', string)
validator.use('number', number)
validator.use('array', array)
object.chain('shape', shape)
const schema = {
name: validator.string(),
age: validator.number(),
friends: validator.array(),
enemies: validator.array()
}
const correct = {
name: 'Luke Skywalker',
age: 42,
}
const incorrect = {
name: 42,
age: 'Luke Skywalker',
friends: []
}
it('should be a function', () => {
expect(shape).to.be.a('function')
})
it('should take one parameter', () => {
expect(shape.length).to.equal(1)
})
it('should be enhanced with `make`', () => {
expect(shape).to.have.property('chained')
expect(shape).to.have.property('chain')
})
it('should throw if no schema is provided', () => {
const result = () => validator.object().shape()
expect(result).to.throw(TypeError, /must be provided/)
})
it('should throw if the schema provided isn\'t an object', () => {
expect(() => validator.object().shape(NaN)).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape(true)).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape(false)).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape(42)).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape('string')).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape(() => {})).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape([])).to.throw(TypeError, /must be an object/)
expect(() => validator.object().shape(null)).to.throw(TypeError, /must be an object/)
})
it('should pass if schema is an empty object', () => {
expect(validator.object().shape({}).test(incorrect)).to.be.true
})
it('should pass if value is an empty object', () => {
expect(validator.object().shape(schema).test({})).to.be.true
})
it('should pass if value has the same shape as the schema provided', () => {
expect(validator.object().shape(schema).test(correct)).to.be.true
})
it('should fail if value doesn\'t have the same shape as the schema provided', () => {
expect(validator.object().shape(schema).test(incorrect)).to.be.false
})
it('shouldn\'t report if schema is an empty object', () => {
expect(validator.object().shape({}).report(incorrect)).to.be.false
})
it('shouldn\'t report if value is an empty object', () => {
expect(validator.object().shape(schema).report({})).to.be.false
})
it('shouldn\'t report if value has the same shape as the schema provided', () => {
expect(validator.object().shape(schema).report(correct)).to.be.false
})
it('should report properties that doesn\'t match the schema', () => {
const result = validator.object().shape(schema).report(incorrect)
expect(result).to.be.an('object')
expect(result).to.have.property('name', 'string')
expect(result).to.have.property('age', 'number')
})
it('should fallback to parent report if value isn\'t provided', () => {
expect(validator.object().shape(schema).report()).to.equal('required')
})
}
|
import React from "react";
import Link from "@material-ui/core/Link";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
const useStyles = makeStyles((theme) => ({
root: {
marginTop: "50px",
textAlign: "center",
[theme.breakpoints.down("sm")]: {
marginBottom: 300,
},
[theme.breakpoints.down("md")]: {
marginBottom: 150,
},
[theme.breakpoints.down("xs")]: {
marginBottom: 100,
},
},
container: {
display: "flex",
justifyContent: "space-evenly",
flexWrap: "wrap",
[theme.breakpoints.down("sm")]: {
flexDirection: "column",
},
},
title: {
fontSize: "1.8rem",
[theme.breakpoints.down("sm")]: {
marginTop: 20,
},
},
phone: {
fontSize: "1.8rem",
},
}));
function Hotline() {
const classes = useStyles();
return (
<div className={classes.root}>
<h1>Help Is Available</h1>
<h3>Speak with a counselor today</h3>
<div className={classes.container}>
{/* SAMHSA */}
<Grid item xs={12} md={6}>
<Typography className={classes.title} component="p">
Substance Abuse and Mental Health Services Administration
</Typography>
<Typography className={classes.phone} component="p">
<a
href="tel:1-800-662-4357"
className="contact-number contact-number--banner"
>
1-800-662-4357
</a>
</Typography>
<Link
href="https://www.samhsa.gov/find-help/national-helpline"
size="small"
target="_blank"
rel="noopener noreferrer"
>
Official Website
</Link>
</Grid>
{/* NSPL */}
<Grid item xs={12} md={6}>
<Typography className={classes.title} component="p">
National Suicide Prevention Lifeline
</Typography>
<Typography className={classes.phone} component="p">
<a
href="tel:1-800-273-8255"
className="contact-number contact-number--banner"
>
1-800-273-8255
</a>
</Typography>
<Link
href="https://suicidepreventionlifeline.org/"
size="small"
target="_blank"
rel="noopener noreferrer"
>
Official Website
</Link>
</Grid>
</div>
</div>
);
}
export default Hotline;
|
/**
* 화면 초기화 - 화면 로드시 자동 호출 됨
*/
function _Initialize() {
// 단위화면에서 사용될 일반 전역 변수 정의
// $NC.setGlobalVar({ });
// 그리드 초기화
grdMasterInitialize();
setUserProgramPermission();
}
function setUserProgramPermission() {
var permission = $NC.getProgramPermission();
// 확정
if (permission.canConfirm) {
$("#btnOrderType").click(btnOrderType);
}
$NC.setEnable("#btnOrderType", permission.canConfirm);
}
function btnOrderType() {
// 데이터 조회
$NC.serviceCall("/CM20020E/callSP.do", {
P_QUERY_ID: "CM_CODE_OUTPROC_SYNC",
P_QUERY_PARAMS: $NC.getParams({
P_USER_ID: $NC.G_USERINFO.USER_ID
})
}, onBtnOrderType);
}
function onBtnOrderType(ajaxData) {
var resultData = $NC.toArray(ajaxData);
if (!$NC.isNull(resultData)) {
if (resultData.O_MSG !== "OK") {
return;
}
}
_Inquiry();
}
/**
* 화면 리사이즈 Offset 세팅
*/
function _SetResizeOffset() {
$NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight
+ $("#divTopView").outerHeight();
}
/**
* Window Resize Event - Window Size 조정시 호출 됨
*/
function _OnResize(parent) {
var clientWidth = parent.width() - $NC.G_LAYOUT.border1;
var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight;
// Container 사이즈 조정
$NC.resizeContainer("#divCenterView", clientWidth, clientHeight);
// Grid 사이즈 조정
$NC.resizeGrid("#grdMaster", clientWidth, clientHeight - $NC.G_LAYOUT.header);
}
/**
* 조회조건이 변경될 때 호출
*/
function onChangingCondition() {
// 전역 변수 값 초기화
$NC.clearGridData(G_GRDMASTER);
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
/**
* Input, Select Change Event 처리
*/
function _OnConditionChange(e, view, val) {
}
/**
* Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨
*/
function _Inquiry() {
// 조회시 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDMASTER);
// 데이터 조회
$NC.serviceCall("/CM01010E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster);
}
/**
* New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨
*/
function _New() {
}
/**
* Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨
*/
function _Save() {
}
/**
* Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨
*/
function _Delete() {
}
/**
* Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨
*/
function _Cancel() {
}
/**
* Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨
*
* @param printIndex
* 선택한 출력물 Index
*/
function _Print(printIndex, printName) {
}
function grdMasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "CODE_CD",
field: "CODE_CD",
name: "주문유형코드",
minWidth: 80,
});
$NC.setGridColumn(columns, {
id: "CODE_NM",
field: "CODE_NM",
name: "주문유형명",
minWidth: 140
});
$NC.setGridColumn(columns, {
id: "SUB_CD",
field: "SUB_CD",
name: "서브코드",
minWidth: 80,
});
return $NC.setGridColumnDefaultFormatter(columns);
}
function grdMasterInitialize() {
var options = {
frozenColumn: 0
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdMaster", {
columns: grdMasterOnGetColumns(),
queryId: "CM20020E.RS_MASTER",
sortCol: "CODE_CD",
gridOptions: options
});
G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll);
}
function grdMasterOnAfterScroll(e, args) {
var row = args.rows[0];
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdMaster", row + 1);
}
function onGetMaster(ajaxData) {
$NC.setInitGridData(G_GRDMASTER, ajaxData);
if (G_GRDMASTER.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDMASTER, 0);
} else {
$NC.setGridDisplayRows("#grdMaster", 0, 0);
}
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons, $NC.G_VAR.printOptions);
}
|
var dilutionData01 = [
// Blue Map
[{
"Source Well": "A1",
"Dest Well": "A2",
"Vol": "50"
},
{
"Source Well": "A2",
"Dest Well": "A11",
"Vol": "50"
},
{
"Source Well": "A3",
"Dest Well": "E22",
"Vol": "50"
}],
// Red Map
[{
"Source Well": "A1",
"Dest Well": "A9",
"Vol": "50"
},
{
"Source Well": "A2",
"Dest Well": "A3",
"Vol": "50"
},
{
"Source Well": "A3",
"Dest Well": "K6",
"Vol": "50"
}],
// Green Map
[{
"Source Well": "A1",
"Dest Well": "A20",
"Vol": "50"
},
{
"Source Well": "A2",
"Dest Well": "A17",
"Vol": "50"
},
{
"Source Well": "A3",
"Dest Well": "B17",
"Vol": "50"
}]
];
var dilutionData02 = [
// Orange Map
[{
"Source Well": "A1",
"Dest Well": "A6",
"Vol": "50"
},
{
"Source Well": "A2",
"Dest Well": "B6",
"Vol": "50"
},
{
"Source Well": "A3",
"Dest Well": "D22",
"Vol": "50"
}],
// Purple Map
[{
"Source Well": "A1",
"Dest Well": "A14",
"Vol": "50"
},
{
"Source Well": "A2",
"Dest Well": "K15",
"Vol": "50"
},
{
"Source Well": "A3",
"Dest Well": "P9",
"Vol": "50"
}],
// Yellow Map
[{
"Source Well": "A1",
"Dest Well": "A5",
"Vol": "50"
},
{
"Source Well": "A2",
"Dest Well": "C18",
"Vol": "50"
},
{
"Source Well": "A3",
"Dest Well": "F9",
"Vol": "50"
}]
];
var fileNames01 = ["blueMap.csv","redMap.csv","greenMap.csv"];
var fileNames02 = ["orangeMap.csv","purpleMap.csv","yellowMap.csv"];
// This function can be modified to turn any set of data into a string with a
// column delimiter separating each element and a line delimiter separating each line
function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
// creates an array of strings that correspond to the keys in the first object of the data array
// this will be used as the header row
result = '';
result += keys.join(columnDelimiter);
// joins all the elements of the keys array into a string inserting the columnDelimiter in between them
result += lineDelimiter;
// concatenates the lineDelimiter at the end of the string
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
}
// This function will turn a string into a CSV file
function downloadCSV(arrData,args,i) {
var data, filename, link;
// Extracts the string of data to be downloaded as a CSV
var csv = convertArrayOfObjectsToCSV({
data: arrData[i] // input is an object with one value "data" which is the array (arrData) of arrays of objects
});
if (csv == null) return;
filename = args[i] || 'export.csv';
// Checks to see if the string is prepended with info that tells the browser
// that this is a CSV file and should be downloaded. If the string does not
// have this information, it is prepended to the string.
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
// Encodes CSV string into the final form to be downloaded using prepended info
data = encodeURI(csv);
// Create element
link = document.createElement('a');
// Set href attribute to the encoded string
link.setAttribute('href', data);
// Set download attribute to file name
link.setAttribute('download', filename);
// Simulate click to download file
link.click();
}
function downloadFiles() {
fileNames=fileNames02;
dilutionData=dilutionData02;
for (i=0;i<fileNames.length;i++) {
downloadCSV(dilutionData,fileNames,i);
}
}
|
var showWidth = 1;
if(showWidth == 1){
$(document).ready(function (){
$(window).resize(function(){
var width = $(window).width();
document.getElementById("output_width").innerHTML="Window Width:" +width.toString();
});
});
}
$(document).ready(function(){
$("#test").click(function(){
var width = $(window).width();
if(width > 750){
$("#myPan").slideToggle("slow");
}
else
{
$(".navbar-toggle").trigger( "click" );
}
});
});
$(document).ready(function(){
$.ajax({
url: "informatii-utilizator.php",
method: "get",
success: function(data){
$("#myPan").html(data);
}
});
});
$(document).ready(function(){
$.ajax({
url: "ldcolor.php",
method: "get",
success: function(data){
var obj = jQuery.parseJSON(data);
var i = 0;
var aux = "";
for(i = 0; i < obj.length; i++)
{
if(obj[i].likeNews == 1 && obj[i].dislikeNews == 0)
{
$("#l" + obj[i].id).css("color", "red");
}
if(obj[i].likeNews == 0 && obj[i].dislikeNews == 1)
{
$("#d" + obj[i].id).css("color", "red");
}
}
}
});
});
|
var boardHTML = null
var columnsHTML = null
var turn = 1
var name1 = null
var nameError = null
var lastname = null
var lastnameError = null
var email = null
var emailError = null
var comments = null
var commentsError = null
var sendBtn = null
var cronos1 = null
var time1 = null
var cronos2 = null
var time2 = null
var corchete = []
var board = [
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null]
]
// TIMER 1
function initialize1() {
cronos1 = setInterval(function () { timer1() }, 1000);
}
function timer1() {
time1 = parseInt(document.getElementById('counter1').value);
document.getElementById('counter1').value = eval(time1 + 1);
}
function reset1() {
time1 = parseInt(document.getElementById('counter1').value);
document.getElementById('counter1').value = "0";
}
function stop1() {
clearInterval(cronos1);
}
// TIMER 2
function initialize2() {
cronos2 = setInterval(function () { timer2() }, 1000);
}
function timer2() {
time2 = parseInt(document.getElementById('counter2').value);
document.getElementById('counter2').value = eval(time2 + 1);
}
function reset2() {
time2 = parseInt(document.getElementById('counter2').value);
document.getElementById('counter2').value = "0";
}
function stop2() {
clearInterval(cronos2);
}
var sendForm = function (evt) {
evt.preventDefault()
if (name1.value.length < 3) {
nameError.innerHTML = 'El nombre debe tener al menos 3 caracteres'
console.log(name1.value)
} else {
nameError.innerHTML = ''
console.log(name1.value)
}
if (lastname.value.length < 3) {
lastnameError.innerHTML = 'El apellido debe tener al menos 3 caracteres'
console.log(lastname.value)
} else {
lastnameError.innerHTML = ''
console.log(lastname.value)
}
if (validateEmail(email.value) == false) {
emailError.innerHTML = 'Email inválido'
console.log(email.value)
} else {
emailError.innerHTML = ''
console.log(email.value)
}
if (comments.value.length < 3) {
commentsError.innerHTML = 'Ingrese comentario'
console.log(comments.value)
} else {
commentsError.innerHTML = ''
console.log(comments.value)
}
window.open("http://www.outlook.com", "email", "width=300,height=300,scrollbars=NO")
return false
}
function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
var CheckWinners = function (turnrecived) {
console.log(board)
console.log(board.length)
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < 6; j++) {
if (board[i][j] != null && board[i][j] != board[6][j]) {
if (board[i][j] == board[i][j + 1] && board[i][j] == board[i][j + 2]
&& board[i][j] == board[i][j + 3] || board[i][j] == board[i + 1][j]
&& board[i][j] == board[i + 2][j] && board[i][j] == board[i + 3][j]
|| board[i][j] == board[i + 1][j + 1] && board[i][j] == board[i + 2][j + 2]
&& board[i][j] == board[i + 3][j + 3]) {
console.log('game ended')
var turn = turnrecived
if (turn == 'blue') {
stop1()
stop2()
alert('player 2 wins')
} else {
stop1()
stop2()
alert('player 1 wins')
}
}
}
// if (board[i][j] != null && board[i][j] == board[6][j]) {
//console.log("entra al check 6 j")
//if (board[i][j] == board[i][j + 1] && board[i][j] == board[i][j + 2]
// && board[i][j] == board[i][j + 3] || board[i][j] == board[i - 1][j]
// && board[i][j] == board[i - 2][j] && board[i][j] == board[i - 3][j]
// || board[i][j] == board[i - 1][j + 1] && board[i][j] == board[i - 2][j + 2]
// && board[i][j] == board[i - 3][j + 3]) {
// console.log("game ended in pos i = 6, j = j")
// }
// }
}
}
}
//check las diagonales inversas:
// board[i][j] == board[i - 1][j + 1] && board[i][j] == board[i - 2][j + 2] && board[i][j] == board[i - 3][j + 3]
//arreglar lo de la ultima columna posicion i= 6 j=0, 1, 2, ...
var ChangeTurn = function () {
turn = (turn === 'blue') ? 'red' : 'blue'
CheckWinners(turn)
if (turn == 'blue') {
initialize1()
stop2()
}
else {
initialize2()
stop1()
}
}
var columnEventHandler = function (evt) {
var columnId = evt.target.id.substr(1, 1)
for (var i = 0; i < board[columnId].length; i++) {
if (!board[columnId][i]) {
board[columnId][i] = turn
ChangeTurn()
render()
break
}
}
}
var bindColumnHandlers = function () {
columnsHTML = document.getElementsByClassName('column')
for (var i = 0; i < columnsHTML.length; i++) {
columnsHTML[i].onclick = columnEventHandler
}
}
var render = function () {
var html = ''
for (var i = 0; i < board.length; i++) {
html += '<div id="c' + i + '" class="column">'
for (var j = board[i].length - 1; j >= 0; j--) {
html += '<div id="s' + i + j + '" class="spot'
if (board[i][j]) html += ' ' + board[i][j]
html += '"></div>'
}
html += '</div>'
}
boardHTML.innerHTML = html
bindColumnHandlers()
}
var init = function () {
boardHTML = document.getElementById('board')
turn = Math.random() > 0.5 ? 'blue' : 'red'
render()
name1 = document.getElementById('name')
lastname = document.getElementById('lastname')
email = document.getElementById('email')
comments = document.getElementById('comments')
sendBtn = document.getElementById('send')
sendBtn.onclick = sendForm
nameError = document.getElementById('nameError')
lastnameError = document.getElementById('lastnameError')
emailError = document.getElementById('emailError')
commentsError = document.getElementById('commentsError')
}
window.onload = init
|
const parser = require('freestyle-parser');
const fileIO = require('bozoid-file-grabber');
const bozoid = fileIO.read('bozoid.json');
exports.eventGroup = 'onMessage';
exports.description = 'Remove on-the-fly phrase response';
exports.masterOnly = true;
exports.command = 'untrigger';
exports.parameters = [
{
input: true,
description: 'phrase'
}
];
exports.script = function(cmd, msg){
fileIO.update("responder.json", function(json){
let succ = false;
if(json.list)
for(var set of json.list){
if(set.trigger == parser.getArg(msg.content, 0)){
json.list.splice(json.list.indexOf(set), 1);
//msg.channel.send("Removed.");
msg.react("👌");
succ = true;
break;
}
}
if(!succ){
msg.react("👎");
}
});
}
|
const express = require("express");
var router = express.Router();
const { check } = require("express-validator");
const { signin, signup, signout, isSignedIn } = require("../controllers/auth");
//signup router
router.post(
"/signup",
[
check("name")
.isLength({ min: 3 })
.withMessage("Name should be atleast 3 characters"),
check("email").isEmail().withMessage("Enter a valid email id"),
check("password")
.isLength({ min: 5 })
.withMessage("Password should be atleast 5 characters long"),
],
signup
);
//signin router
router.post(
"/signin",
[
check("email").isEmail().withMessage("Enter a valid email id"),
check("password")
.isLength({ min: 3 })
.withMessage("Password field is required"),
],
signin
);
//signout router
router.get("/signout", signout);
module.exports = router;
|
var request = require("request");
var base_url = "http://localhost:8080/api/"
describe("GIVEN the API server is running", function() {
describe("WHEN getBogs is called", function() {
it("THEN the status code should be 200", function(done) {
request.get(base_url + '/blog', function(error, response, body) {
expect(response.statusCode).toBe(200);
done();
});
});
it("THEN it should return a list of blogs", function(done) {
request.get(base_url + '/blog', function(error, response, body) {
let jsonRes = JSON.parse(body);
expect(jsonRes.blogs.length).toBe(0);
done();
});
});
});
describe("WHEN blog/:id is called", function() {
it("THEN the status code should be 200", function(done) {
request.get(base_url + '/blog/44', function(error, response, body) {
expect(response.statusCode).toBe(200);
done();
});
});
it("THEN it should return the blog relative to the id specified", function(done) {
request.get(base_url + '/blog/44', function(error, response, body) {
let jsonRes = JSON.parse(body);
expect(parseInt(jsonRes.id)).toBe(44);
done();
});
});
});
});
|
import data from "../data/vendingMachineInventory";
import VendingMachine from "../src/vendingMachine";
const coins = data.coins;
const inventory = data.inventory;
describe("Vending Machine", () => {
beforeEach(() => {
vendingMachine = new VendingMachine(coins, inventory);
});
describe("Refilling with coins", () => {
it("should update the quantity when coins are added", () => {
const nickels = vendingMachine.refillCoins();
expect(nickels).toBe();
});
});
describe("Refilling with products", () => {
it("should update the quantity when products are added", () => {
const coke = vendingMachine.refillInventory();
expect(coke).toBe();
});
});
describe("Buying products", () => {
it("should updated customer credit when coins are inserted", () => {
const credit = vendingMachine.customerCredit();
expect(credit).toBe();
});
it("should alert the customer when credit is insuficient for the product selected", () => {
const credit = vendingMachine.customerCredit();
const product = vendingMachine.selectProduct();
expect(() => vendingMachine()).toThrow(
"Insuficient funds. Please insert more coins."
);
});
it("should update inventory when a product is bought", () => {
const newInventory = vendingMachine.updateInventory();
expect(newInventory).toBe();
});
it("should dispense the change, if any, when the purchase is concluded", () => {
const change = vendingMachine.dispenseChange();
expect(change).toBe();
});
it("should update the coins in the machine when the purchase is concluded", () => {
const newCoins = vendingMachine.updateCoins();
expect(newCoins).toBe();
});
it("should alert the customer when the chosen product is out of stock", () => {
const product = vendingMachine.selectProduct();
expect(() => vendingMachine()).toThrow(
"Product not available. Please select another product."
);
});
it("should alert the customer when out of change", () => {
const noChange = vendingMachine.updateCoins();
expect(() => vendingMachine()).toThrow(
"Change not available. Please insert exact product value."
);
});
it("should not accept coins when completely out of stock", () => {
const outOfStock = vendingMachine.stopOperating();
expect(() => vendingMachine()).toThrow(
"Machine not operating. Out of stock."
);
});
});
});
|
export const ACTION_NAP = 'action_nap'
export const ACTION_EAT = 'action_eat'
export const ACTION_PLAY = 'action_play'
export function actionNap() {
return {
type: ACTION_NAP
};
}
export function actionEat() {
return {
type: ACTION_EAT
};
}
export function actionPlay() {
return {
type: ACTION_PLAY
};
}
|
import React from "react";
import {
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalBody,
ModalCloseButton,
useDisclosure,
} from "@chakra-ui/react";
import NewButton from "../styled/NewButton";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import ClientForm from "../forms/ClientForm";
import ProjectForm from "../forms/ProjectForm";
import TaskForm from "../forms/TaskForm";
import ExpenseForm from "../forms/ExpenseForm";
import PropTypes from "prop-types";
import { CurrencyConsumer } from "../../contexts/currencyContext";
const BaseNewModal = ({
type,
action,
buttonProps,
buttonStyle,
projectId,
}) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const headerSwitch = (type) => {
switch (type) {
case "Project":
return "Start a New Project";
case "Client":
return "Track a New Client";
case "Task":
return "Create a New Task";
case "Expense":
return "Record an Expense";
default:
return null;
}
};
const formSwitch = (type, action) => {
switch (type) {
case "Project":
return (
<CurrencyConsumer>
{() => (
<ProjectForm action={action} onClose={onClose} type={"Create"} />
)}
</CurrencyConsumer>
);
case "Client":
return <ClientForm action={action} onClose={onClose} type={"Create"} />;
case "Task":
return (
<TaskForm
action={action}
onClose={onClose}
type={"Create"}
projectId={projectId}
/>
);
case "Expense":
return (
<CurrencyConsumer>
{() => (
<ExpenseForm
action={action}
onClose={onClose}
type={"Create"}
projectId={projectId}
/>
)}
</CurrencyConsumer>
);
default:
return null;
}
};
return (
<>
<NewButton
onClick={onOpen}
{...buttonProps}
style={buttonStyle}
data-cy="new"
>
<FontAwesomeIcon icon={faPlus} style={{ marginRight: "8px" }} />
New {type}
</NewButton>
<Modal isOpen={isOpen} onClose={onClose} isCentered>
<ModalOverlay />
<ModalContent>
<ModalHeader>{headerSwitch(type)}</ModalHeader>
<ModalCloseButton data-cy="close" />
<ModalBody>{formSwitch(type, action)}</ModalBody>
</ModalContent>
</Modal>
</>
);
};
BaseNewModal.propTypes = {
type: PropTypes.string,
action: PropTypes.func,
buttonProps: PropTypes.object,
buttonStyle: PropTypes.object,
projectId: PropTypes.number,
};
export default BaseNewModal;
|
import { Link } from "react-router-dom";
const FlatItem = ({slug}) => {
return (
<div className="text-center col-lg-4 col-12 col-md-6 ">
<div className="item">
<div className="item-image">
<img className="img-fluid" src="/img/product1.jpeg" alt="flat" />
</div>
<div className="item-description">
<div className="d-flex justify-content-between mb-3">
<span className="item-title">Lorem ipsum dolor sit amet consectetur adipiscing elit</span>
<span className="item-price">$1000</span>
</div>
<div className="item-icon d-flex alig-items-center justify-content-between">
<div>
<i className="fas fa-check-circle"></i> <span>Lorem ipsum dolor</span>
</div>
<div>
<i className="fas fa-check-circle"></i> <span> Lorem </span>
</div>
<Link to={`/flat/${slug}`} className="item-title">
<button className="btn btn-detail">View</button>
</Link>
</div>
</div>
</div>
</div>
)
}
export default FlatItem
|
import React from 'react'
import jQuery from 'jquery'
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
legalRepresentatives: [],
displayEmailError: 'none',
emailErrorContent: '',
displayLegalRepresentativeError: 'none',
legalRepresentativeErrorContent: '',
displayRutError: 'none',
rutErrorContent: '',
displayStockError: 'none',
stockErrorContent: '',
displayNameError: 'none',
displayNameContent: ''
};
this._handleSubmit = this._handleSubmit.bind(this);
this._getLegalRepresentativesOptions = this._getLegalRepresentativesOptions.bind(this);
this._handleEmailChange = this._handleEmailChange.bind(this);
this._checkLegalRepresentative = this._checkLegalRepresentative.bind(this);
this._handleNameBlur = this._handleNameBlur.bind(this);
this._handleRutBlur = this._handleRutBlur.bind(this);
this._handleStockChange = this._handleStockChange.bind(this);
}
componentWillMount() {
this._fetchLegalRepresentatives();
}
_fetchLegalRepresentatives(){
jQuery.ajax({
method: 'GET',
headers: {
"Content-Type": " application/json",
"Accept": "application/json",
"access-token": localStorage.getItem("access-token"),
"client": localStorage.getItem("client"),
"expiry": localStorage.getItem("expiry"),
"token-type": localStorage.getItem("token-type"),
"uid": localStorage.getItem("uid")
},
type: 'json',
url: '/api/v1/legal_representatives',
success: (data, textStatus, request) => {
this.saveTokens(request);
this.setState({ legalRepresentatives: data })
},
error: (data) =>{
this._showError(data);
}
});
}
_handleSubmit(event) {
event.preventDefault();
if(this.props.investor != null){
this._editInvestor(this.props.investor)
}
else {
this._addInvestor()
}
this._name.value = '';
this._email.value = '';
this._nationality.value = '';
}
saveTokens(request){
console.log(request.getResponseHeader('access-token'))
if(request.getResponseHeader('access-token') != null) {
localStorage.setItem('access-token', request.getResponseHeader('access-token'));
localStorage.setItem('client', request.getResponseHeader('client'));
localStorage.setItem('expiry', request.getResponseHeader('expiry'));
localStorage.setItem('token-type', request.getResponseHeader('token-type'));
localStorage.setItem('uid', request.getResponseHeader('uid'));
}
}
_editInvestor(investor){
jQuery.ajax({
method: 'PUT',
headers: {
"Content-Type": " application/json",
"Accept": "application/json",
"access-token": localStorage.getItem("access-token"),
"client": localStorage.getItem("client"),
"expiry": localStorage.getItem("expiry"),
"token-type": localStorage.getItem("token-type"),
"uid": localStorage.getItem("uid")
},
type: 'json',
url: `/api/v1/investors/${investor.id}`,
data: JSON.stringify({
"name": this._name.value,
"email": this._email.value,
"nationality": this._nationality.value,
"phone": this._phone.value,
"address": this._address.value,
"rut": this._rut.value,
"stock": this._stock.value,
"legal_representative_id": this._legalRepresentative.value
}),
success: (data, textStatus, request) => {
this.saveTokens(request);
window.location = '/'
},
error: (data) =>{
this._showError(data);
}
});
}
_addInvestor(){
jQuery.ajax({
method: 'POST',
headers: {
"Content-Type": " application/json",
"Accept": "application/json",
"access-token": localStorage.getItem("access-token"),
"client": localStorage.getItem("client"),
"expiry": localStorage.getItem("expiry"),
"token-type": localStorage.getItem("token-type"),
"uid": localStorage.getItem("uid")
},
type: 'json',
url: `/api/v1/investors/`,
data: JSON.stringify({
"name": this._name.value,
"email": this._email.value,
"nationality": this._nationality.value,
"phone": this._phone.value,
"address": this._address.value,
"rut": this._rut.value,
"stock": this._stock.value,
"legal_representative_id": this._legalRepresentative.value
}),
success: (data, textStatus, request) => {
this.saveTokens(request);
window.location = '/'
},
error: (data) => {
this._showError(data);
}
});
}
_getLegalRepresentativesOptions() {
return this.state.legalRepresentatives.map((legalRepresentative) => {
return (
<option value={legalRepresentative.id}>{legalRepresentative.full_name}</option>
)
});
}
_showError(data){
if(data.responseJSON.errors[0] == 'Bad request just for admins users') {
window.location = 'admin/login';
alert('Bad request just for admins users');
}
else{
var errorString = "";
data.responseJSON.errors.forEach(function (value,index,array) {
console.log('value ' + value+ ' '+ index)
errorString = errorString + value + ' ';
});
alert(errorString);
}
}
_handleEmailChange(event){
console.log('name '+this._name.value);
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(this._email.value)){
this.setState({
displayEmailError: 'none',
emailErrorContent: ''
})
}
else{
this.setState({
displayEmailError: 'block',
emailErrorContent: 'Debe introducir un email valido'
})
}
}
_checkLegalRepresentative(){
if(this._legalRepresentative.value == 'Seleccione un representante legal'){
this.setState({
displayLegalRepresentativeError: 'block',
legalRepresentativeErrorContent: 'Debe seleccionar un representate legal'
})
}
else {
this.setState({
displayLegalRepresentativeError: 'none',
legalRepresentativeErrorContent: 'block'
})
}
}
_handleNameBlur(){
if(this._name.value == ''){
this.setState({
displayNameError: 'block',
nameErrorContent: 'Debe seleccionar un nombre'
})
}
else {
this.setState({
displayNameError: 'none',
nameErrorContent: ''
})
}
}
_handleRutBlur(){
if(this._rut.value == ''){
this.setState({
displayRutError: 'block',
rutErrorContent: 'Debe seleccionar un rut'
})
}
else {
this.setState({
displayRutError: 'none',
rutErrorContent: ''
})
}
}
_handleStockChange(){
if(this._stock.value == ''){
this.setState({
displayStockError: 'block',
stockErrorContent: 'Debe seleccionar un stock valido'
})
}
else {
this.setState({
displayStockError: 'none',
stockErrorContent: ''
})
}
}
render(){
const legalRepresentatives = this._getLegalRepresentativesOptions()
const divStyle = {
width: '40%',
marginLeft: '30%'
};
return(
<div style={divStyle}>
<form onSubmit={this._handleSubmit}>
<div className="form-group">
<label>Email</label>
<input type="email" defaultValue={this.props.investor != null ? this.props.investor.email : ''} className="form-control" ref={input => this._email = input} onBlur={this._handleEmailChange}
placeholder="Introduzca email"/>
<span style={{display: this.state.displayEmailError, color: 'red'}}>{this.state.emailErrorContent}</span>
</div>
<div className="form-group">
<label >Seleccione el representante legal</label>
<select className="form-control" ref={input => this._legalRepresentative = input}>
<option selected disabled>Seleccione un representante legal</option>
{legalRepresentatives}
</select>
<span style={{display: this.state.displayLegalRepresentativeError, color: 'red'}}>{this.state.legalRepresentativeErrorContent}</span>
</div>
<div className="form-group">
<label >Nombre</label>
<input type="text" defaultValue={this.props.investor != null ? this.props.investor.name : ''} ref={input => this._name = input} className="form-control" onBlur={this._handleNameBlur}
placeholder="Introduzca name"/>
<span style={{display: this.state.displayNameError, color: 'red'}}>{this.state.nameErrorContent}</span>
</div>
<div className="form-group">
<label >Nacionalidad</label>
<input type="text" defaultValue={this.props.investor != null ? this.props.investor.nationality : ''} ref={input => this._nationality = input} className="form-control"
placeholder="Introduzca nacionalidad"/>
</div>
<div className="form-group">
<label >Telefono</label>
<input type="text" defaultValue={this.props.investor != null ? this.props.investor.phone : ''} ref={input => this._phone = input} className="form-control"
placeholder="Introduzca telefono"/>
</div>
<div className="form-group">
<label >Direccion</label>
<input type="text" defaultValue={this.props.investor != null ? this.props.investor.address : ''} ref={input => this._address = input} className="form-control"
placeholder="Introduzca direccion"/>
</div>
<div className="form-group">
<label >Rut</label>
<input type="text" onBlur={this._handleRutBlur} defaultValue={this.props.investor != null ? this.props.investor.rut : ''} ref={input => this._rut = input} className="form-control" readOnly={this.props.investor != null ? 'readonly' : ''}
placeholder="Introduzca rut"/>
</div>
<span style={{display: this.state.displayRutError, color: 'red'}}>{this.state.rutErrorContent}</span>
<div className="form-group">
<label >Stock</label>
<input type="text" onChange={this._handleStockChange} defaultValue={this.props.investor != null ? this.props.investor.stock : ''} ref={input => this._stock = input} className="form-control"
placeholder="Introduzca stock"/>
<span style={{display: this.state.displayStockError, color: 'red'}}>{this.state.stockErrorContent}</span>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
}
|
import { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
increaseCount = () => {
const { count } = this.state; // ES6 Destructuring Assignment
this.setState({ count: count + 1 });
}
decreaseCount = () => {
const { count } = this.state; // ES6 Destructuring Assignment
this.setState({ count: count - 1 });
}
render() {
const { count } = this.state; // ES6 Destructuring Assignment.
return (
<div>
<p>{count}</p>
<button type='button' onClick={this.increaseCount}>
Click to increment
</button>
<button type='button' onClick={this.decreaseCount}>
Click to decrement
</button>
</div>
)
}
}
export default Counter;
|
const express = require('express');
const router = express.Router();
const Board = require('../models/board');
// router.<http method>
router.get('/', function (req, res, next) {
const boardList = Board.getBoardList();
res.render(
"board/boardList",
{ boardList: boardList }
);
});
module.exports = router;
|
require('dotenv').config()
const express = require("express");
const path = require("path");
const cookieParser = require('cookie-parser');
const db = require('./models');
const apiRoutes = require('./routes/api');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use('/api', apiRoutes(express.Router()));
const env = process.env.NODE_ENV;
const port = process.env.PORT;
db.sequelize.authenticate()
.then(() => {
app.listen(port, () => {
console.log(`APP RUN ON PORT: ${port} WIH ENV: ${env}`);
});
})
.catch((err) => console.error(err));
|
class Astreoid {
constructor() {
this.mesh = new THREE.Object3D();
const geom = new THREE.SphereGeometry(2, 10, 10);
const mat = new THREE.MeshPhongMaterial({
color: 0x877762
});
const nCricles = 3 + Math.floor(Math.random() * 2);
for (let i = 0; i < nCricles; i++) {
const m = new THREE.Mesh(geom, mat);
m.position.x = i * 1.8;
m.position.y = 1.5 * Math.random();
m.position.z = 1.5 * Math.random();
const s = 0.5 + Math.random();
m.scale.set(s, s, s);
m.castShadow = true;
m.receiveShadow = true;
this.mesh.add(m);
}
}
}
export default Astreoid;
|
describe('P.views.workouts.edit.Exercise', function() {
var View = P.views.workouts.edit.Exercise,
Model = P.models.sets.Exercise;
describe("render()", function() {
PTest.View.template.async(new View({
model: new Backbone.Model()
}));
it('should display exercise name if one exists', function() {
var model = new Model({
name: "snatch"
});
var view = new View({
model: model
});
view.render();
expect(view.el.innerHTML.contains('snatch'))
.toBe(true);
});
it('should have a P.views.workouts.edit.SetCollection subclass', function() {
var view = new View({
model: new Backbone.Model()
});
view.render();
expect(view.$('.exercise-sets')
.html())
.not.toBe('');
});
it('should show the order if set', function() {
var model = new Model({
order: 'A.1'
});
var view = new View({
model: model
});
view.render();
expect(view.$('.js-order')
.text())
.toBe('A.1');
});
});
describe('del()', function() {
var model, view;
beforeEach(function() {
model = new Backbone.Model();
view = new View({
model: model
});
});
it('destroys the model', function() {
var collection = new Backbone.Collection();
collection.add(model);
view.del();
expect(collection.length)
.toBe(0);
});
});
it('listens for changes to order', function() {
var model = new Backbone.Model({
order: 'A'
});
var view = new View({
model: model
});
view.render();
expect(view.$('.js-order')[0].textContent).toBe('A');
model.set('order', 'B');
expect(view.$('.js-order')[0].textContent).toBe('B');
});
describe('save()', function() {
var view, model;
beforeEach(function() {
model = new Model({
'name': 'foo'
});
view = new View({
model: model
});
view.render();
});
it('raises an error if name is not set', function() {
var thrown;
view.$('.js-name').val('');
try {
view.save();
} catch (err) {
thrown = true;
}
expect(thrown).toBe(true);
});
it('calls save on the sets collection view', function() {
spyOn(view.rSets.currentView, 'save');
view.save();
expect(view.rSets.currentView.save.calls.count())
.toBe(1);
});
});
});
|
import React from 'react'
export const ImageContainer = ({
children,
image,
className,
height,
width,
avatar = false
}) => {
return (
<div
className={className}
style={{
backgroundImage: `url(${image})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
height: height,
width: width,
borderRadius: avatar ? '100%' : '0px'
}}
>
{children}
</div>
)
}
|
import React from 'react'
import isPresent from '@reforma/ui/utils/isPresent'
export default function renderBool(value, hints) {
const [yes, no] = do {
if (hints.length === 2) {
hints
} else {
['Yes', 'No']
}
}
const text = do {
if (isPresent(value)) {
yes
} else {
no
}
}
return (
<span className="rf-bool">{text}</span>
)
}
|
global.sendSms = ({ variables_values, to, otp, message }) => {
const reqBody = {
route: "dlt",
sender_id: "DelPay",
message,
variables_values,
flash: 0,
numbers: to.join(),
};
return fetch(`https://www.fast2sms.com/dev/bulkV2`, {
method: "POST",
headers: {
authorization: process.env.FAST2SMS_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify(reqBody),
}).then((res) => res.json());
};
|
import express from "express";
import isAuthenticated from "../middlewares/authenticate.js";
import * as shopCtrl from "../controllers/shop.controller.js";
const router = express.Router();
router.route("/").get(shopCtrl.findAll);
router.route("/:id").get(shopCtrl.findShop);
router.route("/:id").delete(isAuthenticated, shopCtrl.deleteShop);
router.route("/").post(isAuthenticated, shopCtrl.createShop);
router.route("/").put(isAuthenticated, shopCtrl.editShop);
router.route("/city/:name").get(shopCtrl.findInCity);
router.route("/clothing/:clothId").get(shopCtrl.findAllByClothing);
export default router;
|
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import Stories from './screens/Home/Stories';
const Stack = createStackNavigator();
const StoryStack = () => {
return (
<Stack.Navigator mode='modal' headerMode='none' initialRouteName='Stories'>
<Stack.Screen name='Stories' component={Stories} />
</Stack.Navigator>
);
};
export default StoryStack;
|
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
var api_key = "AIzaSyA0TgG8WO6h1YnWcc41_kkS_xFD7tFT1dw";
if(req.query.pageToken && req.query.pageToken != ''){
var pageToken = req.query.pageToken;
var new_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=' + pageToken + '&key=' + api_key;
nextPage(new_url, res);
}else {
var lat = req.query.lat;
var lng = req.query.lng;
var radius = req.query.radius;
var type = req.query.type;
var keyword = req.query.keyword;
var request_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+lat + ',' + lng + '&radius=' + radius + '&type=' + type+ '&keyword=' + keyword + '&key=' + api_key;
firstPage(request_url, res);
}
});
function firstPage(request_url, res) {
var request = require('request');
request(request_url, function (error, response, body) {
var output = {};
if (!error) {
try {
var data = JSON.parse(body);
if (data.results && data.results.length >= 1) {
var entities = data.results;
var entitiesRes = [];
var nextPage = '';
if(data.next_page_token && data.next_page_token != ''){
nextPage = data.next_page_token;
}
for(var i = 0; i < entities.length; i++) {
var category_icon = entities[i]["icon"];
var place_name = entities[i]["name"];
var place_address = entities[i]["vicinity"];
var place_id = entities[i]["place_id"];
var lat = entities[i]["geometry"]["location"]["lat"];
var lng = entities[i]["geometry"]["location"]["lng"];
var resObj = {"category_icon":category_icon, "place_name":place_name, "place_address":place_address,"place_id":place_id , "place_lat":lat, "place_lng":lng};
entitiesRes.push(resObj);
}
output.error = 0;
output.data = entitiesRes;
if(nextPage != '') {
output.nextPageToken = nextPage;
}
}
else {
output.error = 1;
output["error message"] = "No Records has been found";
}
res.send(JSON.stringify(output));
} catch (err) {
output.error = 1;
output["error message"] = "No Records has been found";
res.send(JSON.stringify(output));
}
} else {
output.error = 1;
output["error message"] = "No Records has been found";
res.send(JSON.stringify(output));
}
});
}
function nextPage(new_url, res){
var request = require('request');
var output = {};
request(new_url, function (error, response, body) {
if (!error) {
try {
var data = JSON.parse(body);
if (data.results && data.results.length >= 1) {
var entities = data.results;
var entitiesRes = [];
var nextPage = '';
if(data.next_page_token && data.next_page_token != ''){
nextPage = data.next_page_token;
}
for(var i = 0; i < entities.length; i++) {
var category_icon = entities[i]["icon"];
var place_name = entities[i]["name"];
var place_address = entities[i]["vicinity"];
var place_id = entities[i]["place_id"];
var lat = entities[i]["geometry"]["location"]["lat"];
var lng = entities[i]["geometry"]["location"]["lng"];
var resObj = {"category_icon":category_icon, "place_name":place_name, "place_address":place_address,"place_id":place_id,"place_lat":lat, "place_lng":lng};
entitiesRes.push(resObj);
}
output.error = 0;
output.data = entitiesRes;
if(nextPage != '') {
output.nextPageToken = nextPage;
}
}
else {
output.error = 1;
output["error message"] = "No Records has been found";
}
res.send(JSON.stringify(output));
} catch (err) {
output.error = 1;
output["error message"] = "No Records has been found";
res.send(JSON.stringify(output));
}
} else {
output.error = 1;
output["error message"] = "No Records has been found";
res.send(JSON.stringify(output));
}
});
}
module.exports = router;
|
import React, { Component } from 'react';
import Button from "./calcBtn";
import Display from "./calcDisplay";
import Memory from "./memory";
class Table extends Component {
state = {
value: [
[1, 2, 3, "/"],
[4, 5, 6, "-"],
[7, 8, 9, "+"],
[0, "=", "*", "clear"]
],
disp: "",
memory: [],
}
render() {
return (
<div style={{
backgroundColor: "lightblue",
width: "40vw",
height: "65vh",
margin: "auto",
borderRadius: "5px",
}}>
<Display value={this.state.disp}></Display>
{this.createTbl(this.state.value)}
<Memory value={this.state.disp}></Memory>
</div>
);
}
createCell(value) {
return (
value.map((number) =>
<td><Button onclick={this.onInput.bind(this)} value={number}> </Button></td>
)
)
}
createTbl(tblArr) {
return tblArr.map((row) => {
return (
<tr style={{
}}>
{this.createCell(row)}
</tr>
)
})
}
onInput(e) {
console.log(e)
if (e === "=") {
let old = this.state.disp;
let hold = eval(this.state.disp);
let mem = this.state.memory;
mem.push(old + "=" + hold);
this.setState({
disp: hold,
memory: mem
});
console.log(hold)
}
else if (e === "clear") {
this.setState({
disp: ""
})
}
else if (isNaN(e)) {
this.setState({
disp: this.state.disp + "" + e
})
}
else {
if (!isNaN(this.state.disp)) {
this.setState({
disp: e
})
} else {
this.setState({
disp: this.state.disp + "" + e
})
}
}
}
}
export default Table;
|
import AddNumber from '../Components/AddNumber';
import {connect} from 'react-redux';
function mapDispatchToProps(dispatch) {
return {
onClick : size => {
dispatch({type : 'INCREMENT', size : size});
}
}
}
export default connect(null, mapDispatchToProps)(AddNumber);
/*
import React, {Component} from 'react';
import store from '../store';
export default class extends Component {
render() {
return <AddNumber onClick = {size => {
store.dispatch({type : 'INCREMENT', size : size});
}}></AddNumber>
}
}*/
|
function Way( id, name, type, node1ID, node2ID)
{
this.id = id;
this.name = name;
this.type = type;
this.node1ID = node1ID;
this.node2ID = node2ID;
}
export default Way
|
import { combineReducers } from 'redux'
import { PAY, SAVE_MOVIE, SHOW_BUY_MODAL, HIDE_BUY_MODAL } from '../actions/action-type'
const moneyReducer = (state = 0, action) => {
switch (action.type) {
case PAY:
return state -= action.price
default:
return state
}
}
const movieReducer = (state = [], action) => {
switch (action.type) {
case SAVE_MOVIE:
return [...state, action.id ]
default:
return state
}
}
const movieModalReducer = (state = {}, action) => {
switch (action.type) {
case SHOW_BUY_MODAL:
return {...state, ...action.modalBuy }
case HIDE_BUY_MODAL:
return {...state, show: action.show}
default:
return state
}
}
export default combineReducers({
money: moneyReducer,
movies: movieReducer,
modalBuy: movieModalReducer
})
|
const path = require('path');
const logger = require('../logger');
const utils = require('../utils');
const style = require('../style');
const config = require('../config');
const { isType, isBlank } = utils;
module.exports = function render (doc, entering, node, cfg) {
const { type, isContainer, destination, title } = node;
const { fullName, state } = cfg;
logger.debug(`Render node type: ${type}`, { entering, isContainer, destination, title });
style.link(doc, entering);
if (entering) {
// #region fetch and check image
let newTarget = destination;
const { link: linkTransform } = config.transform;
if (isType(linkTransform, 'Function')) {
newTarget = linkTransform(destination, fullName);
logger.debug(`Transform link target: ${destination} -> ${newTarget}`);
}
// invalid target
if (isBlank(newTarget, { detectSpace: true })) {
logger.warn(`Invalid link target: ${newTarget}`);
return;
}
// anchor target
let anchorName = null;
if ((/^http(s)?:\/\//).test(newTarget)) { // remote http
logger.debug(`Link target to remote http path: ${newTarget}`);
} else if (path.isAbsolute(newTarget)) { // local absolute
logger.debug(`Link target to local absolute path: ${newTarget}`);
} else { // local relative
logger.debug(`Link target to local relative path: ${newTarget}`);
anchorName = newTarget; // only allow relative path
anchorName = decodeURI(anchorName); // decode coded link
}
// #endregion
state.underline = true;
state.goTo = anchorName;
state.link = newTarget;
} else {
delete state.underline;
delete state.goTo;
delete state.link;
}
}
|
"Use strict";
// I want a routine to determine if a dog is infact my dog
// The dog must have fur, have whisker, and have a name
var hasfur = true;
var hasWhiskers = true;
var nameIsCoda = true;
if (hasfur && hasWhiskers && nameIsCoda){
console.log("Who's A ggod girl?? *bark*");
}
//another way
isMyDog = (hasfur && hasWhiskers && nameIsCoda);
if (isMyDog){
console.log("Who's A ggod girl?? *bark*");
}
//logical or
var creditScore = 720;
var cashOnHand = 3000
if (creditScore > 680 || cashOnHand > 3000){
console.log("Congrats! you (the bank) now own a car!");
}
var hasRequiredScoreOrCash = (creditScore > 680) || (cashOnHand > 3000);
var lengthOfEmployment = 6
var hasAdequatelengthofEmployment = (lengthOfEmployment>= 6);
if (hasRequiredScoreOrCash && hasAdequatelengthofEmployment){
console.log("ok, for real. you get a car");
console.log("The inverted value is: " + !true);
//logical not (!)
// ******* Truthy / Falsy *******
// This is an intriguing concept in Javascript, and unique to it and Python
// Essentially, all values are considered 'true' unless they are defined as not
// Weird, right? So, all values except:
// false, 0, -0, 0n, "", null, undefined, and NaN (Not a Number
|
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Accounts from './components/Accounts';
import Exchange from './components/Exchange';
import EventsContainer from './components/Events';
import {
getAccountBalances,
handleTicketTransfer
} from './TicketExchangeActions';
import './TicketExchange.css';
import MetaCoin from '../../../build/contracts/MetaCoin.json';
const contract = require('truffle-contract');
class TicketExchange extends Component {
constructor(props) {
super(props);
this.state = {
accounts: [],
coinbase: '',
ticketPrice: '10'
};
}
componentDidMount() {
const {
web3,
getAccountBalances
} = this.props;
// getAccountBalances(web3);
// const refreshBalances = () => {
// // this.getAccountBalances()
// };
// refreshBalances();
// setInterval(()=>{
// refreshBalances();
// return refreshBalances
// }, 5000)
}
// getAccountBalances = () => {
// const { web3 } = this.props;
//
// web3 && web3.eth.getAccounts(function (err, accs) {
// if (err != null) {
// window.alert('There was an error fetching your accounts.')
// console.error(err);
// return
// }
//
// if (accs.length === 0) {
// window.alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.")
// return
// }
//
// this.setState({
// coinbase: accs[0]
// });
//
// const accountsAndBalances = accs.map((account) => {
// console.log('account', account, this);
//
// this.getAccountBalance(account)
// .then((balance) => ({
// account,
// balance
// }))
// });
//
// Promise.all(accountsAndBalances).then((accountsAndBalances) => {
// this.setState({
// accounts: accountsAndBalances,
// coinbaseAccount: accountsAndBalances[0]
// })
// })
// }.bind(this))
// };
updateSelectedAccount = (account) => {
this.setState({
selectedAccount: account
})
};
handlePurchase = (event, account, quantity) => {
const { coinbase, ticketPrice, accounts } = this.state;
let totalPrice = ticketPrice * quantity.value;
let sender = accounts[accounts.indexOf(account)].account;
console.log('onPurchase', coinbase, totalPrice, event, sender, quantity);
// let meta;
//
// MetaCoin.deployed();
// console.log(`Recipient Address: ${coinbase}`);
//
// meta.sendCoin(coinbase, totalPrice, {from: sender}).then(function() {
// console.log(`Coins sent for ${quantity.value} tickets from ${sender} to ${coinbase}`)
// }).catch(function(e) {
// console.log(e);
// });
};
render() {
const {
accounts,
selectedAccount,
coinbase
} = this.state;
const { web3 } = this.props;
if(!web3) {
return <div>Loading</div>
}
return (
<div style={{display: 'flex', flex: 1, flexWrap: 'wrap', flexDirection: 'column', justifyContent: 'flex-start'}}>
<div>
<Accounts accounts={accounts}
handleAccountSelect={this.updateSelectedAccount}
/>
<Exchange sender={coinbase} account={selectedAccount}/>
</div>
<div>
<EventsContainer accounts={accounts}
handleOpenModal={() => console.log('Kevin')}
onPurchase={this.handlePurchase}
/>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
web3: state.web3.web3Instance
});
const mapDispatchToProps = dispatch => bindActionCreators({
// getAccountBalances
}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(TicketExchange);
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Icon} from '../../src/index';
import styled from 'styled-components'
/**
* The Icon component.
*
* @version 1.0.0
* @author [Himanshu Dixit]
*/
const IconContainer = styled.div`
display: flex;
align-items: center;
&>p{
display: inline;
}
`;
class IconText extends Component {
render() {
// Using tailwing font family, font weight, font size and color.
let icontailwindcss = ``;
// If additional tailwind classes are passed, add to styles.
if (this.props.iconAdditionalTailwindClasses) {
icontailwindcss += ' ' + this.props.iconAdditionalTailwindClasses;
}
return(
<IconContainer onClick={this.props.click}>
<Icon
size={this.props.iconSize}
color={this.props.iconColor}
additionalTailwindClasses={icontailwindcss}
additionalStyle={this.props.iconAdditionalStyle} ></Icon>
{this.props.children}
</IconContainer>
);
}
}
IconText.defaultProps = {
iconSize: '4',
iconColor: 'black'
};
IconText.propTypes = {
/**
* Size of the icon
*/
iconSize: PropTypes.oneOf([1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 24, 32]),
/**
* Color of the icon
*/
iconColor: PropTypes.oneOf(['black', 'golden', 'red', 'grey-dark', 'grey-light', 'white']),
/**
* Additional tailwind class for icon
*/
iconAdditionalStyle: PropTypes.string,
/**
* Additional tailwind class for icon
*/
iconAdditionalTailwindClasses: PropTypes.string,
/**
* Gets called when the user clicks on the button
*/
click: PropTypes.func,
};
export default IconText;
|
import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";
// 这里的@符号就表示了src的相对路径
describe("HelloWorld.vue", () => {
// describe就表示测试集,其中HelloWord.vue是测试集的名称
// 后面的函数表示的是测试方法,其中每一个it表示的是一个最小的单元测试集
it("renders props.msg when passed", () => {
// 同样第一个参数表示的是这个最小单元测试的描述或者名称
// 后面的函数表示的是一个校验的方法
const msg = "new message";
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
});
// shallowMount表示的是浅渲染,这里的浅渲染表示的是不会对这个组件深层次的组件进行渲染
// shallowMount换为了Mount之后就能进行深层渲染了,第一个参数是要测试的组件
// 第二个参数是传入的参数比如:<HelloWorkd masg="new message">
expect(wrapper.text()).toMatch(msg);
// 这里表示断言的意思,希望测试中的值和设置的值是一样的
});
});
|
var yr = yr || require('yate/lib/runtime.js');
(function() {
var cmpNN = yr.cmpNN;
var cmpSN = yr.cmpSN;
var nodeset2xml = yr.nodeset2xml;
var nodeset2boolean = yr.nodeset2boolean;
var nodeset2attrvalue = yr.nodeset2attrvalue;
var nodeset2scalar = yr.nodeset2scalar;
var scalar2attrvalue = yr.scalar2attrvalue;
var xml2attrvalue = yr.xml2attrvalue;
var scalar2xml = yr.scalar2xml;
var xml2scalar = yr.xml2scalar;
var simpleScalar = yr.simpleScalar;
var simpleBoolean = yr.simpleBoolean;
var selectNametest = yr.selectNametest;
var closeAttrs = yr.closeAttrs;
var M = new yr.Module();
var j0 = [ ];
// match /
M.t0 = function t0(m, c0, i0, l0, a0) {
var r0 = '';
var current = [ c0 ];
r0 += closeAttrs(a0);
r0 += "<!doctype html>";
r0 += "<html>";
r0 += "<head>";
r0 += "<meta charset=\"" + "utf-8" + "\"/>";
r0 += "<meta name=\"" + "viewport" + "\" content=\"" + "width=device-width, initial-scale=1" + "\"/>";
r0 += "<meta name=\"" + "robots" + "\" content=\"" + "noindex, nofollow" + "\"/>";
r0 += "<title>" + "Error 404 Not Found" + "</title>";
r0 += "<link href=\"/public/error/error.css\" rel=\"stylesheet\" />";
r0 += "</head>";
r0 += "<body class=\"" + "page" + "\">";
r0 += "<div class=\"" + "content" + "\"><h1><a class=\"" + "logo" + "\" href=\"" + "/" + "\">" + "World Fly" + "</a></h1>";
r0 += "<h2 class=\"" + "title" + "\"><span class=\"" + "title__code" + "\">" + "404." + "</span>" + " Page Not Found." + "</h2>";
r0 += "<p>" + "The requested resource was not found." + "</p>";
r0 += "<p>" + "If you think that something should be here, please " + "<a class=\"" + "link" + "\" href=\"" + "mailto:support@worldfly.info" + "\">" + "tell us: support@worldfly.info" + "</a>" + "." + "</p>";
r0 += "<p>" + "You can " + "<a href=\"" + "/" + "\" class=\"" + "link" + "\">" + "back to the main page" + "</a>" + "." + "</p></div>";
r0 += "</body>";
r0 += "</html>";
return r0;
};
M.t0.j = 1;
M.t0.a = 1;
M.matcher = {
"": {
"": [
"t0"
]
}
};
M.imports = [];
yr.register('error', M);
})();
|
/// <reference path="../typings/lodash.d.ts" />
var cloneDeep = require('lodash/lang/cloneDeep');
var isElement = require('lodash/lang/isElement');
var HTML = (function () {
function HTML(param) {
var _this = this;
this.children = [];
this.parent = null;
//was a parameter provided?
if (param) {
//is String?
if (typeof param === 'string') {
try {
this.element = document.createElement(param);
}
catch (error) {
throw new Error('DOM-HTML: could not create element with tagname "' + param + '"');
}
}
else if ('nodeName' in param) {
this.element = param;
}
else if (param.element) {
//set element
if (typeof param.element === 'string') {
try {
this.element = document.createElement(param.element);
}
catch (error) {
throw new Error('DOM-HTML: could not create element with tagname "' + param + '"');
}
}
else if (typeof param === 'object' && 'nodeName' in param.element) {
this.element = param.element;
}
//class
if (param['class']) {
//if Array...
if (param['class'] instanceof Array) {
var arr = param['class'];
arr.forEach(function (e) {
_this.addClass(e);
});
}
else {
this.addClass(param['class']);
}
}
//id
if (param.id)
this.setId(param.id);
//data
if (param.data)
this.data = param.data;
//html
if (param.html)
this.setHtml(param.html);
//attachment
if (param.appendTo)
this.appendTo(param.appendTo);
if (param.prependTo)
this.prependTo(param.prependTo);
if (param.before)
this.before(param.before);
if (param.after)
this.after(param.after);
}
else {
throw new Error('DOM-HTML: invalid constructor parameters.');
}
}
}
Object.defineProperty(HTML.prototype, "elem", {
/**
* getters
*/
get: function () {
return this.element;
},
enumerable: true,
configurable: true
});
/**
* Element attachment
*/
/**
* appendto
*/
HTML.prototype.appendTo = function (elem) {
if (elem instanceof HTML) {
elem.element.appendChild(this.element);
// elem.append(this);
this.parent = elem;
elem.children.push(this);
return;
}
else if (typeof elem === 'string') {
if (elem.indexOf('#') > -1) {
try {
var id = elem.replace('#', '');
document.getElementById(id).appendChild(this.element);
return;
}
catch (error) {
// throw error;
throw new Error('Dom_HTML#appendTo: invalid element to append to');
}
}
else
throw new Error('DOM-HTML#appendTo: invalid id string (use #)');
}
else if ('nodeName' in elem) {
elem.appendChild(this.element);
return;
}
throw new Error('Dom_HTML#appendTo: invalid element to append to');
};
/**
* append
*/
HTML.prototype.append = function (obj) {
this.element.appendChild(obj.element);
this.children.push(obj);
obj.parent = this;
};
/**
* prependTo
*/
HTML.prototype.prependTo = function (elem) {
if (elem instanceof HTML) {
elem.element.insertBefore(this.element, elem.element.firstChild);
elem.children.push(this);
this.parent = elem;
return;
}
else if (typeof elem === 'string') {
if (elem.indexOf('#') > -1) {
try {
var id = elem.replace('#', '');
var element = document.getElementById(id);
element.insertBefore(this.element, element.firstChild);
return;
}
catch (error) {
// throw error;
throw new Error('Dom_HTML#prependTo: invalid element to prepend to');
}
}
else
throw new Error('DOM-HTML#prependTo: invalid id string (use #)');
}
else if ('nodeName' in elem) {
elem.insertBefore(this.element, elem.firstChild);
return;
}
throw new Error('Dom_HTML#prependTo: invalid element to prepend to');
};
/**
* prepend
*/
HTML.prototype.prepend = function (obj) {
this.element.insertBefore(obj.element, this.element.firstChild);
this.children.push(obj);
obj.parent = this;
};
/**
* before
*/
HTML.prototype.before = function (elem) {
if (elem instanceof HTML) {
elem.element.parentNode.insertBefore(this.element, elem.element);
this.parent = elem.parent;
if (elem.parent)
this.parent.children.push(this);
return;
}
else if (typeof elem === 'string') {
if (elem.indexOf('#') > -1) {
try {
var id = elem.replace('#', '');
var element = document.getElementById(id);
element.parentNode.insertBefore(this.element, element);
return;
}
catch (error) {
// throw error;
throw new Error('Dom_HTML#before: invalid element to insert before');
}
}
else
throw new Error('DOM-HTML#before: invalid id string (use #)');
}
else if ('nodeName' in elem) {
elem.parentNode.insertBefore(this.element, elem);
return;
}
throw new Error('Dom_HTML#before: invalid element to insert before');
};
/**
* after
*/
HTML.prototype.after = function (elem) {
if (elem instanceof HTML) {
elem.element.parentNode.insertBefore(this.element, elem.element.nextSibling);
this.parent = elem.parent;
if (elem.parent)
this.parent.children.push(this);
return;
}
else if (typeof elem === 'string') {
if (elem.indexOf('#') > -1) {
try {
var id = elem.replace('#', '');
var element = document.getElementById(id);
element.parentNode.insertBefore(this.element, element.nextSibling);
return;
}
catch (error) {
// throw error;
throw new Error('Dom_HTML#after: invalid element to insert after');
}
}
else
throw new Error('DOM-HTML#after: invalid id string (use #)');
}
else if ('nodeName' in elem) {
elem.parentNode.insertBefore(this.element, elem.nextSibling);
return;
}
throw new Error('Dom_HTML#after: invalid element to insert after');
};
/**
* moveTo
*/
HTML.prototype.moveTo = function (elem, method) {
if (method === void 0) { method = 'appendTo'; }
this.remove();
this[method](elem);
};
/**
* Classes
*/
HTML.prototype.addClass = function (name) {
if (this.element.classList) {
if (!this.element.classList.contains(name))
this.element.classList.add(name);
}
else {
if (this.element.className.indexOf(name) > -1)
return;
this.element.className += ' ' + name;
}
return this;
};
HTML.prototype.removeClass = function (name) {
if (this.element.classList) {
if (this.element.classList.contains(name))
this.element.classList.remove(name);
}
else {
if (this.element.className.indexOf(name) === -1)
return;
this.element.className = this.element.className.replace(' ' + name, '');
}
return this;
};
HTML.prototype.toggleClass = function (name) {
if (this.element.classList) {
if (this.element.classList.contains(name))
this.removeClass(name);
else
this.addClass(name);
}
else {
if (this.element.className.indexOf(name) > -1)
this.removeClass(name);
else
this.addClass(name);
}
return this;
};
HTML.prototype.hasClass = function (name) {
if (this.element.classList) {
return this.element.classList.contains(name);
}
else {
return this.element.className.indexOf(name) > -1;
}
};
HTML.prototype.setHtml = function (text) {
this.element.innerHTML = text;
return this;
};
HTML.prototype.setWidth = function (value, unit) {
this.element.style.width = value + unit;
return this;
};
HTML.prototype.setHeight = function (value, unit) {
this.element.style.height = value + unit;
return this;
};
HTML.prototype.setPosition = function (pos, unit, type) {
if (type)
this.element.style.position = type;
if (pos.top !== undefined || null)
this.element.style.top = pos.top.toString() + unit;
if (pos.left !== undefined || null)
this.element.style.left = pos.left.toString() + unit;
return this;
};
/**
* Various
*/
HTML.prototype.remove = function () {
try {
if ('remove' in this.element) {
this.element.remove();
}
else {
this.element.parentNode.removeChild(this.element);
}
}
catch (error) {
throw new Error('HTML-DOM: ' + error);
}
//children / parent stuff
if (this.parent) {
var index = this.parent.children.indexOf(this);
this.parent.children.slice(index, 1);
}
};
HTML.prototype.setId = function (value) {
var val = typeof value === 'number' ? parseInt(value, 10) : value;
this.element.id = val;
// this.element.setAttribute('id', <any>val);
return this;
};
HTML.prototype.child = function (predicate) {
for (var i = 0; i < this.children.length; i++) {
if (predicate(this.children[i]) === true)
return this.children[i];
}
return null;
};
/**
* Events
*/
HTML.prototype.on = function (event, handler) {
this.element.addEventListener(event, handler);
};
HTML.prototype.off = function (event, handler) {
this.element.removeEventListener(event, handler);
};
HTML.prototype.trigger = function (eventType) {
var event;
event = document.createEvent('HTMLEvents');
event.initEvent(eventType, true, true);
this.element.dispatchEvent(event);
};
HTML.prototype.findParent = function (predicate) {
var parent = this.element.parentElement;
while (parent && !predicate(parent))
parent = parent.parentElement;
if (parent === null)
throw new Error('Dom_HTML#findParent: could not find parent');
return parent;
};
HTML.findParent = function (element, predicate) {
var parent = element;
while (parent && !predicate(parent))
parent = parent.parentElement;
if (parent === null)
throw new Error('Dom_HTML#findParent: could not find parent');
return parent;
};
HTML.prototype.findChild = function () {
};
/**
* Helper
*/
HTML.prototype.isAttachedToParent = function () {
if (this.element.parentElement) {
return true;
}
else {
return false;
}
//return document.body.contains(this.element);
};
/**
* Cloning
*/
HTML.prototype.clone = function () {
return cloneObject(this, this.parent);
function cloneObject(obj, caller) {
obj = obj && obj instanceof Object ? obj : '';
// Handle Array
if (obj instanceof Array) {
return obj.map(function (value) {
var x = cloneObject(value, null);
if ('parent' in x)
x.parent = caller;
return x;
});
}
else if (obj instanceof Object) {
var copy = new obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
if (attr === 'parent') {
copy['parent'] = null;
}
else if (isElement(obj[attr])) {
copy[attr] = obj[attr].cloneNode(true);
}
else if (obj[attr] instanceof Object) {
copy[attr] = cloneObject(obj[attr], copy);
}
else {
copy[attr] = obj[attr];
}
}
}
return copy;
}
else
return obj;
}
};
return HTML;
})();
exports.HTML = HTML;
|
module.exports.postTransfer = function(req, res, next){
var errors = [];
if(!req.body.serial){
errors.push('Serial is required!');
}
if(!req.body.amount){
errors.push('Amount is required!');
}
if(errors.length){
res.render('transfer/index', {
errors: errors,
values: req.body
});
return;
}
next();
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import AddCircle from '@material-ui/icons/AddCircle';
import styles from './styles';
const AddTodoItem = ({ classes, addTodoItem }) => (
<div
className={classes.addTodoItemContainer}
onClick={addTodoItem}
>
<div className={classes.addTodoItem}>
<AddCircle />
<span className={classes.addTodoItemTitle}>Add a to-do</span>
</div>
</div>
);
AddTodoItem.propTypes = {
addTodoItem: PropTypes.func
};
AddTodoItem.defaultProps = {
addTodoItem: () => null
};
export default withStyles(styles)(AddTodoItem);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'underscore';
import AssessmentTasks from 'mgmt/TaskAssignments/components/AssessmentTasks';
import FinishedTaskFilter from 'mgmt/TaskAssignments/components/FinishedTaskFilter';
import Loading from 'shared/components/Loading';
import RobTasks from 'mgmt/TaskAssignments/components/RobTasks';
import { fetchTasks, hydrateTasks } from 'mgmt/TaskAssignments/actions';
class Assignments extends Component {
constructor(props) {
super(props);
this.toggleFilter = this.toggleFilter.bind(this);
this.state = {
filterTasks: true,
taskFilter: (task) => {return task.status !== 30 && task.status !== 40;},
};
}
componentWillMount() {
this.props.dispatch(hydrateTasks());
this.props.dispatch(fetchTasks());
}
formatTasks() {
return _.chain(this.props.tasks.list)
.filter(this.state.taskFilter)
.filter((task) => task.owner.id == this.props.config.user)
.groupBy((task) => { return task.study.assessment.name; })
.value();
}
toggleFilter() {
if (this.state.filterTasks){
this.setState({
filterTasks: false,
taskFilter: () => true,
});
} else {
this.setState({
filterTasks: true,
taskFilter: (task) => {return task.status !== 30 && task.status !== 40;},
});
}
}
renderNoTasks() {
return <p className="help-block">There are no tasks available.</p>;
}
render() {
if (!this.props.tasks.isLoaded) return <Loading/>;
const groupedTasks = this.formatTasks(),
renderTasks = _.keys(groupedTasks).length !== 0;
// only show assessment header if assessment is unspecified
let showAssessment = (this.props.config.assessment_id === undefined);
return (
<div>
<FinishedTaskFilter checked={this.state.filterTasks} onChange={this.toggleFilter} />
{renderTasks ?
_.map(groupedTasks, (tasks, key) =>
<AssessmentTasks key={key} tasks={tasks} showAssessment={showAssessment} />
) :
this.renderNoTasks()
}
<RobTasks tasks={this.props.tasks.robTasks} showAssessment={showAssessment} />
</div>
);
}
}
function mapStateToProps(state){
const { config, tasks } = state;
return {
config,
tasks,
};
}
export default connect(mapStateToProps)(Assignments);
|
www
2222
2020-04-03 09:07--切换分支会带来什么好处
<<<<<<< HEAD
2020-04-03 10:16 创建hotfix分支,指向hotfix分支
=======
创建iss53 分支,现已指向iss53分支
2020-04-03 10:32 删除了hotfix分支,切换到iss53分支
>>>>>>> iss53
|
// INSTANTIATION
var APP = require("/core");
var args = arguments[0] || {};
var map = OS_IOS ? Ti.Map : Alloy.Globals.Map;
var _isLogged = false;
var latitude = 0;
var longitude = 0;
var _updateLatitude = 0;
var _updateLongitude = 0;
var shouldLoadMap = false;
if (OS_ANDROID) {
var latitudeDelta = 0.01;
var longitudeDelta = 0.01;
} else {
var latitudeDelta = 0.02;
var longitudeDelta = 0.02;
}
var days = [{
title : 'Last 24 hours',
filterID : 'last1'
}, {
title : 'Last 3 days',
filterID : 'last3'
}, {
title : 'Last 7 days',
filterID : 'last7'
}, {
title : 'Last 30 days',
filterID : 'last30'
}, {
title : 'Last 90 days',
filterID : 'last90'
}, {
title : 'All Days',
filterID : 'ALL'
}];
// FUNCTIONS
function changeSettings() {
/* $.settingsView.animate({
view:$.typesView,
transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
});*/
var a = Titanium.UI.createAnimation({
left : APP.numberOperation(-$.mapView.size.width, "/", 2, false),
duration : 300
});
var a2 = Titanium.UI.createAnimation({
left : 20,
duration : 300
});
var b = Titanium.UI.createAnimation({
left : APP.numberOperation($.mapView.size.width, "/", 2, false),
duration : 300
});
var o = Titanium.UI.createAnimation({
opacity : 0.8,
duration : 300
});
var o2 = Titanium.UI.createAnimation({
opacity : 1,
duration : 300
});
if ($.typesView.isOpen) {
a.addEventListener('complete', function() {
$.typesView.zIndex = 98;
$.typesView.animate(a2);
});
if (OS_IOS) {
$.typesView.animate(o);
}
$.typesView.animate(a);
b.addEventListener('complete', function() {
$.settingsView.zIndex = 99;
if (OS_IOS) {
$.settingsView.animate(o2);
}
$.settingsView.animate(a2);
});
$.settingsView.animate(b);
} else {
a.addEventListener('complete', function() {
$.settingsView.zIndex = 98;
$.settingsView.animate(a2);
});
if (OS_IOS) {
$.settingsView.animate(o);
}
$.settingsView.animate(a);
b.addEventListener('complete', function() {
$.typesView.zIndex = 99;
if (OS_IOS) {
$.typesView.animate(o2);
}
$.typesView.animate(a2);
});
$.typesView.animate(b);
}
$.typesView.isOpen = !$.typesView.isOpen;
}
function changeSwitch(_event) {
if (_event.source.value == true) {
if (_event.source.filterID == 0) {
shouldLoadMap = true;
$.fsw2.value = true;
$.fsw3.value = true;
$.fsw4.value = true;
$.fsw5.value = true;
$.fsw6.value = true;
$.fsw7.value = true;
$.fsw8.value = true;
$.fsw9.value = true;
$.fsw10.value = true;
$.fsw11.value = true;
$.fsw12.value = true;
$.fsw13.value = true;
$.fsw14.value = true;
$.fsw15.value = true;
$.fsw17.value = true;
$.fsw16.value = true;
setTimeout(function() {
shouldLoadMap = false;
Ti.API.info("load map");
getCrimes({
lat : latitude,
lon : longitude
});
}, 1500);
} else {
var tempString = Ti.App.Properties.getString('MapFilter.Categories.EnabledCategories');
Ti.App.Properties.setString('MapFilter.Categories.EnabledCategories', tempString + "," + _event.source.filterID);
}
} else {
if (_event.source.filterID == 0) {
shouldLoadMap = true;
$.fsw2.value = false;
$.fsw3.value = false;
$.fsw4.value = false;
$.fsw5.value = false;
$.fsw6.value = false;
$.fsw7.value = false;
$.fsw8.value = false;
$.fsw9.value = false;
$.fsw10.value = false;
$.fsw11.value = false;
$.fsw12.value = false;
$.fsw13.value = false;
$.fsw14.value = false;
$.fsw15.value = false;
$.fsw17.value = false;
$.fsw16.value = false;
setTimeout(function() {
shouldLoadMap = false;
getCrimes({
lat : latitude,
lon : longitude
});
}, 1500);
} else {
var tempString = Ti.App.Properties.getString('MapFilter.Categories.EnabledCategories', '4,1,2,3,5,6,7,9,10,11,12,13,14,15,16,18,19');
var regString = new RegExp("," + _event.source.filterID + "\\b", "g");
Ti.App.Properties.setString('MapFilter.Categories.EnabledCategories', tempString.replace(regString, ""));
}
}
//Ti.API.info(Ti.App.Properties.getString('MapFilter.Categories.EnabledCategories'));
if (shouldLoadMap == false) {
getCrimes({
lat : latitude,
lon : longitude
});
}
}
function currentPosition() {
APP.getCurrentLocation(function(_event) {
if (_event.success) {
_event.faname = "Current Location";
getCrimes(_event);
}else{
APP.hideActivityindicator();
}
});
}
function getAlerts( event , callback ){
APP.getToken({
openLogin : true,
callback : function( token ){
var _ws_request = {
atoken : token,
flat : event.lat,
flon : event.lon,
usehome : 0
};
/**** / Ti.API.info( 'getAlerts >>> _ws_request:' + JSON.stringify( _ws_request ) ); /****/
APP.http.request({
url : L( 'ws_getalerts' ),
type : 'GET',
format : 'JSON',
data : _ws_request
},function( response ){
/**** / Ti.API.info( 'getAlerts >>> response:' + JSON.stringify( response ) ); /****/
if( response._result == 0 ){
//alert( L( 'something_wrong' ) );
APP.closeWindow();
}
else{
if( response._data.errorcode != 0 ){
Ti.API.warn( response._data.message );
callback && callback();
}
else{
callback && callback( response._data.data );
}
}
return true;
});
return true;
}
});
return true;
}
function getCountCrimes(_event) {
var dataTemp = {
url : L("ws_getcrimelevel"),
type : 'POST',
format : 'JSON',
data : {
atoken : APP.getToken({
openLogin : false
}),
flat : _event.lat,
flon : _event.lon,
usehome : 0
}
};
APP.http.request(dataTemp, function(_result) {
//Ti.API.info("-->"+JSON.stringify(_result));
if (_result._result == 1) {
if (_result._data.errorcode == 0) {
$.crimeTitle.text = _result._data.data[0].crimecnt;
$.sexTitle.text = _result._data.data[0].oscount;
} else {
//alert(_result._data.message);
//alert("No messages were found.");
}
} else {
//alert("Internet connection error, please try again.");
}
});
}
function getCrimes(_event) {
APP.showActivityindicator();
latitude = _event.lat;
longitude = _event.lon;
/** [M] ** /
$.mapView.setLocation({
latitude : _event.lat,
longitude : _event.lon,
animate : true,
latitudeDelta : latitudeDelta,
longitudeDelta : longitudeDelta
});
/****/
$.mapView.setRegion({
latitude : _event.lat,
longitude : _event.lon,
animate : true,
latitudeDelta : latitudeDelta,
longitudeDelta : longitudeDelta
});
$.alertsTitle.text = _event.faname;
//if(APP.getToken({openLogin : true})){
getCountCrimes(_event);
var dataTemp = {
url : L("ws_getcrimes"),
type : 'POST',
format : 'JSON',
data : {
atoken : APP.getToken({
openLogin : false
}),
flat : _event.lat,
flon : _event.lon,
usehome : 0,
weathercheck : 1,
sodcheck : 1,
neighborcheck : 1,
location : "",
rdate : Ti.App.Properties.getString('MapFilter.Days.NumberOfDays', "ALL"),
ctype : Ti.App.Properties.getString('MapFilter.Categories.EnabledCategories', '4,1,2,3,5,6,7,9,10,11,12,13,14,15,16,18,19')
}
};
APP.http.request(dataTemp, function(_result) {
//Ti.API.info("-->"+JSON.stringify(_result));
if (_result._result == 1) {
if (_result._data.errorcode == 0) {
var tempCrimeList = _result._data.data;
var tempCrimeAnno = [];
for (var i = 0; i < tempCrimeList.length; i++) {
//Ti.API.info(JSON.stringify(_result._data.data[i]));
var tempImage = tempCrimeList[i].ncticon.slice(19, -4) + '.png';
tempImage = tempImage.split("/");
var alertImage = "/images/Crimes/" + tempImage[tempImage.length - 1];
tempCrimeList[ i ].image = alertImage;
// image
//Ti.API.info(alertImage);
if (tempCrimeList[i].cdtype == "Weather" || tempCrimeList[i].cdtype === 'Sex Offender')// URL
var baseurl = tempCrimeList[i].url;
else if (tempCrimeList[i].cdtype == "Neighbor") {
var baseurl = 'http://alertid.com/commmore.asp?athread=' + tempCrimeList[i].pkcrimedata;
baseurl = "Neighbor";
} else
var baseurl = 'http://alertid.com/commmore.asp?cdid=' + tempCrimeList[i].pkcrimedata;
tempCrimeAnno.push({
anno : map.createAnnotation({
latitude : _result._data.data[i].cdlat,
longitude : _result._data.data[i].cdlon,
title : _result._data.data[i].ncttype,
subtitle : _result._data.data[i].cddatetime + " - " + tempCrimeList[i].miles + " miles away " + tempCrimeList[i].cdagency,
pincolor : Titanium.Map.ANNOTATION_RED,
animate : true,
rightButton : alertImage,
image : alertImage,
crimeid : _result._data.data[i].pkcrimedata,
url : baseurl
})
});
$.mapView.addAnnotation(tempCrimeAnno[i].anno);
}
getAlerts(_event,function( alertsData ){
setListView( alertsData , tempCrimeList , tempCrimeAnno );
return true;
});
APP.hideActivityindicator();
} else {
//alert(_result._data.message);
//alert("No messages were found.");
APP.hideActivityindicator();
}
} else {
APP.hideActivityindicator();
// alert("Internet connection error, please try again..");
}
});
//}else{
// APP.hideActivityindicator();
//}
}
function openListView(_forceClose) {
if (_forceClose == true) {
$.listView.isOpen = true;
} else {
openSettings(true);
}
if ($.listView.isOpen) {
if (OS_IOS) {
$.listView.animate({
right : APP.numberOperation(-$.mapView.size.width, "-", 0, false),
duration : 150
});
}
$.listView.animate({
top : APP.numberOperation($.mapView.size.height, "+", 20, false),
duration : 150
});
} else {
if (OS_IOS) {
$.listView.animate({
right : 20,
duration : 150
});
}
$.listView.animate({
top : 64,
duration : 150
});
}
$.listView.isOpen = !$.listView.isOpen;
}
function openSettings( _forceClose ){
APP.popOut();
if (_forceClose == true) {
$.settingsView.isOpen = true;
} else {
openListView(true);
}
if ($.settingsView.isOpen) {
if (OS_IOS) {
$.settingsView.animate({
left : APP.numberOperation(-$.mapView.size.width, "-", 0, false),
duration : 150
});
$.typesView.animate({
left : APP.numberOperation(-$.mapView.size.width, "-", 0, false),
duration : 150
});
}
$.settingsView.animate({
top : APP.numberOperation($.mapView.size.height, "+", 20, false),
duration : 150
});
$.typesView.animate({
top : APP.numberOperation($.mapView.size.height, "+", 20, false),
duration : 150
});
} else {
if (OS_IOS) {
$.settingsView.animate({
left : 20,
duration : 150
});
$.typesView.animate({
left : 20,
duration : 150
});
}
$.settingsView.animate({
top : 64,
duration : 150
});
$.typesView.animate({
top : 64,
duration : 150
});
}
$.settingsView.isOpen = !$.settingsView.isOpen;
}
function searchAddress(_address) {
if (APP.getToken({openLogin : false})) {
APP.showActivityindicator();
var dataTemp = {
url : "http://maps.google.com/maps/api/geocode/json?address=" + _address + "&sensor=true",
type : 'GET',
format : 'JSON'
};
// Ti.API.info('dataTemp:'+JSON.stringify(dataTemp));
APP.http.request(dataTemp, function(_result) {
//Ti.API.info("-->"+JSON.stringify(_result._data));
if (_result._result == 1) {
if (_result._data.results.length > 0) {
getCrimes({
lat : _result._data.results[0].geometry.location.lat,
lon : _result._data.results[0].geometry.location.lng,
faname : _address
});
APP.openCloseOptions();
} else {
//alert(_result._data.message);
// alert("No messages were found.");
APP.hideActivityindicator();
}
} else {
//alert("Internet connection error, please try again.");
APP.hideActivityindicator();
}
});
}
//xhrGeocode.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
}
function selectDays() {
//Ti.API.info(Ti.App.Properties.getString('MapFilter.Days.NumberOfDays'));
var daysSelectDialog = Titanium.UI.createOptionDialog({
title : 'Select Days Filter',
options : ['Last 24 hours', 'Last 3 days', 'Last 7 days', 'Last 30 days', 'Last 90 days', 'All days'],
cancel : -1
});
daysSelectDialog.addEventListener('click', function(e) {
if (e.index >= 0) {
//Ti.App.Properties.setString('MapFilter.Days.NumberOfDays', days[e.index].filterID);
$.daysLabel.text = "Show: " + days[e.index].title;
getCrimes({
lat : latitude,
lon : longitude
});
}
});
daysSelectDialog.show();
}
function selectRegion() {
var zoomSelectDialog = Titanium.UI.createOptionDialog({
title : 'Select Region',
options : ['Neighborhood', 'Community', 'City'],
cancel : -1
});
zoomSelectDialog.addEventListener('click', function(e) {
if (e.index >= 0) {
if (OS_ANDROID) {
if (e.index === 0) {
latitudeDelta = 0.01;
longitudeDelta = 0.01;
$.regionLabel.text = "Region: Neighborhood";
} else if (e.index === 1) {
latitudeDelta = 0.04;
longitudeDelta = 0.04;
$.regionLabel.text = "Region: Community";
} else if (e.index === 2) {
latitudeDelta = 0.001;
longitudeDelta = 0.001;
$.regionLabel.text = "Region: City";
}
} else {
if (e.index === 0) {
latitudeDelta = 0.02;
longitudeDelta = 0.02;
$.regionLabel.text = "Region: Neighborhood";
} else if (e.index === 1) {
latitudeDelta = 0.04;
longitudeDelta = 0.04;
$.regionLabel.text = "Region: Community";
} else if (e.index === 2) {
latitudeDelta = 0.17;
longitudeDelta = 0.18;
$.regionLabel.text = "Region: City";
}
}
$.mapView.setRegion({
latitude : latitude,
longitude : longitude,
animate : true,
latitudeDelta : latitudeDelta,
longitudeDelta : longitudeDelta
});
}
});
zoomSelectDialog.show();
}
function setHybView() {
$.mapView.setMapType(Titanium.Map.HYBRID_TYPE);
}
function setListView( alerts_data , advisors_data , advisors_annotations ){
$.listView.remove( $.tableAlerts );
$.tableAlerts = Alloy.createController('MyAlerts/TableAlerts',{
map : $.mapView,
alerts_data : alerts_data,
advisors_data : advisors_data,
advisors_annotations : advisors_annotations,
openListView : function(){
openListView();
return true;
}
}).getView();
$.listView.add( $.tableAlerts );
}
function setSatView() {
$.mapView.setMapType(Titanium.Map.SATELLITE_TYPE);
}
function setStandView() {
$.mapView.setMapType(Titanium.Map.STANDARD_TYPE);
}
function setTrafficView(){
if(OS_IOS){
APP.openWindow({controller:"MyAlerts/TrafficView",controllerParams:{title:"Traffic View",lat:latitude,lon:longitude}});
}else{
$.mapView.setTraffic(!$.mapView.getTraffic());
}
}
function updateView() {
APP.headerbar.removeAllCustomViews()
APP.headerbar.setLeftButton(0, false);
APP.headerbar.setRightButton(0, false);
APP.headerbar.setLeftButton(APP.OPENMENU, true);
APP.headerbar.setRightButton(APP.OPENOPTIONS, true, {}, 1);
APP.headerbar.setTitle("My Alerts");
APP.optionbar.changeView(1, function() {
APP.openWindow({
controller : 'Settings/EditAddress',
controllerParams : {
callback : function() {
APP.optionbar.updateMyAddresses();
}
}
});
});
if(!APP.getToken({openLogin : false})){
$.alertsTitle.text = "";
_isLogged = false;
}else{
if(_isLogged == false){
currentPosition();
}
_isLogged = true;
}
return true;
}
function refreshMap(){
if(APP.getToken({openLogin : true})){
getCrimes({lat:_updateLatitude,lon:_updateLongitude});
}
}
function initializeView(){
APP.optionbar.changeView(1, function() {
APP.openWindow({
controller : 'Settings/EditAddress',
controllerParams : {
callback : function() {
APP.optionbar.updateMyAddresses();
}
}
});
});
currentPosition();
}
// CODE
currentPosition();
$.alertsTitleContainer.top = 43 + APP.fixSizeIos7();
$.refreshMap.top = 78 + APP.fixSizeIos7();
$.settingsView.isOpen = false;
$.typesView.isOpen = true;
$.listView.isOpen = false;
var tempFilters = Ti.App.Properties.getString('MapFilter.Categories.EnabledCategories', '4,1,2,3,5,6,7,9,10,11,12,13,14,15,16,18,19');
var regString = new RegExp("," + $.fsw2.filterID + "\\b", "g");
$.fsw2.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw3.filterID + "\\b", "g");
$.fsw3.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw4.filterID + "\\b", "g");
$.fsw4.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw5.filterID + "\\b", "g");
$.fsw5.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw6.filterID + "\\b", "g");
$.fsw6.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw7.filterID + "\\b", "g");
$.fsw7.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw8.filterID + "\\b", "g");
$.fsw8.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw9.filterID + "\\b", "g");
$.fsw9.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw10.filterID + "\\b", "g");
$.fsw10.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw11.filterID + "\\b", "g");
$.fsw11.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw12.filterID + "\\b", "g");
$.fsw12.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw13.filterID + "\\b", "g");
$.fsw13.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw14.filterID + "\\b", "g");
$.fsw14.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw15.filterID + "\\b", "g");
$.fsw15.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw16.filterID + "\\b", "g");
$.fsw16.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
var regString = new RegExp("," + $.fsw17.filterID + "\\b", "g");
$.fsw17.value = (tempFilters.match(regString) != null && tempFilters.match(regString).length > 0) ? true : false;
if (tempFilters.length >= 2) {
$.fsw0.value = true;
} else {
$.fsw0.value = false;
}
// LISTENERS
$.mapView.addEventListener("postlayout", function() {
var tempWidth = $.mapView.size.width;
var tempHeight = $.mapView.size.height;
if (OS_IOS) {
$.settingsView.opacity = 0.8;
}
$.settingsView.width = APP.numberOperation(tempWidth, "-", 36, false);
$.settingsView.height = APP.numberOperation(tempHeight, "-", 144, false);
$.settingsView.left = (OS_ANDROID) ? 20 : APP.numberOperation(-tempWidth, "-", 0, false);
$.settingsView.top = APP.numberOperation(tempHeight, "+", 20, false);
$.typesView.width = APP.numberOperation(tempWidth, "-", 36, false);
$.typesView.height = APP.numberOperation(tempHeight, "-", 144, false);
$.typesView.left = (OS_ANDROID) ? 20 : APP.numberOperation(-tempWidth, "-", 0, false);
$.typesView.top = APP.numberOperation(tempHeight, "+", 20, false);
$.listView.width = APP.numberOperation(tempWidth, "-", 40, false);
$.listView.height = APP.numberOperation(tempHeight, "-", 144, false);
$.listView.right = (OS_ANDROID) ? 20 : APP.numberOperation(-tempWidth, "-", 0, false);
$.listView.top = APP.numberOperation(tempHeight, "+", 20, false);
});
$.mapView.addEventListener('click', function(evt) {
//Ti.API.info(evt.annotation.crimeid);
var annotation = evt.annotation;
var url = (evt.annotation) ? evt.annotation.url : 'http://alertid.com/our-story.asp';
if (evt.clicksource === 'subtitle' || evt.clicksource === 'leftButton' || evt.clicksource === 'annotation' || evt.clicksource === 'rightButton' || evt.clicksource === 'title') {
if (url == "Neighbor") {
APP.openWindow({controller:"MyNeighborhoods/MyNeighborhoods",controllerParams:{pknmessage:annotation.crimeid}});
} else {
APP.openWindow({
controller : 'Widgets/Browser',
controllerParams : {
url : url,
title : evt.annotation.title
}
});
}
}
});
$.mapView.addEventListener('regionChanged', function(e){
//Ti.API.info(JSON.stringify(e));
_updateLatitude = e.latitude;
_updateLongitude = e.longitude;
});
// EXPORTS
exports.updateView = updateView;
exports.getCrimes = getCrimes;
exports.currentPosition = currentPosition;
exports.searchAddress = searchAddress;
exports.initializeView = initializeView;
|
/**
* Created by Kriku on 16.03.2016.
*/
(function ($) {
$(function () {
var users = JSON.parse(localStorage.users);
for (var key in users) {
if (users.hasOwnProperty(key) && users[key].student == 'true') {
$('#students tbody').append('<tr><td>{0}</td><td><div class="waves-effect waves-green btn green darken-2 grades-button" data-user="{0}">Edit grades</div></td><td><div class="waves-effect waves-green btn green darken-2 statistics-button">Show statistics</div></td></tr>'
.format(key));
}
}
$('#students').DataTable({
"bLengthChange": false,
"bInfo": false
});
$('#students tbody').on('click', '.grades-button', function(event) {
localStorage.toDisplay = $(event.target).attr('data-user');
$main.load('html/in/grades.html');
});
$('#students tbody').on('click', '.statistics-button', function(event) {
$main.load('html/in/statistics.html');
});
});
})(jQuery);
|
import React from 'react';
import ReactDOM from 'react-dom';
import 'reset-css';
import './scss/main.scss';
import Header from './component/Header';
import Nav from './component/Nav'
import Main from './component/Main'
import AboutMe from './component/AboutMe'
import { Route, HashRouter as Router, Switch } from 'react-router-dom';
import Calendar from './component/Calendary';
import Footer from './component/Footer';
const Index = () => {
return(
<>
<Nav />
<Header />
<Main />
<AboutMe />
<Footer />
</>
)
}
const App = () => {
return (
<>
<Nav />
<Calendar />
</>
)
}
const ReactRouter = () => {
return (
<Router>
<Switch>
<Route exact path='/' component={Index} />
<Route exact path='/termin' component={App} />
</Switch>
</Router>
)
}
ReactDOM.render(
<ReactRouter />
,
document.getElementById('root')
);
|
require('../typedefs');
const core = require("@actions/core");
const { getExportValue, suggest } = require('../util');
/**
* Requires the use of | instead of + to combine jwt access flags
* @param {Deployment} deployment
*
* @returns {Array<Result>}
*/
async function jwtAccessFlags(deployment) {
if (!deployment.ordersContents) {
console.log(`No Orders Present - Skipping ${deployment.serviceName}`);
return [];
}
console.log(`JWT Access Flags - ${deployment.ordersPath}`);
/** @type {Array<Result>} */
const results = [];
for (let i = 0; i < deployment.ordersContents.length; i++) {
const line = deployment.ordersContents[i];
const accessFlags = getExportValue(line, "JWT_ACCESS_FLAGS");
if (accessFlags && accessFlags.includes("+")) {
results.push({
title: "Syntax Error in JWT_ACCESS_FLAGS",
problems: [suggest("Use a `|` instead", line.replace(/\+/g, "|"))],
line: i + 1,
level: "failure",
});
}
}
return results;
}
module.exports = jwtAccessFlags;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.