text
stringlengths 7
3.69M
|
|---|
angular.module('housing.search', [])
.controller('SearchController', function($scope, $location, Service) {
$scope.search = function() {
// Service.sendSearch($scope.location, $scope.term, $scope.budget).then(function() {
// $location.path('/result')
// });
$location.path('/result')
}
})
|
import { createGlobalStyle } from "styled-components"
const GlobalStyle = createGlobalStyle`
html {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
${(props) => props.theme.fluidType(0)};
* { box-sizing: border-box; }
}
body {
margin: 0;
// Use system fonts: https://css-tricks.com/snippets/css/system-font-stack/
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
color: ${(props) => props.theme.colours.black};
background-color: ${(props) => props.theme.colours.white};
}
h1, h2, h3, h4, h5, h6,
.h1, .h2, .h3, .h4, .h5, .h6 {
line-height: 1.1;
margin-top: 1rem;
margin-bottom: 1rem;
}
p,
ol, ul, li,
code, kbd, pre, samp {
line-height: 1.5;
margin-top: 0.8rem;
margin-bottom: 0.8rem;
}
h1, h2, h3, h4, h5, h6,
.h1, .h2, .h3, .h4, .h5, .h6 {
font-weight: bold;
a { text-decoration: none; }
a:hover { text-decoration: none; }
}
h1, .h1 { ${(props) => props.theme.fluidType(4)}; }
h2, .h2 { ${(props) => props.theme.fluidType(3)}; }
h3, .h3 { ${(props) => props.theme.fluidType(2)}; }
h4, .h4 { ${(props) => props.theme.fluidType(1)}; }
h5, .h5 { ${(props) => props.theme.fluidType(0)}; }
h6, .h6 { ${(props) => props.theme.fluidType(-1)}; }
li {
margin-top: 0;
margin-bottom: 0;
}
small, p.small { ${(props) => props.theme.fluidType(-1)}; }
code, kbd, pre, samp {
font-family: monospace;
white-space: normal;
}
ul {
padding-left: 1rem;
list-style-type: disc;
}
ol {
padding-left: 1rem;
list-style-type: decimal;
}
video {
width: 100%;
height: auto;
margin-bottom: 1rem;
}
// Specific to PrismicRichText component
.block-img {
img {
width: 100%;
height: auto;
display: block;
margin: 3rem 0;
}
}
// Specific to PrismicRichText component
.embed {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
margin: 3rem 0;
iframe,
object,
embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
em, i { font-style: italic; }
strong, b { font-weight: bold; }
blockquote {
font-weight: bold;
padding-left: 1rem;
}
a { color: inherit; }
sup, sub {
vertical-align: baseline;
position: relative;
top: -0.4em;
}
sub { top: 0.4em; }
label {
${(props) => props.theme.fluidType(-1)};
line-height: 1.2;
font-weight: normal;
}
.fieldset {
margin: 0.5rem 0;
}
.text-input,
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime-local"],
input[type="email"],
input[type="month"],
input[type="number"],
input[type="range"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
input[type="week"],
textarea {
display: block;
font-family:inherit;
${(props) => props.theme.fluidType(0)};
padding: 0.2rem 0.5rem;
margin-top: 1rem;
margin-bottom: 1rem;
border: 1px solid;
border-radius: 2px;
line-height: 1.6;
background-color: transparent;
-webkit-appearance: none;
&:focus {
border: 1px ${(props) => props.theme.colours.focus} solid;
}
}
::placeholder {
color: ${props => props.theme.colours.black};
opacity: 0.6;
}
.file-input,
input[type="file"],
.radio-input,
input[type="radio"],
.checkbox-input,
input[type="checkbox"],
select {
font-family:inherit;
}
// Select
select {
// A reset of styles, including removing the default dropdown arrow
appearance: none;
// Additional resets for further consistency
background-color: transparent;
border: none;
padding: 0;
margin: 0;
width: 100%;
height: 2rem;
font-family: inherit;
font-size: inherit;
cursor: inherit;
line-height: inherit;
outline: none;
color: ${props => props.theme.colours.black};
}
select::-ms-expand {
display: none;
}
.fieldset.select {
width: 100%;
border-bottom: 1px solid;
border-radius: 0;
padding: 0;
margin: 0.5rem 0 1.5rem 0;
${props => props.theme.fluidType( 0 )};
cursor: pointer;
line-height: 1.1;
background-color: transparent;
grid-template-areas: "select";
display: grid;
align-items: center;
max-width: 15rem;
&:after {
content: "";
width: 0.8rem;
height: 0.5rem;
background-color: ${props => props.theme.colours.black};
clip-path: polygon(100% 0%, 0 0%, 50% 100%);
justify-self: end;
}
select,
&:after {
grid-area: select;
}
}
.button,
button,
input[type="submit"],
input[type="button"],
input[type="reset"] {
display: inline-block;
padding: 0 1rem;
font-family:inherit;
${(props) => props.theme.fluidType(0)};
line-height: 2;
text-decoration: none;
white-space: nowrap;
border: 1px solid;
border-radius: 2px;
color: inherit;
background-color: transparent;
&:hover {
text-decoration: none;
}
&.link {
border: none;
padding: 0;
background-color: transparent;
}
&.icon {
border: none;
padding: 0;
background-color: transparent;
svg {
height: 3rem;
width: auto;
display: block;
}
}
}
.errorMsg {
color: ${(props) => props.theme.colours.error};
}
`
export default GlobalStyle
|
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
const options = {
// we init with resources
resources: {
en: {
translations: {
// url
urlalacarte: "alacarte",
urlsupper: "supper",
urlgallery: "gallery",
urlcontact: "contact",
urlcombo: "combo",
// navbar
menu: "Menu",
alacarte: "À la carte",
supper: "Supper",
gallery: "Gallery",
contact: "Contact",
combo: "Combo",
// home
introtext1:
"At Sasa Sushi, we are always looking for something new and better.",
// introtext2:
// "According to the inspiration of the moment and fresh ingredients found at the market, our chef creates new dishes or can develop tasting menus.",
introtext3:
"We would like to inform you that our restaurant will be closed from December 25 to December 30. We will be open again on December 31. We wish you a happy holiday season.",
// footer
addresstitle: "Location",
address1: "71 Chemin St-Francois-Xavier",
address2: "Candiac, QC J5R 4V4",
hourstitle: "Hours",
// hours1: "Lunch | Tuesday - Friday | 11:30pm - 2pm",
hours2: "Supper | Wednesday - Saturday | 4:00PM - 8:00PM",
// hours3: "Supper | Thursday, Friday, Saturday | 5pm - 9pm",
contacttitle: "Contact",
contact1: "450.632.0559",
// sidebar
sbalacarte: "À LA CARTE",
sbsupper: "SUPPER",
sbcombo: "COMBO",
// a la carte
catdesc1:
"(Choice of either Nigiri (2pcs) or Sashimi (2pcs or 3pcs indicated by *) unless stated otherwise)",
maguro: "Tuna",
albacore: "White Tuna",
hamachi: "Yellowtail",
sake: "Salmon",
shiromi: "White Fish",
shimesaba: "Mackerel",
karamehotategai: "Scallop, Caviar, Strawberry, Scallion, Spicy Mayo",
hotategai: "Scallop",
sunrise: "Caviar, Scallop",
tobiko: "Flying Fish Roe",
massago: "Smelt Roe",
sushitempura: "Shrimp Tempura, Teriyaki Sauce",
sakekunsei: "Smoked Salmon",
ebi: "Shrimp",
unagi: "Freshwater Eel",
kanikama: "Crab Stick",
tako: "Octopus",
nigirionly: "(Nigiri Only)",
grilledsalmonskintitle: "Grilled Salmon Skin",
grilledsalmonskin: "Grilled Salmon Skin, Cucumber",
sakemakititle: "Sake Maki (6pcs)",
sakemaki: "Salmon Roll",
tekkamakititle: "Tekka Maki (6pcs)",
tekkamaki: "Tuna Roll",
unakyutitle: "Unakyu (6pcs)",
unakyu: "Eel, Cucumber",
karamesabatitle: "Karame Saba (6pcs)",
karamesaba: "Mackerel, Caviar, Scallion, Jalapeno Sauce",
karamesaketitle: "Karame Sake (6pcs)",
karamesake: "Salmon, Caviar, Scallion, Spicy Mayo",
karamemagurotitle: "Karame Maguro (6pcs)",
karamemaguro: "Tuna, Caviar, Scallion, Spicy Mayo",
karamenerihamachititle: "Karame Neri Hamachi (6pcs)",
karamenerihamachi: "Yellowtail, Caviar, Scallion, Spicy Mayo",
bostontitle: "Boston (5pcs)",
boston: "Shrimp, Crab Stick, Cucumber, Lettuce, Mayo",
newyorktitle: "New York (5pcs)",
newyork: "Caviar, Crab Stick, Cucumber, Lettuce, Mayo",
californiatitle: "California (5pcs)",
california: "Caviar, Crab Stick, Cucumber, Avocado, Mayo",
kamikazetitle: "Kamikaze (5pcs)",
kamikaze: "Avocado, Cucumber, Tempura, Scallion, Spicy Mayo",
tempurarolltitle: "Tempura (4pcs)",
tempuraroll: "Shrimp, Salmon, Scallion (Fried Roll)",
phillytitle: "Philly (5pcs)",
philly:
"Smoked Salmon, Caviar, Cucumber, Spinach, Scallion Tempura, Cream Cheese",
toritorititle: "Tori Tori (5pcs)",
toritori:
"Chicken Katsu, Caviar, Avocado, Cucumber, Tempura, Scallion, Spicy Mayo",
threeamigostitle: "Three Amigos (5pcs)",
threeamigos: "Three Types of Fish, Caviar, Scallion, Jalapeno Sauce",
quebectitle: "Québec (5pcs)",
quebec:
"Shrimp Tempura, Crab Stick, Avocado, Scallion Tempura, Spicy Mayo",
montrealtitle: "Montréal (5pcs)",
montreal: "Salmon, White Fish, Carrot, Scallion (Fried Roll)",
twistertitle: "Twister (5pcs)",
twister: "Shrimp, Udon, Carrot, Scallion (Fried Roll)",
sasaducheftitle: "Sasa du Chef (6pcs)",
sasaduchef: "Scallop Katsu, Caviar, Strawberry, Asparagus, Mayo",
nijimakititle: "Niji (5pcs)",
nijimaki:
"Tuna, Salmon, Crab Stick, Caviar, Avocado, Cucumber, Spicy Mayo",
elninotitle: "El Nino (5pcs)",
elnino: "White Tuna, Eggplant Tempura, Caviar, Jalapeno Sauce",
alohatitle: "Aloha (5pcs)",
aloha: "Tuna, Caviar, Mango, Tempura, Scallion, Spicy Mayo",
volcanotitle: "Volcano (5pcs)",
volcano: "Grilled Mackerel, Sun-dried Tomato, Caviar, Jalapeno Sauce",
eyeofthetigertitle: "Eye of the Tiger (5pcs)",
eyeofthetiger: "Three Types of Fish Tempura, Spinach Tempura, Caviar",
spidertitle: "Spider (5pcs)",
spider: "Fried Soft-shell Crab, Caviar, Avocado, Cucumber, Spicy Mayo",
zentitle: "Zen (5pcs)",
zen: "Nori Tempura, Eel, Crab Stick, Caviar, Avocado, Scallion",
karamelobstertitle: "Karame Lobster (5pcs)",
karamelobster: "Lobster Tempura, Caviar, Avocado, Spicy Mayo",
dragoneyetitle: "Dragon Eye (6pcs)",
dragoneye: "Salmon, White Fish, Carrot, Scallion (Fried Roll)",
cattitle3: "Veggie Maki",
kappamakititle: "Kappa (6pcs)",
kappamaki: "Cucumber Roll",
avocadomakititle: "Avocado (6pcs)",
avocadomaki: "Avocado Roll",
oshinkotitle: "Oshinko (6pcs)",
oshinko: "Marinated Radish, Cucumber",
yasaimakititle: "Yasai (5pcs)",
yasaimaki: "Steamed Vegetables",
shoujinagetitle: "Shoujin Age (5pcs)",
shoujinage: "Vegetable Tempura",
sicilititle: "Sicili (5pcs)",
sicili: "Saute Vegetables",
cattitle4: "Sasa Sushi Speciality",
tunaspecialtitle: "Tuna Special",
tunaspecial:
"Pieces of Tuna Lightly Fried, Caviar, Scallion, Special Mayo",
lanina: "Fried Eggplant, White Tuna, Caviar, Jalapeno Sauce",
avalanche: "Grilled Mackerel, Sun-dried Tomato, Caviar, Jalapeno Sauce",
soleilcandiactitle: "Soleil Candiac (8pcs)",
soleilcandiac: "Salmon, Spicy Salmon, Caviar, Avocado",
francemakititle: "France (8pcs)",
francemaki:
"Salmon, White Fish, Shrimp Tempura, Caviar, Avocado, Mango, Scallion",
pizzatitle: "Pizza (4pcs)",
pizza:
"Homemade Rice Cracker, Smoked Salmon, Crab Stick, Avocado, Cucumber, Mayo",
caterpillartitle: "Caterpillar (6pcs)",
caterpillar:
"Shrimp Tempura, Salmon, Crab Stick, Avocado, Marinated Rice",
labelletitle: "La Belle (8pcs)",
labelle: "Tuna, Caviar, Asparagus, Scallion, Spicy Mayo",
labetetitle: "La Bête (6pcs)",
labete: "Salmon, Caviar, Asparagus (Lightly Fried Roll)",
reddragontitle: "Red Dragon (8pcs)",
reddragon:
"Panko Shrimp, Tuna, Caviar, Crab Stick, Cucumber, Spicy Mayo",
clementinetitle: "Clementine (8pcs)",
clementine:
"Panko Shrimp, Salmon, Caviar, Crab Stick, Avocado, Spicy Mayo",
dragontitle: "Green Dragon (8pcs)",
dragon: "Eel, Crab Stick, Tempura, Caviar, Avocado, Cucumber",
trustmetitle: "Trust Me (5pcs)",
trustme: "Eel, Shrimp Tempura, Caviar, Tempura, Avocado",
yinyangtitle: "Yin Yang (5pcs)",
yinyang:
"Tuna, Salmon, Caviar, Special Avocado Sauce (Lightly Grilled Roll)",
cattitle5: "Rice Paper Roll",
catdesc5: "(Served with Special Sauce)",
indochinetitle: "Indochine (6pcs)",
indochine: "Salmon, Crab Stick, Caviar, Lettuce, Cucumber",
illusiontitle: "Illusion (6pcs)",
illusion: "Shrimp, Caviar, Mixed Salad, Cucumber",
fantasiatitle: "Fantasia (6pcs)",
fantasia: "Shrimp Tempura, Sweet Potato Tempura, Mixed Salad",
exoticatitle: "Exotica (6pcs)",
exotica:
"Smoked Salmon, Caviar, Strawberry, Mango, Cucumber, Mixed Salad",
voiliertitle: "Voilier (6pcs)",
voilier: "Grilled Shrimp, Red Pepper, Caviar, Vermicelli, Mixed Salad",
passiontitle: "Passion (6pcs)",
passion:
"Shrimp, Crab Stick, Caviar, Mango, Cucumber, Vermicelli, Mixed Salad",
amoureuxtitle: "Amoureux (6pcs)",
amoureux:
"Salmon & Crab Stick Panko, Caviar, Cucumber, Vermicelli, Mixed Salad",
nuetitle: "Nue (5pcs)",
nue: "Vegetable Tempura, Shrimp, Caviar, Avocado",
// combo
comboroll: "Combo Roll",
comboonetitle: "Combo 1 (26pcs)",
comboonelist: "Dragon Eye, Québec, California, Chef's Roll, Kappa",
combotwotitle: "Combo 2 (26pcs)",
combotwolist: "Kamikaze, Aloha, Chef's Roll, Sake Maki, Yasai",
combothreetitle: "Combo 3 (52pcs)",
combothreelist: "2 Kamikaze, 2 Aloha, 2 Chef's Roll, 2 Québec, 2 Yasai",
combofourtitle: "Combo 4 (96pcs)",
combofourlist:
"2 Kamikaze, 2 Aloha, 2 Dragon Eye, 2 Québec, 2 Chef's Roll, 2 New York, 2 Boston, 2 Sake Maki, 2 Yasai Maki",
// lunch
appetizer: "Appetizer",
yakitori: "Grilled chicken skewers served with teriyaki sauce",
gyoza: "Japanese dumplings served with house sauce",
vegetabletempuratitle: "Vegetable Tempura",
vegetabletempura: "Deep fried vegetables served with tempura sauce",
hotmeals: "Hot Meals",
hotmealsdesc: "(Served with miso soup or salad, rice included)",
chickenkatsutitle: "Chicken Katsu",
chickenkatsu: "Fried breaded chicken served with katsu sauce",
teriyaki:
"Grilled dish garnished with vegetables served with teriyaki sauce",
chicken: "Chicken",
salmon: "Salmon",
steak: "Steak",
tempura: "Deep fried shrimps & vegetables served with tempura sauce",
sasaspecial:
"Grilled chicken brochettes, deep fried shrimps and vegetables served with teriyaki sauce",
sushicombodesc: "(Served with miso soup or salad)",
sushimoriowase:
"Assortment of raw fish and shellfish sushi & a Kamikaze maki",
sashimiandmaki: "Assortment of raw fish sashimi served with rice",
withoutrice: "without Rice",
withrice: "with Rice",
makicombo: "Combo of Kamikaze & California",
// dinner
harumaki:
"Japanese spring roll wrapped with shrimp, pork, and vegetables",
dinnerpizza:
"Rice cake topped with smoked salmon, crab stick, avocado, cucumber, and mayo",
dinnerlanina:
"Deep fried eggplant topped with lightly grilled white tuna, caviar, and jalapeno sauce",
dinneravalanche:
"Grilled mackerel and sun-dried tomato topped with caviar, and jalapeno sauce",
tunasteaktitle: "Tuna Steak",
tunasteak: "Lightly grilled tuna served with special sauce",
dinnertunaspecialtitle: "Tuna Special",
dinnertunaspecial:
"Lightly fried tuna topped with caviar, scallion, and special sauce",
soup: "Soup",
misoshiru: "White soybean paste soup",
seafoodmisotitle: "Seafood Miso",
seafoodmiso: "Seafood miso soup",
sumashi: "Chicken broth with seafood",
udon: "Shrimp broth with noodles",
vegetarian: "Vegetarian",
shrimptempura: "Shrimp Tempura",
salad: "Salad",
mixedsaladtitle: "Mixed Salad",
mixedsalad: "Mixed salad served with house dressing",
ohitashi: "Steamed spinach served with sesame sauce",
seafoodsaladtitle: "Seafood Salad",
seafoodsalad:
"Mixed salad with smoked salmon, shrimp, and crab stick served with house dressing",
dinnerhotmealsdesc: "(Served with rice)",
seafood: "Seafood",
shrimp: "Shrimp",
seafoodyakiudontitle: "Seafood Yaki Udon",
seafoodyakiudon:
"Stir fry shrimps and scallops with shichimi spice, served with yaki udon (spicy)",
assortedsushititle: "Assorted Sushi (16pcs)",
assortedsushi: "6 nigiri sushi & 10 pieces of maki roll",
sushisashimititle: "Sushi & Sashimi (17pcs)",
sushisashimi: "5 nigiri, 6 pieces of sashimi & 6 pieces of maki roll",
sashimititle: "Sashimi (16pcs)",
sashimi: "16 pieces of sashimi served with rice",
notincluded: "Soup or Salad is not included for takeout orders.",
},
},
fr: {
translations: {
// url
urlalacarte: "alacarte",
urlsupper: "souper",
urlgallery: "galerie",
urlcontact: "contact",
urlcombo: "combo",
// navbar
menu: "Menu",
alacarte: "À la carte",
supper: "Souper",
gallery: "Galerie",
contact: "Contact",
combo: "Combo",
// home
introtext1:
"Chez Sasa Sushi, nous cherchons sans cesse à vous faire profiter de ce qu'il y a de nouveau et de meilleur.",
// introtext2:
// "Selon l'inspiration du moment et les ingrédients frais trouvés au marché, notre chef crée de nouveaux plats ou peut élaborer des menus de dégustation.",
introtext3:
"Nous tenons à vous informer que notre restaurant sera fermé du 25 Décembre au 30 Décembre. Nous serons de nouveau ouverts le 31 Décembre. Nous vous souhaitons de passer de bonne fêtes de fin d'année.",
// footer
addresstitle: "Location",
address1: "71 Chemin St-Francois-Xavier",
address2: "Candiac, QC J5R 4V4",
hourstitle: "Heures",
// hours1: "Dîner | Mardi - Vendredi | 11:30pm - 2pm",
hours2: "Souper | Mercredi - Samedi | 4:00PM - 8:00PM",
// hours3: "Souper | Jeudi, Vendredi, Samedi | 5pm - 9pm",
contacttitle: "Contact",
contact1: "450.632.0559",
// sidebar
sbalacarte: "À LA CARTE",
sbsupper: "SOUPER",
sbcombo: "COMBO",
// a la carte
catdesc1:
"(Choix entre Nigiri (2mcx) ou Sashimi (2mcx ou 3mcx indiqués par *) sauf indication contraire)",
maguro: "Thon",
albacore: "Thon Blanc",
hamachi: "Thon à Queue Jaune",
sake: "Saumon",
shiromi: "Poisson Blanc",
shimesaba: "Maquereau",
karamehotategai: "Pétoncle, Caviar, Fraise, Oignon Vert, Mayo Épicée",
hotategai: "Pétoncle",
sunrise: "Caviar, Pétoncle",
tobiko: "Oeuf de Poisson Volant",
massago: "Oeufs d'Éperlan",
sushitempura: "Crevette Tempura, Sauce Teriyaki",
sakekunsei: "Saumon Fumée",
ebi: "Crevette",
unagi: "Anguille",
kanikama: "Imitation de Crabe",
tako: "Pieuvre",
nigirionly: "(Nigiri Seulement)",
grilledsalmonskintitle: "Peau de Saumon Grillé (6mcx)",
grilledsalmonskin: "Peau de Saumon Grillé, Concombre",
sakemakititle: "Sake Maki (6mcx)",
sakemaki: "Rouleau de Saumon",
tekkamakititle: "Tekka Maki (6mcx)",
tekkamaki: "Rouleau de Thon",
unakyutitle: "Unakyu (6mcx)",
unakyu: "Anguille, Concombre",
karamesabatitle: "Karame Saba (6mcx)",
karamesaba: "Maquereau, Caviar, Oignon Vert, Sauce Jalapeno",
karamesaketitle: "Karame Sake (6mcx)",
karamesake: "Saumon, Caviar, Oignon Vert, Mayo Épicée",
karamemagurotitle: "Karame Maguro (6mcx)",
karamemaguro: "Thon, Caviar, Oignon Vert, Mayo Épicée",
karamenerihamachititle: "Karame Neri Hamachi (6mcx)",
karamenerihamachi:
"Thon à Queue Jaune, Caviar, Oignon Vert, Mayo Épicée",
bostontitle: "Boston (5mcx)",
boston: "Crevette, Imitation de Crabe, Concombre, Laitue, Mayo",
newyorktitle: "New York (5mcx)",
newyork: "Caviar, Imitation de Crabe, Concombre, Laitue, Mayo",
californiatitle: "Californie (5mcx)",
california: "Caviar, Imitation de Crabe, Concombre, Avocat, Mayo",
kamikazetitle: "Kamikaze (5mcx)",
kamikaze: "Avocat, Concombre, Tempura, Oignon Vert, Mayo Épicée",
tempurarolltitle: "Tempura (4mcx)",
tempuraroll: "Crevette, Saumon, Oignon Vert (Rouleau Frit)",
phillytitle: "Philly (5mcx)",
philly:
"Saumon Fumée, Caviar, Concombre, Épinard, Oignon Vert Tempura, Fromage à la Crème",
toritorititle: "Tori Tori (5mcx)",
toritori:
"Poulet Katsu, Caviar, Avocat, Concombre, Tempura, Oignon Vert, Mayo Épicée",
threeamigostitle: "Trois Amigos (5mcx)",
threeamigos:
"Trois Sortes de Poissons, Caviar, Oignon Vert, Sauce Jalapeno",
quebectitle: "Québec (5mcx)",
quebec:
"Crevette Tempura, Imitation de Crabe, Avocat, Oignon Vert Tempura, Mayo Épicée",
montrealtitle: "Montréal (5mcx)",
montreal: "Saumon, Poisson Blanc, Carotte, Oignon Vert (Rouleau Frit)",
twistertitle: "Twister (5mcx)",
twister: "Crevette, Udon, Carotte, Oignon Vert (Rouleau Frit)",
sasaducheftitle: "Sasa du Chef (6mcx)",
sasaduchef: "Pétoncle Pané, Caviar, Strawberry, Asperge, Mayo",
nijimakititle: "Niji (5mcx)",
nijimaki:
"Thon, Saumon, Imitation de Crabe, Caviar, Avocat, Concombre, Mayo Épicée",
elninotitle: "El Nino (5mcx)",
elnino: "Thon Blanc, Aubergine Tempura, Caviar, Sauce Jalapeno",
alohatitle: "Aloha (5mcx)",
aloha: "Thon, Caviar, Mangue, Tempura, Oignon Vert, Mayo Épicée",
volcanotitle: "Volcano (5mcx)",
volcano: "Maquereau Grillé, Tomate Séchée, Caviar, Sauce Jalapeno",
eyeofthetigertitle: "Oeil du Tigre (5mcx)",
eyeofthetiger:
"Trois Sortes de Poisson Tempura, Épinard Tempura, Caviar",
spidertitle: "Araignée (5mcx)",
spider:
"Crabe à Carapace Molle Frit, Caviar, Avocat, Concombre, Mayo Épicée",
zentitle: "Zen (5mcx)",
zen:
"Nori Tempura, Anguille, Imitation de Crabe, Caviar, Avocat, Oignon Vert",
karamelobstertitle: "Karame Homard (5mcx)",
karamelobster: "Homard Tempura, Caviar, Avocat, Mayo Épicée",
dragoneyetitle: "Dragon Eye (6mcx)",
dragoneye: "Saumon, Poisson Blanc, Carotte, Oignon Vert (Rouleau Frit)",
cattitle3: "Maki Végétarien",
kappamakititle: "Kappa (6mcx)",
kappamaki: "Rouleau de Concombre",
avocadomakititle: "Avocat (6mcx)",
avocadomaki: "Rouleau d'Avocat",
oshinkotitle: "Oshinko (6mcx)",
oshinko: "Radis Mariné, Concombre",
yasaimakititle: "Yasai (5mcx)",
yasaimaki: "Légume Cuit à la Vapeur",
shoujinagetitle: "Shoujin Age (5mcx)",
shoujinage: "Légume Tempura",
sicilititle: "Sicile (5mcx)",
sicili: "Légumes Sautés",
cattitle4: "Sasa Sushi Spécialité",
tunaspecialtitle: "Thon Spécial",
tunaspecial:
"Morceaux de Thon Légèrement Frit, Caviar, Oignon Vert, Mayo Spécial",
lanina: "Aubergine Frit, Thon Blanc, Caviar, Sauce Jalapeno",
avalanche: "Maquereau Grillé, Tomate Séchée, Caviar, Sauce Jalapeno",
soleilcandiactitle: "Soleil Candiac (8mcx)",
soleilcandiac: "Saumon, Saumon Épicée, Caviar, Avocat",
francemakititle: "France (8mcx)",
francemaki:
"Saumon, Poisson Blanc, Crevette Tempura, Caviar, Avocat, Mangue, Oignon Vert",
pizzatitle: "Pizza (4mcx)",
pizza:
"Galette de Riz, Saumon Fumée, Imitation de Crabe, Avocat, Concombre, Mayo",
caterpillartitle: "Caterpillar (6mcx)",
caterpillar:
"Crevette Tempura, Saumon, Imitation de Crabe, Avocat, Riz Mariné",
labelletitle: "La Belle (8mcx)",
labelle: "Thon, Caviar, Asperge, Oignon Vert, Mayo Épicée",
labetetitle: "La Bête (6mcx)",
labete: "Saumon, Caviar, Asperge (Rouleau Légèrement Frit)",
reddragontitle: "Dragon Rouge (8mcx)",
reddragon:
"Crevette Panée, Thon, Caviar, Imitation de Crabe, Concombre, Mayo Épicée",
clementinetitle: "Clémentine (8pcs)",
clementine:
"Crevette Panée, Saumon, Caviar, Imitation de Crabe, Acvocat, Spicy Mayo",
dragontitle: "Dragon Vert (8mcx)",
dragon:
"Anguille, Imitation de Crabe, Tempura, Caviar, Avocat, Concombre",
trustmetitle: "Crois-moi (5mcx)",
trustme: "Anguille, Crevette Tempura, Caviar, Tempura, Avocat",
yinyangtitle: "Yin Yang (5mcx)",
yinyang:
"Thon, Saumon, Caviar, Sauce Avocat Special (Rouleau Légèrement Grillé)",
cattitle5: "Rouleau de Papier de Riz",
catdesc5: "(Servi avec Sauce Spécial)",
indochinetitle: "Indochine (6mcx)",
indochine: "Saumon, Imitation de Crabe, Caviar, Laitue, Concombre",
illusiontitle: "Illusion (6mcx)",
illusion: "Crevette, Caviar, Salade Mixte, Concombre",
fantasiatitle: "Fantasia (6mcx)",
fantasia: "Crevette Tempura, Patate Douce Tempura, Salade Mixte",
exoticatitle: "Exotica (6mcx)",
exotica:
"Saumon Fumée, Caviar, Strawberry, Mangue, Concombre, Salade Mixte",
voiliertitle: "Voilier (6mcx)",
voilier:
"Crevette Grillé, Poivron Rouge, Caviar, Vermicelle, Salade Mixte",
passiontitle: "Passion (6mcx)",
passion:
"Crevette, Imitation de Crabe, Caviar, Mangue, Concombre, Vermicelle, Salade Mixte",
amoureuxtitle: "Amoureux (6mcx)",
amoureux:
"Saumon & Imitation de Crabe Panées, Caviar, Concombre, Vermicelle, Salade Mixte",
nuetitle: "Nue (5mcx)",
nue: "Légume Tempura, Crevette, Caviar, Avocat",
// combo
comboroll: "Combo Rouleau",
comboonetitle: "Combo 1 (26mcx)",
comboonelist: "Dragon Eye, Québec, California, Rouleau du Chef, Kappa",
combotwotitle: "Combo 2 (26mcx)",
combotwolist: "Kamikaze, Aloha, Rouleau du Chef, Sake Maki, Yasai",
combothreetitle: "Combo 3 (52mcx)",
combothreelist:
"2 Kamikaze, 2 Aloha, 2 Rouleau du Chef, 2 Québec, 2 Yasai",
combofourtitle: "Combo 4 (96mcx)",
combofourlist:
"2 Kamikaze, 2 Aloha, 2 Dragon Eye, 2 Québec, 2 Rouleau du Chef, 2 New York, 2 Boston, 2 Sake Maki, 2 Yasai",
// lunch
appetizer: "Entrée",
yakitori: "Brochettes de poulet grillé servies avec sauce teriyaki",
gyoza: "Dumplings Japonais au porc et légumes servis avec sauce maison",
vegetabletempuratitle: "Légumes Tempura",
vegetabletempura: "Légumes panés servis avec sauce tempura",
hotmeals: "Plats Chauds",
hotmealsdesc: "(Servi avec une soupe miso ou salade, riz inclus)",
chickenkatsutitle: "Poulet Katsu",
chickenkatsu:
"Poulet pané avec chapelure japonaise servi avec sauce katsu",
teriyaki: "Plat grillé garni de légumes servi avec sauce teriyaki",
chicken: "Poulet",
salmon: "Saumon",
steak: "Steak",
tempura: "Crevettes et légumes frits accompagnés d'une sauce tempura",
sasaspecial:
"Brochettes de poulet grillé, crevettes et légumes frits servis avec sauce teriyaki",
sushicombodesc: "(Servi avec soupe miso ou salade)",
sushimoriowase:
"Assortiment de sushis de poisson et de fruits de mer crus avec un rouleau Kamikaze",
sashimiandmaki:
"Assortiment de sashimi de poisson cru servi avec du riz",
withoutrice: "sans Riz",
withrice: "avez Riz",
makicombo: "Combo de Kamikaze & California",
// dinner
harumaki:
"Rouleau de printemps japonais enrobé de crevettes, de porc et de légumes",
dinnerpizza:
"Galette de riz garnie de saumon fumé, bâtonnet de crabe, avocat, concombre et mayo",
dinnerlanina:
"Aubergines frites garnies de thon blanc légèrement grillé, de caviar et de sauce jalapeno",
dinneravalanche:
"Maquereaux grillés et tomates séchées, garnis de caviar et de sauce jalapeno",
tunasteaktitle: "Steak de Thon",
tunasteak: "Thon légèrement grillé servi avec une sauce spéciale",
dinnertunaspecialtitle: "Thon Spécial",
dinnertunaspecial:
"Thon légèrement frit garni de caviar, échalote et sauce spéciale",
soup: "Soupe",
misoshiru: "Soupe de pâte de soja blanche",
seafoodmisotitle: "Miso aux Fruits de Mer",
seafoodmiso: "Soupe miso aux fruits de mer",
sumashi: "Bouillon de poulet aux fruits de mer",
udon: "Bouillon de crevettes avec des nouilles udon",
vegetarian: "Végétarien",
shrimptempura: "Crevette Tempura",
salad: "Salade",
mixedsaladtitle: "Salade Mixte",
mixedsalad: "Salade mixte servie avec vinaigrette maison",
ohitashi: "Épinards cuits à la vapeur servis avec sauce au sésame",
seafoodsaladtitle: "Salade de Fruit de Mer",
seafoodsalad:
"Salade mixte garnie de saumon fumé, de crevettes et d'imitation de crabe servie avec une vinaigrette maison",
dinnerhotmealsdesc: "(Servi avec riz)",
seafood: "Fruit de Mer",
shrimp: "Crevette",
seafoodyakiudontitle: "Yaki Udon aux Fruits de Mer",
seafoodyakiudon:
"Sauté de crevettes et de pétoncles aux épices shichimi, servi avec du yaki udon (épicé)",
assortedsushititle: "Sushi Assortis (16mcx)",
assortedsushi: "6 nigiri sushi & 10 morceaux de rouleau maki",
sushisashimititle: "Sushi & Sashimi (17mcx)",
sushisashimi:
"5 nigiri, 6 morceaux de sashimi & 6 morceaux de rouleau maki",
sashimititle: "Sashimi (16mcx)",
sashimi: "16 morceaux de sashimi servis avec du riz",
notincluded:
"Soupe ou Salade n'est pas inclue pour les commandes à emporter.",
},
},
},
fallbackLng: ["fr", "en"],
// debug: true,
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
keySeparator: false, // we use content as keys
interpolation: {
escapeValue: false, // not needed for react!!
formatSeparator: ",",
},
react: {
wait: true,
},
load: "languageOnly",
whitelife: ["fr", "en"],
};
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init(options);
export default i18n;
|
"use strict";
function display_user_editor()
{
document.getElementById("user_editor").style.display = "block";
}
function hide_user_editor()
{
document.getElementById("user_editor").style.display = "none";
}
|
import React, { PropTypes, Component } from 'react';
import _ from 'lodash';
import { ControlLabel, Row, Col, FormGroup } from 'react-bootstrap';
import form from '../common/form';
import IconsAndText from '../common/IconsAndText';
import DropdownWrapper from '../common/DropdownWrapper';
const configuration = {
default: {
iconSize: 'medium',
inItemAlignment: 'left',
listAlignment: 'top',
},
iconSize: {
small: 'Small',
medium: 'Medium',
large: 'Large',
},
inItemAlignment: {
left: 'Left',
center: 'Center',
right: 'Right',
},
listAlignment: {
top: 'Top',
middle: 'Middle',
bottom: 'Bottom',
},
};
export class GeneralSettings extends Component {
constructor(props) {
super(props);
this.saveForm = this.saveForm.bind(this);
props.onFieldChange(this.saveForm);
}
saveForm() {
const layoutSettings = this.props.form.toObject();
this.props.onSettingsChanged(layoutSettings);
}
render() {
const { fields, settings, onSettingsChanged } = this.props;
const {
topOffset,
listAlignment,
inItemAlignment,
iconSize,
} = fields;
const showIcon = _.get(settings, ['showIcon'], true);
return (
<div>
<h3>General settings</h3>
<form>
<FormGroup>
<Row>
<Col md={6}>
<IconsAndText
settings={settings}
onSettingsChanged={onSettingsChanged}
/>
</Col>
<Col md={6}>
<ControlLabel>Icon size</ControlLabel>
<DropdownWrapper
valuesMap={configuration.iconSize}
defaultKey={configuration.default.iconSize}
field={iconSize}
disabled={!showIcon}
/>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col md={4}>
<ControlLabel>List alignment</ControlLabel>
<DropdownWrapper
valuesMap={configuration.listAlignment}
defaultKey={configuration.default.listAlignment}
field={listAlignment}
/>
</Col>
<Col md={4}>
<ControlLabel>Offset from top (px)</ControlLabel>
<input name="cols" type="number" className="form-control" {...topOffset} />
</Col>
<Col md={4}>
<ControlLabel>In-item alignment</ControlLabel>
<DropdownWrapper
valuesMap={configuration.inItemAlignment}
defaultKey={configuration.default.inItemAlignment}
field={inItemAlignment}
/>
</Col>
</Row>
</FormGroup>
</form>
</div>
);
}
}
GeneralSettings.propTypes = {
settings: PropTypes.object.isRequired,
onSettingsChanged: PropTypes.func.isRequired,
fields: PropTypes.object.isRequired,
form: PropTypes.object,
onFieldChange: PropTypes.func,
};
export default form((props) => {
const { settings } = props;
return {
fields: ['topOffset', 'listAlignment', 'inItemAlignment', 'iconSize'],
defaultValues: {
topOffset: settings.topOffset,
listAlignment: settings.listAlignment,
inItemAlignment: settings.inItemAlignment,
iconSize: settings.iconSize,
},
validation: {},
};
})(GeneralSettings);
|
'use strict';
// Load modules
const Fs = require('fs');
const Path = require('path');
const Os = require('os');
const Boom = require('boom');
const Request = require('promise-request-retry');
const Axios = require('axios').default;
// let newpath = Path.resolve( __dirname, "./plugin/axiosFormatize.js" )
// console.log(newpath);
// const AxiosFM = require(newpath);
const Moment= require('moment');
const { Console } = require('console');
const { partial } = require('lodash');
exports.plugin = {
name: 'appenateApi',
register: function (server) {
const {
Knack,
KnackAuth
} = server.plugins;
const KNACK_OBJECTS_IDS = Knack.objects();
const knackBaseUrl = 'https://api.knack.com/v1/';
const builderTimezone = "Pacific/Auckland";
const AxiosAPNT = Axios.create({
// baseURL: 'https://secure.appenate.com/api/v2/',
baseURL: 'https://secure-au.appenate.com/api/v2/',
// timeout: 1000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
var sendKnackViewRequest = (submitInfo) => {
return new Promise( async (resolve,reject) => {
Request({
...submitInfo,
headers: {
'X-Knack-Application-Id': process.env.KNACK_APP_ID,
'X-Knack-REST-API-KEY': process.env.KNACK_API_KEY
},
dataType: 'json',
contentType: 'application/json',
retry : 3,
accepted: [400,401,402,403,404,419, 500, 503],
delay: 5000
})
.then(function(response){
resolve(response);
})
.catch(function(error){
console.log(error.message);
console.log(error.error);
reject(error);
});
});
};
async function deleteRecordOnAPNT(formatType, recordsList){
if(!formatType) return false;
// if(!recordsList) return false;
let datasourceID="";
switch (formatType) {
case "knack_fileviewer": datasourceID = process.env.APNT_Files_dsID; break;
default: return false; break;
}
let delArray = [];
try {
let apntTableInfo = await getFromAPNT({
"Id": datasourceID,
"ReturnRows": true,
// "ExternalId": formatType,
});
if(apntTableInfo.TotalRows == 0) return false;
// console.log(apntTableInfo.ExternalId,apntTableInfo.TotalRows);
for (var knRecord of recordsList) {
// console.log(knRecord);
let found = apntTableInfo.Rows.find(apntRow => apntRow[0]==knRecord.id);
if(found) delArray.push(found[0]);
}
console.log("To delete: ", delArray);
} catch (e) {
console.log(e);
return false;
}
if(delArray.length == 0) return true;
try {
let delResponse = await postToAPNT({
"Id": datasourceID,
"DeletedRows": delArray
});
return true;
} catch (e) {
console.log(e);
}
return false;
};
async function updateAPNTdataSource(formatType, recordsList, stage){
if(!formatType) return false;
var datasourceID="", knackObj="", sFilters=[];
if (formatType=="Asset_maintenance_form"){
knackObj = KNACK_OBJECTS_IDS.AssetsJobs;
datasourceID = process.env.ASSETJOBS;
}else if(formatType=="Asset_Issues_Update"){
knackObj = KNACK_OBJECTS_IDS.AssetIssues;
datasourceID = process.env.ASSETISSUES;
}
var knackRecords="";
// console.log(recordsList);
if(recordsList)
knackRecords = recordsList;
else {
try {
knackRecords = await Knack.getAllRecords(1,sFilters,knackObj);
// if(formatType=="am_notes") knackRecords = knackRecords.slice(0,5);
} catch (e) {
console.log(e);
}
}
//console.log(knackRecords.length);
if(knackRecords.length == 0) return false;
let formatForAPNT=[];
if(formatType=="amiConcatNotes"){
formatForAPNT = await ApntAmiConcatNotesFormat(knackRecords);
}else{
formatForAPNT = ConvertRecordsFormat_APNT(formatType, knackRecords);
}
console.log(formatForAPNT.length);
if(formatForAPNT.length == 0) return false;
// return formatForAPNT;
//console.log(formatForAPNT);
console.log("updateApenate")
try {
postToAPNT({
// "CompanyId": process.env.APPENATE_COMPANY_ID,
// "IntegrationKey": process.env.APPENATE_INTEGRATION_KEY,
"Id": datasourceID,
"NewRows": formatForAPNT
});
} catch (e) {
console.log(e);
}
};
function postToAPNT(postData){
return new Promise( async (resolve,reject) => {
console.log("Updating datasource...");
AxiosAPNT.put("datasource/", {
...postData,
"CompanyId": process.env.APPENATE_COMPANY_ID,
"IntegrationKey": process.env.APPENATE_INTEGRATION_KEY,
// "Id": datasourceID,
// "NewRows": formatForAPNT
})
.then(function(response){
console.log("Res Status: "+response.status+"-"+response.statusText);
resolve(response);
})
.catch(function(error){
console.log(error);
reject(error);
});
});
};
function getFromAPNT(getData){
if(!getData) return false;
return new Promise( async (resolve,reject) => {
console.log("Getting records...");
let getURLext = `?CompanyId=${process.env.APPENATE_COMPANY_ID}&IntegrationKey=${process.env.APPENATE_INTEGRATION_KEY}`;
getURLext+=`&Id=${getData.Id}&ReturnRows=${getData.ReturnRows || false}`;
if(getData.ExternalId) getURLext+=`&ExternalId=${getData.ExternalId}`;
// console.log(getURLext);
AxiosAPNT.get("datasource"+getURLext)
.then(function(response){
console.log("Res Status: "+response.status+"-"+response.statusText);
resolve(response.data.DataSource);
})
.catch(function(error){
let {status, statusText, headers, config, data} = error.response;
console.log(data);
// console.log(data.ResponseStatus.Errors);
reject(data);
});
});
};
var ConvertRecordsFormat_APNT = (recordType, knackRecords) => {
let newRecords = [];
let convertRecord = false;
switch (recordType) {
case "Asset_maintenance_form": convertRecord = apntAssetJobs; break;
case "Asset_Issues_Update": convertRecord = apntAssetIssues; break;
}
if(!convertRecord) return false;
for (var recbody of knackRecords) {
try {
let payload = convertRecord(recbody);
if(payload) newRecords.push(payload);
} catch (e) {
console.log(e);
}
}
return newRecords;
};
var apntAssetJobs = (recbody) => {
//console.log(recbody);
try {
let payload = {
"KnackID": recbody.id,
"Job Id": recbody.field_180,
"Asset ID": recbody.field_93_raw[0].id,
"Display": recbody.field_181,
"Issue Count": recbody.field_182,
"Assigned To": "",
"Description": recbody.field_194,
"Status": recbody.field_95,
"Maintenance Status": "Stopped",
};
return Object.values(payload);
// return payload;
} catch (e) {
console.log(e);
}
return false;
};
var apntAssetIssues = (recbody) => {
//console.log(recbody);
try {
let payload = {
"KnackID": recbody.id,
"Issue": recbody.field_162,
"Asset Job ID": recbody.field_161_raw[0].id,
"Assigned To": recbody.field_165_raw[0].id,
"Issue Status": recbody.field_163,
"Status": recbody.field_164,
"Issue Logs": recbody.field_194
};
return Object.values(payload);
// return payload;
} catch (e) {
console.log(e);
}
return false;
};
var parsePageFormat = (jsonObj) => {
let objArray = Object.entries(jsonObj);
let newObj = {};
for (var pair of objArray) {
let attrVal = pair[1] === null? "" : pair[1];
if(typeof pair[1] =="string"){
pair[1] = pair[1].replace(/\r?\n|\r/g, ".");
}
if(pair[1] == null) pair[1] = "";
newObj[ pair[0] ] = pair[1];
}
return newObj;
};
var getFormFields = (formPayload) =>{
let {AnswersJson, ...formData}=formPayload;
let pages = Object.keys(AnswersJson).map(iKey => {return AnswersJson[iKey];});
// console.log("PAGES: ", pages);
for (var page of pages) {
let parsedObj = parsePageFormat(page);
formData = {...formData, ...parsedObj};
}
return formData;
}
var knackBehaviorSelection = (formType) => {
switch (formType) {
case "Asset_maintenance_form": return updateMaintenance;
case "Create_jobs_form": return createJob;
case "Create_issues_form": return takeIssues;
}
return false;
};
async function executeKnackBehavior(formPayload){
let fieldsData;
let formType = "";
if(formPayload.Entry) {
console.log("Received normal APNT request");
fieldsData = getFormFields(formPayload.Entry);
formType = fieldsData.FormCode;
}
//console.log(fieldsData);
//console.log("FormID: ", formType);
// return false;
if(formType){
let executeFN = knackBehaviorSelection(formType);
console.log(executeFN);
if (!executeFN) {
return console.log("KnackBehavior not found.");
}
let result = await executeFN(formPayload, fieldsData, formType);
console.log(result);
}else return console.log("Form not recognized.");
};
//*********************** */
//knackBehavior Functions
//*********************** */
var createJob = async (formPayload, formData, formType) => {
//console.log(formData);
let knacksend = {
method: 'POST',
uri: knackBaseUrl+'scenes/scene_88/views/view_164/records/',
form: {
field_93: formData.assetSelect,
//field_194: formData.description,
}
};
try {
var res = await sendKnackViewRequest(knacksend);
var jsonRes = JSON.parse( res.replace(/\r?\n|\r/g, "."))
//console.log(jsonRes.record.id);
} catch (e) {
console.log(e);
}
takeIssues(jsonRes.record.id,formData)
updateAPNTdataSource("Asset_maintenance_form");
}
var takeIssues2 = async (formData) => {
console.log("issues");
if(formData.countNewIssues > 1){
for (var i = 0 ; i < formData.countNewIssues ; i++){
createIssues2(formData,formData.newIssue[i]);
}
}else if(formData.countNewIssues == 1){
createIssues2(formData,formData.newIssue);
}
}
var createIssues2 = async (formData,partialData) => {
console.log(partialData);
let knacksend = {
method: 'POST',
uri: knackBaseUrl+'scenes/scene_95/views/view_182/records/',
form: {
"field_254": formData.assetDb,//asset
"field_161": formData.assetSelected, //Assetjob
"field_162": partialData.issueDescription, // description
"field_163": partialData.status, // status
"field_165": formData.staffId, //asigned to
"field_252": partialData.workDoneNI,//work done
"field_253": partialData.commentsNI,//comments
"field_164": partialData.resolvedStatusNI
}
};
try {
await sendKnackViewRequest(knacksend);
} catch (e) {
console.log(e);
}
updateAPNTdataSource("Asset_Issues_Update");
}
var takeIssues = async (jobID, formData) => {
createIssues(formData,formData,jobID)
/*
if(formData.countIssues > 1){
for (var i = 0 ; i < formData.countIssues ; i++){
createIssues(formData,formData.issues[i],jobID);
}
}else if(formData.countIssues == 1){
createIssues(formData,formData.issues,jobID);
}
*/
}
var createIssues = async (formData,partialData,jobID) => {
console.log(partialData);
let knacksend = {
method: 'POST',
uri: knackBaseUrl+'scenes/scene_95/views/view_182/records/',
form: {
"field_254": formData.assetSelect,//asset
"field_161": jobID, //Assetjob
"field_162": partialData.issueDescription, // description
"field_163": partialData.status, // status
//"field_165": partialData.asignedTo //asigned to
}
};
try {
await sendKnackViewRequest(knacksend);
} catch (e) {
console.log(e);
}
updateAPNTdataSource("Asset_Issues_Update");
}
var updateMaintenance = async (formPayload, formData, formType) => {
let knackRecordsAssetRecords = await Knack.getAllRecords(1,[],KNACK_OBJECTS_IDS.AssetsJobs);
//console.log(staffID)
let replyBody = {status:"FAILED", error:null};
if (formData.start){
var foundID = knackRecordsAssetRecords.find(kr =>
formData.assetSelect == kr.id
);
var knackPayload = {
"field_240": "In Progress",
"field_241": formData.staffId
}
createMaintenance("", formData,"");
}else{
takeIssues2(formData);
updateAPNTdataSource("Asset_maintenance_form");
updateMaintenancehours("", formData,"");
updateAssets("", formData,"");
if(formData.CountParts > 1){
for (var i = 0 ; i < formData.CountParts ; i++){
createMaintenancePart(formData,formData.partsUsedTable[i]);
}
}else if(formData.CountParts == 1){
createMaintenancePart(formData,formData.partsUsedTable);
}
if(formData.countAllCompletedItems > 1){
for (var i = 0 ; i < formData.countAllCompletedItems ; i++){
updateAssetIssues(formData,formData.workDoneTable[i]);
}
}else if(formData.countAllCompletedItems == 1){
updateAssetIssues(formData,formData.workDoneTable);
}
var foundID = knackRecordsAssetRecords.find(kr =>
formData.assetSelected == kr.id
);
var knackPayload = {
"field_240": "Stopped",
"field_95": formData.assetStatus
}
}
//console.log(knackPayload)
try {
let knackCreate = await Knack.update({
objectKey: KNACK_OBJECTS_IDS.AssetsJobs,
id: foundID.id,
body: knackPayload
})
console.log("knack result");
replyBody.status="SUCCESS"
} catch (e) {
console.log(e.error);
console.log("Unexpected error updating record on database.")
}
return replyBody
}
//*********************** */
//knackBehavior Extra Functions
//*********************** */
var createMaintenancePart = async (formData,part ) => {
//let numberOfParts = formData.partsUsedTable
var knackPayload = {
"field_124": formData.CompleteTime,//date
"field_130": formData.assetSelected, //Assetjob
"field_109": part.stockDB, // stock
"field_111": part.stockBuyValue,
"field_112": part.stockSellValue,
"field_113": part.quantityUsed
}
try {
let knackCreate = await Knack.create({
objectKey: KNACK_OBJECTS_IDS.MaintenanceParts,
body: knackPayload,
})
//console.log("knack result parts");
//console.log(knackPayload);
} catch (e) {
console.log(e.error);
console.log("Unexpected error updating record parts on database.")
}
}
var updateAssetIssues = async (total, partialData) => {
let knackRecordsIssues = await Knack.getAllRecords(1,[],KNACK_OBJECTS_IDS.AssetIssues);
var foundID = knackRecordsIssues.find(kr =>
partialData.assetIssue == kr.id
);
var knackPayload = {
//"field_163": total.assetStatus,//status
"field_164": partialData.resolvedStatus, //Resolved
"field_165": total.staffId, //Asigned to
"field_252": partialData.workDone,// work done
"field_253": partialData.comments// comments
}
console.log(knackPayload);
//console.log(foundID.id);
try {
let knackCreate = await Knack.update({
objectKey: KNACK_OBJECTS_IDS.AssetIssues,
id: foundID.id,
body: knackPayload,
})
console.log("knack result Assets issues");
} catch (e) {
console.log(e.error);
console.log("Unexpected error updating record assets issues on database.")
}
//updateAPNTdataSource("")
}
var createMaintenance = async (formPayload, formData, formType) => {
//let knackRecordsAssetRecords = await Knack.getAllRecords(1,[],KNACK_OBJECTS_IDS.MaintenanceHours);
var knackPayload = {
"field_190": formData.CompleteTime,
"field_135": formData.assetSelect,
"field_133": formData.staffId,
"field_186": "",
"field_188": "",
"field_243": formData.final_start_time,
"field_244": "",
}
try {
let knackCreate = await Knack.create({
objectKey: KNACK_OBJECTS_IDS.MaintenanceHours,
body: knackPayload,
})
//console.log("knack result");
} catch (e) {
console.log(e.error);
console.log("Unexpected error updating record on database.")
}
return true
}
var updateAssets = async (formPayload, formData, formType) => {
let knackPayload = {
"field_89": (formData.assetStatus=='Resolved')?'Operational':formData.assetStatus
}
let knackRecordsAssets = await Knack.getAllRecords(1,[],KNACK_OBJECTS_IDS.Assets);
//console.log("payload");
//console.log(knackPayload);
//console.log("asset selected")
//console.log(formData.assetSelected);
var foundID = knackRecordsAssets.find(kr =>
formData.assetDb == kr.id
);
//console.log(foundID)
try {
let knackCreate = await Knack.update({
objectKey: KNACK_OBJECTS_IDS.Assets,
id: foundID.id,
body: knackPayload
})
console.log("knack result");
} catch (e) {
console.log(e.error);
console.log("Unexpected error updating record on database.")
}
}
var updateMaintenancehours = async (formPayload, formData, formType) => {
let knackRecordsMaintenance = await Knack.getAllRecords(1,[],KNACK_OBJECTS_IDS.MaintenanceHours);
var foundID = knackRecordsMaintenance.find(kr => {
if (kr.field_135){
return formData.assetSelected == kr.field_135_raw[0].id && kr.field_244 == ""
}else return false;
});
//console.log(foundID)
var knackPayload = {
"field_244": formData.untitled61,
}
try {
let knackCreate = await Knack.update({
objectKey: KNACK_OBJECTS_IDS.MaintenanceHours,
id: foundID.id,
body: knackPayload,
})
//console.log("knack result update");
//console.log(foundID.id)
//console.log(knackPayload)
} catch (e) {
console.log(e.error);
console.log("Unexpected error updating final time record on database.")
}
return true
}
//*********************** */
//Utility Functions
//*********************** */
var removeEmptyFields = (obj) => {
// ES10/ES2019 version doesn't work on Node v10.16.0
// return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null && v != ""));
return Object.entries(obj)
.filter(([_, v]) => v != null && v != "")
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
};
const GetNumericValue = (numVal) =>{
// If empty string, will treat as 0. Must validate empty in different function.
if(!numVal) numVal = 0;
return isNaN(numVal)? null : numVal = parseFloat(numVal);
}
// ***********
// ENDPOINTS
// ***********
server.route({
method: 'POST',
path: '/captureFileConnector',
handler: async function (request, h) {
let formPayload = request.payload;
if(!formPayload.Entry) return false;
let fieldsData = getFormFields(formPayload.Entry);
let dataStr = JSON.stringify(fieldsData);
return {jsonStr: dataStr};
}
});
server.route({
method: 'POST',
path: '/captureFormsAPNT',
handler: async function (request, h) {
let formPayload = request.payload;
// if(!formPayload.Entry) return false;
//console.log(formPayload);
executeKnackBehavior(formPayload);
return formPayload;
}
});
server.route({
method: 'GET',
path: '/test',
handler: async function (request, h) {
//console.log("Endpoint Here");
//console.log(KNACK_OBJECTS_IDS)
updateAssets("timesheetsDB");
return "Ok";
}
});
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DNDStat;
(function (DNDStat) {
DNDStat["str"] = "Strength";
DNDStat["dex"] = "Dexterity";
DNDStat["con"] = "Constitution";
DNDStat["int"] = "Intelligence";
DNDStat["wis"] = "Wisdom";
DNDStat["cha"] = "Charisma";
})(DNDStat = exports.DNDStat || (exports.DNDStat = {}));
class myCharacter {
constructor(name, hp, saveThrows) {
this.CharacterName = name;
this.HitPointTotal = hp;
this.SavingThrows = saveThrows;
this.CurrentHP = hp;
}
;
getName() {
return this.CharacterName;
}
;
isDown() {
return (this.CurrentHP <= 0);
}
;
proficientInWhat() {
return this.SavingThrows;
}
;
}
exports.myCharacter = myCharacter;
const myName = 'Solis';
let myHP = 100;
let savingThrows = [DNDStat['dex'], DNDStat['cha']];
console.log("Creating a character with name " + myName + ", Hit Point Total: " + myHP + ", and ");
console.log("Saving throws: " + savingThrows);
const solis = new myCharacter(myName, myHP, savingThrows);
console.log("\n Is he down? ");
console.log(solis.isDown().toString());
let proficiencies = solis.proficientInWhat();
console.log("He is proficient in the following saving throws: " +
proficiencies[0] + ' and ' + proficiencies[1]);
|
import { render, screen } from '@testing-library/react';
import App from './App';
import ReactDOM from 'react-dom';
import { ViewerContainer } from './Viewer/ViewerContainer';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/dashboard/i);
expect(linkElement).toBeInTheDocument();
});
it('render without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<ViewerContainer/>, div)
})
it('sensors working', () => {
render(<App />);
setTimeout(() => {
expect(document.querySelectorAll('Viewer_sensor')).toBeTruthy()
}, 3000)
setTimeout()
})
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is MozMill Test code.
*
* The Initial Developer of the Original Code is Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Henrik Skupin <hskupin@mozilla.com>
* Geo Mealer <gmealer@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* @fileoverview
* The ModalDialogAPI adds support for handling modal dialogs. It
* has to be used e.g. for alert boxes and other commonDialog instances.
*
* @version 1.0.2
*/
// Include required modules
var utils = require("utils");
const gTimeout = 5000;
// Default bookmarks.html file lives in omni.jar, get via resource URI
const BOOKMARKS_RESOURCE = "resource:///defaults/profile/bookmarks.html";
// Bookmarks can take up to ten seconds to restore
const BOOKMARKS_TIMEOUT = 10000;
// Observer topics we need to watch to know whether we're finished
const TOPIC_BOOKMARKS_RESTORE_SUCCESS = "bookmarks-restore-success";
/**
* Instance of the bookmark service to gain access to the bookmark API.
*
* @see http://mxr.mozilla.org/mozilla-central (nsINavBookmarksService.idl)
*/
var bookmarksService = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
getService(Ci.nsINavBookmarksService);
/**
* Instance of the history service to gain access to the history API.
*
* @see http://mxr.mozilla.org/mozilla-central (nsINavHistoryService.idl)
*/
var historyService = Cc["@mozilla.org/browser/nav-history-service;1"].
getService(Ci.nsINavHistoryService);
/**
* Instance of the livemark service to gain access to the livemark API
*
* @see http://mxr.mozilla.org/mozilla-central (nsILivemarkService.idl)
*/
var livemarkService = Cc["@mozilla.org/browser/livemark-service;2"].
getService(Ci.nsILivemarkService);
/**
* Instance of the browser history interface to gain access to
* browser-specific history API
*
* @see http://mxr.mozilla.org/mozilla-central (nsIBrowserHistory.idl)
*/
var browserHistory = Cc["@mozilla.org/browser/nav-history-service;1"].
getService(Ci.nsIBrowserHistory);
/**
* Instance of the observer service to gain access to the observer API
*
* @see http://mxr.mozilla.org/mozilla-central (nsIObserverService.idl)
*/
var observerService = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
/**
* Check if an URI is bookmarked within the specified folder
*
* @param (nsIURI) uri
* URI of the bookmark
* @param {String} folderId
* Folder in which the search has to take place
* @return Returns if the URI exists in the given folder
* @type Boolean
*/
function isBookmarkInFolder(uri, folderId)
{
var ids = bookmarksService.getBookmarkIdsForURI(uri, {});
for (let i = 0; i < ids.length; i++) {
if (bookmarksService.getFolderIdForItem(ids[i]) == folderId)
return true;
}
return false;
}
/**
* Restore the default bookmarks for the current profile
*/
function restoreDefaultBookmarks() {
// Set up the observer -- we're only checking for success here, so we'll simply
// time out and throw on failure. It makes the code much clearer than handling
// finished state and success state separately.
var importSuccessful = false;
var importObserver = {
observe: function (aSubject, aTopic, aData) {
if (aTopic == TOPIC_BOOKMARKS_RESTORE_SUCCESS) {
importSuccessful = true;
}
}
}
observerService.addObserver(importObserver, TOPIC_BOOKMARKS_RESTORE_SUCCESS, false);
try {
// Fire off the import
var bookmarksURI = utils.createURI(BOOKMARKS_RESOURCE);
var importer = Cc["@mozilla.org/browser/places/import-export-service;1"].
getService(Ci.nsIPlacesImportExportService);
importer.importHTMLFromURI(bookmarksURI, true);
// Wait for it to be finished--the observer above will flip this flag
mozmill.utils.waitFor(function () {
return importSuccessful;
}, "Default bookmarks have finished importing", BOOKMARKS_TIMEOUT);
}
finally {
// Whatever happens, remove the observer afterwards
observerService.removeObserver(importObserver, TOPIC_BOOKMARKS_RESTORE_SUCCESS);
}
}
/**
* Synchronous wrapper around browserHistory.removeAllPages()
* Removes history and blocks until done
*/
function removeAllHistory() {
const TOPIC_EXPIRATION_FINISHED = "places-expiration-finished";
// Create flag visible to both the eval and the observer object
var finishedFlag = {
state: false
}
// Set up an observer so we get notified when remove completes
let observer = {
observe: function(aSubject, aTopic, aData) {
observerService.removeObserver(this, TOPIC_EXPIRATION_FINISHED);
finishedFlag.state = true;
}
}
observerService.addObserver(observer, TOPIC_EXPIRATION_FINISHED, false);
// Remove the pages, then block until we're done or until timeout is reached
browserHistory.removeAllPages();
mozmill.controller.waitForEval("subject.state == true", gTimeout, 100, finishedFlag);
}
// Export of variables
exports.bookmarksService = bookmarksService;
exports.historyService = historyService;
exports.livemarkService = livemarkService;
exports.browserHistory = browserHistory;
// Export of functions
exports.isBookmarkInFolder = isBookmarkInFolder;
exports.restoreDefaultBookmarks = restoreDefaultBookmarks;
exports.removeAllHistory = removeAllHistory;
|
import * as dispatcher from './dispatcher'
import { validateSchema } from './middleware'
export function index(router) {
return router
.get('/', ctx => {
ctx.body = `usage: curl -H "Content-Type: application/json"`
+ ` -X POST -d '{"event":"foo","data":"bar"}'`
+ ` http://localhost:3000/`
})
// This is the 'events' endpoint. It expects event payloads.
.post('/', validateSchema, async(ctx) => {
try {
const {body} = ctx.request
// We're dispatching or 'emitting' raw events to the dispatcher.
// In this example the dispatcher is set up to collect results from
// all the registered handlers and then return it in the body, causing
// the HTTP request to block.
ctx.body = await dispatcher.dispatch(body)
} catch (e) {
ctx.throw(e, 404)
}
})
}
|
'use babel'
import * as _ from 'lodash'
import * as fs from 'fs-plus'
import * as path from 'path'
import Texdoc from './docs/texdoc'
import Mthelp from './docs/mthelp'
const keywordRegExp = /\\(?:input|documentclass|usepackage|RequirePackage|LoadPackage)\s*(?:\[.*\])?\s*{([^}]+)}/g
const grammarScopes = ['text.tex', 'text.tex.latex', 'text.tex.latex.memoir', 'text.tex.latex.beamer']
function iconForPath (filePath) {
const extension = path.extname(filePath)
if (fs.isSymbolicLinkSync(filePath)) {
return 'file-symlink-file'
} else if (fs.isReadmePath(filePath)) {
return 'book'
} else if (fs.isCompressedExtension(extension)) {
return 'file-zip'
} else if (fs.isImageExtension(extension)) {
return 'file-media'
} else if (fs.isPdfExtension(extension)) {
return 'file-pdf'
} else if (fs.isBinaryExtension(extension)) {
return 'file-binary'
} else {
return 'file-text'
}
}
const Main = {
activate () {
this.setDocProvider()
atom.config.onDidChange('intentions-texdoc.provider', () => {
this.setDocProvider()
})
require('atom-package-deps').install('intentions-texdoc')
.then(() => {
console.log('All dependencies installed, good to go')
})
},
deactivate () {
},
provideIntentionsList () {
return {
grammarScopes: grammarScopes,
getIntentions: ({textEditor, bufferPosition}) => {
let text
textEditor.scan(keywordRegExp, ({range, match, stop}) => {
if (range.containsPoint(bufferPosition)) {
text = match[1]
stop()
} else if (range.start.isGreaterThan(bufferPosition)) {
stop()
}
})
if (!text) return []
return global.doc.search(text.split(','))
.then(matches => _.map(matches,
(match, index) => {
return {
priority: match.rank || (match.length - index),
icon: iconForPath(match.path),
title: `${path.basename(match.path)}${match.description ? ' \u2014 ' + match.description : ''} [${path.basename(path.dirname(match.path))}]`,
selected: () => global.doc.view(match)
}
}))
}
}
},
provideIntentionsHighlight () {
return {
grammarScopes: grammarScopes,
getIntentions: ({textEditor, visibleRange}) => {
return new Promise(resolve => {
const matches = []
textEditor.scanInBufferRange(keywordRegExp, visibleRange, ({range}) => {
matches.push({
range: range,
created: ({textEditor, element, marker, matchedText}) => {}
})
})
resolve(matches)
})
}
}
},
setDocProvider () {
global.doc = (atom.config.get('intentions-texdoc.provider') === 'mthelp') ? new Mthelp() : new Texdoc()
}
}
export default Main
|
define(["esri/dijit/Popup", "dojo/_base/declare", "dojo/dom-class", "dojo/_base/kernel", "dojo/query", "dojo/_base/array", "dojo/_base/lang"],
function (Popup,declare, domClass, kernel, query, array, lang) {
return declare([Popup], {
_subclass:"",
constructor: function (options, srcNoderef) {
//lang.mixin(this,options);
//this._resetable = options.resetable;
this._subclass = (options.hasOwnProperty("subclass")) ? options.subclass :"";
domClass.add(this.domNode, this._subclass);
},
postCreate: function () {
this.inherited(arguments);
},
startup: function () {
this.inherited(arguments);
},
show:function(a,b){
this.inherited(arguments);
}
});
});
|
//GET/dogs
// GET /dogs?name="...":
// Obtener un listado de las razas de perro que contengan la palabra ingresada como query parameter
// Si no existe ninguna raza de perro mostrar un mensaje adecuado
const {Router}=require('express');
const router=Router();
const{allDogs}=require('../utils/dataApiDogs');
router.get('/dogs',async(req,res)=>{
const {name}=req.query; //recibo la raza por query
const totalDogs=await allDogs(); //Espero todos los perros traidos de la api y de la base de datos(pre concatenados en el archivo dataApi)
if(name){
let dogName=await totalDogs.filter(d=>d.name.toLowerCase().includes(name.toLowerCase())); //pregunto si esa raza existe y con .filter() traigo las coincidencias que incluyan esa raza
dogName.length ? //si tengo algo
res.status(200).send(dogName) : //lo envio, si no
res.status(404).send('Sorry, that breed is not available. Try again ❤') //mensaje de error
}else {
res.status(200).send(totalDogs); //por defecto manda todos los perros(de spi o de la base)
}
});
module.exports=router;
|
if(!window["dic"]){
window["dic"] = {};
}
dic.paymentMethod = [
{"value":"","text":""},
{"value":"1","text":"1 - 城镇职工基本医疗保险"},
{"value":"2","text":"2 - 城镇居民基本医疗保险"},
{"value":"3","text":"3 - 新型农村合作医疗"},
{"value":"4","text":"4 - 贫困救助"},
{"value":"5","text":"5 - 商业医疗保险"},
{"value":"6","text":"6 - 全公费"},
{"value":"7","text":"7 - 全自费"},
{"value":"8","text":"8 - 其他社会保险"},
{"value":"9","text":"9 - 其他"}
]
|
/*global requestAnimationFrame:false,superCanvas:false,openFile:false */
var setCurrentFrame;
var getCurrentFrame;
var getTotalFrames;
var animatorNamespace = "hi";
var drawTimeline;
(function(){
var mousedown = false;
var currentFrameNo = 0;
var totalFrames = 0;
getTotalFrames = function(){
return totalFrames;
};
var frameSelect = document.querySelector("#frameRange");
setCurrentFrame = function(newFrame){
frameSelect.value = currentFrameNo = newFrame;
};
frameSelect.addEventListener("change", function(){
setCurrentFrame(parseInt(this.value, 10));
}, false);
getCurrentFrame = function(){
return currentFrameNo;
};
var layerHeader = document.querySelector(".layers .layerHeader");
var frameHeader = document.querySelector(".keyframes .frameHeader");
var frames = document.querySelector(".keyframes .frames");
var layers = document.querySelector(".layers .layers");
var layerHCtx = superCanvas(layerHeader);
var frameHCtx = superCanvas(frameHeader);
var frameCtx = superCanvas(frames);
var layerCtx = superCanvas(layers);
//Preperation, create some patterns
var canvas = document.createElement("canvas");
var context = superCanvas(canvas);
canvas.width = 10;
canvas.height = 20;
context.drawPath("M10,0 10,20 0,20");
context.stroke();
var grid = context.createPattern(canvas, "repeat");
canvas.width = 10*5;
canvas.height = 20;
context.drawPath("M40,0 50,0 50,20 40,20");
context.fillStyle="#eee";
context.fill();
var visibleLayer = superCanvas.bakeMatrixIntoPath(superCanvas.Matrix().scale(1/28,1/28).scale(20,20), superCanvas.parsePath("M16,8.286C8.454,8.286,2.5,16,2.5,16s5.954,7.715,13.5,7.715c5.771,0,13.5-7.715,13.5-7.715S21.771,8.286,16,8.286zM16,20.807c-2.649,0-4.807-2.157-4.807-4.807s2.158-4.807,4.807-4.807s4.807,2.158,4.807,4.807S18.649,20.807,16,20.807zM16,13.194c-1.549,0-2.806,1.256-2.806,2.806c0,1.55,1.256,2.806,2.806,2.806c1.55,0,2.806-1.256,2.806-2.806C18.806,14.451,17.55,13.194,16,13.194z"));
var invisibleLayer = superCanvas.bakeMatrixIntoPath(superCanvas.Matrix().scale(1/28,1/28).scale(20,20),superCanvas.parsePath("M11.478,17.568c-0.172-0.494-0.285-1.017-0.285-1.568c0-2.65,2.158-4.807,4.807-4.807c0.552,0,1.074,0.113,1.568,0.285l2.283-2.283C18.541,8.647,17.227,8.286,16,8.286C8.454,8.286,2.5,16,2.5,16s2.167,2.791,5.53,5.017L11.478,17.568zM23.518,11.185l-3.056,3.056c0.217,0.546,0.345,1.138,0.345,1.76c0,2.648-2.158,4.807-4.807,4.807c-0.622,0-1.213-0.128-1.76-0.345l-2.469,2.47c1.327,0.479,2.745,0.783,4.229,0.783c5.771,0,13.5-7.715,13.5-7.715S26.859,13.374,23.518,11.185zM25.542,4.917L4.855,25.604L6.27,27.02L26.956,6.332L25.542,4.917z"));
var everyfill = context.createPattern(canvas, "repeat");
var timelineGradient = context.createLinearGradient(0, 0, 0, 20);
timelineGradient.addColorStop(0, "#d0d0d0");
timelineGradient.addColorStop(0.7, "#d0d0d0");
timelineGradient.addColorStop(1, "#b4b4b4");
var draw = function(doc){
//Draw the headers....
//layers
layerHeader.width = layerHeader.parentNode.clientWidth;
layerHeader.height=20;
layerHCtx.fillStyle=timelineGradient;
layerHCtx.fillRect(0,0, layerHeader.width, layerHeader.height);
frameHeader.width = frameHeader.parentNode.clientWidth;
frameHeader.height=20;
frameHCtx.fillStyle=timelineGradient;
frameHCtx.fillRect(0,0, frameHeader.width, frameHeader.height);
frameHCtx.save();
frameHCtx.rect(0,0,frameHeader.width,3);
frameHCtx.rect(0,17,frameHeader.width, 3);
frameHCtx.clip();
frameHCtx.translate(-frameHeader.parentNode.scrollLeft, 0);
frameHCtx.fillStyle=grid;
frameHCtx.fillRect(frameHeader.parentNode.scrollLeft,0,frameHeader.width, 20);
frameHCtx.restore();
frameHCtx.font = "12px monospace";
//Draw the frame numbers...
frameHCtx.fillStyle="black";
frameHCtx.translate(-frameHeader.parentNode.scrollLeft, 0);
for(var i = 0; i < frameHeader.parentNode.scrollWidth; i+=5){
var width = frameHCtx.measureText(i).width/2;
frameHCtx.fillText(i, i*10-width+5, 20-6);
}
//Draw the current Frame
frameHCtx.fillStyle = "rgba(255,0,0,0.5)";
frameHCtx.fillRect(currentFrameNo*10, 0, 10, 20);
//Draw te bodies
// layers...
layers.width=layers.parentNode.clientWidth;
layers.height=layers.parentNode.clientHeight-20;
layerCtx.font = "12px monospace";
layerCtx.fillStyle="rgb(230,230,230)";
layerCtx.fillRect(0,0,layers.width, layers.height);
layerCtx.translate(0, -frames.parentNode.scrollTop);
var layersArray = [];
if(doc){
var docRoot = doc.documentElement;
var layerNum = 0;
for(var i = 0; i != docRoot.childNodes.length; i++){
var node = docRoot.childNodes[i];
if(node.nodeName == "g"){
layersArray.push(node);
layerCtx.save();
layerCtx.translate(0,layerNum*20);
layerCtx.save();
layerCtx.beginPath();
layerCtx.rect(0,0,layers.width,20);
layerCtx.closePath();
layerCtx.clip();
layerCtx.rect(0,0,layers.width,20);
layerCtx.fillStyle="rgba(212,208,200,1)";
layerCtx.fill();
layerCtx.strokeStyle="white";
layerCtx.beginPath();
layerCtx.moveTo(0,0);
layerCtx.lineTo(layers.width,0);
layerCtx.stroke();
layerCtx.closePath();
layerCtx.strokeStyle="rgb(128,128,128)";
layerCtx.beginPath();
layerCtx.moveTo(0,20);
layerCtx.lineTo(layers.width,20);
layerCtx.stroke();
layerCtx.closePath();
layerCtx.restore();
layerCtx.fillStyle="black";
layerCtx.fillText(node.getAttributeNS(animatorNamespace,"label") || ("layer"+layerNum), 0, 20-6);
layerCtx.save();
layerCtx.translate(layers.width-28,0);
if(layers.mousedown === true && layers.x > 180)
node.style.display = node.style.display=="none"?"block":"none";
if(node.style.display=="none"){
layerCtx.drawPath(invisibleLayer);
}else{
layerCtx.drawPath(visibleLayer);
}
layerCtx.fill();
layerCtx.restore();
layerCtx.restore();
layerNum++;
}
}
}
//frames...
var maxWidth = frames.parentNode.clientWidth/10;
for(i = 0; i < layersArray.length; i++){
var mLength = 0;
var L = layersArray[i];
for(k = 0; k < L.childNodes.length; k++){
if(L.childNodes[k].nodeName!="g") continue;
mLength += parseInt(L.childNodes[k].getAttributeNS(animatorNamespace, "length"), 10)||0;
}
maxWidth = Math.max(mLength, maxWidth);
}
//add 10 to maxWidth so that the user can see a bit past the end
totalFrames = maxWidth;
frames.width = (maxWidth + 10) * 10;
frames.height = Math.max((frames.parentNode.clientHeight-20), layersArray.length*10);
frameCtx.fillStyle = grid;
frameCtx.fillRect(0,0,frames.width, frames.height);
//Now, draw the keyframes
for(i = 0; i < layersArray.length; i++){
var at = 0;
var L = layersArray[i];
for(var k = 0; k < L.childNodes.length; k++){
var frame = L.childNodes[k];
if(frame.nodeName != "g")continue;
var l = parseInt(frame.getAttributeNS(animatorNamespace, "length"),10)||1;
frameCtx.fillStyle="white";
frameCtx.strokeStyle="black";
//frameCtx.lineWidth = 0.5;
frameCtx.save();
frameCtx.translate(at*10, i * 20);
frameCtx.beginPath();
frameCtx.rect(1,0,l*10-2, 20-1);
frameCtx.closePath();
frameCtx.fill();
//frameCtx.stroke();
frameCtx.beginPath();
frameCtx.arc(5,15, 2, 0, Math.PI*2, false);
frameCtx.fillStyle="black";
frameCtx.fill();
frameCtx.stroke();
frameCtx.closePath();
frameCtx.restore();
at+=l;
}
}
frameCtx.beginPath();
frameCtx.strokeStyle = "rgba(255,0,0,0.5)";
frameCtx.moveTo(currentFrameNo*10 + 5,0);
frameCtx.lineTo(currentFrameNo*10 + 5, frames.height);
frameCtx.stroke();
frameCtx.closePath();
//requestAnimationFrame(function(){draw(doc);});
};
var frameClickHandler = function(e){
var x = (e.offsetX||e.layerX) + e.target.parentElement.scrollLeft;
var frameN = Math.floor(x/10);
//console.log(x, frameN);
setCurrentFrame(frameN);
};
frameHeader.addEventListener("mousedown", frameClickHandler, false);
frameHeader.addEventListener("mousedown", function(){ mousedown = true; }, false);
frameHeader.addEventListener("mouseup", function(){ mousedown = false; }, false);
frameHeader.addEventListener("mousemove", function(e){
if(mousedown) frameClickHandler(e);
}, false);
layers.addEventListener("mousedown", function(e){
this.mousedown = true;
}, false);
layers.addEventListener("mousemove", function(e){
this.mouse.x = e.clientX;
this.mouse.y = e.clientY;
layers.addEventListener("mouseup", function(e){
layers.mousedown = false;
}, false);
drawTimeline = draw;
//
//draw();
})();
|
function backtracking(text, counter) {
if (counter >= text.length) {
console.log("done");
return;
}
text = swap(text, 0, counter);
console.log("swapped: " + text);
backtracking(text, counter + 1);
text = swap(text, 0, counter);
console.log("unswapped: " + text);
}
function swap(text, first, second) {
let textArr = text.split("");
let temp = textArr[first];
textArr[first] = textArr[second];
textArr[second] = temp;
return textArr.join("");
}
console.log(backtracking("abc", 0));
|
const express = require('express'); // express module
const app = express(); // aplication
const { Area } = require('../classes/area'); // Area class
const { Cite } = require('../classes/cite'); // Cite class
// home route
app.get('/', (req, res) => {
res.render('home', {
page: 'Inicio'
})
});
// signup route
app.get('/signup', async(req, res) => {
res.render('register', {
page: 'Registro',
areas: await Area.findAll()
.then(resp => resp.data)
.catch(() => [])
})
});
// cite route
app.get('/cite', async(req, res) => {
res.render('register_cite', {
page: 'Registro de citas',
areas: await Area.findAll()
.then(resp => resp.data)
.catch(() => []),
cites: await Cite.findAllFisrtArea()
.then(resp => resp.data)
.catch(() => [])
})
});
// login route
app.get('/login', (req, res) => {
// delete session
if (req.session.user) {
req.session = null;
res.locals = { user: null };
}
res.render('login', {
page: 'Iniciar sesión'
})
});
module.exports = app;
|
import React, { Component } from 'react';
import { Formik } from 'formik';
import { connect } from 'react-redux';
import { auth } from '../../Redux/authActionCrators';
import Spiner from '../Spinner/spinner';
import { Alert } from 'reactstrap';
const mapDispatchToProps = dispatch => {
return {
auth: (email, password, mode) => dispatch(auth(email, password, mode))
}
}
const mapStateToProps = state => {
return {
authLoading: state.authLoading,
authFaildMsg: state.authFaildMsg,
}
}
class Auth extends Component {
state = {
mode: "Sign Up"
}
switchModeHandler = () => {
this.setState({
mode: this.state.mode === "Sign Up" ? "Login" : "Sign Up"
})
}
render() {
let err = null;
if (this.props.authFaildMsg!==null){
err = <Alert color = "danger" >{this.props.authFaildMsg}</Alert>
}
let form = null;
if (this.props.authLoading) {
form = <Spiner />
}
else {
form = <Formik
initialValues={
{
email: "",
password: "",
passwordConfirm: "",
}
}
onSubmit={
(values) => {
this.props.auth(values.email, values.password, this.state.mode)
}
}
validate={(values) => {
const errors = {};
if (!values.email) {
errors.email = "Required";
}
// else if () {
// errors.email = "Invalid Email Address"
// }
if (!values.password) {
errors.password = "Required";
}
else if (values.password.length < 8) {
errors.password = "Min 8 Carecter required ";
}
if (this.state.mode === "Sign Up") {
if (!values.passwordConfirm) {
errors.passwordConfirm = "Required";
}
else if (values.password !== values.passwordConfirm) {
errors.passwordConfirm = "Password Filed doesn't match"
}
}
return errors;
}}
>
{({ values, handleChange, handleSubmit, errors }) => (
<div style={{
border: "1px solid black",
padding: "15px",
borderRadius: "7px"
}}>
<button style={{
width: "100%",
padding: "5px",
background: "#D70F64",
borderRadius: "7pox",
marginBottom: "10px",
color: "#ffffff"
}} class="btn btn-lg" onClick={this.switchModeHandler}>Switch to {this.state.mode === "Sign Up" ? "login" : "Sign Up"}</button>
<form onSubmit={handleSubmit}>
<input name="email" placeholder="Your Email" className="form-control" value={values.email} onChange={handleChange} />
<span style={{ color: "red" }}>{errors.email}</span>
<br />
<input name="password" placeholder="Your Password" className="form-control" value={values.password} onChange={handleChange} />
<span style={{ color: "red" }}>{errors.password}</span>
<br />
{this.state.mode === "Sign Up" ?
<div>
<input name="passwordConfirm" placeholder="Confirm Password" className="form-control" value={values.passwordConfirm} onChange={handleChange} />
<span style={{ color: "red" }}>{errors.passwordConfirm}</span>
<br />
</div> : null}
<button type="submit" className="btn btn-success">{this.state.mode === "Sign Up" ? "Sign Up" : "Login"}</button>
</form>
</div>
)
}
</Formik>
}
return (
<div>
{err}
{form}
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Auth);
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import * as BooksAPI from './BooksAPI'
import Book from './Book'
class Search extends Component {
state = {
query: '',
filteredBooks: [],
hasError: false
}
updateQuery = (query) => {
if (query === '') {
/* when the search field is empty or erased by user */
this.setState({ query: '', filteredBooks: [] })
} else {
this.setState({ query })
BooksAPI.search(query)
.then(results => {
if (results.error) {
/* catching possibly search error, sources https://reactjs.org/docs/error-boundaries.html */
this.setState({ filteredBooks: [], hasError: true})
} else {
this.rightShelf(results)
}
})
}}
rightShelf(results) {
/* filling the filteringBooks array with search result and assigning the right shelf to searched books (big thanks to Maeva FEND Study Jam) */
/*this.setState({ filteredBooks: results }) */
results.map((resultBook) => {
resultBook.shelf = 'none'
this.props.books.map((book) => {
(resultBook.id === book.id) ? (resultBook.shelf=book.shelf) : ('')}
)})
this.setState({ filteredBooks: results })
}
newSearch = () => {
this.setState({ hasError: false, query: '', filteredBooks: [] })
}
render() {
return (
<div className="search-books">
<div className="search-books-bar">
<Link to="/" className="close-search">Close</Link>
<div className="search-books-input-wrapper">
<input
type="text"
placeholder="Search by title or author"
value={this.state.query}
onChange={(event) => this.updateQuery(event.target.value)} />
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{/* Showing the grid or error message of limited searched words */}
{this.state.hasError ? (
<div>
<span>Demo version. For possible search words see ReadMe file.</span>
<button onClick={this.newSearch}>New Search</button>
</div>
) : (
<Book
books={this.state.filteredBooks}
changeShelf={this.props.changeShelf}
/>
)}
</ol>
</div>
</div>
)
}
}
export default Search
|
import React from 'react'
import './App.css';
import { Button } from 'semantic-ui-react'
import ContactList from './Components/ContactList';
import {Link, Switch,Route} from "react-router-dom"
import Add from "./Components/Add"
import Edit from "./Components/Edit"
function App() {
return (
<div className="App">
<h2>workshop MERN</h2>
<Button inverted color="blue">
<Link to="/add"> Add Contact</Link>
</Button>
<Button inverted color="blue">
<Link to="/"> Contact List</Link>
</Button>
<Switch>
<Route exact path="/" component={ContactList}/>
<Route path="/add" component={Add}/>
<Route path="/edit/:id" component={Edit}/>
</Switch>
</div>
);
}
export default App;
|
import React, {Component} from 'react';
import TextField from 'material-ui/TextField';
import ParentNode from './ParentNode';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
class ExistingArticles extends Component {
constructor(props) {
super(props);
this.handleTemplateChange = this.handleTemplateChange.bind(this);
this.handleCreateTree = this.handleCreateTree.bind(this);
this.handleDeleteArticle = this.handleDeleteArticle.bind(this);
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleTemplateChange(event, newValue) {
this.props.onTemplateChange(newValue, this.props.template1Indices[this.props.dropdownSelected]);
}
handleCreateTree() {
this.props.onCreateTree(this.props.template1Indices[this.props.dropdownSelected]);
}
handleDeleteArticle() {
this.props.onDeleteArticle(this.props.template1Indices[this.props.dropdownSelected]);
this.setState({"dropdownSelected": 0});
}
handleDropdownChange(event, index, value) {
this.props.onDropdownChange(value);
}
render() {
// note here we can assume template1Articles has length at least 1, otherwise this component won't be rendered by Main
const activeArticle = this.props.template1Articles[this.props.dropdownSelected];
const template = activeArticle.template.p1;
const dropdownOptions = this.props.template1Articles.map((article, count) => {
return <MenuItem
key={article.name}
value={count}
primaryText={article.name}
/>
});
// note here we NEED TO ASSUME that every tree for any article starts with a parent node (that node can have just one child that is a leaf, but it needs at least a child)
// also note that not planning to support reordering of trees (will always be based on order of occurence in the template), so using order as key is fine
const trees = activeArticle.trees.map((tree, i) => {
return <ParentNode
onPromptChange={this.props.onPromptChange}
onChoiceChange={this.props.onChoiceChange}
onCreateChoice={this.props.onCreateChoice}
onDeleteChoice={this.props.onDeleteChoice}
onBranch={this.props.onBranch}
onDeleteParent={this.props.onDeleteParent}
path={[]}
content={tree}
key={i}
articleNum={this.props.template1Indices[this.props.dropdownSelected]}
treeNum={i}
numChoices={tree.choices.length}
isRoot={true}
numTrees={activeArticle.trees.length}
onDeleteTree={this.props.onDeleteTree}
/>;
});
return (
<div>
<SelectField
floatingLabelText="Existing Article Name"
value={this.props.dropdownSelected}
onChange={this.handleDropdownChange}
>
{dropdownOptions}
</SelectField>
{this.props.numArticles > 1 && <RaisedButton
onTouchTap={this.handleDeleteArticle}
label="Delete Current Article"
primary={true}
style={{"margin": "10px"}}
/>}
<br />
<TextField
value={template}
floatingLabelText="Template"
multiLine={true}
fullWidth={true}
onChange={this.handleTemplateChange}
/>
{trees}
<RaisedButton
onTouchTap={this.handleCreateTree}
label="Create New Tree"
primary={true}
style={{"margin": "10px"}}/>
</div>
);
}
}
export default ExistingArticles;
|
import React, { Component, Fragment } from 'react'
import { Container, Row, Col, Jumbotron, Button } from 'react-bootstrap'
import { MyNavbar } from './MyNavbar'
import style from './App.scss'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { renderPentagon } from './ShapeActions'
import { clear } from './AppActions'
class Shape extends Component {
constructor() {
super()
this.goToHome = this.goToHome.bind(this)
}
goToHome() {
this.props.clear()
this.props.history.push('/')
}
componentDidMount() {
if (this.props.app.number < 1)
this.props.history.push('/')
else
this.props.renderPentagon(this.props.app.number, this.props.app.dots)
}
render() {
return (
<Fragment>
<MyNavbar />
<Container className={[style.shape, style.container].join(' ')}>
<Row>
<Col>
<Jumbotron>
<h1>Desenhamos especialmente para você :P</h1>
<h2>{this.props.app.dots} {this.props.app.dots == 1 ? 'ponto' : 'pontos'}</h2>
<div className="pentagon">
<svg viewBox="0 0 500 500">
<circle cx="250" cy="250" r="20" fill="blue" stroke="black" strokeWidth="3" />
{this.props.shape.html}
</svg>
</div>
<Button variant="primary" size="lg" onClick={this.goToHome}>Começar de novo ;)</Button>
</Jumbotron>
</Col>
</Row>
</Container>
</Fragment>
)
}
}
const mapStateToProps = state => {
return {
app: state.app,
shape: state.shape
}
}
const mapDispatchToProps = dispatch => bindActionCreators({ renderPentagon, clear }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(Shape)
|
var test = require("tape");
function asyncTest(name, cb) {
test(name, function (t) {
cb(t).then(function () { return t.end(); });
});
}
exports.asyncTest = asyncTest;
|
/*组合使用构造函数模式和原型模式
* 构造函数定义实例属性,原型模式定义方法和共享的属性
* */
function Person(name,age){
this.name = name;
this.age = age;
this.friends=["persona","personb"];
}
Person.prototype={
constructor:Person,
getName:function(){
console.log(this.name);
}
};
var person1=new Person('xiaochuan',21);
var person2=new Person('dachuan',26);
person1.friends.push('personc');
console.log(person1.friends); //[ 'persona', 'personb', 'personc' ]
console.log(person2.friends); //[ 'persona', 'personb' ]
|
#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = __importDefault(require("commander"));
const config_1 = require("./config");
const child_process_1 = require("child_process");
const fs_1 = require("fs");
const bufferSize = process.env.BUFFER_SIZE || '50000';
const executeCmd = (machine, command) => {
return new Promise((resolve, reject) => {
const prefixA = `${machine.shortName}: `;
const prefixB = `\n${machine.shortName}> `;
const sizeLine = process.stdout.columns - prefixA.length - 1;
let dataOut = '';
const filterData = (data) => data
// .replace(/(\r|\n)$/, '')
.split('\n')
.map(v => {
const totalLines = Math.ceil(v.length / sizeLine);
let result = '';
for (let x = 0; (x < totalLines && !commander_1.default.trunc) || x === 0; x++) {
const subPart = v.substr(x * sizeLine, sizeLine);
const prefixResult = x === 0 ? prefixA : prefixB;
result += prefixResult + subPart;
}
return result;
})
.join('\n');
const shell = machine.local
? { shell: '/bin/sh', args: [] }
: {
shell: 'ssh',
args: [
// '-t',
`-p ${machine.port}`,
`${machine.user}@${machine.name}`,
'/bin/sh'
]
};
const shellCmd = child_process_1.spawn(shell.shell, shell.args);
shellCmd.stdout.on('data', data => {
dataOut += data.toString();
});
shellCmd.stderr.on('data', data => {
dataOut += data.toString();
});
shellCmd.on('close', code => {
if (code !== 0)
dataOut += `\n${machine.shortName}: exit with code ${code}`;
resolve(filterData(dataOut));
});
shellCmd.stdin.write(`export LINES=${bufferSize}\n`);
shellCmd.stdin.write(`export COLUMNS=${bufferSize}\n`);
shellCmd.stdin.write('export TERM=vt220\n');
shellCmd.stdin.write(command);
shellCmd.stdin.end();
});
};
const readScript = (file) => {
if (fs_1.existsSync(file)) {
return fs_1.readFileSync(file).toString();
}
console.error(`File ${file} not found!`);
return '\n';
};
const executeAll = (cmd) => {
console.log('Cluster Execution:', cmd.split('\n'));
const nodesToRun = config_1.clusterConfig.machine.filter(m => commander_1.default.tag === undefined || m.tags.includes(commander_1.default.tag));
const allPromises = nodesToRun.map(m => executeCmd(m, cmd));
Promise.all(allPromises).then(allLogs => allLogs.forEach(log => console.log(log)));
};
commander_1.default
.helpOption('-h, --help', 'show options')
.option('--no-trunc', 'no truncate lines')
.option('-t, --tag <tag>', 'only nodes with specific tag')
.option('-l, --list', 'list all nodes in cluster', () => {
console.log('Servidores encontrados:', config_1.clusterConfig.machine);
});
commander_1.default.command('exec-script <script>').action((env, others) => {
executeAll(readScript(env));
});
commander_1.default
.command('*')
.alias('exec-command')
.action((env, others) => {
executeAll(others.join(' '));
});
commander_1.default.parse(process.argv);
|
global.ROUTER.web.temp = {};
|
var app = angular.module("app", []);
app.controller("AppCtrl", function ($scope, $http) {
$scope.doLogin = function () {
var data = $.param({
user: $scope.username,
pwd: $scope.password
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('http://vendorbloomapi.azurewebsites.net/api/user/authenticate', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
});
|
#! /usr/bin/env node
let args = process.argv.slice(2)
if(!args[0]) {
console.log("Commands:\nping")
process.stdin.on("data", (data) => {
require(`./commands/${data.slice(0, -2)}.js`).run(args)
})
} else {
try {
const cmd = require(`./commands/${args[0]}`)
cmd.run(args)
} catch(err) {
if(err.code === "MODULE_NOT_FOUND") {
const cmd = require(`./commands/help.js`)
cmd.run(args)
} else {
console.log(`Error: ${err.message}\n${err.stack}`)
}
}
}
|
// Exercise 1.0
// ------------
const targetBody = document.querySelector("body");
targetBody.addEventListener("mousedown", (event) => {
const addText = document.createElement("p");
addText.innerText = "You Win!";
targetBody.appendChild(addText);
});
console.log('exercise-1');
|
import React, { Component } from 'react'
import Demo1 from './Demo1.js';
import Demo2 from './Demo2.js';
export default class Index extends Component {
render() {
return (
<div>
<Demo1 />
{/* <Demo2 /> */}
</div>
)
}
}
|
"use strict";
/*global alert: true, ODSA, PARAMS */
$(document).ready(function () {
// Process about button: Pop up a message with an Alert
function about() {
alert(ODSA.AV.aboutstring(interpret(".avTitle"), interpret("av_Authors")));
}
// Set click handlers
$("#about").click(about);
function init() {
var nodeNum = 10;
if (bh) {
bh.clear();
}
$.fx.off = true;
var test = function (data) {
bh = av.ds.binheap(data, {size: nodeNum, stats: true, tree: false});
var stats = bh.stats;
bh.clear();
return (stats.swaps > 3 && stats.recursiveswaps > 0 && stats.leftswaps > 0 &&
stats.rightswaps > 0 && stats.partlyrecursiveswaps > 0);
};
initData = JSAV.utils.rand.numKeys(10, 100, nodeNum, {test: test, tries: 50});
// Log the initial state of the exercise
var exInitData = {};
exInitData.gen_array = initData;
ODSA.AV.logExerciseInit(exInitData);
bh = av.ds.binheap(initData, {heapify: false});
swapIndex = av.variable(-1);
av._undo = [];
$.fx.off = false;
return bh;
}
function model(modeljsav) {
var modelbh = modeljsav.ds.binheap(initData, {heapify: false, nodegap: 20});
modelbh.origswap = modelbh.swap; // store original heap grade function
// set all steps gradeable that include a swap
modelbh.swap = function (ind1, ind2, opts) {
this.origswap(ind1, ind2, opts);
this.jsav.stepOption("grade", true);
};
modeljsav._undo = [];
for (var i = Math.floor(modelbh.size() / 2); i > 0; i--) {
modeljsav.umsg(interpret("av_c1") + i + ")");
modeljsav.step();
modeljsav.umsg("");
modelbh.heapify(i);
}
return modelbh;
}
function fixState(modelHeap) {
var size = modelHeap.size();
swapIndex.value(-1); // only swaps are graded so swapIndex cannot be anything else after correct step
for (var i = 0; i < size; i++) {
if (bh.value(i) !== modelHeap.value(i)) {
bh.value(i, modelHeap.value(i));
}
}
bh.unhighlight(true); // unhighlight all
bh.heapsize(modelHeap.heapsize());
}
function clickHandler(index) {
av._redo = []; // clear the forward stack, should add a method for this in lib
var sIndex = swapIndex.value();
if (sIndex === -1) { // if first click
bh.highlight(index);
swapIndex.value(index);
av.step();
} else if (sIndex === index) { // 2nd click on same index -> unselect
bh.unhighlight(index);
swapIndex.value(-1);
av.step();
} else { // second click will swap
bh.swap(sIndex, index, {});
bh.unhighlight([sIndex, index]);
swapIndex.value(-1);
exercise.gradeableStep();
}
}
//////////////////////////////////////////////////////////////////
// Start processing here
//////////////////////////////////////////////////////////////////
// AV variables
var initData,
bh,
swapIndex,
pseudo,
// Load the configurations created by odsaAV.js
config = ODSA.UTILS.loadConfig(),
interpret = config.interpreter,
code = config.code,
codeOptions = {after: {element: $(".instructions")}, visible: true},
settings = config.getSettings(); // Settings for the AV
// Create a JSAV instance
var av = new JSAV($('.avcontainer'), {settings: settings});
av.recorded();
// show a JSAV code instance only if the code is defined in the parameter
// and the parameter value is not "none"
if (PARAMS["JXOP-code"] && code) {
pseudo = av.code($.extend(codeOptions, code));
}
$(".jsavcontainer").on("click", ".jsavindex", function () {
var index = $(this).parent(".jsavarray").find(".jsavindex").index(this);
clickHandler(index);
}).on("click", ".jsavbinarynode", function () {
var index = $(this).data("jsav-heap-index") - 1;
clickHandler(index);
});
var exercise = av.exercise(model, init,
{controls: $('.jsavexercisecontrols'), fix: fixState});
exercise.reset();
});
|
/* eslint-disable no-console */
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const { getData } = require('../database/index.js');
const app = express();
const port = 3003;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// serve static files
app.use(express.static(path.join(__dirname, '../client/dist')));
// get request response for property_id = 0
app.get('/api/0', (req, res) => {
getData((error, results) => {
if (error) {
console.log('error retrive data from reviews table: ', error);
} else {
console.log('successfully get data from reviews table!');
res.send(results);
}
});
});
// start server on port 3003
app.listen(port, () => console.log(`app listening on port ${port}!`));
|
var Client = require('coinbase').Client;
var client = new Client({'apiKey': "blah", 'apiSecret': "blahh"});
client.getBuyPrice({'currencyPair': 'BTC-USD'}, function(err, obj) {
console.log('total amount: ' + obj.data.amount);
});
|
/**
* Created by ssanchez on 28/12/15.
*/
/**
* Home controller
*
* @param $rootScope
* @param $scope
* @constructor
*/
function UsersCtrl ($rootScope, $scope, $window) {
}
app
.controller('UsersCtrl', [
'$rootScope',
'$scope',
'$window',
UsersCtrl
]);
|
let arr = ['roll-in-left','slit-in-diagonal-2','slit-in-vertical','roll-in-left','slit-in-diagonal-2','slit-in-vertical'];
//let arr = ['rotate-scale-up','roll-in-left','roll-in-left','roll-in-left','roll-in-left','roll-in-left'];
let dig_box = document.querySelectorAll('.dignities_box');
function test() {
dig_box.forEach(function(card, index){
if (card.getBoundingClientRect().top <= window.innerHeight && card.classList.length <= 1 ) {
card.classList.add(arr[index]);
}
});
}
test();
document.addEventListener('scroll', function(event){
test();
});
|
/* -----------------------------------------
CAROUSEL INIT - /source/js/cagov/carousel.js
----------------------------------------- */
$(document).ready(function () {
$(".carousel-video").initCAVideo();
$('.carousel-content').each(initContent);
// Owl Carousel https://github.com/OwlFonk/OwlCarousel2 Requires Owl Carousel
// 2.0.3+ Banner Carousel Plugin
(function ($) {
$.fn.owlBannerCarousel = function (options) {
var settings = $.extend({
delay: 4000,
smallSearch: true
}, options);
return this.each(function () {
if (settings.smallSearch) {
$('.navigation-search').addClass('small-search');
}
var headerSlider = $('.header-slideshow-banner');
headerSlider.addClass('enabled');
// calculate top of screen on next repaint
window.setTimeout(function () {
var MAXHEIGHT = 450;
var headerTop = headerSlider.offset().top;
var windowHeight = $(window).height();
var height = windowHeight - headerTop;
height = (height > MAXHEIGHT)
? MAXHEIGHT
: height;
// fill up the remaining heaight of this device
headerSlider.css({'height': height});
}, 0)
var $this = $(this);
// If browser is IE9 and below set transition speed to 0
var transitionSpeed = (!$('html').hasClass('oldie'))
? 250
: 0;
// Initiate carousel
$this.owlCarousel({
//responsiveRefreshRate: 0,
items: 1,
smartSpeed: transitionSpeed,
animateOut: 'fadeOut',
loop: true,
autoplay: true,
autoplayTimeout: settings.delay,
autoplayHoverPause: false,
mouseDrag: false,
touchDrag: false,
pullDrag: false,
pagination: true,
dotsClass: 'banner-pager', dotClass: 'banner-control',
dotsContainer: false
});
// Add pause and play buttons
var owlBannerControl = $('<div class="banner-play-pause"><div class="banner-control"><span class="play ca-gov-icon-carousel-play" aria-hidden="true"></span><span class="pause ca-gov-icon-carousel-pause" aria-hidden="true"></span></div></div>');
$this.append(owlBannerControl);
var playControl = owlBannerControl.find('.play').hide();
var pauseControl = owlBannerControl.find('.pause');
playControl.on('click', function() {
$(this).hide(); $(this).parent().removeClass('active');
pauseControl.show(); $this.trigger('play.owl.autoplay', [settings.delay]);
$this.owlCarousel('next'); // Manually play next since autoplay waits for delay
});
pauseControl.on('click', function() { $(this).hide();
$(this).parent().addClass('active'); playControl.show();
$this.trigger('stop.owl.autoplay'); });
// Number the items in .banner-pager
var dots = $('.banner-pager .banner-control'); dots.each(function(){
$(this).find('span').append($(this).index() + 1); });
});
}
}(jQuery));
// Banner Carousel Init
$("body .carousel-banner").owlBannerCarousel();
// Init with options: $(".banner-carousel").owlBannerCarousel({delay: 4000,
// smallSearch:true});
if ($.fn.owlCarousel) {
// Media Carousel Init
$(".carousel-media").owlCarousel({
// all these callbacks are to make sure any js inside carousl items can refresh
// themselves
onResized: function () {
window.setTimeout(function () {
$(window).trigger('resize');
}, 0)
},
onDragged: function () {
window.setTimeout(function () {
$(window).trigger('resize');
}, 0)
},
onTranslated: function () {
window.setTimeout(function () {
$(window).trigger('resize');
}, 0)
},
responsive: true,
margin: 10,
nav: true,
loop: true,
responsiveClass: true,
responsive: {
0: {
items: 1,
nav: true
},
400: {
items: 2
},
700: {
items: 3,
nav: true
},
1000: {
items: 4,
nav: true
}
},
navText: [
'<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>'
],
dots: false
});
// Link Icon Carousel Init
$(".carousel-link").owlCarousel({
margin: 25,
autoWidth: true,
nav: true,
navText: [
'<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>'
],
dots: false
});
// Social Media Slider Init
$(".carousel-slider").owlCarousel({
items: 1,
nav: true,
navText: [
'<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>'
],
dots: false
});
// Gallery Image Slider
$(".carousel-gallery").owlCarousel({
items: 1,
nav: true,
navText: [
'<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>'
],
dots: false
});
}
});
function initContent() {
var carousel = $(this);
$(window).on("load", function () {
carousel.owlCarousel({
items: 1,
autoHeight: true,
loop: true,
nav: true,
navText: [
'<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>'
],
dots: true,
// all these callbacks are to make sure any js inside carousl items can refresh
// themselves
onResized: function () {
window.setTimeout(function () {
$(window).trigger('resize');
}, 0)
},
onDragged: function () {
window.setTimeout(function () {
$(window).trigger('resize');
}, 0)
},
onTranslated: function () {
window.setTimeout(function () {
$(window).trigger('resize');
}, 0)
}
});
carousel.on('changed.owl.carousel', function (event) {
setTimeout(function () {
carousel.find('.owl-item.active .item video').each(function () {
$(this).get(0).play();
})
}, 10)
})
})
}
(function($) {
$.fn.initCAVideo = function(bool) {
// Iterate over each object in collection
return this.each( function() {
var carousel = $(this);
var didSet = carousel.attr("data-loaded");
if (didSet) {
return;
}
carousel.attr("data-loaded", "true");
// get first video
var vidHref = carousel.find('.item a').first().attr('href') || "";
var vidID = vidHref.split("?v=").pop();
var mainIndex = 0;
var length = carousel.find('.item').length;
// Video Slider
carousel.owlCarousel({
items: 1,
loop: false,
nav: true,
lazyLoad: false,
video: true,
navText: [
'<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>'
],
dots: false
});
carousel.on('translated.owl.carousel', function(event) {
// get current video id
vidID = carousel.find('.owl-item.active')
.attr('data-video').split(/\?v=|\/v\//).pop();
setCurrentSubVideo();
mainIndex = event.item.index;
// show the item in view
submenu.trigger('to.owl.carousel', [ mainIndex, 300, true ] )
});
// create the proper video play icon for each video image preview
carousel.find('.owl-video-play-icon').append($('<span class="ca-gov-icon-play" />'));
// create the overlay for each video image preview
carousel.find('.owl-video-tn').after($('<div />').addClass('item-overlay'));
// the submenu lives as a sibling to the carousel.
var submenu = $('<div></div>').insertAfter(carousel);
submenu.addClass('carousel owl-carousel carousel-video-submenu');
// create the sub menu for the videos
var items = carousel.find('a.owl-video');
items.each(function (index) {
// get this slide and its video url
var oldItem = $(this);
var href = oldItem.attr('href');
// attach the triggers for each thumbnail
var item = $('<div/>').addClass('item-thumbnail');
item.on('click', function () {
// force the main carousel to jump to the requested video
carousel.trigger('to.owl.carousel', [
index % length,
300,
true
]);
submenu.find('.watching').removeClass('watching');
$(this).parents('.owl-item').addClass('watching');
// start playing immediately
carousel.find(".active .owl-video-play-icon").trigger("click");
});
// thumbnail related
var regex = new RegExp('ab+c', 'i');
var youtubeID = href.split(/\?v=|\/v\//).pop();
var youtubeThumb = 'http://img.youtube.com/vi/' + youtubeID + '/0.jpg';
var thumbnail = $('<img />').attr('src', youtubeThumb);
// overlay related
var overlay = $('<div />').addClass('item-overlay');
overlay.append($('<span class="ca-gov-icon-play" />'))
// Append it into the DOM
item.append(thumbnail).append(overlay);
submenu.append(item);
});
submenu = carousel.next();
submenu.on('initialized.owl.carousel', function() {
setCurrentSubVideo();
});
// have owlCarousel init this submenu
submenu.owlCarousel({
items: 4,
loop: false,
nav: true,
margin: 20,
dots: false,
navText: ['<span class="ca-gov-icon-arrow-prev" aria-hidden="true"></span>', '<span class="ca-gov-icon-arrow-next" aria-hidden="true"></span>']
});
submenu.on('changed.owl.carousel', function() {
setTimeout(setCurrentSubVideo, 50);
});
function setCurrentSubVideo() {
// remove old watched item
submenu.find('.watching').removeClass('watching');
submenu.find('img[src*="' + vidID + '"]').parents('.owl-item').addClass('watching');
}
});
}
}(jQuery));
|
define([],
function() {
return {
name: 'footer',
init: function() {
this.pageInit()
},
pageInit: function() {
var aqImg = $("#anquanBox").find("img");
setTimeout(function() {
$("#anquanImg").html(aqImg[0]).css({
"width": aqImg.width(),
"height": aqImg.height()
})
}, 1000);
$('li[data-tab="problems"]').on("click",function(){
var idx = $(this).index();
$("#tab_nav").find("a").eq(idx).trigger('click');
})
}
}
})
|
define(["QDP"], function (QDP) {
"use strict";
return {
define: {
name: "商户上线成功率统计",
version: "1.0.0.0",
copyright: " Copyright 2017-2027 WangXin nvlbs,Inc."
},
/** 加载模块 */
init: function () {
var options = {
"apis": { "list": QDP.api.logs.datas },
"plugins": ['city'],
"columns": [
{ name: "_index", text: "序号" },
{ name: "province_code", text: "省份", dict: "province", filter: true, filterindex: 1 },
{ name: "city_code", text: "地市", dict: "city", filter: true, filterindex: 2 },
{ name: "county_code", text: "区县", dict: "county", filter: true, filterindex: 3 },
{ name: "begin_date", text: "订单开始时间", type: "date", filter: true, filterindex: 4, display: false },
{ name: "end_date", text: "订单结束时间", type: "date", filter: true, filterindex: 5, display: false },
{ name: "n1", text: "通过上线审核总数" },
{ name: "n2", text: "发起上线审核总数" },
{ name: "n3", text: "上线通过率" },
{ name: "n4", text: "上线成功率" },
{ name: "n5", text: "上线数量" },
{ name: "n6", text: "发布数量" },
]
};
QDP.generator.init(options);
},
/** 卸载模块 */
destroy: function () {
}
};
});
|
// create svg canvas
const canvHeight = 600, canvWidth = 800;
const svg = d3.select("body").append("svg")
.attr("width", canvWidth)
.attr("height", canvHeight)
.style("border", "1px solid");
// calc the width and height depending on margins.
const margin = { top: 50, right: 80, bottom: 50, left: 60 };
const width = canvWidth - margin.left - margin.right;
const height = canvHeight - margin.top - margin.bottom;
// chart title
svg.append("text")
.attr("y", 0)
.attr("x", margin.left)
.attr("dy", "1.5em")
.attr("font-family", "sans-serif")
.attr("font-size", "24px")
.style("text-anchor", "left")
.text("Height vs Weight");
// create parent group and add left and top margin
const g = svg.append("g")
.attr("id", "chart-area")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// text label for the x axis
g.append("text")
.attr("y", height + margin.bottom / 2)
.attr("x", width / 2)
.attr("dy", "1em")
.attr("font-family", "sans-serif")
.style("text-anchor", "middle")
.text("Height");
// text label for the y axis
g.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.attr("font-family", "sans-serif")
.style("text-anchor", "middle")
.text("Weight");
function createLegend(legendDomain, colorScale) {
// 1. create a group to hold the legend
// 2. create the legend boxes and the text label
// a. use .data(legendDomain) on an empty DOM selection
// store enter()-loop in variable legend_entry
// b. add coloured rect to legend_entry
// c. add text label to legend_entry
// 3. create the main border of the legend
}
// load the data from the cleaned csv file.
// note: the call is done asynchronous.
// That is why you have to load the data inside of a
// callback function.
d3.csv("./data/persons.csv").then(function (data) {
const heightDomain = d3.extent(data, d => Number(d.Height));
const weightDomain = d3.extent(data, d => Number(d.Weight));
// 1. create scales for x and y direction and for the color coding
const xScale = d3.scaleLinear()
.domain(heightDomain)
.rangeRound([0, width])
.nice(5);
const yScale = d3.scaleLinear()
.domain(weightDomain)
.rangeRound([height, 0])
.nice(5);
const colorScale = d3.scaleOrdinal(d3.schemeCategory10);
// 2. create and append
// a. x-axis
// create xAxis
const xAxis = d3.axisBottom(xScale);
g.append("g") // create a group and add axis
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// b. y-axis
const yAxis = d3.axisLeft(yScale);
g.append("g") // create a group and add axis
.call(yAxis);
// 3. add data-points (circle)
// add circle
g.selectAll("circle") // this results in an empty selection
.data(data) // which is joined with the data
.enter() // and a selection of new elements is created
.append("circle")
.attr("cx", d => xScale(d.Height))
.attr("cy", d => yScale(d.Weight))
.attr("r", 4)
.style("fill", d => colorScale(d["Shirt Size"]));
// 4. create legend
legendDomain = ["S", "M", "L"];
createLegend(legendDomain, colorScale);
// 5. Create tooltip
//var tooltip = d3.select("body").append("div").classed("tooltip", true);
});
|
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import test1 from '@/components/test1'
import test2 from '@/components/test2'
import test3 from '@/components/test3'
Vue.use(Router)
Vue.use(BootstrapVue)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test1',
name: 'test1',
component: test1
},
{
path: '/test2',
name: 'test2',
component: test2
},
{
path: '/test3',
name: 'test3',
component: test3
}
]
})
|
// 如果是export default 的方式导出的, 那么在导入时可以任意的取名字
import dname from './06-exportDefault-daochu.js'
console.log(dname);
|
const openhabConfig = {
baseUrl: 'http://otto.local:8080',
events: {
endpoint: '/rest/events',
subscribe: [
'ITEM_ADDED',
'ITEM_REMOVED',
'ITEM_STATE_CHANGED',
'THING_ADDED',
'THING_REMOVED',
'THING_STATUS_INFO_CHANGED',
'CHANNEL_TRIGGERED',
],
},
};
module.exports.openhabConfig = openhabConfig;
|
function addButtons() {
var button = document.createElement("button");
button.innerHTML = "Start Game";
button.addEventListener("click", () => {
game.start();
});
get("menu").appendChild(button);
}
|
import * as Turbo from '@hotwired/turbo';
import * as Bootstrap from 'bootstrap';
import { Application } from '@hotwired/stimulus';
import { definitionsFromContext } from '@hotwired/stimulus-webpack-helpers';
import ApplicationController from './controllers/application_controller';
window.Turbo = Turbo;
window.Bootstrap = Bootstrap;
window.application = Application.start();
window.Controller = ApplicationController;
const context = require.context('./controllers', true, /\.js$/);
application.load(definitionsFromContext(context));
window.addEventListener('turbo:before-fetch-request', (event) => {
let state = document.getElementById('screen-state').value;
if (state.length > 0) {
event.detail?.fetchOptions?.body?.append('_state', state)
}
});
|
import React from 'react';
const ImpactFactor ={
title: "Impact Factor",
options: [
{ value: "All" },
{ value: "50+" },
{ value: "100+" },
{ value: "500+" },
{ value: "1000+" }
]
}
const ArticleType = {
title: "Article Type",
options: [
{ value: "Books and Document" },
{ value: "Clinical Trial" },
{ value: "Meta-Analysis" },
{ value: "Randomized Controlled Trial" },
{ value: "Review" },
{ value: "Systematic Reviews" }
]
}
export default class FilterComponent extends React.Component{
// TODO: state should only refer to the current value.
state = {
filter: [ ImpactFactor, ArticleType ]
}
render(){
return(
<form className="basic-margin">
<div className="form-row"> {
this.state.filter.map((value, index) => { return (
<div className="col" key={ index }>
<span>{ value.title }</span>
<select className="browser-default custom-select"> {
value.options.map((option, index) => { return (
<option value={ option.value } key={ index }>
{ option.value }
</option>
)})
}
</select>
</div>
)})
}
<button type="button" className="btn btn-deep-orange">Apply</button>
<button type="button" className="btn btn-dark-green">Search</button>
</div>
</form>
)
}
}
|
import { Data, newCharacter, newSkill, newSkillEffect, newDamageSkill, newSingleTargetDamageSkill, newBasicSingleTargetDamageSkill } from '../CharacterDataStructure'
Data.characters.push(newCharacter('Remilia Scarlet', 'https://en.touhouwiki.net/images/thumb/e/e7/Th105Remilia.png/413px-Th105Remilia.png', 18, 80, 140, [
newSkill('Vampire Claw', 'enemy', 0, [
newSkillEffect('DamageTargetWithLifeSteal', {
scaling: 0.8,
boostscaling: 0,
lifesteal: 0.4
})]),
newSkill('Divine Spear "Spear the Gungnir"', 'enemy', 10, [
newSkillEffect('ExecuteTarget', {
scaling: 1.3,
boostscaling: 0.2
})]),
newSkill('Destiny "Miserable Fate"', 'enemy', 30, [
newSkillEffect('ApplyBasicCondition', {
name: 'Miserable Fate (power)',
attribute: 'attack',
value: -0.4,
boostscaling: 0.2,
duration: 30
}),
newSkillEffect('ApplyBasicCondition', {
name: 'Miserable Fate (agility)',
attribute: 'speed',
value: -0.4,
boostscaling: 0.2,
duration: 30
})])
]))
|
/*console.log("holi")*/
class Persona{
constructor(name,edad,telefono,email){
this.nombre = name
this.edad = edad
this.telefono = telefono
this.email = email
}
presentarse(){
return "Hola me llamo" + this.name + " y tengo " + this.edad + " años. "
}
correr(){
return "Estoy corriendo"
}
}
var x = 1
var arturo = new Persona ("Arturo",34,554123321213,"arturo@gmail.com")
console.log(arturo.presentarse())
var daniel = new Persona ("Daniel",26,41231231,"daniel@gmail.com")
console.log(daniel.presentarse())
let ken = new Desarrollador ("Ken",25,12341231,"ken@gmail.com","ensamblador")
console.log(daniel.presentarse())
console.log(daniel.programar())
//crear un objeto de tipo triángulo con atributo base y altura y tener el metodo area y perimetro - base x altura / 2 es el area de un triángulo - la suma de los lados es el perimetro
class Triangulo{
constructor(base,altura){
this.base = base
this.altura = altura
}
area(){
return "El area de este triangulo es " + ((this.base*this.altura)/2)
}
perimetro(){
return "El perimetro es " + (this.lados+this.lados)
}
}
var triangulo = new Triangulo (4,2)
console.log(triangulo.area())
class Desarrollador extends Persona{
constructor(name,edad,telefono,email,lenguaje)
super(name,edad,telefono,email)
this.lenguaje = lenguaje
}
programar(){
return "El desarrollador" + this.name + " está programando " + this.lenguaje
}
|
import _ from 'lodash';
/**
*
* @param {any} items
* @param {string} sortKey
* @param {'asc'|'desc'}sortOrder
* @returns any[]
*/
export const sorter = (items, sortKey, sortOrder) => {
return _.orderBy(items, [sortKey], [sortOrder]);
};
|
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { APP_BASE_HREF } from '@angular/common';
import { EnvService } from './shared/env/env.service';
import { ServerEnvService } from './shared/env/server.env.service';
var AppServerModule = (function () {
function AppServerModule() {
}
return AppServerModule;
}());
export { AppServerModule };
AppServerModule.decorators = [
{ type: NgModule, args: [{
imports: [
ServerModule,
AppModule
],
bootstrap: [
AppComponent
],
providers: [
// { provide: NgModuleFactoryLoader, useClass: ServerRouterLoader }
{ provide: APP_BASE_HREF, useValue: '/' },
{ provide: EnvService, useClass: ServerEnvService }
]
},] },
];
/** @nocollapse */
AppServerModule.ctorParameters = function () { return []; };
|
angular.module("ngApp.previewMAWB")
.controller("PreviewMAWBAddressController", function ($scope, $state, PreviewMAWBService, TradelaneBookingService, TopCountryService, $translate, Address, $uibModalInstance, toaster, ModalService, SessionService, AppSpinner, DirectBookingService, DirectShipmentService, $rootScope, TradelaneShipmentService, DateFormatChange) {
//Set Multilingual for Modal Popup
var setModalOptions = function () {
$translate(['FrayteSuccess', 'Frayte-Error', 'FrayteWarning', 'Error_In_Updating_Address', 'Please_Correct_Validation_Error']).then(function (translations) {
$scope.FrayteSuccess = translations.FrayteSuccess;
$scope.FrayteWarning = translations.FrayteWarning;
$scope.FrayteError = translations.FrayteError;
$scope.Error_In_Updating_Address = translations.Error_In_Updating_Address;
$scope.Please_Correct_Validation_Error = translations.Please_Correct_Validation_Error;
});
};
//end
$scope.editAddress = function (Type) {
if (Type) {
ModalInstance = $uibModal.open({
Animation: true,
templateUrl: 'previewMAWB/mawb.tpl.html',
controller: 'PreviewMAWBController',
keyboard: true,
windowClass: 'DirectBookingDetail',
size: 'lg',
backdrop: 'static',
resolve: {
Address: function () {
if (Type === "Shipper") {
return $scope.mAwbDetail.ShipmentDetail.ShipFrom;
}
else {
return $scope.mAwbDetail.ShipmentDetail.ShipTo;
}
}
}
});
}
};
$scope.shipFromToggleState = function (Country) {
return TradelaneBookingService.toggleState(Country);
};
$scope.changeAddress = function (IsValid) {
if (IsValid) {
console.log($scope.address);
PreviewMAWBService.ChangeAddress($scope.address).then(function (response) {
$uibModalInstance.close();
}, function () {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Error_In_Updating_Address,
showCloseButton: true
});
});
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.Please_Correct_Validation_Error,
showCloseButton: true
});
}
};
var setStatePostCodeForHKGUK = function (Country, Type) {
if (Country.Code === 'HKG') {
if (Type === 'Shipper') {
$scope.address.PostCode = null;
$scope.address.State = null;
}
}
else if (Country.Code === 'GBR') {
if (Type === 'Shipper') {
$scope.address.State = null;
}
}
};
$scope.SetShipinfo = function (Country, Action) {
if (Country) {
if (Action === 'Shipper') {
$scope.showPostCodeDropDown = false;
for (var i = 0 ; i < $scope.CountryPhoneCodes.length ; i++) {
if ($scope.CountryPhoneCodes[i].CountryCode === Country.Code) {
$scope.ShipFromPhoneCode = "(+" + $scope.CountryPhoneCodes[i].PhoneCode + ")";
break;
}
}
}
setStatePostCodeForHKGUK(Country, Action);
}
};
var screenInitials = function () {
TradelaneBookingService.BookingInitials($scope.userInfo.EmployeeId).then(function (response) {
// Set Country type according to given order
$scope.CountriesRepo = TopCountryService.TopCountryList(response.data.Countries);
$scope.CountryPhoneCodes = response.data.CountryPhoneCodes;
$scope.SetShipinfo($scope.address.Country, "Shipper");
},
function (response) {
});
};
function init() {
$scope.Template = 'directBooking/ajaxLoader.tpl.html';
$scope.userInfo = SessionService.getUser();
setModalOptions();
if ($scope.userInfo) {
if (Address) {
$scope.address = Address;
}
screenInitials();
}
else {
$state.go("login");
}
}
init();
});
|
import React from "react";
import featureone from "../../crispimage/feature1.png";
import featuretwo from "../../crispimage/feature2.png";
import featurethree from "../../crispimage/feature3.png";
import featurefour from "../../crispimage/feature4.png";
const Feature = () => {
return (
<section class="feature p-6 container-full bg-primary">
<div className="content-65">
<h6 class="light-text">As feature in</h6>
<div className="companies">
<img src={featureone} class="logo-nav" alt="" />
<img src={featuretwo} class="logo-nav" alt="" />
<img src={featurethree} class="logo-nav" alt="" />
<img src={featurefour} class="logo-nav" alt="" />
<img src={featureone} class="logo-nav" alt="" />
<img src={featuretwo} class="logo-nav" alt="" />
<img src={featurethree} class="logo-nav" alt="" />
<img src={featurefour} class="logo-nav" alt="" />
</div>
</div>
</section>
);
};
export default Feature;
|
import React, { Component } from 'react';
import StarRatingComponent from 'react-star-rating-component';
import './EditBookForm.css'
class EditBookForm extends Component {
constructor(props) {
super(props);
this.state = {
title: this.props.book.title,
author: this.props.book.author,
publisher: this.props.book.publisher,
publicationDate: this.props.book.publicationDate,
rating: this.props.book.rating,
status: this.props.book.status
}
this.onChange = this.onChange.bind(this);
this.onSelectChange = this.onSelectChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSelectChange(e) {
this.setState({ status: e.target.value });
}
onSubmit(e) {
e.preventDefault();
const book = {
title: this.state.title,
author: this.state.author,
publisher: this.state.publisher,
publicationDate: this.state.publicationDate,
rating: this.state.rating,
status: this.state.status,
editing: false
}
this.props.store.dispatch({ type: 'UPDATE', id: this.props.book.id, data: book })
}
onStarClick(nextValue, prevValue, name) {
this.setState({ rating: nextValue });
}
render() {
return (
<div class='edit-book-form'>
<h2>Edit Book</h2>
<form onSubmit={this.onSubmit} id="edit-book-form">
<div>
<label>Title: </label>
<br />
<input class='edit-text-limit' required maxlength="64" type="text" name="title" placeholder={this.state.title} onChange={this.onChange} value={this.state.title} />
</div>
<div>
<label> Author: </label><br />
<input class='edit-text-limit' required maxlength="64" type="text" name="author" value={this.state.author} onChange={this.onChange} />
</div>
<div>
<label> Publisher: </label><br />
<input class='edit-text-limit' required maxlength="64" type="text" name="publisher" value={this.state.publisher} onChange={this.onChange} />
</div>
<div>
<label> Publication Date: </label><br />
<input type="text"
name="publicationDate"
data-parse="date"
placeholder="MM/DD//YYYY"
pattern="\d{2}\/\d{2}/\d{4}"
value={this.state.publicationDate}
onChange={this.onChange} required
/>
</div>
<div>
<label> Rating: </label><br />
<StarRatingComponent class= "browser-default"
name='rating'
starCount={3}
value={this.state.rating}
onStarClick={this.onStarClick.bind(this)}
/>
</div>
<div>
<label> Status: </label><br />
<select value={this.state.status} onChange={this.onSelectChange}>
<option value="Checked In">Checked In</option>
<option value="Checked Out">Checked Out</option>
</select>
</div>
<br />
<button type="submit">Save</button>
</form>
</div>
)
}
}
export default EditBookForm;
|
import { EventEmitter } from "events";
import { mapActions, mapComputed, mapEffects } from "./utils";
export default class Store extends EventEmitter {
constructor({ actions = {}, state = {}, computed = {}, effects = {} }) {
super();
const update = setState.bind(this);
this.state = state;
this.actions = mapActions.call(this, actions);
this.computed = mapComputed.call(this, computed);
this._computed = computed;
this.effects = mapEffects.call(this, effects, update);
}
getState = () => {
return this.state;
};
dispatch = (key, ...args) => {
this.actions[key](...args);
};
commit = (key, ...args) => {
this.effects[key](...args);
};
}
const setState = function(state) {
this.state = { ...this.state, ...state };
this.computed = mapComputed.call(this, this._computed);
this.emit("update", this);
Object.keys(state).forEach(key => {
this.emit(key, this.state[key]);
});
};
|
describe("Expandable content", function () {
"use strict";
var $fixture;
describe("with default settings", function () {
beforeEach(function () {
fixture.load("expandable_content/default.html.erb");
$fixture = $(fixture.el).find('[data-module="expandable-content"]');
new GOVUKAdmin.Modules.ExpandableContent().start($fixture);
});
it("starts with the content collapsed", function () {
expect(content()).not.toHaveClass("in");
});
it("shows the expansion button", function () {
expect(buttonWrapper()).not.toHaveClass("hidden");
});
it("starts with the button collapsed", function () {
expect(button()).toHaveClass("collapsed")
});
});
describe("starting expanded", function () {
beforeEach(function () {
fixture.load("expandable_content/start_expanded.html.erb");
$fixture = $(fixture.el).find('[data-module="expandable-content"]');
new GOVUKAdmin.Modules.ExpandableContent().start($fixture);
});
it("starts with the content expanded", function () {
expect(content()).toHaveClass("in");
});
it("shows the expansion button", function () {
expect(buttonWrapper()).not.toHaveClass("hidden");
});
it("starts with the button not collapsed", function () {
expect(button()).not.toHaveClass("collapsed");
});
});
function buttonWrapper() {
return $fixture.find(".js-expand-button-wrapper").first();
}
function button() {
return $fixture.find("button").first();
}
function content() {
return $fixture.find("#additionalContent").first();
}
});
|
// validation event listeners
var myForm = document.getElementById("shipping");
var c = 0;
myForm.addEventListener('submit', function(event) {
// stop the event from its default action: submitting the form (for our validation, submission is not desired)
var fName = document.querySelector('input[name=first-name]');
var lName = document.querySelector('input[name=last-name]');
var address = document.querySelector('input[name=address]');
var city = document.querySelector('input[name=city]');
var country = document.querySelector('input[name=country]');
var fVal = fName.value;
var lVal = lName.value;
var aVal = address.value;
var cityVal = city.value;
var countryVal = country.value;
alert('number '+ c++ + " " +fVal);
if (!validator.isTrimmed(fVal) || validator.isEmpty(fVal)) {
fName.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
} else {
fName.setCustomValidity("");
}
if (!validator.isTrimmed(lVal) || validator.isEmpty(lVal)) {
lName.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
} else {
lName.setCustomValidity("");
}
// if (!validator.isTrimmed(aVal) || validator.isEmpty(aVal)) {
// address.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// address.setCustomValidity("");
// }
// if (!validator.isTrimmed(cityVal) || validator.isEmpty(cityVal)) {
// city.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// city.setCustomValidity("");
// }
// if (!validator.isTrimmed(countryVal) || validator.isEmpty(countryVal)) {
// country.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// country.setCustomValidity("");
// }
// var billing = document.querySelector("input[name=same]").checked;
// if (!billing){
// var bfName = document.querySelector('input[name=b-first-name]');
// var blName = document.querySelector('input[name=b-last-name]');
// var baddress = document.querySelector('input[name=b-address]');
// var bcity = document.querySelector('input[name=b-city]');
// var bcountry = document.querySelector('input[name=b-country]');
// var bfVal = bfName.value;
// var blVal = blName.value;
// var baVal = baddress.value;
// var bcityVal = bcity.value;
// var bcountryVal = bcountry.value;
// if (!validator.isTrimmed(bfVal) || validator.isEmpty(bfVal)) {
// bfName.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// bfName.setCustomValidity("");
// }
// if (!validator.isTrimmed(blVal) || validator.isEmpty(blVal)) {
// blName.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// blName.setCustomValidity("");
// }
// if (!validator.isTrimmed(baVal) || validator.isEmpty(baVal)) {
// baddress.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// baddress.setCustomValidity("");
// }
// if (!validator.isTrimmed(bcityVal) || validator.isEmpty(bcityVal)) {
// bcity.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// bcity.setCustomValidity("");
// }
// if (!validator.isTrimmed(bcountryVal) || validator.isEmpty(bcountryVal)) {
// bcountry.setCustomValidity("Please double check your entry, it is either empty or has too many spaces");
// } else {
// bcountry.setCustomValidity("");
// }
// }
event.preventDefault();
});
|
import Homepage from './homepage';
import {connect} from '../data';
export default connect(() => `/data.json`, data => ({
hero: data.page.hero,
posts: data.posts.items.slice(0, 3)
}))(Homepage);
|
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
var Dom =
/*#__PURE__*/
function () {
function Dom() {
_classCallCheck(this, Dom);
}
_createClass(Dom, [{
key: "findByClass",
value: function findByClass(className) {
return document.querySelector(className);
}
}, {
key: "findById",
value: function findById(id) {
return document.getElementById(id);
}
}, {
key: "createEl",
value: function createEl() {
return document.createElement('div');
}
}, {
key: "destroyEl",
value: function destroyEl(el) {
if (el !== null) {
return el.parentNode.removeChild(el);
}
}
}, {
key: "setClass",
value: function setClass(parent, className) {
parent.className = "".concat(className);
}
}, {
key: "setId",
value: function setId(parent, id) {
parent.setAttribute('id', id);
}
}, {
key: "setBackground",
value: function setBackground(parent, image) {
image = image.toLowerCase();
parent.style.backgroundImage = "url(images/".concat(image, ".png)");
}
}, {
key: "setBackgroundColor",
value: function setBackgroundColor(parent, color) {
parent.style.backgroundImage = 'none';
parent.style.backgroundColor = "".concat(color);
}
}, {
key: "addChild",
value: function addChild(parent, child) {
parent.appendChild(child);
}
}, {
key: "removeChild",
value: function removeChild(parent, child) {
parent.removeChild(child);
}
}, {
key: "clear",
value: function clear(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
}, {
key: "setHTML",
value: function setHTML(parent, html) {
parent.innerHTML = "".concat(html);
}
}, {
key: "setText",
value: function setText(parent, text) {
parent.innerText = text;
}
}, {
key: "addListener",
value: function addListener(parent, type, action) {
return parent.addEventListener("".concat(type), action);
}
}, {
key: "createField",
value: function createField() {
return document.createElement('input');
}
}, {
key: "createButton",
value: function createButton(text) {
var button = document.createElement('button');
this.setText(button, text);
return button;
}
}]);
return Dom;
}();
export { Dom as default };
|
function route(process, pathname, response, postData) {
if (typeof process[pathname] === 'function' ) {
return process[pathname](response, postData);
} else {
console.log("no processor found for " + pathname);
return "error"
}
}
exports.route = route;
|
const seeder = require("mongoose-seed");
const db = require("./config/keys").mongoURI;
seeder.connect(db, function () {
seeder.loadModels(["models/User.js", "models/View.js", "models/Comment.js"]);
seeder.clearModels(["user"], function() {
seeder.disconnect()
})
// , function () {
// seeder.populateModels(userData, function () {
// seeder.disconnect();
// });
// });
seeder.clearModels(["view"], function() {
seeder.disconnect()
})
// , function () {
// seeder.populateModels(viewData, function () {
// seeder.disconnect();
// });
// });
seeder.clearModels(["comment"], function() {
seeder.disconnect()
})
// , function () {
// seeder.populateModels(commentData, function () {
// seeder.disconnect();
// });
// });
});
// seeder.connect(db, function () {
// seeder.loadModels(["models/User.js", "models/View.js", "models/Comment.js"]);
// seeder.clearModels(["user"], function () {
// seeder.populateModels(userData, function () {
// seeder.disconnect();
// });
// });
// seeder.clearModels(["view"], function () {
// seeder.populateModels(viewData, function () {
// seeder.disconnect();
// });
// });
// seeder.clearModels(["comment"], function () {
// seeder.populateModels(commentData, function () {
// seeder.disconnect();
// });
// });
// });
// const userData = [
// {
// model: "user",
// documents: [
// {
// name: "demo",
// email: "demo@demo.com",
// password:
// "$2a$10$JSwpSv3.03GcRVg.I8luWO9xEcrbn5/NUgm1Bg0qeNLCx8lIXwvuy",
// },
// {
// name: "demo one",
// email: "a@user.com",
// password:
// "$2a$10$ZUjwjnBIlOfhDVN/PqYzh.3d/7OLjzo.5/2CGFM//4zHDQhh/OcPW",
// },
// {
// name: "demo two",
// email: "b@user.com",
// password:
// "$2a$10$ZUjwjnBIlOfhDVN/PqYzh.3d/7OLjzo.5/2CGFM//4zHDQhh/OcPW",
// },
// {
// name: "demo ",
// email: "c@user.com",
// password:
// "$2a$10$ZUjwjnBIlOfhDVN/PqYzh.3d/7OLjzo.5/2CGFM//4zHDQhh/OcPW",
// },
// {
// name: "Prince",
// email: "d@user.com",
// password:
// "$2a$10$ZUjwjnBIlOfhDVN/PqYzh.3d/7OLjzo.5/2CGFM//4zHDQhh/OcPW",
// },
// {
// name: "Carly Simon",
// email: "e@user.com",
// password:
// "$2a$10$ZUjwjnBIlOfhDVN/PqYzh.3d/7OLjzo.5/2CGFM//4zHDQhh/OcPW",
// },
// ],
// },
// ];
// const viewData = [
// {
// model: "view",
// documents: [
// //1
// {
// _id: "60c9209d5af3a21b96a2a068",
// photos: [],
// comments: [],
// latitude: 37.8041386457992,
// longitude: -122.46503785348509,
// locationName: "the drunken oyster",
// },
// //2
// {
// _id: "60c9209d5af3a21b96a2a078",
// photos: [],
// comments: [],
// latitude: 37.810616699474515,
// longitude: 122.47692231355698,
// locationName: "sunnyside",
// },
// //3
// {
// _id: "60c9209d5af3a21b96a2a088",
// photos: [],
// comments: [],
// latitude: 40.71535,
// longitude: -73.95827,
// locationName: "willow glen",
// },
// //4
// {
// _id: "60c9209d5af3a21b96a2a098",
// photos: [],
// comments: [],
// latitude: 37.810616699474515,
// longitude: -122.47692231355698,
// locationName: "china beach",
// },
// //5
// {
// _id: "60c9209d5af3a21b96a2a168",
// photos: [],
// comments: [],
// latitude: 37.810616699474515,
// latitude: -122.47692231355698,
// locationName: "kjdf",
// },
// //6
// {
// _id: "60c9209d5af3a21b96a2a268",
// photos: [],
// comments: [],
// latitude: 37.79629962576967,
// latitude: 122.47795891725578,
// locationName: "kjdf",
// },
// //7
// {
// _id: "60c9209d5af3a21b96a2a368",
// photos: [],
// comments: [],
// latitude: 37.79629962576967,
// latitude: -122.47795891725578,
// locationName: "kjdf",
// },
// //8
// {
// _id: "60c9209d5af3a21b96a2a468",
// photos: [],
// comments: [],
// latitude: 37.79629962576967,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //9
// {
// _id: "60c9209d5af3a21b96a2a568",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //10
// {
// _id: "60c9209d5af3a21b96a2a668",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //11
// {
// _id: "60c9209d5af3a21b96a2a768",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //12
// {
// _id: "60c9209d5af3a21b96a2a868",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //13
// {
// _id: "60c9209d5af3a21b96a2a968",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //14
// {
// _id: "60c9209d5af3a21b96a2a178",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //15
// {
// _id: "60c9209d5af3a21b96a2a278",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //16
// {
// _id: "60c9209d5af3a21b96a2a288",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //17
// {
// _id: "60c9209d5af3a21b96a2a298",
// photos: [],
// comments: [],
// latitude: 40.71535,
// latitude: -73.95827,
// locationName: "kjdf",
// },
// //18
// {
// _id: "60c9209d5af3a21b96a2a308",
// photos: [],
// comments: [],
// latitude: 37.7792829923467,
// latitude: -122.3894637661022,
// locationName: "kjdf",
// },
// //19
// {
// _id: "60c9209d5af3a21b96a2a318",
// photos: [],
// comments: [],
// latitude: 37.76826023975391,
// latitude: -122.46920127394549,
// locationName: "kjdf",
// },
// //20
// {
// _id: "60c9209d5af3a21b96a2a328",
// photos: [],
// comments: [],
// latitude: 37.7792829923467,
// latitude: -122.3894637661022,
// locationName: "kjdf",
// },
// ],
// },
// ];
// const commentData = [
// {
// model: "comment",
// documents: [
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// {
// user: "60632aeb42e8d0a9a732a82f",
// text: "What a view",
// date: 2021 - 06 - 01,
// },
// ],
// },
// ];
|
import React, { useState } from "react"
import { View, Text } from "react-native"
import * as Animatable from 'react-native-animatable';
export default function SuccessMessage(props) {
const [isActive, setIsActive] = useState(props.show || false)
if (isActive) {
return (
<View style={{flexDirection:"column",width:"100%",height:"100%",position:"absolute",alignItems:"center",justifyContent:"center"}}>
<Text>aluruurururu</Text>
</View>
)
}
}
|
$(document).ready(function() {
var index=1;
var time;
var leftvalue;
var number=2;
var animated;
var offset=$(".slides").width();
//循环播放
time=setInterval(go,3000);
//动画
function go(){
leftvalue=$(".slides .img_list").get(0).offsetLeft;
if(leftvalue==-3*offset){
$(".slides .img_list").css('left', '-1024px');
index=1;
}
if(leftvalue==0){
$(".slides .img_list").css('left', -1024*number+'px');
index=number;
}
$(".slides .img_list").animate({left:'-='+offset+'px'},'slow');
if(offset>0){
index++;
if(index>number)
index=1;
show();
}
else{
index--;
if(index<0)
inex=number;
show();
}
}
//显示圆点
function show(){
$(".img_btn span").removeClass("on");
$(".img_btn span").eq(index-1).addClass("on");
}
//显示左右箭头
(function(){
$('.slides').hover(function() {
clearInterval(time);
$('.ctrl').css('display', 'block');
}, function() {
$('.ctrl').css('display', 'none');
time=setInterval(go,3000);
});
}());
//下一张
$('.next').click(function() {
offset=1024;
go();
});
//上一张
$('.pre').click(function() {
offset=-1024;
go();
});
});
|
import axios from 'axios';
import {server} from './config.js'
export const getNetworkData = () => {
return axios({
method: 'get',
url: `${server.url}:${server.port}/roam-data`
})
}
export const getNetworkOptions = () => {
return axios({
method: 'get',
url: `${server.url}:${server.port}/roam-network-options`
})
}
export const getFileInfo = () => {
return axios({
method: 'get',
url: `${server.url}:${server.port}/roam-get-file-changes`
})
}
export const getFileChanges = (version) => {
return axios({
method: 'get',
url: `${server.url}:${server.port}/roam-recent-changes?version=${version}`
})
}
|
'use strict';
$(document).ready(() => {
// On every click, add numbers to inputs accordingly
$('.firstRow, .secondRow, .thirdRow, .fourthRow, .fifthRow').click((event) => {
let input1 = $('#inp1 span'),
input2 = $('#inp2 span');
let id = event.target.id;
// Check if numbers are at most 8
// then proceed for appending more
// numbers, else ignore
if (id === 'backspace') {
input2.text(input2.text().slice(0, -1));
input2.text() === '' ? input2.text('0') : input2.text(input2.text());
} else if (id === 'C') {
input2.text('0');
input1.text('');
} else {
if (input2.text().length < 8) { // TODO: handle maxlength + 'operator' case
if (input2.text()[0] === '0' && input1.text() === '') { input2.text(''); } // TODO: Handle 0 + 0 case
if (id === 'one') { input1.text() === '' ? input2.append('1') : input2.text('1'); }
else if (id === 'two') { input1.text() === '' ? input2.append('2') : input2.text('2'); }
else if (id === 'three') { input1.text() === '' ? input2.append('3') : input2.text('3'); }
else if (id === 'four') { input1.text() === '' ? input2.append('4') : input2.text('4'); }
else if (id === 'five') { input1.text() === '' ? input2.append('5') : input2.text('5'); }
else if (id === 'six') { input1.text() === '' ? input2.append('6') : input2.text('6'); }
else if (id === 'seven') { input1.text() === '' ? input2.append('7') : input2.text('7'); }
else if (id === 'eight') { input1.text() === '' ? input2.append('8') : input2.text('8'); }
else if (id === 'nine') { input1.text() === '' ? input2.append('9') : input2.text('9'); }
else if (id === 'zero') { input1.text() === '' ? input2.append('0') : input2.text('0'); }
else if (id === 'decimal') {
if (input2.text().includes('.') === false) {
input2.append('.');
}
}
else if (id === 'plus') {
input1.append(input2.text() + ' + ');
}
else if (id === 'minus') {
input1.append(input2.text() + ' - ');
}
else if (id === 'divide') {
input1.append(input2.text() + ' \u00F7 ');
}
else if (id === 'multiply') {
input1.append(input2.text() + ' \u00D7 ');
}
else if (id === 'modulus') {
input1.append(input2.text() + ' \u0025 ');
}
else if (id === 'equalTo') {
let finalExp = input1.text().replace('\u00F7', '/')
.replace('\u00D7', '*')
.replace('\u0025', '%')
+ input2.text();
input2.text(eval(finalExp));
input1.text('');
}
}
}
});
});
|
var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff", "brunofin", "comster404", "test_channel", "cretetion", "sheevergaming", "TR7K", "OgamingSC2", "ESL_SC2"];
function getChannel() {
channels.forEach(function(channel) {
function makeURL(category, name) {
return "https://wind-bow.gomix.me/twitch-api/" + category + "/" + name + "?callback=?";
}
var status, game;
$.getJSON(makeURL("streams", channel), function(json) {
if (json.stream === null) {
status = "offline";
} else {
status = "online";
}
console.log(status, channel);
$.getJSON(makeURL("channels", channel), function(json) {
var html = "";
var logo = json.logo ? json.logo : "http://images.clipartpanda.com/question-mark-black-and-white-Icon-round-Question_mark.jpg";
var name = json.display_name ? json.display_name : channel;
var description = status === "online" ? json.game + "<span class='hidden-xs'>: " + json.status + "</span>" : status === "closed" ? "Account Closed" : "Offline";
console.log(status, channel, description);
var url = json.url ? json.url : "";
html += "<a href='" + url + "' target='__blank'><div class='row " + status + "'><div class='col-xs-2' id='logo'><img class='img-responsive center-block' src='" + logo + "' /></div><div class='col-xs-10 col-sm-2 text-center' id='name'><strong>" + name + "</strong></div><div class='col-xs-10 col-sm-8 text-center' id='desc'>" + description + "</div></div></a>";
status === "online" ? $("#display").prepend(html) : $("#display").append(html);
});
});
});
}
$(document).ready(function() {
getChannel();
$("#buttons button").click(function() {
if ($(this).attr('id') == "online") {
$(".offline, .undefined, .closed").slideUp();
$(".online").slideDown();
} else if ($(this).attr('id') == "offline") {
$(".online, .closed, .undefined").slideUp();
$(".offline").slideDown();
} else {
$(".offline, .undefined, .closed, .online").slideDown();
}
});
});
|
import request from '@/utils/request'
export function listAgent(query) {
return request({
url: '/agent/api/list',
method: 'get',
params: query
})
}
export function createAgent(data) {
return request({
url: '/agent/api/create',
method: 'post',
data
})
}
export function readAgent(data) {
return request({
url: '/agent/api/read',
method: 'get',
data
})
}
export function updateAgent(data) {
return request({
url: '/agent/api/update',
method: 'post',
data
})
}
export function deleteAgent(data) {
return request({
url: '/agent/api/delete',
method: 'post',
data
})
}
export function listPrice(query) {
return request({
url: '/agent/api/listPrice',
method: 'get',
params: query
})
}
export function createPrice(data) {
return request({
url: '/agent/api/createPrice',
method: 'post',
data
})
}
export function updatePrice(data) {
return request({
url: '/agent/api/updatePrice',
method: 'post',
data
})
}
export function deletePrice(data) {
return request({
url: '/agent/api/deletePrice',
method: 'post',
data
})
}
|
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 500;
const colorArray = ['Indigo', 'blue', 'CadetBlue', 'pink', 'black']
const rand = function(num) {
return Math.floor(Math.random() * num) + 1;
};
let Arr = [];
const createBoxes = function (count, canvasWidth, canvasHeight) {
for (let i = 0; i < count; i++) {
const rectObj = {
x: rand(canvas.width-50),
y: rand(canvas.height-50),
width: 50,
height: 50,
xDelta: 2,
yDelta: 2,
color: colorArray[rand(5) - 1],
draw : function () {
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.width, this.height);
},
update : function() {
if (this.x + this.width >= canvas.width) {
this.xDelta = this.xDelta * -1
}
if(this.y + this.height >= canvas.height) {
this.yDelta = this.yDelta * -1;
}
if(this.x <= 0) {
this.xDelta = this.xDelta * -1;
}
if(this.y <=0) {
this.yDelta = this.yDelta * -1;
}
this.x += this.xDelta;
this.y += this.yDelta;
}
}
Arr[Arr.length] = rectObj;
}
return Arr;
};
let boxes = createBoxes(30, canvas.width, canvas.height);
let draw = function(){
context.fillStyle = 'AntiqueWhite';
context.fillRect(0,0, canvas.width, canvas.height);
boxes.forEach(function(index){
index.draw();
});
}
let update = function(){
boxes.forEach(function(index){
index.update();
})
}
const loop = function() {
draw();
update();
requestAnimationFrame(loop);
};
loop()
//2
|
/**
* Created by Des on 15/10/27.
*/
blog.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/login', {
controller: "loginController",
templateUrl: "view/login.html"
});
$routeProvider.when('/main', {
controller:"blogController",
templateUrl: "view/blog/index.html"
});
$routeProvider.when('/blog', {
controller:"blogController",
templateUrl: "view/blog/index.html"
});
$routeProvider.when('/blog/type/:type', {
controller:"blogController",
templateUrl: "view/blog/index.html"
});
$routeProvider.when('/type', {
controller:"typeController",
templateUrl:"view/type/index.html"
});
$routeProvider.otherwise( {
redirectTo: '/login'
});
}]);
|
/*global PIFRAMES */
// Initial draft by Mostafa Mohammed and Cliff Shaffer
$(document).ready(function () {
"use strict";
var av_name = "EquivFS";
var av = new JSAV(av_name);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("An :term:`equivalence relation` is an especially important type of relation. Relation $R$ on set $S$ is an equivalence relation if it is <b>reflexive</b>, <b>symmetric</b>, and <b>transitive</b>. An equivalence relation can be viewed as partitioning a set into :term:`equivalence classes`. If two elements $a$ and $b$ are equivalent to each other, we write $a \\equiv b$. A :term:`partition` of a set $S$ is a collection of subsets that are :term:`disjoint` from each other (that is, they share no elements) and whose union is $S$. An equivalence relation on $S$ partitions the set into disjoint subsets whose elements are equivalent. The UNION/FIND algorithm efficiently maintains equivalence classes on a set. Two graph algorithms that make use of disjoint sets are :term:`connected component` finding and computing a :term:`minimal-cost spanning tree`.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("equivalent"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("eqclass"));
av.step();
// Frame 4
av.umsg("For the integers, $=$ is an equivalence relation that partitions each element into a distinct subset. In other words, for any integer $a$, three things are true. (1) $a = a$, (2) if $a = b$ then $b = a$, and (3) if $a = b$ and $b = c$, then $a = c$.<br/><br/>Of course, for distinct integers $a$, $b$, and $c$, there are never cases where $ a = b$, $b = a$, or $b = c$. So the requirements for symmetry and transitivity are never violated, and therefore the relation is symmetric and transitive.");
av.step();
// Frame 5
av.umsg(Frames.addQuestion("mod"));
av.step();
// Frame 6
av.umsg("A binary relation is called a :term:`partial order` if it is antisymmetric and transitive. If the relation is reflexive, it is called a :term:`non-strict partial order`. If the relation is irreflexive, it is called a :term:`strict partial order`. The set on which the partial order is defined is called a :term:`partially ordered set` or a :term:`poset`. Elements $x$ and $y$ of a set are :term:`comparable` under a given relation $R$ if either $xRy$ or $yRx$. If every pair of distinct elements in a partial order are comparable, then the order is called a :term:`total order` or :term:`linear order`.");
av.step();
// Frame 7
av.umsg(Frames.addQuestion("partorder"));
av.step();
// Frame 8
av.umsg("For the integers, relations $<$ and $\\leq$ define partial orders. Operation $<$ is a total order because, for every pair of integers $x$ and $y$ such that $x \\neq y$, either $x < y$ or $y < x$. Likewise, $\\leq$ is a total order because, for every pair of integers $x$ and $y$ such that $x \\neq y$, either $x \\leq y$ or $y \\leq x$.");
av.step();
// Frame 9
av.umsg("For the powerset of the integers, the subset operator defines a partial order (because it is antisymmetric and transitive). For example, $\\{1, 2\\} \\subseteq \\{1, 2, 3\\}$. However, sets $\\{1, 2\\}$ and $\\{1, 3\\}$ are not comparable by the subset operator, because neither is a subset of the other. Therefore, the subset operator does not define a total order on the powerset of the integers.");
av.step();
// Frame 10
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
Template.chartEditEmbed.helpers({
useBase64Images: function() {
if (app_settings.s3 && app_settings.s3.enable) {
return false;
} else {
return true;
}
},
angleBracket: function() {
return "<";
},
pfx: function() {
if (prefix) {
return prefix;
}
},
embedCSS: function() {
if (app_settings) {
return app_settings.embedCSS + app_version + "/chart-tool.min.css";
}
},
embedJS: function() {
if (app_settings) {
return app_settings.embedJS + app_version + "/chart-tool.min.js";
}
},
app_build: function() {
if (app_build && app_version) {
return app_version + "-" + app_build;
}
},
embedJSON: function() {
if (!isEmpty(this)) {
return JSON.stringify(embed(this), null, 2);
}
}
});
|
var express = require('express');
var router = express.Router();
var Blog = require('../models/blog');
var middleware = require('../middleware/index');
const ITEMS_PER_PAGE = 6;
// Show all blogs in DB
// router.get('/', (req, res) => {
// const page = req.query.page;
// Blog.find({}, (err, allBlogs) => {
// if(err) {
// console.log(err);
// } else {
// res.render('blogs/index', {blogs: allBlogs, currentUser: req.user})
// }
// }).sort({created: -1}).skip((page -1) * ITEMS_PER_PAGE).limit(ITEMS_PER_PAGE);
// });
router.get('/', (req, res) => {
const page = +req.query.page || 1;
let totalBlogs;
Blog.find().countDocuments().then(numBlogs => {
totalBlogs = numBlogs;
return Blog.find().sort({created: -1}).skip((page - 1) * ITEMS_PER_PAGE).limit(ITEMS_PER_PAGE).populate('postedBy');
})
.then(allBlogs => {
res.render('blogs/index', {
blogs: allBlogs,
currentPage: page,
hasNextPage: ITEMS_PER_PAGE * page < totalBlogs,
hasPreviousPage: page > 1,
nextPage: page + 1,
previousPage: page - 1,
lastPage: Math.ceil(totalBlogs / ITEMS_PER_PAGE)})
})
});
// Post to all blogs
router.post('/blog', (req, res) => {
const blogInfo = {
title: req.body.title,
content: req.body.content,
image: req.body.image,
postedBy: req.body.userId
}
const blog = new Blog(blogInfo);
blog.save().then(done => res.json(done)).catch(e => console.error(e));
// var title = req.body.title;
// var image = req.body.image;
// var content = req.body.content;
// var author = {
// id: req.user._id,
// username: req.user.username
// }
// console.log(req.body.content);
// var newBlog = {title: title, image: image, content: content, author: author}
// // create the blog
// console.log(newBlog);
// Blog.create(newBlog, (err, newlyCreated) => {
// if(err) {
// console.log(err);
// } else {
// res.redirect('/blogs');
// }
// });
});
// Render the new blog form
router.get('/new', middleware.isLoggedIn, (req, res) => {
res.render('blogs/new');
});
// Show more info about a blog
router.get('/:id', (req, res) => {
// find blog with provided ID
Blog.findById(req.params.id).populate('comments').exec((err, foundBlog) => {
if(err) {
console.log(err);
} else {
res.render('blogs/show', {blog: foundBlog});
}
});
});
// edit blog
router.get('/:id/edit', middleware.checkBlogOwnership, (req, res) => {
Blog.findById(req.params.id, (err, foundBlog) => {
res.render('blogs/edit', {blog: foundBlog})
});
});
// update blog
router.put('/:id', middleware.checkBlogOwnership, (req, res) => {
// find and update
Blog.findByIdAndUpdate(req.params.id, req.body.blog, (err, updatedBlog) => {
if(err) {
res.redirect('/blogs');
} else {
// redirect
res.redirect('/blogs/' + req.params.id);
}
});
});
// delete blog route
router.delete('/:id', middleware.checkBlogOwnership, (req, res) => {
Blog.findByIdAndRemove(req.params.id, (err) => {
if(err) {
res.redirect('/blogs');
} else {
res.redirect('/blogs');
}
});
});
module.exports = router;
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Login from './components/login/loginpage';
import Registerpage from './components/register/registerpage';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
ReactDOM.render(
<Router>
<div>
<Route exact path="/" component={Login} />
<Route path="/sign-up" component={Registerpage} />
</div>
</Router> , document.getElementById('root'));
registerServiceWorker();
|
/**
* Created by TIMYY on 2014/7/28.
*/
doe.presets.Collection = function(collection) {
var presets = {
collection: collection,
item: function(id) {
return _.find(collection, function(d) {
return d.id === id;
});
}
};
return presets;
}
|
$(function(){
//头部无logoA
$('#menu').click(function(){
$(this).hide();
$('#menu2').show();
$('.menu-list').slideDown();
});
$('#menu2').click(function() {
$(this).hide();
$('#menu').show();
$('.menu-list').slideUp();
})
//
//动态--关注--分类导航
var tabsNav=$('.dis-q1-tabs .tabs-nav-1');
var tabsBd=$('.tabs-bd .am-tab-panel');
tabsNav.find('.item').click(function(){
var index=$(this).index();
$(this).addClass('active').siblings('.item').removeClass('active');
tabsBd.eq(index).show().siblings('.am-tab-panel').hide();
})
//大师---作品
var oParent=$('.master-works');
oParent.find('.user').css('height',oParent.find('.img-bg').height()+'px');
oParent.find('.user-nav li').click(function(){
$(this).addClass('active').siblings('li').removeClass('active');
$(this).append('<i class="user-arrow-up"></i>').siblings('li').find('.user-arrow-up').remove();
});
//
$('img').load(function(){
var box = $('.item');
var boxHeight = {
leftBox:[],
centerBox:[],
rightBox:[]
}
for(var i=0;i<box.length;i++){
var now = i%3; //now的值为0,1,2
switch(now){
case 0:
box.eq(i).css('left','10px');
boxHeight.leftBox.push(box.eq(i).height());
var now2 = Math.floor(i/3);
if(now2==0){
box.eq(i).css('top',0);
}else{
var total = 0;
for(var j=0;j<now2;j++){
total += boxHeight.leftBox[j]+10;
}
box.eq(i).css('top',total+'px')
}
break;
case 1:
box.eq(i).css('left','270px');
boxHeight.centerBox.push(box.eq(i).height());
var now2 = Math.floor(i/3);
if(now2==0){
box.eq(i).css('top',0);
}else{
var total = 0;
for(var j=0;j<now2;j++){
total += boxHeight.centerBox[j]+10;
}
box.eq(i).css('top',total+'px')
}
break;
case 2:
box.eq(i).css('left','530px');
boxHeight.rightBox.push(box.eq(i).height());
var now2 = Math.floor(i/3);
if(now2==0){
box.eq(i).css('top',0);
}else{
var total = 0;
for(var j=0;j<now2;j++){
total += boxHeight.rightBox[j]+10;
}
box.eq(i).css('top',total+'px')
}
break;
}
}
});
})
|
import React from "react";
import ReactGA from "react-ga";
export default function SocialIcons() {
return (
<div>
<a
target="_blank"
rel="noopener noreferrer"
href="https://twitter.com/consensys_space/"
onClick={() => {
ReactGA.event({
category: "Outbound link",
action: "Clicked a social link",
label: "Clicked Twiter link"
});
}}
>
<img
className="social-icon social-icon--first"
src="https://trusat-assets.s3.amazonaws.com/TwitterIcon.png"
alt="twitter"
></img>
</a>
<a
target="_blank"
rel="noopener noreferrer"
href="https://facebook.com/consensys.space"
onClick={() => {
ReactGA.event({
category: "Outbound link",
action: "Clicked a social link",
label: "Clicked Facebook link"
});
}}
>
<img
className="social-icon"
src="https://trusat-assets.s3.amazonaws.com/FacebookIcon.png"
alt="facebook"
></img>
</a>
<a
target="_blank"
rel="noopener noreferrer"
href="https://instagram.com/consensys_space/"
onClick={() => {
ReactGA.event({
category: "Outbound link",
action: "Clicked a social link",
label: "Clicked Instagram link"
});
}}
>
<img
className="social-icon"
src="https://trusat-assets.s3.amazonaws.com/InstagramIcon.png"
alt="instagram"
></img>
</a>
<a
target="_blank"
rel="noopener noreferrer"
href="https://github.com/trusat"
onClick={() => {
ReactGA.event({
category: "Outbound link",
action: "Clicked a social link",
label: "Clicked Github link"
});
}}
>
<img
className="social-icon social-icon__last"
src="https://trusat-assets.s3.amazonaws.com/GithubIcon.png"
alt="github"
></img>
</a>
</div>
);
}
|
import PropTypes from "prop-types";
const CustomTooltip = ({ active, payload, label, type }) => {
if (active && payload) {
return (
<div className="custom-tooltip">
<p className="label custom-tooltip__date">{`${label}`}</p>
{type === "high" && (
<p className="label">{`High: ${payload[0]?.payload[type]}`}</p>
)}
{type === "low" && (
<p className="label">{`Low: ${payload[0]?.payload[type]}`}</p>
)}
{type === "open" && (
<p className="label">{`Open: ${payload[0]?.payload[type]}`}</p>
)}
{type === "close" && (
<p className="label">{`Close: ${payload[0]?.payload[type]}`}</p>
)}
{type === "volume" && (
<p className="label">{`Volume: ${payload[0]?.payload[type]}`}</p>
)}
{type === "dividend" && (
<p className="label">{`Ex-Dividend: ${payload[0]?.payload[type]}`}</p>
)}
</div>
);
}
return null;
};
CustomTooltip.prototype = {
active: PropTypes.bool,
payload: PropTypes.object,
label: PropTypes.string,
};
export default CustomTooltip;
|
import { StyleSheet } from 'react-native';
import * as colors from 'kitsu/constants/colors';
export const styles = StyleSheet.create({
imageBackground: {
backgroundColor: colors.lightGrey,
},
});
|
var viewModel = {}
$(document).ready(function () {
initPrerequisiteAdd();
ko.applyBindings(viewModel);
});
function getPrequisiteList() {
var apiUrlPrerequisite = GetWebAPIURL() + '/api/Prerequisite?parentId=0';
var dataPrerequisiteObj;
//To get Category name from Category table
$.ajax({
url: apiUrlPrerequisite,
type: 'GET',
async: false,
//headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
success: function (data) {
dataPrerequisiteObj = data;
},
error: function (xhr, status, error) {
alert('Error :' + status);
}
});
return dataPrerequisiteObj;
}
function initPrerequisiteAdd() {
viewModel.prerequisiteName = ko.observable('');
viewModel.selectedPrerequisite = ko.observable('');
viewModel.prerequisite = ko.observableArray();
var dataPrerequisiteObj = getPrequisiteList();
viewModel.prerequisite.push({ name: "Prerequisite", id: "" });
for (da in dataPrerequisiteObj) {
viewModel.prerequisite.push({ name: dataPrerequisiteObj[da].PrerequisiteName, id: dataPrerequisiteObj[da].Id });
}
}
viewModel.savePrerequisite = function () {
var jsonObjectWorkExperience = ko.toJS(viewModel);
var dataobjWorkExpereince;
var jobseekerworkExperienceObj = {}
jobseekerworkExperienceObj.PrerequisiteName = jsonObjectWorkExperience.prerequisiteName;
jobseekerworkExperienceObj.ParentId = jsonObjectWorkExperience.selectedPrerequisite.toString();
dataobjWorkExpereince = JSON.stringify(jobseekerworkExperienceObj);
alert(dataobjWorkExpereince);
var apiUrlWorkExperience = GetWebAPIURL() + '/api/Prerequisite/';
alert(apiUrlWorkExperience);
//To create WorkHistory table
$.ajax({
url: apiUrlWorkExperience,
type: "POST",
data: dataobjWorkExpereince,
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
},
error: function (xhr, error) {
alert('Error :' + error);
}
});
}
|
/**
* Created by Aadil on 5/4/2017.
*/
angular.module('phprescriptionServices',[])
.factory('phPrescription', ['$http','Conf', function($http,Conf){
const phprescriptionFactory = [];
phprescriptionFactory.getPhPrescription = function(){
return $http.get(Conf.prescription_service.concat('/prescription/pharmacist')).then(function(data){
return data;
})
};
phprescriptionFactory.getPhPrescriptionDetails = function(number){
return $http.get(Conf.prescription_service.concat('/prescription/pharmacist/' + number)).then(function(data){
return data;
})
};
phprescriptionFactory.getPhprescriptionByDate = function(date){
return $http.get(Conf.prescription_service.concat('/prescription/pharmacist/date/' + date)).then(function(data){
return data;
})
};
phprescriptionFactory.getPhprescriptionByDocName = function(name){
return $http.get(Conf.prescription_service.concat('/prescription/pharmacist/dname/' + name)).then(function(data){
return data;
})
};
phprescriptionFactory.getPhprescriptionByPatientName = function(name){
return $http.get(Conf.prescription_service.concat('/prescription/pharmacist/pname/' + name)).then(function(data){
return data;
})
};
phprescriptionFactory.getPhprescriptionByPharmacistName = function(name){
return $http.get(Conf.prescription_service.concat('/prescription/pharmacist' + name)).then(function(data){
return data;
})
};
phprescriptionFactory.addPHprescription = function(data){
return $http.post(Conf.prescription_service.concat('/prescription/pharmacist'),data).then(function(data){
return data;
})
};
return phprescriptionFactory;
}])
|
import React from 'react'
export const Card = ({ header, title, desc, footer }) =>(
<div className="card">
<div className="card-header">{ header }</div>
<div className="card-body">
<div className="card-title">{ title }</div>
<div className="card-text">{ desc }</div>
</div>
<div className="card-footer">{ footer }</div>
</div>
)
export const Button = ({ text, classes }) =>(
<div className={classes}>{ text }</div>
)
export const Breadcrumb = ({ items = [] }) => (
<ul className="breadcrumb">
{
items.length > 0 ?
items.map((item, index) => (
<li
className={`bread-item ${index == items.length - 1 ? "active" : ""}`}
>
{item} {index == items.length - 1 ? "" : "/"}
</li>
)) : null
}
</ul>
)
export const Navbar= ({ items = [] }) => (
<ul className="navbar outline">
{
items.length > 0 ?
items.map((item, index) => (
<li
className={`nav-item ${index == items.length - 1 ? "active" : ""}`}
>
{item} {index == items.length - 1 ? "" : ""}
</li>
)) : null
}
</ul>
)
export const Container = ({ children, classes }) => (
<div className={ classes }>{ children }</div>
)
export const Jumbotron = ({ header, body, footer }) => {
const Header = () => <div className="jumbo-header">{ header }</div>
const Body = () => <div className="jumbo-body">{ body }</div>
const Footer = () => <div className="jumbo-footer">{ footer }</div>
const Content = () => (
<>
<Header />
<Body />
<Footer />
</>
)
return(
<Container classes="jumbotron" ><Content /></Container>
)
}
|
const dbWrapper = require('./db-wrapper');
const url = require('url');
const querystring = require('querystring');
const map = { s: 0, t: 1, r: 2 };
const getPrivilege = (token) => {
return new Promise((resolve, reject) => {
dbWrapper.getUserByToken(token).then((user) => {
if (user) resolve(user.role);
else reject('Token not found');
});
});
};
const checkPrivilegeGet = (req, res, next, filter) => {
const parsedUrl = url.parse(req.url);
const parsedQs = querystring.parse(parsedUrl.query);
const token = parsedQs['token'];
if (!token)
return res.json({
success: false,
message: 'Auth token not supplied',
});
getPrivilege(token).then((userPrivilege) => {
if (!userPrivilege)
return res.json({
success: false,
message: 'Bad db record',
});
if (filter[0] == '!' && filter[1] != userPrivilege) return next();
if (filter[0] == '<' && map[filter[1]] > map[userPrivilege]) next();
if (filter[0] == '>' && map[filter[1]] > map[userPrivilege]) next();
if (userPrivilege >= filter) return next();
else
res.json({
success: false,
message: "User's privilege is not high enough",
});
});
};
const checkPrivilegePost = (req, res, next, filter) => {
let token = req.body.token;
if (!token)
return res.json({
success: false,
message: 'Auth token not supplied',
});
getPrivilege(token).then((userPrivilege) => {
if (!userPrivilege)
res.json({
success: false,
message: 'Bad db record',
});
if (filter[0] == '!' && filter[1] != userPrivilege) return next();
if (filter[0] == '<' && map[filter[1]] >= map[userPrivilege])
return next();
if (filter[0] == '>' && map[filter[1]] <= map[userPrivilege])
return next();
console.log(userPrivilege + ' ' + filter);
if (userPrivilege == filter) return next();
else
res.json({
success: false,
message: "User's privilege is not high enough",
});
});
};
function checkRepPost(req, res, next) {
return checkPrivilegePost(req, res, next, 'r');
}
function checkTeacherPost(req, res, next) {
checkPrivilegePost(req, res, next, 't');
}
function checkNotTeacherPost(req, res, next) {
checkPrivilegePost(req, res, next, '!t');
}
function checkStudentPost(req, res, next) {
checkPrivilegePost(req, res, next, 's');
}
function checkNotStudentPost(req, res, next) {
checkPrivilegePost(req, res, next, '!s');
}
function checkRepGet(req, res, next) {
checkPrivilegeGet(req, res, next, 'r');
}
function checkTeacherGet(req, res, next) {
checkPrivilegeGet(req, res, next, 't');
}
function checkNotTeacherGet(req, res, next) {
checkPrivilegeGet(req, res, next, '!t');
}
function checkStudentGet(req, res, next) {
checkPrivilegeGet(req, res, next, 's');
}
function checkNotStudentGet(req, res, next) {
checkPrivilegeGet(req, res, next, '!s');
}
module.exports = {
checkPrivilegePost,
checkPrivilegeGet,
};
|
import React, { Component } from 'react'
import Layout from '../components/Layout'
import { graphql } from 'gatsby'
import StyledHero from '../components/StyledHero'
import Tours from '../components/Tours/Tours'
class ToursPage
extends Component {
render() {
return (
<Layout>
<StyledHero img={this.props.data.file.childImageSharp.fluid}/>
<Tours/>
</Layout>
)
}
}
export const getImage = graphql`
{
file(relativePath:{eq:"defaultBcg.jpeg"}) {
childImageSharp {
fluid (maxWidth: 4160, quality: 90){
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`
export default ToursPage
|
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const pointSchema = new Schema({
type: {
type: String,
enum: ['Point']
},
coordinates: {
// Note that longitude comes first in a GeoJSON coordinate array, not latitude.
type: [Number]
}
})
const myModule = (module.exports = mongoose.model('Point', pointSchema))
myModule.pointSchema = pointSchema
|
dataFilter: function (data,type) {
// var currentTime = new Date(data.CreateTime*1000).toLocaleTimeString('chinese',{hour12:false})
var currentTime = data.CreateTime;
var _reg = new RegExp('\\[(.+?)\\]',"g");
var matchArray = data.Content.match(_reg);//筛选qqemojj表情
var str = data.Content;
var contentItem;
var imgType = false;
var message_content = '';
str = str.replace(/\n\n\n/gi,'');
// str = str.replace("<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>",'');//解决word copy产生空格问题
// str = str.replace("<br/><br/><br/><br/><br/><br/><br/><br/>",'');//解决note copy产生空格问题
// window.debugger(str);
str = str.replace(/↵/g,"<br>");//过滤换行标签
str = str.replace(/_web/g,'');//过滤换行标签
// str = str.replace("<br/><br/><br/>",'');
// alert(kewords)
//过滤关键字
if(data.MsgType !=47&&data.MsgType !=3){
for(var k = 0;k <kewords.length;k++){
str = str.replace(kewords[k],"<b style='color: #f36565'>"+kewords[k]+"</b>")
}
}
// alert(data.MsgType);
//过滤type类型
if(data.MsgType==47){
str = '<img class="type47" src="'+str+'" style="display:none" onload="addEventlisten.imgLoading($(this))">'
imgType = true;
}
if(data.MsgType==49){
str = '<a href='+str+' target="_Blank">'+str+'</a>'
}
if(data.MsgType==3){
str = '<img class="type3" src="http://nfs.gemii.cc/'+str+'" onerror="addEventlisten.detailFunction.reSetImgUrl(this,this.src,15)" onclick="addEventlisten.changeImgSize($(this))" style="display:none" onload="addEventlisten.imgLoading($(this))">'
imgType = true;
}
if(data.MsgType==34){
str = '<audio src="http://nfs.gemii.cc/'+str+'" controls="controls">' +
'Your browser does not support the audio element'+
'</audio>'
}
// this.msgTypeFilter(str)
//如果有qqemojj表情则开始过滤
if(matchArray!=null){
var index;
for (var i = 0;i < matchArray.length;i++){
if(qqEmoji_array.indexOf(matchArray[i])==-1&&qqEmoji_array_chinese.indexOf(matchArray[i])!=-1){
index = (qqEmoji_array_chinese.indexOf(matchArray[i]));
}else if(qqEmoji_array_chinese.indexOf(matchArray[i])==-1&&qqEmoji_array.indexOf(matchArray[i])!=-1){
index = (qqEmoji_array.indexOf(matchArray[i]));
}
window.debugger("index"+index)
if(index==undefined){
str = str .replace(matchArray[i],' '+matchArray[i]+' ');
}else {
str = str .replace(matchArray[i],'<img class="qqemoji'+' '+"qqemoji"+index+'" src="images/spacer.png">');
}
}
}
if(data.MsgType==10002){
if(type=='front'){
$(".content_wrap").prepend('<div class="messageItem" id="'+data.MsgId+'">' +
' <div class="message_head" id="'+currentTime+'" style="display: none">' +
'<div class="enterGroup" id="'+data.RoomID+'" style="display: none"></div>' +
'</div>'+
'<div class="drawBack">'+data.UserNickName+' 撤回了一条消息</div>' +
'</div>');
}else {
$(".content_wrap").append('<div class="messageItem" id="'+data.MsgId+'">' +
' <div class="message_head" id="'+currentTime+'" style="display: none">' +
'<div class="enterGroup" id="'+data.RoomID+'" style="display: none"></div>' +
'</div>'+
'<div class="drawBack">'+data.UserNickName+' 撤回了一条消息</div>' +
'</div>');
}
}else if(data.MsgType==10000){
if(type=='front'){
$(".content_wrap").prepend('<div class="messageItem" id="'+data.MsgId+'">' +
' <div class="message_head" id="'+currentTime+'" style="display: none">' +
'<div class="enterGroup" id="'+data.RoomID+'" style="display: none"></div>' +
'</div>'+
'<div class="drawBack">'+data.Content+'</div>' +
'</div>');
}else {
$(".content_wrap").append('<div class="messageItem" id="'+data.MsgId+'">' +
' <div class="message_head" id="'+currentTime+'" style="display: none">' +
'<div class="enterGroup" id="'+data.RoomID+'" style="display: none"></div>' +
'</div>'+
'<div class="drawBack">'+data.Content+'</div>' +
'</div>');
}
}else {
if(type=='front'){
//判断是否点击'点击入群'
var clickIcon = '';
window.debugger(data.click);
if(data.click==1){
clickIcon = '<div class="enterGroup" style="visibility: '+dataModel.visibleType+'; color: rgba(0,0,0,0.4)" id="'+data.RoomID+'"' +
'onclick="addEventlisten.detailFunction.enterGroupByroomID($(this))">点击入群</div>'
}else {
clickIcon = '<div class="enterGroup" style="visibility: '+dataModel.visibleType+';" id="'+data.RoomID+'"' +
'onclick="addEventlisten.detailFunction.enterGroupByroomID($(this))">点击入群</div>'
}
if(imgType){
message_content = '<div class="message_content"><div class="m-load2" style="margin:0 auto;"><div class="line"><div></div><div></div><div></div><div></div><div></div><div></div></div><div class="circlebg"></div></div>';
}else {
if(dataModel.userType=='1'){
message_content = '<div class="message_content" style="cursor: pointer" onclick="addEventlisten.detailFunction.questionOrAnswer($(this))">';
}else {
message_content = '<div class="message_content">';
}
// message_content = '<div class="message_content" onclick="addEventlisten.detailFunction.questionOrAnswer($(this))">'; for inner
};
//开始向dom添加元素加工
$(".content_wrap").prepend('<div class="messageItem" id="'+data.MsgId+'">'
+'<div class="message_inner">'
+'<img class="mes_profile" src="http://nfs.gemii.cc/users/'+data.MemberID +'.jpg" alt="">'
+' <div class="contentBox">'
+' <div class="message_head" id="'+currentTime+'">'
+'<div class="memberInfo">['+addEventlisten.detailFunction.ToGB2312(data.UserNickName)+'] '+currentTime+'</div>'
+clickIcon
+'</div>'
+message_content+str
+'</div>'
+'</div>'
+'</div>'
+'</div>')
}else {
//判断是否点击'点击入群'
var clickIcon = '';
if(data.click==1){
clickIcon = '<div class="enterGroup" style="visibility: '+dataModel.visibleType+'; color: rgba(0,0,0,0.4)" id="'+data.RoomID+'"' +
'onclick="addEventlisten.detailFunction.enterGroupByroomID($(this))">点击入群</div>'
}else {
clickIcon = '<div class="enterGroup" style="visibility: '+dataModel.visibleType+';" id="'+data.RoomID+'"' +
'onclick="addEventlisten.detailFunction.enterGroupByroomID($(this))">点击入群</div>'
}
if(imgType){
message_content = '<div class="message_content"><div class="m-load2" style="margin:0 auto;"><div class="line"><div></div><div></div><div></div><div></div><div></div><div></div></div><div class="circlebg"></div></div>';
}else {
if(dataModel.userType=='1'){
message_content = '<div class="message_content" style="cursor: pointer" onclick="addEventlisten.detailFunction.questionOrAnswer($(this))">';
}else {
message_content = '<div class="message_content">';
}
// message_content = '<div class="message_content" onclick="addEventlisten.detailFunction.questionOrAnswer($(this))">'; for inner
};
//开始向dom添加元素加工
$(".content_wrap").append('<div class="messageItem" id="'+data.MsgId+'">'
+'<div class="message_inner">'
+'<img class="mes_profile" src="http://nfs.gemii.cc/users/'+data.MemberID +'.jpg" alt="">'
+' <div class="contentBox">'
+' <div class="message_head" id="'+currentTime+'">'
+'<div class="memberInfo">['+addEventlisten.detailFunction.ToGB2312(data.UserNickName)+'] '+currentTime+'</div>'
+clickIcon
+'</div>'
+message_content+str
+'</div>'
+'</div>'
+'</div>'
+'</div>')
}
}
//对指定元素赋予表情
if(matchArray!=null){
for (var i = 0;i < matchArray.length;i++){
var index;
if(qqEmoji_array.indexOf(matchArray[i])==-1||qqEmoji_array.indexOf(matchArray[i])==undefined){
index = (qqEmoji_array_chinese.indexOf(matchArray[i]));
}else if(qqEmoji_array_chinese.indexOf(matchArray[i])==-1||qqEmoji_array_chinese.indexOf(matchArray[i])==undefined){
index = (qqEmoji_array.indexOf(matchArray[i]));
}
if(index<=14&&index>=0){
$(".qqemoji"+index).css("backgroundPosition",-(3+index*25)+'px'+' '+-2+'px');
}
else if(index<=29&&index>=15){
$(".qqemoji"+index).css("backgroundPosition",-(1.5+(index-15)*25)+'px'+' '+-27+'px');
}
else if(index<=44&&index>=30){
$(".qqemoji"+index).css("backgroundPosition",-(3+(index-30)*25)+'px'+' '+-52+'px');
}
else if(index<=59&&index>=45){
$(".qqemoji"+index).css("backgroundPosition",-(3+(index-45)*25)+'px'+' '+-77+'px');
}
else if(index<=74&&index>=60){
$(".qqemoji"+index).css("backgroundPosition",-(3+(index-60)*25)+'px'+' '+-102+'px');
}
else if(index<=89&&index>=75){
$(".qqemoji"+index).css("backgroundPosition",-(3+(index-75)*25)+'px'+' '+-127+'px');
}
else{
$(".qqemoji"+index).css("backgroundPosition",-(3+(index-90)*25)+'px'+' '+-152+'px');
}
}
}
}
|
import React, { useState, useEffect } from 'react'
import {
StyleSheet,
View,
Text,
TouchableOpacity,
TextInput
} from 'react-native'
import AsyncStorage from '@react-native-community/async-storage'
import { connect } from 'react-redux'
import { login } from '../store/actions/user.actions'
import { fonts, colors } from '../utils/styles'
const Login = props => {
const [state, setState] = useState({
name: '',
email: '',
})
useEffect(() => {
async function getUser() {
const user = JSON.parse(await AsyncStorage.getItem('userData'))
if (user) {
props.onLogin({ ...user })
props.navigation.navigate('Profile')
}
}
getUser()
}, [])
const login = async () => {
props.onLogin({ ...state })
setState({ name: '', email: '' })
props.navigation.navigate('Profile')
}
return (
<View style={styles.container}>
<Text style={[styles.text, styles.textTitle]}>PicUser</Text>
<View style={styles.form}>
<View style={styles.formItem}>
<Text style={[styles.text, styles.textInput]}>Nome</Text>
<TextInput style={styles.input}
autoFocus={true}
value={state.name}
onChangeText={text => setState({ ...state, name: text })}
/>
</View>
<View style={styles.formItem}>
<Text style={[styles.text, styles.textInput]}>E-mail</Text>
<TextInput style={styles.input}
keyboardType="email-address"
value={state.email}
onChangeText={text => setState({ ...state, email: text })}
secureTextEntry={true}
/>
</View>
<View style={styles.formItem}>
<TouchableOpacity activeOpacity={0.7} style={[styles.button, styles.buttonLogin]} onPress={() => login()}>
<Text style={[styles.text, styles.textLogin]}>Entrar</Text>
</TouchableOpacity>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: { flex: 1, marginHorizontal: 30, marginTop: 20 },
text: { fontFamily: fonts.poppins, color: colors.text.primary, fontSize: 20 },
textTitle: { fontSize: 30, fontFamily: fonts.poppinsBold, fontWeight: 'bold' },
textInput: { color: colors.text.subText, marginBottom: 10, },
textLogin: { color: colors.text.secondary, textAlign: 'center' },
textRegister: { color: colors.text.primary, textAlign: 'center' },
form: { marginTop: 30 },
formItem: { marginVertical: 20 },
input: { borderWidth: 1, borderColor: colors.text.primary, borderRadius: 5 },
button: {
padding: 15,
justifyContent: 'center',
alignContent: 'center',
borderRadius: 5,
borderColor: colors.text.primary,
borderWidth: 1
},
buttonLogin: { backgroundColor: colors.blue.primary, borderColor: colors.blue.dark },
buttonRegister: { marginTop: -20 }
});
const mapDispatchToProps = dispatch => {
return {
onLogin: user => dispatch(login(user))
}
}
const mapStateToProps = ({ user }) => {
return { user }
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)
|
/**
* Subscription methods
* @author - tayyi
*/
Meteor.startup(function(){
Meteor.subscribe('AllDocs');
Meteor.subscribe("AllUsers");
Meteor.subscribe("AllVideos");
});
|
//https://developers.google.com/apps-script/guides/services/external
//JIRA CONTROLER
Jira = {
headers: {
get: {
'contentType': 'application/json',
'Authorization': 'Basic ' + Settings.jiraCredsToken
},
post: {
'contentType': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + Settings.jiraCredsToken
}
},
sheet: SpreadsheetApp.openById(docTasks).getSheetByName(sheetTaskName),
status: {
connected: false
},
Tools: {
parseResponse: function(response) {
response.getContentText();
return JSON.parse(response);
}
},
MessageHandler: {
getError: function(response) {
var res = Jira.Tools.parseResponse(response);
if (res.errorMessages) {
if (res.errorMessages.length > 0) {
return res.errorMessages[0];
}
}
return false;
}
},
PrivateActivities: {
sendRequest: function(url, options) {
var r = UrlFetchApp.fetch(url, options);
// UrlFetchApp.getRequest(url, options);
Logger.log(r);
return r;
}
},
TestActivities: {
login: function() {
var options = {
'method': 'get',
'headers': Jira.headers.send
};
var response = Jira.PrivateActivities.sendRequest(Settings.jiraServerUrl + Settings.jiraMe, options);
return "Login to JIRA :" + Jira.MessageHandler.getError(response);
}
}
};
//functions
function jiraPublishBanner(row) {
if (!row) {
row = SpreadActivities.getSelectedRow();
}
if (!Jira.status.connected) {
Logger.log("not logged !!");
} else {
//create banner object
var banner = VO.banner;
banner.fields.project.key = getItemValue("CLIENT", Jira.sheet, row);
banner.fields.parent.key = "ROLEX-374";
banner.fields.summary = "dqsqsest gdoc" + getItemValue("ADNAME", Jira.sheet, row);
banner.fields.components = [{id: "10100"}];// getItemValue("*LANGUAGE", Jira.sheet, row)
//create options
var options = {
'method': 'post',
'headers': Jira.headers.post,
'payload': JSON.stringify(banner),
'contentType': 'application/json'
};
//send request
var request = UrlFetchApp.getRequest(Settings.jiraServerUrl + Settings.jiraRestUrl + Settings.jiraRestUrlIssue, options);
var response = Jira.PrivateActivities.sendRequest(Settings.jiraServerUrl + Settings.jiraRestUrl + Settings.jiraRestUrlIssue, options);
Logger.log(response);
}
};
function jiralogin() {
var options = {
'method': 'get',
'headers': Jira.headers.get
};
var response = UrlFetchApp.fetch(Settings.jiraServerUrl + Settings.jiraLoginUrl, options);
if (Jira.MessageHandler.getError(response)) {
Browser.msgBox("Login error", Jira.Message.getError(response), []);
} else {
//continue
Logger.log("logged !!");
Jira.status.connected = true;
}
}
|
const stylelint = require("stylelint");
const ruleName = "css/interim";
const messages = stylelint.utils.ruleMessages(ruleName, {
expected: "Interim should only be used as .interim &",
noNestedRules: "Nested rules should not be used in interim block"
});
module.exports = stylelint.createPlugin(ruleName, () => {
return (postcssRoot, postcssResult) => {
postcssRoot.walkRules((rule) => {
if (!rule.selector.includes(".interim")) {
return;
}
if (rule.selector.replace(".interim &", "").trim() !== "") {
stylelint.utils.report({
ruleName: ruleName,
result: postcssResult,
node: rule,
message: messages.expected
});
}
rule.walkRules((nestedRule) => {
stylelint.utils.report({
ruleName: ruleName,
result: postcssResult,
node: nestedRule,
message: messages.noNestedRules
});
})
})
}
})
module.exports.ruleName = ruleName
module.exports.messages = messages
|
// author.js - 作者路由模块
const express = require('express');
const router = express.Router();
// 主页路由
router.get('/', (req, res) => {
res.send('网站作者:刘鹏');
});
// “关于页面”路由
router.get('/about', (req, res) => {
res.send('关于此网站作者');
});
// “关于页面”路由
router.get('/about/github', (req, res) => {
res.send('作者GitHub: https://github.com/liupengzhoyi');
});
module.exports = router;
|
/*
* Sonatype Nexus (TM) Open Source Version. Copyright (c) 2008 Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at
* http://nexus.sonatype.org/dev/attributions.html This program is licensed to
* you under Version 3 only of the GNU General Public License as published by
* the Free Software Foundation. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License Version 3 for more details. You should have received a copy of
* the GNU General Public License Version 3 along with this program. If not, see
* http://www.gnu.org/licenses/. Sonatype Nexus (TM) Professional Version is
* available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc.
*/
(function() {
Sonatype.lib.Permissions = {
READ : 1, // 0001
EDIT : 2, // 0010
DELETE : 4, // 0100
CREATE : 8, // 1000
ALL : 15, // 1111
NONE : 0, // 0000
// returns bool indicating if value has all perms
// all values are base 10 representations of the n-bit representation
// Example: for 4-bit permissions: 3 (base to) represents 0011 (base 2)
checkPermission : function(value, perm /* , perm... */) {
var p = perm;
if (Sonatype.user.curr.repoServer)
{
Ext.each(Sonatype.user.curr.repoServer, function(item, i, arr) {
if (item.id == value)
{
value = item.value;
return false;
}
});
}
if (arguments.length > 2)
{
var perms = Array.slice(arguments, 2);
Ext.each(perms, function(item, i, arr) {
p = p | item;
});
}
return ((p & value) == p);
}
};
/*
* Adapted from ExtJS v2.0.2 Ext.state.CookieProvider; removed inheritance
* from Ext.state.Provider @cfg {String} path The path for which the cookie is
* active (defaults to root '/' which makes it active for all pages in the
* site) @cfg {Date} expires The cookie expiration date (defaults to 7 days
* from now) @cfg {String} domain The domain to save the cookie for. Note that
* you cannot specify a different domain than your page is on, but you can
* specify a sub-domain, or simply the domain itself like 'extjs.com' to
* include all sub-domains if you need to access cookies across different
* sub-domains (defaults to null which uses the same domain the page is
* running on including the 'www' like 'www.extjs.com') @cfg {Boolean} secure
* True if the site is using SSL (defaults to false) @constructor Create a new
* CookieProvider @param {Object} config The configuration object
*/
Sonatype.lib.CookieProvider = function(config) {
this.namePrefix = 'st-'; // added alternate default prefix
this.path = "/";
this.expires = new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 7)); // 7
// days
this.domain = null;
this.secure = false;
Ext.apply(this, config);
this.state = this.readCookies();
};
Sonatype.lib.CookieProvider.prototype = {
/**
* Returns the current value for a key
*
* @param {String}
* name The key name
* @param {Mixed}
* defaultValue A default value to return if the key's value is not
* found
* @return {Mixed} The state data
*/
get : function(name, defaultValue) {
return typeof this.state[name] == "undefined" ? defaultValue : this.state[name];
},
// private
set : function(name, value) {
if (typeof value == "undefined" || value === null)
{
this.clear(name);
return;
}
this.setCookie(name, value);
this.state[name] = value;
},
// private
clear : function(name) {
this.clearCookie(name);
delete this.state[name];
},
// private
readCookies : function() {
var cookies = {};
var c = document.cookie + ";";
var re = /\s?(.*?)=(.*?);/g;
var matches;
while ((matches = re.exec(c)) != null)
{
var name = matches[1];
var value = matches[2];
if (name && name.substring(0, 3) == this.namePrefix)
{
cookies[name.substr(3)] = this.decodeValue(value);
}
}
return cookies;
},
// private
setCookie : function(name, value) {
document.cookie = this.namePrefix + name + "=" + this.encodeValue(value) + ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) + ((this.path == null) ? "" : ("; path=" + this.path))
+ ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : "");
},
// private
clearCookie : function(name) {
document.cookie = this.namePrefix + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : "");
},
/**
* Decodes a string previously encoded with {@link #encodeValue}.
*
* @param {String}
* value The value to decode
* @return {Mixed} The decoded value
*/
decodeValue : function(cookie) {
var re = /^(a|n|d|b|s|o)\:(.*)$/;
var matches = re.exec(unescape(cookie));
if (!matches || !matches[1])
return; // non state cookie
var type = matches[1];
var v = matches[2];
switch (type)
{
case "n" :
return parseFloat(v);
case "d" :
return new Date(Date.parse(v));
case "b" :
return (v == "1");
case "a" :
var all = [];
var values = v.split("^");
for (var i = 0, len = values.length; i < len; i++)
{
all.push(this.decodeValue(values[i]));
}
return all;
case "o" :
var all = {};
var values = v.split("^");
for (var i = 0, len = values.length; i < len; i++)
{
var kv = values[i].split("=");
all[kv[0]] = this.decodeValue(kv[1]);
}
return all;
default :
return v;
}
},
/**
* Encodes a value including type information. Decode with
* {@link #decodeValue}.
*
* @param {Mixed}
* value The value to encode
* @return {String} The encoded value
*/
encodeValue : function(v) {
var enc;
if (typeof v == "number")
{
enc = "n:" + v;
}
else if (typeof v == "boolean")
{
enc = "b:" + (v ? "1" : "0");
}
else if (Ext.isDate(v))
{
enc = "d:" + v.toGMTString();
}
else if (Ext.isArray(v))
{
var flat = "";
for (var i = 0, len = v.length; i < len; i++)
{
flat += this.encodeValue(v[i]);
if (i != len - 1)
flat += "^";
}
enc = "a:" + flat;
}
else if (typeof v == "object")
{
var flat = "";
for (var key in v)
{
if (typeof v[key] != "function" && v[key] !== undefined)
{
flat += key + "=" + this.encodeValue(v[key]) + "^";
}
}
enc = "o:" + flat.substring(0, flat.length - 1);
}
else
{
enc = "s:" + v;
}
return escape(enc);
}
};
})();
|
const getAllMovies = require('../../../../../../src/application/use_cases/movie/search/getAllMovies');
const movieRepository = require('../../../../../../src/domain/movie/MovieRepository');
describe('getAllMovies unit test', () => {
test('should resolve with all the movies persisted in repository', async () => {
const moviesMock = [
{
id: "123",
title: "The silence of the lambs",
generalDescription: "Real thriller movie, bro.",
actorList: ["Anthony Hopkins", "Jodie Foster", "Ted Levine"],
directors: ["Jonathan Demme", "Tim Galvin"],
quantity: 13,
price: 1000,
created_at: new Date(),
updated_at: new Date()
},
{
id: "124",
title: "Shutter Island",
generalDescription: "Real thriller movie, bro.",
actorList: ["Leonardo DiCaprio", "Mark Ruffalo", "Ben Kingsley"],
directors: ["Martin Scorsese"],
quantity: 12,
price: 1200,
created_at: new Date(),
updated_at: new Date()
}
];
const mockMovieRepository = new movieRepository();
mockMovieRepository.find = () => moviesMock;
const movies = await getAllMovies({movieRepository: mockMovieRepository});
expect(movies).toEqual(moviesMock);
});
});
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import './Button.css'
class Button extends Component {
static propTypes = {
submit: PropTypes.bool,
reset: PropTypes.bool,
}
state = {
type: 'button'
}
constructor(props) {
super(props)
if (props.submit)
this.state.type = 'submit'
else if (props.reset)
this.state.type = 'reset'
}
render () {
var { submit, reset, children, ...pass_props} = this.props
return (
<button type={this.state.type} {...pass_props}>
<div className='button-content'>
{children}
</div>
</button>
)
}
}
export default Button
|
//Ecommerce Settings
var dataVal = $("#MinimumOrderQuantity").attr("data-val");
if (dataVal == "true") {
$('#Minimum-Order-Quantity').css('display', 'block');
}
else {
$('#Minimum-Order-Quantity').css('display', 'none');
}
var dataVal = $("#ClickAndCollect").attr("data-val");
if (dataVal == "true") {
$('#Click-And-Collect').css('display', 'block');
}
else {
$('#Click-And-Collect').css('display', 'none');
}
var dataVal = $("#OnlinePayment").attr("data-val");
if (dataVal == "true") {
$('#online-payment').css('display', 'block');
}
else {
$('#online-payment').css('display', 'none');
}
var dataVal = $("#BankPayment").attr("data-val");
if (dataVal == "true") {
$('#bank-details').css('display', 'block');
}
else {
$('#bank-details').css('display', 'none');
}
$("#MinimumOrderQuantity").click(function (ev) {
var dataVal = $("#MinimumOrderQuantity").attr("data-val");
//alert(dataVal);
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
if ($(this).val() === "false") {
$('#Minimum-Order-Quantity').fadeIn().css('display', 'block');
}
else {
$('#Minimum-Order-Quantity').fadeOut(600);
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveMinimumOrderQuantity",
data: {
PaidTimeOff: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#MinimumOrderQuantity").attr("data-val", dataVal);
}
});
});
$("#ClickAndCollect").click(function (ev) {
var dataVal = $("#ClickAndCollect").attr("data-val");
//alert(dataVal);
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
if ($(this).val() === "false") {
$('#Click-And-Collect').fadeIn().css('display', 'block');
}
else {
$('#Click-And-Collect').fadeOut(600);
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveClickAndCollectSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#ClickAndCollect").attr("data-val", dataVal);
}
});
});
$("#OnlinePayment").click(function (ev) {
var dataVal = $("#OnlinePayment").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
if ($(this).val() === "false") {
$('#online-payment').fadeIn().css('display', 'block');
}
else {
$('#online-payment').fadeOut(600);
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveOnlinePaymentSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#OnlinePayment").attr("data-val", dataVal);
}
});
});
$("#BankPayment").click(function (ev) {
var dataVal = $("#BankPayment").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
if ($(this).val() === "false") {
$('#bank-details').fadeIn().css('display', 'block');
}
else {
$('#bank-details').fadeOut(600);
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveBankPaymentSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#BankPayment").attr("data-val", dataVal);
}
});
});
$("#includeVATforTrader").click(function (ev) {
//debugger;
var dataVal = $("#includeVATforTrader").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveIncludeVATforTraderSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#includeVATforTrader").attr("data-val", dataVal);
}
});
});
$("#includeVATforRetailer").click(function (ev) {
var dataVal = $("#includeVATforRetailer").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveIncludeVATforRetailerSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#includeVATforRetailer").attr("data-val", dataVal);
}
});
});
$("#ShippingFreeForAll").click(function (ev) {
var dataVal = $("#ShippingFreeForAll").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveShippingFreeForAllSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#ShippingFreeForAll").attr("data-val", dataVal);
}
});
});
$("#ShippingFreeForEconomy").click(function (ev) {
var dataVal = $("#ShippingFreeForEconomy").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveShippingFreeForEconomySettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#ShippingFreeForEconomy").attr("data-val", dataVal);
}
});
});
$("#ShippingFreeForStandard").click(function (ev) {
var dataVal = $("#ShippingFreeForStandard").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveShippingFreeForStandardSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#ShippingFreeForStandard").attr("data-val", dataVal);
}
});
});
$("#ShippingFreeForExpress").click(function (ev) {
var dataVal = $("#ShippingFreeForExpress").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveShippingFreeForExpressSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#ShippingFreeForExpress").attr("data-val", dataVal);
}
});
});
$("#OutOfStock").click(function (ev) {
var dataVal = $("#OutOfStock").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveOutOfStockSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#OutOfStock").attr("data-val", dataVal);
}
});
});
$("#CashOnDelivery").click(function (ev) {
var dataVal = $("#CashOnDelivery").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveCashOnDeliverySettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#CashOnDelivery").attr("data-val", dataVal);
}
});
});
$("#OnlineOrder").click(function (ev) {
var dataVal = $("#OnlineOrder").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SaveOnlineOrderSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#OnlineOrder").attr("data-val", dataVal);
}
});
});
$("#PaymentAtPickup").click(function (ev) {
var dataVal = $("#PaymentAtPickup").attr("data-val");
if (dataVal === "false") {
dataVal = "true";
}
else {
dataVal = "false";
}
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SavePaymentAtPickupSettings",
data: {
Approval: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
$("#PaymentAtPickup").attr("data-val", dataVal);
}
});
});
//--- Ecommerce Shipping Management
//Add Shipping Company
$('.addNewCompany').on('click', function () {
var target = "";
target = "/Secure/Ecommerce/_ShippingCompanyRecord";
// load the url and show modal on success
$("#addNewCompany-Modal .modal-dialog").load(target, function () {
$("#addNewCompany-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//Edit Shipping Company
$(document.body).on('click','.editsc', function (ev) {
ev.preventDefault();
var Id = $(this).attr("data-id");
var target = "";
target = "/Secure/Ecommerce/_ShippingCompanyRecord/"+Id;
// load the url and show modal on success
$("#addNewCompany-Modal .modal-dialog").load(target, function () {
$("#addNewCompany-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//View Shipping Company
$(document.body).on('click', '.viewsc', function (ev) {
ev.preventDefault();
var Id = $(this).attr("data-id");
var target = "";
target = "/Secure/Ecommerce/_ShippingCompany/" + Id;
// load the url and show modal on success
$("#addNewCompany-Modal .modal-dialog").load(target, function () {
$("#addNewCompany-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//View Shipping Company Report
$(document.body).on('click', '.reportsc', function (ev) {
ev.preventDefault();
var Id = $(this).attr("data-id");
var target = "";
target = "/Secure/Ecommerce/_ShippingCompany/" + Id;
// load the url and show modal on success
$("#addNewCompany-Modal .modal-dialog").load(target, function () {
$("#addNewCompany-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
/*------------------- Json Requests for Shipping Companies -------------------*/
function getshippingCompanies(dataTable) {
$.get('/Secure/Ecommerce/GetAllCompanies').success(function (data) {
var markup = "";
for (var x = 0; x < data.length; x++) {
markup += '<tr>';
markup += '<td><input type="checkbox" class="checkIt" value="' + data[x].ShippingCompanyId + '" /></td>';
markup += '<td><a href="javascript://" class="scTitle" data-id="' + data[x].ShippingCompanyId + '">' + data[x].Title + '</a></td>';
//markup += '<td><a href="' + data[x].CompanyWebAddrress + '" target="_blank">' + data[x].CompanyWebAddrress + '</a></td>';
//markup += '<td><a href="' + data[x].TrackingUrl + '" target="_blank">' + data[x].TrackingUrl + '</a></td>';
//markup += '<td>' + formatDateTime(data[x].UpdatedOn) + '</td>';
//markup += '<td>' + formatDateTime(data[x].CreatedOn) + '</td>';
var deleteRecordData = "deleteDelableRecord('/Secure/Ecommerce/ShippingCompanyDeleteAble', '/Secure/Ecommerce/ShippingCompanyDelete','" + data[x].ShippingCompanyId + "')";
markup += '<td class="text-center"><div class="btn-group btn-group-xs" role="group">';
markup += '<a href="javascript://" data-id="' + data[x].ShippingCompanyId + '" class="btn btn-primary viewsc" title="View"><i class="fa fa-share"></i></a>';
markup += '<a href="javascript://" data-id="' + data[x].ShippingCompanyId + '" class="btn btn-info editsc" title="Edit"><i class="fa fa-edit"></i></a>';
markup += '<a href="javascript://" data-id="' + data[x].ShippingCompanyId + '" class="btn btn-warning reportsc" title="View Report"><i class="fa fa-file-text-o"></i></a>';
markup += '<a href="javascript://" onclick="' + deleteRecordData + '" class="btn btn-danger" title="Delete"><i class="fa fa-trash"></i></a>';
markup += '</div></td>';
markup += "</tr>";
}
$(dataTable + ' tbody').html(markup);
});
};
/*--------------------------------------*/
//--- Ecommerce Shipping Packages Management
//Load Shipping Packages of Single Company
$(document.body).on("click", ".scTitle", function (ev) {
var Id = $(this).attr("data-id");
if (Id > 0) {
getshippingPackages("#shippingPackages-dataTable", Id);
}
});
/*------------------- Json Requests for Selected Shipping Packages -------------------*/
function getshippingPackages(dataTable, Id) {
//debugger;
$.get('/Secure/Ecommerce/GetShippingPackages/' + Id).success(function (data) {
var markup = "";
for (var x = 0; x < data.length; x++) {
markup += '<tr>';
markup += '<td><input type="checkbox" class="checkIt" value="' + data[x].Id + '" /></td>';
markup += '<td>' + data[x].Title + '</td>';
markup += '<td>' + data[x].PackageType + '</td>';
markup += '<td>' + data[x].DeliveryTime + '</td>';
markup += '<td>' + data[x].Price + '</td>';
var deleteRecordData = "deleteDelableRecord('/Secure/Ecommerce/ShippingCompanyDeleteAble', '/Secure/Ecommerce/ShippingCompanyDelete','" + data[x].Id + "')";
markup += '<td class="text-center"><div class="btn-group btn-group-xs" role="group">';
markup += '<a href="javascript://" data-id="' + data[x].Id + '" class="btn btn-primary viewsp" title="View" target="_blank"><i class="fa fa-share"></i></a>';
markup += '<a href="javascript://" data-id="' + data[x].Id + '" class="btn btn-info editsp" title="Edit"><i class="fa fa-edit"></i></a>';
markup += '<a href="javascript://" onclick="' + deleteRecordData + '" class="btn btn-danger" title="Delete"><i class="fa fa-trash"></i></a>';
markup += '</div></td>';
markup += "</tr>";
}
$(dataTable + ' tbody').html(markup);
});
};
//Add Shipping Package
$('.addNewPackage').on('click', function () {
var target = "";
target = "/Secure/Ecommerce/_ShippingPackageRecord";
// load the url and show modal on success
$("#addNewPackage-Modal .modal-dialog").load(target, function () {
$("#addNewPackage-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//Edit Shipping Package
$(document.body).on('click', '.editsp', function (ev) {
ev.preventDefault();
var Id = $(this).attr("data-id");
var target = "";
target = "/Secure/Ecommerce/_ShippingPackageRecord/" + Id;
// load the url and show modal on success
$("#addNewPackage-Modal .modal-dialog").load(target, function () {
$("#addNewPackage-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//View Shipping Package
$(document.body).on('click', '.viewsp', function (ev) {
ev.preventDefault();
var Id = $(this).attr("data-id");
var target = "";
target = "/Secure/Ecommerce/_ShippingPackage/" + Id;
// load the url and show modal on success
$("#addNewPackage-Modal .modal-dialog").load(target, function () {
$("#addNewPackage-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
/*--------------------------------------*/
/*------------------- Json Requests for Selected Shipping PostCodes -------------------*/
function getshippingPostcodes(dataTable) {
//debugger;
$.get('/Secure/Ecommerce/GetAllPostcodes').success(function (data) {
var markup = "";
for (var x = 0; x < data.length; x++) {
markup += '<tr>';
markup += '<td><input type="checkbox" class="checkIt" value="' + data[x].Id + '" /></td>';
markup += '<td>' + data[x].Postcode + '</td>';
markup += '<td>' + data[x].StrRestrictionLevels + '</td>';
markup += '<td>' + data[x].FirstItemPrice + '</td>';
markup += '<td>' + data[x].EachAdditionalItemPrice + '</td>';
markup += '<td>' + formatDateTime(data[x].CreatedOn) + '</td>';
var deleteRecordData = "deleteRecord('/Secure/Ecommerce/ShippingPostcodeDelete','" + data[x].Id + "','/Secure/Setting/Ecommerce')";
markup += '<td class="text-center"><div class="btn-group btn-group-xs" role="group">';
markup += '<a href="javascript://" data-id="' + data[x].Id + '" class="btn btn-info editPostcode" title="Edit"><i class="fa fa-edit"></i></a>';
markup += '<a href="javascript://" onclick="' + deleteRecordData + '" class="btn btn-danger" title="Delete"><i class="fa fa-trash"></i></a>';
markup += '</div></td>';
markup += "</tr>";
}
$(dataTable + ' tbody').html(markup);
});
};
/*--------------------------------------*/
//Post Code Managemnt
//Add New PostCode
$('.addNewPostCode').on('click', function () {
var target = "";
target = "/Secure/Ecommerce/_ShippingPostcodeRecord";
// load the url and show modal on success
$("#addNewPostCode-Modal .modal-dialog").load(target, function () {
$("#addNewPostCode-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//Edit PostCode
$(document.body).on('click', '.editPostcode', function (ev) {
ev.preventDefault();
var Id = $(this).attr("data-id");
var target = "";
target = "/Secure/Ecommerce/_ShippingPostcodeRecord/" + Id;
// load the url and show modal on success
$("#addNewPostCode-Modal .modal-dialog").load(target, function () {
$("#addNewPostCode-Modal").modal("show");
//filterDataTable("#employees-dataTable", [1, 2, 3, 4, 5, 6], [0]);
$('#loading-mask').hide();
});
});
//Payment Gateway
$(".btnApply").click(function (ev) {
var dataVal = $(this).attr("data-id");
if (dataVal != "")
{
$.ajax({
type: "POST",
url: "/Secure/Ecommerce/SavePaymentGateway",
data: {
value: dataVal
},
error: function (xhr, status, error) {
alert(error);
},
success: function (response) {
window.location.reload(true);
}
});
}
});
|
'use strict';
const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');
const debug = require('debug')('cfgram:photoalbum-router');
const PhotoAlbum = require('../model/photoalbum.js');
const bearerAuth = require('../lib/bearer-auth-middleware.js');
const photoAlbumRouter = module.exports = Router();
photoAlbumRouter.post('/api/photoalbum', bearerAuth, jsonParser, (req, res, next) => {
debug('POST: /api/photoalbum');
req.body.userId = req.user._id;
new PhotoAlbum(req.body).save()
.then( photoAlbum => res.json(photoAlbum))
.catch(err => {
err = createError(404, err.message);
next(err);
});
});
photoAlbumRouter.get('/api/photoalbum/:photoalbumId', bearerAuth, jsonParser, (req, res, next) => {
debug('GET: /api/photoalbum/:photoalbumId');
PhotoAlbum.findById(req.params.photoalbumId)
.then(photoAlbum => res.json(photoAlbum))
.catch(err => {
err = createError(404, err.message);
return next(err);
});
});
photoAlbumRouter.get('/api/photoalbum/user/me', bearerAuth, jsonParser, (req, res, next) => {
debug('GET: /api/photoalbum/user/me');
PhotoAlbum.find({userId: req.user._id})
.then(albums => res.json(albums))
.catch(err => {
err = createError(404, err.message);
return next(err);
});
});
photoAlbumRouter.get('/api/photoalbum/user/:userId', bearerAuth, (req, res, next) => {
debug('GET: /api/photoalbum/user/:userId');
PhotoAlbum.find({userId: req.params.userId})
.then(albums => res.json(albums))
.catch(err => {
err = createError(404, err.message);
return next(err);
});
});
photoAlbumRouter.put('/api/photoalbum/:photoalbumId', bearerAuth, jsonParser, (req, res, next) => {
debug('PUT: /api/photoalbum/:photoalbumId');
if(!req.body) return next(createError(400, 'invalid body'));
PhotoAlbum.findByIdAndUpdate(req.params.photoalbumId, req.body, {new:true})
.then(photoalbum => res.json(photoalbum))
.catch(err => {
err = createError(404, err.message);
return next(err);
});
});
photoAlbumRouter.delete('/api/photoalbum/:photoalbumId', bearerAuth, (req, res, next) => {
debug('DELETE: /api/photoalbum/:photoalbumId');
PhotoAlbum.findByIdAndRemove(req.params.photoalbumId)
.then( () => res.status(204).send())
.catch(next);
});
|
import React, {Component} from 'react'
import GooglePlacesAutocomplete from 'react-google-places-autocomplete'
import DistanceCalculator from '../DistanceCalculator';
import withQueryParams from '../hocs/withQueryParams'
class FormPage extends Component{
state={
origin: '',
destination: '',
date: '',
amountOfPeople: 0,
calculateDistance: false,
}
componentDidMount(){
if (!!this.props.query['origin']){
this.setState({origin: this.props.query['origin']})
}
if (!!this.props.query['destination']){
this.setState({destination: this.props.query['destination']})
}
if (!!this.props.query['date']){
this.setState({date: this.props.query['date']})
}
if (!!this.props.query['people']){
this.setState({amountOfPeople: parseInt(this.props.query['people'])})
}
}
handleDateChange =(event)=>{
this.setState({date: event.target.value})
}
handleAmountOfPeopleChange =(event)=>{
this.setState({amountOfPeople: event.target.value})
}
handleSubmit = (event) =>{
event.preventDefault()
if(!this.state.origin || !this.state.destination || !this.state.date || !this.state.amountOfPeople ){
alert('All Fields are required!!')
}else {
this.setState({calculateDistance:true})
}
}
render() {
if (this.state.calculateDistance){
return <DistanceCalculator
origin={this.state.origin}
destination={this.state.destination}
date={this.state.date}
people={this.state.amountOfPeople}
/>
}
return (
<div>
<h3>SEARCH FORM</h3>
<form onSubmit={this.handleSubmit}>
<label>Origin</label><br/><br/>
<GooglePlacesAutocomplete
initialValue={this.state.origin}
onSelect={({description})=>{this.setState({origin:description})}}
/><br/>
<label>Destination</label><br/><br/>
<GooglePlacesAutocomplete
initialValue={this.state.destination}
onSelect={({description})=>{this.setState({destination:description})}}
/><br/>
<label>Date</label><br/><br/>
<input name='date' type='date' value={this.state.date}
onChange={this.handleDateChange} /><br/><br/>
<label>Amount of Travellers</label><br/><br/>
<input name='amountOfPeople' type='number'
value={this.state.amountOfPeople}
onChange={this.handleAmountOfPeopleChange} /><br/><br/>
<button type="submit">
CALCULATE
</button>
</form>
</div>
);
}
}
export default withQueryParams(FormPage)
|
var port = process.env.PORT || 5000;
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost';
//setup express, mongo, and server vars
var express = require("express"),
app = new express();
var mongo = require('mongodb');
var ObjectId = mongo.ObjectID;
var Server = mongo.Server,
Db = mongo.Db;
var server = new Server(mongoUri, 27017, {auto_reconnect: true});
var recipedb = new Db('recipe', server);
app.set('view engine', 'ejs');
var fs = require('fs');
var XMLWriter = require('xml-writer');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/views'));
//init template data
var header = fs.readFileSync("head.txt","utf8");
var footer = fs.readFileSync("footer.txt","utf8");
var navbar = fs.readFileSync("navbar.txt","utf8");
var templateData = {
head: header,
footer: footer,
navbar: navbar
}
//console.log(header);
// Homepage
app.get('/', function(req, res){
res.render('home', {td:templateData});
});
app.get("/xml/recipe/:id", function(req, res){
var recipe_id = req.params['id'];
if (recipe_id){
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.findOne({_id:new ObjectId(recipe_id)}, function(err, recipe){
xw = recipesToXML([recipe], true, true);
res.render("recipe_xml", {recipe: xw.toString()});
});
});
});
} else {
res.send(404);
}
});
app.get("/xml/recipes", function(req,res){
console.log("request recieved");
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.find({},function(err, cursor){
cursor.toArray(function(err, arr){
arr.sort(function(a,b){
if(a.title<b.title) return -1;
if(a.title===b.title) return 0;
if(a.title>b.title) return 1;
});
//console.log(arr);
xw = recipesToXML(arr, false, false);
res.render("recipe_list_xml", {recipes: xw.toString()});
});
});
});
});
});
function recipesToXML(arr, ingredients, instructions) {
var xw = new XMLWriter;
xw.startDocument();
xw.startElement('root').writeAttribute("xmlns:h", "com.atommarvel.RecipeNation");
for(index in arr) {
xw.startElement("recipe").writeAttribute("_id",
arr[index]._id.toString()).writeAttribute("title",
arr[index].title.toString()).writeAttribute("servingSize",
arr[index].servingSize.toString());
if(ingredients) {
xw.startElement("ingredients");
for (ingred in arr[index].ingredients){
xw.startElement("ingredient").writeAttribute("item",
arr[index].ingredients[ingred].item).writeAttribute("category",
arr[index].ingredients[ingred].category);
xw.endElement("ingredient");
}
xw.endElement("ingredients");
}
if(instructions) {
xw.startElement("instructions");
for (step in arr[index].instructions){
xw.startElement("step").writeAttribute("value", arr[index].instructions[step]);
xw.endElement("step");
}
xw.endElement("instructions");
}
xw.endElement('recipe');
}
xw.endElement('root');
xw.endDocument();
return xw;
}
app.get('/recipes', function(req,res){
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.find({},function(err, cursor){
cursor.toArray(function(err, arr){
arr.sort(function(a,b){
if(a.title<b.title) return -1;
if(a.title===b.title) return 0;
if(a.title>b.title) return 1;
});
res.render("recipe_list", {recipes: arr, td:templateData});
});
});
});
});
});
app.get("/recipe/:id", function(req, res){
var recipe_id = req.params['id'];
if (recipe_id){
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.findOne({_id:new ObjectId(recipe_id)}, function(err, recipe){
res.render("recipe", {id: recipe_id, recipe: recipe, td:templateData});
});
});
});
} else {
res.send(404);
}
});
// This takes the user to a page that can be used to submit a recipe.
app.get('/newrecipe', function(req, res){
res.render('new_recipe', {td:templateData});
});
app.get('/updaterecipe/:id', function(req, res){
var recipe_id = req.params['id'];
if (recipe_id){
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.findOne({_id:new ObjectId(recipe_id)}, function(err, recipe){
res.render('update_recipe',{recipe: recipe, td:templateData});
});
});
});
} else {
res.send(404);
}
});
app.put('/updaterecipe/:id',function(req, res){
var recipe_id = req.params['id'];
var ingreds = new Array();
var instr = new Array();
var i = 0;
for(i=0; i<=20;i++){
if(req.body['ingredient'+i])
ingreds[ingreds.length]={item: req.body['ingredient'+i], category: req.body['category'+i]};
}
for(i=0; i<=20;i++){
if(req.body['newingredient'+i])
ingreds[ingreds.length]={item: req.body['newingredient'+i], category: req.body['newcategory'+i]};
}
for(i=0; i<=10;i++){
if(req.body['step'+i])
instr[instr.length]=req.body['step'+i];
}
for(i=0; i<=10;i++){
if(req.body['newstep'+i])
instr[instr.length]=req.body['newstep'+i];
}
var new_recipe = {
title: req.body['title'],
servingSize: req.body['size'],
ingredients: ingreds,
instructions: instr
};
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.update({_id:ObjectId(recipe_id)},new_recipe, function(err){
res.redirect('/');
});
});
});
});
app.post("/newrecipe", function(req, res){
//console.log(req.body);
if (req.body['title']){
var ingreds = new Array();
var instr = new Array();
var i = 0;
for(i=0; i<=20;i++){
if(req.body['ingredient'+i])
ingreds[ingreds.length]={item: req.body['ingredient'+i], category: req.body['category'+i]};
}
for(i=0; i<=10;i++){
if(req.body['step'+i])
instr[instr.length]=req.body['step'+i];
}
var new_recipe = {
title: req.body['title'],
servingSize: req.body['size'],
ingredients: ingreds,
instructions: instr
};
//console.log(new_recipe);
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.insert(new_recipe, function(err){
res.redirect('/');
});
});
});
} else {
res.send(400);
}
});
app.get('/newgroceryl', function(req, res){
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.find({},function(err, cursor){
cursor.toArray(function(err, arr){
arr.sort(function(a,b){
if(a.title<b.title) return -1;
if(a.title===b.title) return 0;
if(a.title>b.title) return 1;
});
res.render('new_grocerylist', {recipes:arr, td:templateData});
});
});
});
});
});
app.post('/groceryl', function(req,res){
//console.log(Object.keys(req.body).length);
console.log(req.body);
//create array of recipes
var recipes = new Array();
var ids = new Array();
for(key in req.body){
ids.push({_id:new ObjectId(key)});
}
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.find({$or:ids}, function(err, cursor){
cursor.toArray(function(err,arr){
//console.log(arr);
res.render('grocerylist', {recipes: arr, td:templateData});
});
});
});
});
//console.log(recipes);
});
app.delete("/recipe/:id", function(req, res){
var recipe_id = req.params['id'];
if(recipe_id){
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('recipe', function(err, coll){
coll.remove({_id:new ObjectId(recipe_id)}, function(err){
res.redirect('/recipes');
});
});
});
} else {
res.send(404);
}
});
app.listen(port);
|
export default (metric = [], year = undefined, project = undefined) => {
return (((metric.filter((data) => {
if (year === undefined || year == "Year")
return data.year !== year;
else
return data.year == year;
}
)).filter((data) => {
if (project == undefined || project == "Project") {
return data.podName !== undefined;
}
else {
return data.podName == project;
}
})).sort((a, b) => a.month - b.month))
}
|
import FadeIn from "../FadeIn";
import Link from "next/link";
import Chip from "@material-ui/core/Chip";
export default function PayrollSystem() {
const tech = ["C#", "MariaDB"];
return (
<>
<FadeIn>
<hr className="mt-4" />
<div>
<div>
<h6 className="middle-underline d-inline">Payroll System</h6>
</div>
<p className="mt-2">
Employee payroll system capable of generating salary slips,
calculating salaries and maintaining a list of employees and their
financial details. The software was built for Windows systems using
C#.
</p>
{/* <h6 className="mt-4">Releases</h6> */}
<div className="d-none">
<Link passHref href={""}>
<a className="grey-to-white text-decoration-none">v1 (latest)</a>
</Link>
</div>
<h6 className="mt-4">Technologies</h6>
<div class="tech-badges">
{tech.map((chip) => {
return <Chip size="small" key={chip} label={chip} />;
})}
</div>
</div>
</FadeIn>
</>
);
}
|
/**
* Função para envio de ajax
*
*/
function Ajax(settings)
{
//objeto que vai receber dados a serem enviados
var dados = {};
//link que vai receber a requisição ajax
if(!settings.link)
{
settings.link = "index.php?option=com_stoledo_ajax";
}
if(settings.tmpl)
settings.link += "&tmpl="+settings.tmpl;
if(settings.acao)
settings.link += "&acao="+settings.acao;
if(settings.moduleId)
settings.link += "&moduleId="+settings.moduleId;
if(settings.modulePosition)
settings.link += "&modulePosition="+settings.modulePosition;
//referencia para uso de preloader
if(!settings.preloader)
settings.preloader = "#preloader";
//função chamada quando se recebe um retorno do ajax
if(!settings.callback)
settings.callback = function(dado)
{
};
//evento chamado quando se inicia um evento ajax
if(!settings.ajaxStart)
settings.ajaxStart = function()
{
$(settings.preloader).show();
};
//evento chamado quando se termina um evento ajax
if(!settings.ajaxStop)
settings.ajaxStop = function()
{
$(settings.preloader).hide();
};
this.setDado = function(nome, valor)
{
dados[nome] = valor;
}
$('body').ajaxStart
(
function()
{
settings.ajaxStart();
}
);
this.enviar = function()
{
$.post
(
settings.link,
dados,
settings.callback
);
}
$('body').ajaxStop(
function()
{
settings.ajaxStop();
}
);
}
/**
* Função para só permitir números nos inputs dos forms
*
* Ex:
* <input maxlength="9" onkeydown="javascript:return numeros(event); " onkeypress="formatar(this, '#####-###'); " name="cep">
*/
function numeros(event){
var tecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if ((tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) || tecla == 8 || tecla == 9){
return true;
}else{
return false;
}
}
/**
* Formata o número double em formato real
*
*/
function formatReal(num) {
x = 0;
if(num<0) {
num = Math.abs(num);
x = 1;
}
if(isNaN(num)) num = "0";
cents = Math.floor((num*100+0.5)%100);
num = Math.floor((num*100+0.5)/100).toString();
if(cents < 10) cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+'.'
+num.substring(num.length-(4*i+3));
ret = num + ',' + cents;
if (x == 1) ret = ' - ' + ret;
return ret;
}
/**
* Função para mascara de entrada de dados
*
*
* Ex;
* <input maxlength="9" onkeydown="javascript:return numeros(event); " onkeypress="formatar(this, '#####-###'); " name="cep">
*/
function formatar(src, mask) {
var i = src.value.length;
var saida = mask.substring(0,1);
var texto = mask.substring(i)
if (texto.substring(0,1) != saida) {
src.value += texto.substring(0,1);
}
}
/**
* Função para limpar campo de texto
*
* Ex:: <input type="text" onfocus="limpaCampo(this)" onblur="originalCampo(this, 'Seu nome')" value="Seu Nome" name="nomePratoDia">
*/
function limpaCampo(object)
{
$(object).val('');
}
/**
* Função para colocar texto em um campo se ele for fazio
*
* Ex:: <input type="text" onfocus="limpaCampo(this)" onblur="originalCampo(this, 'Seu nome')" value="Seu Nome" name="nomePratoDia">
*/
function originalCampo(object, value)
{
if(!$(object).val())
{
$(object).val(value);
}
}
/**
* Função para validação de email
*
* Ex:: $.validateEmail('fulano@email.com.br');
*
*/
$.validateEmail = function (email)
{
er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
if(er.exec(email))
return true;
else
return false;
};
/**
* Extensão do jquery para carregar o site por partes
*
* var map =
{
0 : {pg:'pagina_0', fn:main_pg_0},
1 : {pg:'pagina_1', fn:main_pg_1},
2 : {pg:'pagina_9', fn:main_pg_9},
3 : {pg:'pagina_2', fn:main_pg_2},
4 : {pg:'pagina_4', fn:main_pg_4},
5 : {pg:'pagina_5', fn:main_pg_5},
6 : {pg:'pagina_3', fn:main_pg_3},
7 : {pg:'pagina_6', fn:main_pg_6},
8 : {pg:'pagina_7', fn:main_pg_7},
9 : {pg:'pagina_8', fn:main_pg_8}
};
$.modules(map, 'index.php?option=com_content&view=category&layout=blog&id=2&Itemid=101&');
var map =
{
0 : {pg:'docentes', fn:function(){alert("asdf")}}
};
$.modules(map, '');
*
*/
(function($){
$.extend
({
module: function(id)
{
function addHtml(dado)
{
$('body').html(dado);
}
var ajax = new Ajax
(
{
callback :addHtml
}
);
ajax.setDado('moduleId', id);
ajax.enviar();
},
modules: function(map, link)
{
var map = map;
var tamanho = -1;
var i = 0;
$.each(map, function(key, value) {
tamanho++;
});
if(tamanho >= 0)
enviar();
function addHtml(dado)
{
//$('#meio').append(dado);
$('#'+map[i].pg).html(dado);
if(map[i].fn)
map[i].fn();
i++;
enviar();
}
function enviar()
{
if(i <= tamanho)
{
var ajax = new Ajax
(
{
link : link,
callback :addHtml
}
);
ajax.setDado('modulePosition', map[i].pg);
ajax.enviar();
}
//else
// main();
}
}
});
})($);
|
$(document).ready(function() {
$('select').addClass('form-control');
$("#id_filterset_form input,select").change(function() {
$("#id_filterset_form").submit();
});
if($("#id_sprint_end").size()){
select= $("#id_sprint_end");
date = $("<input type='date' >").addClass('form-control').hide();
cal = $("<div class='glyphicon glyphicon-calendar'></div>").css('padding-left','5px');
close = $("<div class='glyphicon glyphicon-remove'></div>").css('padding-left','5px').hide();
select.after(date);
select.after(cal);
date.after(close);
cal.click(function(){handler(1);});
close.click(function(){handler(0);});
list = [];
options = $('#id_sprint_end option');
options.each(function(){
list.push(this.value);
});
function handler(arg){
select.toggle();
cal.toggle();
close.toggle();
date.toggle();
if(arg){
select.attr('name','');
date.attr('name','sprint_end');
}else {
date.attr('name','');
select.attr('name','sprint_end');
if($.inArray(date.val(), list) != -1){
select.val(date.val());
}
}
}
date.keypress(function(e){
if(e.which == 13){
$("#id_filterset_form").submit();
}
});
if(DUE_PARAM){
if($.inArray(DUE_PARAM,list ) == -1){
cal.click();
date.val(DUE_PARAM);
}
}
}
});
|
import React, { Component, PropTypes } from 'react'
import Dropzone from "react-dropzone";
import Cropper from 'react-cropper';
import Input from './Input';
import { config } from '../config.js'
const API_URL = config.API_URL;
export default class ItemImageForm extends Component {
constructor(props) {
super(props);
this.state = {
image: "",
base64: "",
downloadUrl:false
};
}
onDrop(files) {
this.setState({
image: files[0].preview
});
}
componentWillReceiveProps(nextProps){
if (nextProps.image){
this.setState({
image: API_URL+nextProps.image
});
}
}
crop(){
this.setState({base64: this.refs.cropper.getCroppedCanvas().toDataURL("image/png")});
}
onBlurUrl(e){
if (!this.props.downloadImage) {
if (this.state.downloadUrl==false){
this.setState({downloadUrl: true});
this.props.onDownloadImage(e.target.value);
setTimeout(this.onBlurUrl.bind(this, e), 1000);
return;
}
}
this.setState({image: API_URL+this.props.imageDownloaded})
}
deleteImage(){
this.setState({image:""})
this.setState({downloadUrl: false});
this.props.onDeleteImage;
}
render() {
const {image, onDownloadImage, imageDownloaded, errorMessage, onDeleteImage} = this.props
return (
<div className="item-image-form">
{this.state.image != "" ?
<div className="item-image-form-cropper">
<Cropper
ref='cropper'
src={this.state.image}
style={{height: 380, width: "100%"}}
guides={false}
dragMode={"move"}
background={false}
modal={false}
crop={this.crop.bind(this)}
checkCrossOrigin={true}
/>
<div className="item-image-form-cropper-btn btn1" onClick={this.deleteImage.bind(this)}>Changer la photo</div>
<Input
className=" hidden "
placeholder="image"
name="image"
type="text"
value={this.state.base64}
/>
</div>
:
<div className="item-image-form-upload">
<Dropzone onDrop={this.onDrop.bind(this)} className="item-image-form-upload-dropzone">
<div className="item-image-form-upload-dropzone-text"><span className="c-main">Cliquez-glissez</span> une photo ici, ou <span className="c-main">cliquez</span> pour sélectionner une photo à uploader</div>
</Dropzone>
<div className="item-image-form-upload-field">
<label htmlFor="url" className="c-main">Entrez-une URL pour télécharger une photo</label>
<input
type="text"
name="url"
placeholder="Url"
id="url"
onBlur={this.onBlurUrl.bind(this)}
/>
</div>
</div>
}
</div>
)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.