entities listlengths 1 8.61k | max_stars_repo_path stringlengths 7 172 | max_stars_repo_name stringlengths 5 89 | max_stars_count int64 0 82k | content stringlengths 14 1.05M | id stringlengths 2 6 | new_content stringlengths 15 1.05M | modified bool 1 class | references stringlengths 29 1.05M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": " Bubbles quote\n#\n# Notes:\n# None\n#\n# Author:\n# carmstrong\n\njroc = [\n \"There's 2 things mafukas gonna know ",
"end": 350,
"score": 0.9994996190071106,
"start": 340,
"tag": "USERNAME",
"value": "carmstrong"
},
{
"context": ",\n \"(To Lahey and Randy) Why d... | src/scripts/tpb.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# Quotes by the Trailer Park Boys
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hey j-roc - Display a random J-ROC quote
# hey lahey - Display a random Lahey quote
# hey ricky - Display a random Ricky quote
# hey bubbles - Display a random Bubbles quote
#
# Notes:
# None
#
# Author:
# carmstrong
jroc = [
"There's 2 things mafukas gonna know about J-to-the-ROC: I spin more rhymes than a lazy Susan, and I'm innocent until mah guilt is proven! Peace! Representin' Sunnyvale, straight-the-fuck-up.",
"(To Lahey and Randy) Why don't you run along, Gut Cassidy and the Sundance Cheeseburger. Don't look into my eyes like I got candy for you.",
"Only wacksuckas like Cory and Trevor steal gas...and deal dope.",
"Yo Julian, I'm going to be a daddy. Not once but two times dawg, two times.",
"You know what I'm sayin'?",
"Rayyyyy - Kojak's got a wig on, RAYYY!",
"So why don't you move it along, you Rico-Suave-lookin' mafucka, cuz you ain't beatin' nobody.",
"You mean we can't go on with the game cuz some mafucka can't go to Canadian Mafacka (Tire) and get a new orange mafucka (ball) for $2.99? That's wack, Jules.",
"Yo, it's Rocky and Bullma'fucker.",
"J-Roc an' da Rock-Pile ALL UP IN DIS' MA' !",
"Naw, man, I don't play guns, mafucka.",
"We ain't down with killin', we down with chillin'. Peace!",
"The day J-ROC loses his flow, is the day the hair on Jim Lahey's bald head grow!",
"(referring to Jacob) That's the fuckin' law bitch from the grocery store y'man, who you pointin' at, skeleton?",
"This is BULL-ISH!",
"I can't even breathe up in this piece!",
"(to Randy) Oh what, you ain't pregnant with a bucketa chicken?",
"(to Randy) What you talkin' 'bout, you inflatable Elvis?",
"Oh, no, you di'n't just call me Jamie!",
"(holding his chains to Randy's gut like a stethoscope) I hear chicken. I hear cola fizz, and mustard and relish coagulating together with french fries and onion rings, but you know what? I don't hear a heart.",
"Carpe Dizem!"
]
ricky = [
"Lucy is banging cops which is no big deal, I guess. I don't run Lucy. She's for to be her own woman (free to be)",
"Lucy might have a problem, but what Lucy doesn't know won't learn her. (hurt)",
"Get me two bags of chips: Dressed All Over, and Zesty Mordant. (All Dressed and Zesty. Mordant is French for Zesty and is a mix-up of reading both languages on the bilingual packaging in Canada)",
"Yeah, get me some ja-LAP-ano chips (jalapeño)",
"Worst case Ontario... (scenario)",
"It's basically Peach'n'Cake (a piece of cake)",
"Denial and Error... (trial)",
"Make my words (Mark)*",
"Hey Bubs, are you watching that documentary on Saskatchewans?(Sasquatches)*",
"(While addressing the Judge in court) Thank you, Your Majesty. (Honour, which is still incorrect. In Canada a female judge is referred to as My Lady.)",
"I'm trying to try here, Sarah.",
"Who's playing the pianio? (piano)",
"Make like a tree and fuck off. (leave)",
"I'm not the kind of person to say atodaso, but you know what? Atodaso, I-fucking-atodaso. (I told you so)",
"It was golfing flames, flames just golfing, golfing. (engulfed in flames)",
"It's a Catch-23 situation. (Catch-22)",
"(To Alex Lifeson of Rush) Well, play that Diane Sawyer song, then. (Tom Sawyer - Rush song)",
"Looks like a tropical earthquake blew through here. (storm)",
"We can get 2 birds stoned at once. (kill 2 birds with one stone)",
"Why do you look like Indianapolis Jones? (Indiana)",
"He passed with flying fucking carpets. (colours)",
"It doesn't take rocket appliances. (science)",
"Trinity's at the age where it's gorilla see gorilla do. (monkey)",
"Do you got a search warranty for that? (warrant)*",
"I must be fire retarded or something. (retardant)",
"I'm not a pezmist, I'm an optometrist. (Pessimist, Optimist)",
"These plates got me from Tuscany, Arizona to Kentville, Nova Scotia. (Tucson) - Ray, Ricky's Dad",
"I'll drive you back to the park, Lucy, but there is probably a pretty good chance that it might be over between us (Ricky uses a triple conditional; just one would be sufficient)",
"If my dad and Julian and Bubbles hadn't had been out all night getting lap-dances and getting drunk, the whole thing could have been preventative. (prevented)",
"To be honest with you, I fucking hate bagminten. (badminton)",
"Breaker, Breaker, come in earth. This is Rocketship 27, some aliens fucked over the carbinator in engine number four, we are going to try to refuckulate it and land on Juniper. (carburetor, repair, Jupiter)",
"That's not a ladybug. It's a cannerpillar. (caterpillar)",
"...how to get Buhurbon stains out of Kahayki pants (Bourbon, Khaki)",
"One man's garbage is another man person's good ungarbage. (One man's garbage is another man's treasure)",
"Au gratin (gratis, free; au gratin is with cheese)",
"I-surance (Insurance)*",
"Swallow my prize (pride)",
"Neither here, there, or everywhere (Neither here nor there)",
"Boys, let's make toast (Let's make a toast)",
"There's no lurches in there, Bubbles, is there? (leeches)",
"I know what you're doing, Lahey, you're trying to fill my feet. (fill my shoes)",
"You gotta remember, every kid goes through phrases. (phases)",
"What Julian don't grow won't burn him. (know, hurt)",
"Nice decnals! (decals)",
"I'm just stretched out! (stressed)*",
"I don't need your cherry trees. (charity)*",
"What if he has radies? (rabies)",
"Supply and command. (demand)",
"What comes around is all around (What goes around comes around)",
"What, do you own space? No. Nay-saw does. (NASA)",
"Do unto others as you do unto you. (Do unto others as you would have them do unto you)",
"One day I will go somewhere that is hot, like Majaica or the Dromedary Republic (Jamaica, Dominican Republic)",
"Trinity made a life-ing thing basically out of this chicken. Started with a little eggy thing, and heated it up under these incu-baker things, and it...it was bornt. (living, incubator, born)",
"We'll split 50/50/50. (three ways.)",
"(To Trevor and Cory) Well, I'd like for you two to come with us, but apparently it's clear to see who makes the pants here. (wears the pants)",
"I hate to have to give you an ultimarium (ultimatum)",
"It's me or Gumby and Pifuckio (Cory and Trevor)",
"Raykins! That's what they are, Julian, fuckin' raykins! (raccoons)",
"I'm not working for J-Roc, that's against my vice principals (principles)",
"Bubbles, I don't want any rich peopleman's food, I want some fuckin' meat that's cooked. (people's)",
"It's survival of the fitness, boys. (fittest)",
"If Randy thinks he's smartener than me, he's wrong. (smarter)*",
"You gotta do illegal things once in a while, and then maturinate into a better person. (mature)",
"Your thoughts might be better than mine, but I have thoughts going around in my head too, about...different thinkings...about brain things that you can use and...doing different things.",
"Sweet empowered chicken things (sweet and sour chicken)",
"(To Shitty Bill) Take a shower for fuck's sake! You look like a fuckin' hobolo! (hobo)",
"(To Randy) Why don't you fuck off and go get some hypo-suction! (liposuction)",
"It was my mother's mating name. (maiden name)",
"Holy shit, you got us a lemon-zine? (Limousine)",
"Randy bornt my baby. (Randy is the father of Lucy's 2nd child)",
"Lucy, I will make you have a eternity test. (paternity)",
"He's gettin' all frustated. (frustrated)",
"You can go to college and get your little Pf.D, or whatever the fuck it's called! (Ph.D.)",
"Child reports (Child Support)",
"Get us the fuckin' land papers A.S.A.T! (Land papers because he couldn't pronounce 'topographic map', A.S.A.P)",
"I'm fucked over from being electromecuted! (electrocuted)",
"Those them cigarettes in there is our lifes! (are our lives)",
"...it's distraculating my case. (distracting)",
"Amernicans! (Americans)",
"I have responsibles now... (Responsibilities)",
"Well, now we gotta go to the library and get a book on horficulture. (Horticulture)",
"I self-learned myself. (self-taught)"
]
lahey = [
"When you plant shit-seeds, you get shit-weeds.",
"Birds of a shitfeather flock together, Randy.",
"We're in the eye of a shiticane here, Julian, and Ricky's a low-shit system!",
"Shit-storm troopers",
"The shit-apple doesn't fall far from the shit-tree",
"Captain Shittacular",
"I'm watching you like a shithawk",
"We're sailing into a shit-typhoon Randy, we'd better haul in the jib before it gets covered in shit.",
"When you're getting pelted with shitballs, deputy, you gotta get a shit-bat.",
"The shit pool's gettin full, Randy, time to strain the shit before it overflows. I will not have a Pompeiian catastrophie happening in Sunnyvale.* How dare you involve my daughter in your hemisphere of shit?",
"Your shit-goose is cooked, Ricky",
"Shit-apples never fall far from the shit-tree",
"He's about to enter the shit-tornado to Oz.",
"Do you know what a shit-rope is Julian? It's a rope covered in shit that criminals try to cling to. Y'see, the shit acts like grease, and the harder you tighten your grip, the more you slide down it.",
"A shit-leopard can't change its spots.",
"We need more shit puppets for our play, Randy, and we need angry shit puppets but they aren't mad at us. Shit puppets only get angry at other shit puppets",
"Randy: Cops and dope don't mix, do they Mr. Lahey? Lahey: Like shit and strawberry shortcake Randy.",
"I live by the golden rule: if you don't cross my shitline I won't cross yours. But when Ray told everybody in the park that I was drinking again, he crossed the goddamn shitline.",
"Lahey: Do you know what a shit barometer is, Bubbles? Measures the shit pressure in the air. You can feel it. Listen, Bubs. You hear that? The sounds of the whispering winds of shit? You can hear it.",
"Do you feel that, Randy, the way the shit clings to the air? Shit Blizzard.",
"Never Cry Shitwolf.",
"Did you see that Randy, Goddamn shitapple driving the shitmobile. Nobody else in this park gives a fuck, why should I?",
"Lahey -You know what's at work here, it's shit tectonics, when two shit plates strike and come together under incredible pressure, do you know what happens, Bubbles?",
"Yes I used to drink, Randy, but I got the shitmonkey off my back for good.",
"You just opened Pandora's Shitbox, Ray",
"You know what you get when two shit-tectonic plates collide? Shitquakes, Julian. Shitquakes.",
"The ole shit liner is coming to port, and I'll be there to tie her up.",
"Y'see, Ricky started off as a little shitspark from the ol' shitflint that eventually grew into a shitbonfire, and driven by the winds of his monumental ignorance, grew into a raging shitfirestorm. If I marry Barb, I'll have total control of Sunnyvale, and then I'll be able to unleash a shitnami tidal wave that will extinguish Ricky and his shitflames forever. And with any luck, he'll drown in the undershit of that wave...shitwaves.",
"Tic Toc, Shit clock's tickin' Rick.",
"We got the key to shitty city, Ran, and Julian's the muscular mayor.",
"You boys have loaded up a hair-trigger, double barrelled shitmachinegun, and the barrel's pointing right at your own heads.",
"Shit flowers, Randy. From a distance they look like ordinary flowers, but when you get right down and stick your nose in them you realize they're shit flowers, and there's a whole fucking bouquet down there right in front of Ray's trailer.",
"Lahey: Shit moths, Randy. Randy: Is that you or the liquor speaking, Mr Lahey?",
"Hey Sexian (Lahey adressing Julian)",
"Whenever I'm sober, the boys are careful, they're scared of me cause they know what I'll do. They're cautious, it's hard to catch them. But when I'm drinking, their shitguards are down and they fuck up, but the problem is when I'm drinking, I fuck up too, a lot, Barb. I gotta be drinking, but not drinking, ya see? The only way to do that, is to pretend, I am gonna pretend to be drunk, collect evidence and build a solid case against them. Sober as a judge I'm gonna show up today at the cheeseburger picnic, and I'm gonna pretend to be a drunken idiot. And why? Shitguards, Barb...shitguards.",
"This place is a dump. You have my permission to do whatever you want, any time any place, and you don't have to listen to Pilsbandy Doughboy (Randy) or Team Sexy (the police)"
]
bubbles = [
"I'd like to see that Red Blue Green cocksucker put one of those together fucking duct taping it.",
"Dino. Did you call Fred and Barney too? How about Mr. Slate?",
"I won't tell anyone you have splinters in your lips if you don't tell anyone I have a wooden cock.",
"Randy: Does that thing really launch, Bubbles? Bubbles: Does the Tin Man have a sheet-metal cock?",
"Julian, what's a shit hawk? Is it some kind of shitty bird that swoops down and puts poop on you?",
"Ricky, what happened to your fucking eyes? You look like Alice Cooper?",
"(in reference to the Helix song Rock You) I'm not giving anyone a fucking R!",
"Ricky, those laws are there to protect kids, not so goofballs like you can put them in the car with no door on it, and drive around the fuckin' neighbourhood stealin' barbecues!",
"Can I come out now? I think I have a leech on my bird.",
"Julian, we're both baked. That's why were probably not making any sense.",
"No, he's just a really big kitty, and he's baked!",
"Bubbles: Stealing gas? Why, Cory and Trevor, that's highly illegal, you shouldn't be stealing gas, Cory and Trevor.",
"(Rapping) I got a grey kitty, white one, and a tabby too/ And a big orange guy who put snakes in my shoes/ Mad MC skills, leave ya struck, and I roll with ma kitties, and I'am hard as fuck/ I am down with Plato and Socrates/ And I like to get busy with all the ladies. Grunt, grunt/ sumthin,' sumthin,' sumthin,'/ Grunt/ Up in ma shed, up in ma shed...",
"Holy fuck boys, this shed is like a fucking palace! Indoor plumbing (toilet seat inside), satellite tv, 400 channels, anything I wanna watch, it's right there, space for my kitties, Mobile phone, new technology (holds up an ancient mobile phone), this is the best fucking shed there ever was!",
"Here, Cory-Trevor, Cory-Trevor!",
"Hampton: Can you read, my son? Bubbles: Well, that depends, can you go fuck yourself?",
"Trevor: Julian, this looks like a pirate gun. Bubbles: Well Trevor, I guess that makes you Long John Dickweed, then.",
"Green Bastard, from parts unknown (grunts and inhales).",
"Lahey, can you please get the flyin' fuck out of our way!",
"COCK-SUCKER!",
"There's a note pinned to a tree! Diddly-dee!",
"(To Randy re: cheeseburgers) How many did you drive into that big fuckin cheeseburger-locker?",
"Well, when I was a little guy, I always wanted to go up into space, be a space-man. But you gotta be able to see really fuckin' good to do that job. Some guy would take one look at me and say 'Uhhh, sorry sir, you gotta be able to see a little better than you'... I don't give a fuck.",
"Holy sweet flying fuck!"
]
module.exports = (robot) ->
robot.hear /.*(hey bubbles).*/i, (msg) ->
msg.send msg.random bubbles
robot.hear /.*(hey ricky).*/i, (msg) ->
msg.send msg.random ricky
robot.hear /.*(hey j-roc).*/i, (msg) ->
msg.send msg.random jroc
robot.hear /.*(hey lahey).*/i, (msg) ->
msg.send msg.random lahey | 143879 | # Description:
# Quotes by the Trailer Park Boys
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hey j-roc - Display a random J-ROC quote
# hey lahey - Display a random Lahey quote
# hey ricky - Display a random Ricky quote
# hey bubbles - Display a random Bubbles quote
#
# Notes:
# None
#
# Author:
# carmstrong
jroc = [
"There's 2 things mafukas gonna know about J-to-the-ROC: I spin more rhymes than a lazy Susan, and I'm innocent until mah guilt is proven! Peace! Representin' Sunnyvale, straight-the-fuck-up.",
"(To Lahey and Randy) Why don't you run along, <NAME> and the Sundance Cheeseburger. Don't look into my eyes like I got candy for you.",
"Only wacksuckas like Cory and Trevor steal gas...and deal dope.",
"Yo <NAME>, I'm going to be a daddy. Not once but two times dawg, two times.",
"You know what I'm sayin'?",
"Rayyyyy - Kojak's got a wig on, RAYYY!",
"So why don't you move it along, you Rico-Suave-lookin' mafucka, cuz you ain't beatin' nobody.",
"You mean we can't go on with the game cuz some mafucka can't go to Canadian Mafacka (Tire) and get a new orange mafucka (ball) for $2.99? That's wack, Jules.",
"Yo, it's Rocky and Bullma'fucker.",
"J-Roc an' da Rock-Pile ALL UP IN DIS' MA' !",
"Naw, man, I don't play guns, mafucka.",
"We ain't down with killin', we down with chillin'. Peace!",
"The day J-ROC loses his flow, is the day the hair on <NAME>'s bald head grow!",
"(referring to <NAME>) That's the fuckin' law bitch from the grocery store y'man, who you pointin' at, skeleton?",
"This is BULL-ISH!",
"I can't even breathe up in this piece!",
"(to <NAME>) Oh what, you ain't pregnant with a bucketa chicken?",
"(to R<NAME>) What you talkin' 'bout, you inflatable Elvis?",
"Oh, no, you di'n't just call me <NAME>!",
"(holding his chains to Randy's gut like a stethoscope) I hear chicken. I hear cola fizz, and mustard and relish coagulating together with french fries and onion rings, but you know what? I don't hear a heart.",
"<NAME>!"
]
ricky = [
"<NAME> is banging cops which is no big deal, I guess. I don't run <NAME>y. She's for to be her own woman (free to be)",
"<NAME> might have a problem, but what <NAME>y doesn't know won't learn her. (hurt)",
"Get me two bags of chips: Dressed All Over, and Zesty Mordant. (All Dressed and Zesty. Mordant is French for Zesty and is a mix-up of reading both languages on the bilingual packaging in Canada)",
"Yeah, get me some ja-LAP-ano chips (jalapeño)",
"Worst case Ontario... (scenario)",
"It's basically Peach'n'Cake (a piece of cake)",
"Denial and Error... (trial)",
"Make my words (Mark)*",
"Hey Bubs, are you watching that documentary on Saskatchewans?(Sasquatches)*",
"(While addressing the Judge in court) Thank you, Your Majesty. (Honour, which is still incorrect. In Canada a female judge is referred to as My Lady.)",
"I'm trying to try here, <NAME>.",
"Who's playing the pianio? (piano)",
"Make like a tree and fuck off. (leave)",
"I'm not the kind of person to say atodaso, but you know what? Atodaso, I-fucking-atodaso. (I told you so)",
"It was golfing flames, flames just golfing, golfing. (engulfed in flames)",
"It's a Catch-23 situation. (Catch-22)",
"(To <NAME> of Rush) Well, play that Diane Sawyer song, then. (Tom <NAME> - Rush song)",
"Looks like a tropical earthquake blew through here. (storm)",
"We can get 2 birds stoned at once. (kill 2 birds with one stone)",
"Why do you look like Indianapolis Jones? (Indiana)",
"He passed with flying fucking carpets. (colours)",
"It doesn't take rocket appliances. (science)",
"Trinity's at the age where it's gorilla see gorilla do. (monkey)",
"Do you got a search warranty for that? (warrant)*",
"I must be fire retarded or something. (retardant)",
"I'm not a pezmist, I'm an optometrist. (Pessimist, Optimist)",
"These plates got me from Tuscany, Arizona to Kentville, Nova Scotia. (Tucson) - Ray, R<NAME>'s Dad",
"I'll drive you back to the park, <NAME>, but there is probably a pretty good chance that it might be over between us (Ricky uses a triple conditional; just one would be sufficient)",
"If my dad and <NAME> and <NAME> hadn't had been out all night getting lap-dances and getting drunk, the whole thing could have been preventative. (prevented)",
"To be honest with you, I fucking hate bagminten. (badminton)",
"Breaker, Breaker, come in earth. This is Rocketship 27, some aliens fucked over the carbinator in engine number four, we are going to try to refuckulate it and land on Juniper. (carburetor, repair, Jupiter)",
"That's not a ladybug. It's a cannerpillar. (caterpillar)",
"...how to get Buhurbon stains out of Kahayki pants (Bourbon, Khaki)",
"One man's garbage is another man person's good ungarbage. (One man's garbage is another man's treasure)",
"Au gratin (gratis, free; au gratin is with cheese)",
"I-surance (Insurance)*",
"Swallow my prize (pride)",
"Neither here, there, or everywhere (Neither here nor there)",
"Boys, let's make toast (Let's make a toast)",
"There's no lurches in there, Bubbles, is there? (leeches)",
"I know what you're doing, Lahey, you're trying to fill my feet. (fill my shoes)",
"You gotta remember, every kid goes through phrases. (phases)",
"What Julian don't grow won't burn him. (know, hurt)",
"Nice decnals! (decals)",
"I'm just stretched out! (stressed)*",
"I don't need your cherry trees. (charity)*",
"What if he has radies? (rabies)",
"Supply and command. (demand)",
"What comes around is all around (What goes around comes around)",
"What, do you own space? No. Nay-saw does. (NASA)",
"Do unto others as you do unto you. (Do unto others as you would have them do unto you)",
"One day I will go somewhere that is hot, like Majaica or the Dromedary Republic (Jamaica, Dominican Republic)",
"Trinity made a life-ing thing basically out of this chicken. Started with a little eggy thing, and heated it up under these incu-baker things, and it...it was bornt. (living, incubator, born)",
"We'll split 50/50/50. (three ways.)",
"(To Trevor and Cory) Well, I'd like for you two to come with us, but apparently it's clear to see who makes the pants here. (wears the pants)",
"I hate to have to give you an ultimarium (ultimatum)",
"It's me or <NAME> and <NAME>io (<NAME> and T<NAME>)",
"<NAME>ins! That's what they are, <NAME>, fuckin' raykins! (raccoons)",
"I'm not working for J-Roc, that's against my vice principals (principles)",
"Bubbles, I don't want any rich peopleman's food, I want some fuckin' meat that's cooked. (people's)",
"It's survival of the fitness, boys. (fittest)",
"If <NAME> thinks he's smartener than me, he's wrong. (smarter)*",
"You gotta do illegal things once in a while, and then maturinate into a better person. (mature)",
"Your thoughts might be better than mine, but I have thoughts going around in my head too, about...different thinkings...about brain things that you can use and...doing different things.",
"Sweet empowered chicken things (sweet and sour chicken)",
"(To <NAME>) Take a shower for fuck's sake! You look like a fuckin' hobolo! (hobo)",
"(To <NAME>) Why don't you fuck off and go get some hypo-suction! (liposuction)",
"It was my mother's mating name. (maiden name)",
"Holy shit, you got us a lemon-zine? (Limousine)",
"<NAME> bornt my baby. (<NAME> is the father of <NAME>'s 2nd child)",
"<NAME>, I will make you have a eternity test. (paternity)",
"He's gettin' all frustated. (frustrated)",
"You can go to college and get your little Pf.D, or whatever the fuck it's called! (Ph.D.)",
"Child reports (Child Support)",
"Get us the fuckin' land papers A.S.A.T! (Land papers because he couldn't pronounce 'topographic map', A.S.A.P)",
"I'm fucked over from being electromecuted! (electrocuted)",
"Those them cigarettes in there is our lifes! (are our lives)",
"...it's distraculating my case. (distracting)",
"Amernicans! (Americans)",
"I have responsibles now... (Responsibilities)",
"Well, now we gotta go to the library and get a book on horficulture. (Horticulture)",
"I self-learned myself. (self-taught)"
]
lahey = [
"When you plant shit-seeds, you get shit-weeds.",
"Birds of a shitfeather flock together, <NAME>.",
"We're in the eye of a shiticane here, <NAME>, and <NAME>'s a low-shit system!",
"Shit-storm troopers",
"The shit-apple doesn't fall far from the shit-tree",
"<NAME>",
"I'm watching you like a shithawk",
"We're sailing into a shit-typhoon <NAME>, we'd better haul in the jib before it gets covered in shit.",
"When you're getting pelted with shitballs, deputy, you gotta get a shit-bat.",
"The shit pool's gettin full, <NAME>, time to strain the shit before it overflows. I will not have a Pompeiian catastrophie happening in Sunnyvale.* How dare you involve my daughter in your hemisphere of shit?",
"Your shit-goose is cooked, <NAME>",
"Shit-apples never fall far from the shit-tree",
"He's about to enter the shit-tornado to Oz.",
"Do you know what a shit-rope is <NAME>? It's a rope covered in shit that criminals try to cling to. Y'see, the shit acts like grease, and the harder you tighten your grip, the more you slide down it.",
"A shit-leopard can't change its spots.",
"We need more shit puppets for our play, <NAME>, and we need angry shit puppets but they aren't mad at us. Shit puppets only get angry at other shit puppets",
"<NAME>: Cops and dope don't mix, do they Mr. <NAME>? Lahey: Like shit and strawberry shortcake <NAME>.",
"I live by the golden rule: if you don't cross my shitline I won't cross yours. But when Ray told everybody in the park that I was drinking again, he crossed the goddamn shitline.",
"<NAME>: Do you know what a shit barometer is, Bubbles? Measures the shit pressure in the air. You can feel it. Listen, Bubs. You hear that? The sounds of the whispering winds of shit? You can hear it.",
"Do you feel that, <NAME>, the way the shit clings to the air? Shit Blizzard.",
"Never Cry Shitwolf.",
"Did you see that <NAME>, Goddamn shitapple driving the shitmobile. Nobody else in this park gives a fuck, why should I?",
"<NAME> -You know what's at work here, it's shit tectonics, when two shit plates strike and come together under incredible pressure, do you know what happens, Bubbles?",
"Yes I used to drink, <NAME>, but I got the shitmonkey off my back for good.",
"You just opened Pandora's Shitbox, <NAME>",
"You know what you get when two shit-tectonic plates collide? Shitquakes, <NAME>. Shitquakes.",
"The ole shit liner is coming to port, and I'll be there to tie her up.",
"Y'see, <NAME> started off as a little shitspark from the ol' shitflint that eventually grew into a shitbonfire, and driven by the winds of his monumental ignorance, grew into a raging shitfirestorm. If I marry <NAME>, I'll have total control of Sunnyvale, and then I'll be able to unleash a shitnami tidal wave that will extinguish <NAME> and his shitflames forever. And with any luck, he'll drown in the undershit of that wave...shitwaves.",
"T<NAME> T<NAME>, Shit clock's tickin' Rick.",
"We got the key to shitty city, <NAME>, and Julian's the muscular mayor.",
"You boys have loaded up a hair-trigger, double barrelled shitmachinegun, and the barrel's pointing right at your own heads.",
"Shit flowers, <NAME>. From a distance they look like ordinary flowers, but when you get right down and stick your nose in them you realize they're shit flowers, and there's a whole fucking bouquet down there right in front of Ray's trailer.",
"Lahey: Shit moths, <NAME>. R<NAME>: Is that you or the liquor speaking, Mr La<NAME>?",
"H<NAME> <NAME> (Lahey adressing Julian)",
"Whenever I'm sober, the boys are careful, they're scared of me cause they know what I'll do. They're cautious, it's hard to catch them. But when I'm drinking, their shitguards are down and they fuck up, but the problem is when I'm drinking, I fuck up too, a lot, Barb. I gotta be drinking, but not drinking, ya see? The only way to do that, is to pretend, I am gonna pretend to be drunk, collect evidence and build a solid case against them. Sober as a judge I'm gonna show up today at the cheeseburger picnic, and I'm gonna pretend to be a drunken idiot. And why? Shitguards, Barb...shitguards.",
"This place is a dump. You have my permission to do whatever you want, any time any place, and you don't have to listen to Pilsbandy Doughboy (Randy) or Team Sexy (the police)"
]
bubbles = [
"I'd like to see that Red Blue Green cocksucker put one of those together fucking duct taping it.",
"<NAME>. Did you call <NAME> and <NAME> too? How about Mr. Slate?",
"I won't tell anyone you have splinters in your lips if you don't tell anyone I have a wooden cock.",
"<NAME>: Does that thing really launch, Bubbles? Bubbles: Does the Tin Man have a sheet-metal cock?",
"<NAME>, what's a shit hawk? Is it some kind of shitty bird that swoops down and puts poop on you?",
"<NAME>, what happened to your fucking eyes? You look like <NAME>?",
"(in reference to the Helix song Rock You) I'm not giving anyone a fucking R!",
"<NAME>, those laws are there to protect kids, not so goofballs like you can put them in the car with no door on it, and drive around the fuckin' neighbourhood stealin' barbecues!",
"Can I come out now? I think I have a leech on my bird.",
"<NAME>, we're both baked. That's why were probably not making any sense.",
"No, he's just a really big kitty, and he's baked!",
"Bubbles: Stealing gas? Why, Cory and Trevor, that's highly illegal, you shouldn't be stealing gas, Cory and Trevor.",
"(Rapping) I got a grey kitty, white one, and a tabby too/ And a big orange guy who put snakes in my shoes/ Mad MC skills, leave ya struck, and I roll with ma kitties, and I'am hard as fuck/ I am down with Plato and Socrates/ And I like to get busy with all the ladies. Grunt, grunt/ sumthin,' sumthin,' sumthin,'/ Grunt/ Up in ma shed, up in ma shed...",
"Holy fuck boys, this shed is like a fucking palace! Indoor plumbing (toilet seat inside), satellite tv, 400 channels, anything I wanna watch, it's right there, space for my kitties, Mobile phone, new technology (holds up an ancient mobile phone), this is the best fucking shed there ever was!",
"Here, Cory-Trevor, Cory-Trevor!",
"<NAME>: Can you read, my son? Bubbles: Well, that depends, can you go fuck yourself?",
"Trevor: <NAME>, this looks like a pirate gun. Bubbles: Well Trevor, I guess that makes you Long <NAME>, then.",
"Green Bastard, from parts unknown (grunts and inhales).",
"Lahey, can you please get the flyin' fuck out of our way!",
"COCK-SUCKER!",
"There's a note pinned to a tree! Diddly-dee!",
"(To Randy re: cheeseburgers) How many did you drive into that big fuckin cheeseburger-locker?",
"Well, when I was a little guy, I always wanted to go up into space, be a space-man. But you gotta be able to see really fuckin' good to do that job. Some guy would take one look at me and say 'Uhhh, sorry sir, you gotta be able to see a little better than you'... I don't give a fuck.",
"Holy sweet flying fuck!"
]
module.exports = (robot) ->
robot.hear /.*(hey bubbles).*/i, (msg) ->
msg.send msg.random bubbles
robot.hear /.*(hey ricky).*/i, (msg) ->
msg.send msg.random ricky
robot.hear /.*(hey j-roc).*/i, (msg) ->
msg.send msg.random jroc
robot.hear /.*(hey lahey).*/i, (msg) ->
msg.send msg.random lahey | true | # Description:
# Quotes by the Trailer Park Boys
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hey j-roc - Display a random J-ROC quote
# hey lahey - Display a random Lahey quote
# hey ricky - Display a random Ricky quote
# hey bubbles - Display a random Bubbles quote
#
# Notes:
# None
#
# Author:
# carmstrong
jroc = [
"There's 2 things mafukas gonna know about J-to-the-ROC: I spin more rhymes than a lazy Susan, and I'm innocent until mah guilt is proven! Peace! Representin' Sunnyvale, straight-the-fuck-up.",
"(To Lahey and Randy) Why don't you run along, PI:NAME:<NAME>END_PI and the Sundance Cheeseburger. Don't look into my eyes like I got candy for you.",
"Only wacksuckas like Cory and Trevor steal gas...and deal dope.",
"Yo PI:NAME:<NAME>END_PI, I'm going to be a daddy. Not once but two times dawg, two times.",
"You know what I'm sayin'?",
"Rayyyyy - Kojak's got a wig on, RAYYY!",
"So why don't you move it along, you Rico-Suave-lookin' mafucka, cuz you ain't beatin' nobody.",
"You mean we can't go on with the game cuz some mafucka can't go to Canadian Mafacka (Tire) and get a new orange mafucka (ball) for $2.99? That's wack, Jules.",
"Yo, it's Rocky and Bullma'fucker.",
"J-Roc an' da Rock-Pile ALL UP IN DIS' MA' !",
"Naw, man, I don't play guns, mafucka.",
"We ain't down with killin', we down with chillin'. Peace!",
"The day J-ROC loses his flow, is the day the hair on PI:NAME:<NAME>END_PI's bald head grow!",
"(referring to PI:NAME:<NAME>END_PI) That's the fuckin' law bitch from the grocery store y'man, who you pointin' at, skeleton?",
"This is BULL-ISH!",
"I can't even breathe up in this piece!",
"(to PI:NAME:<NAME>END_PI) Oh what, you ain't pregnant with a bucketa chicken?",
"(to RPI:NAME:<NAME>END_PI) What you talkin' 'bout, you inflatable Elvis?",
"Oh, no, you di'n't just call me PI:NAME:<NAME>END_PI!",
"(holding his chains to Randy's gut like a stethoscope) I hear chicken. I hear cola fizz, and mustard and relish coagulating together with french fries and onion rings, but you know what? I don't hear a heart.",
"PI:NAME:<NAME>END_PI!"
]
ricky = [
"PI:NAME:<NAME>END_PI is banging cops which is no big deal, I guess. I don't run PI:NAME:<NAME>END_PIy. She's for to be her own woman (free to be)",
"PI:NAME:<NAME>END_PI might have a problem, but what PI:NAME:<NAME>END_PIy doesn't know won't learn her. (hurt)",
"Get me two bags of chips: Dressed All Over, and Zesty Mordant. (All Dressed and Zesty. Mordant is French for Zesty and is a mix-up of reading both languages on the bilingual packaging in Canada)",
"Yeah, get me some ja-LAP-ano chips (jalapeño)",
"Worst case Ontario... (scenario)",
"It's basically Peach'n'Cake (a piece of cake)",
"Denial and Error... (trial)",
"Make my words (Mark)*",
"Hey Bubs, are you watching that documentary on Saskatchewans?(Sasquatches)*",
"(While addressing the Judge in court) Thank you, Your Majesty. (Honour, which is still incorrect. In Canada a female judge is referred to as My Lady.)",
"I'm trying to try here, PI:NAME:<NAME>END_PI.",
"Who's playing the pianio? (piano)",
"Make like a tree and fuck off. (leave)",
"I'm not the kind of person to say atodaso, but you know what? Atodaso, I-fucking-atodaso. (I told you so)",
"It was golfing flames, flames just golfing, golfing. (engulfed in flames)",
"It's a Catch-23 situation. (Catch-22)",
"(To PI:NAME:<NAME>END_PI of Rush) Well, play that Diane Sawyer song, then. (Tom PI:NAME:<NAME>END_PI - Rush song)",
"Looks like a tropical earthquake blew through here. (storm)",
"We can get 2 birds stoned at once. (kill 2 birds with one stone)",
"Why do you look like Indianapolis Jones? (Indiana)",
"He passed with flying fucking carpets. (colours)",
"It doesn't take rocket appliances. (science)",
"Trinity's at the age where it's gorilla see gorilla do. (monkey)",
"Do you got a search warranty for that? (warrant)*",
"I must be fire retarded or something. (retardant)",
"I'm not a pezmist, I'm an optometrist. (Pessimist, Optimist)",
"These plates got me from Tuscany, Arizona to Kentville, Nova Scotia. (Tucson) - Ray, RPI:NAME:<NAME>END_PI's Dad",
"I'll drive you back to the park, PI:NAME:<NAME>END_PI, but there is probably a pretty good chance that it might be over between us (Ricky uses a triple conditional; just one would be sufficient)",
"If my dad and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI hadn't had been out all night getting lap-dances and getting drunk, the whole thing could have been preventative. (prevented)",
"To be honest with you, I fucking hate bagminten. (badminton)",
"Breaker, Breaker, come in earth. This is Rocketship 27, some aliens fucked over the carbinator in engine number four, we are going to try to refuckulate it and land on Juniper. (carburetor, repair, Jupiter)",
"That's not a ladybug. It's a cannerpillar. (caterpillar)",
"...how to get Buhurbon stains out of Kahayki pants (Bourbon, Khaki)",
"One man's garbage is another man person's good ungarbage. (One man's garbage is another man's treasure)",
"Au gratin (gratis, free; au gratin is with cheese)",
"I-surance (Insurance)*",
"Swallow my prize (pride)",
"Neither here, there, or everywhere (Neither here nor there)",
"Boys, let's make toast (Let's make a toast)",
"There's no lurches in there, Bubbles, is there? (leeches)",
"I know what you're doing, Lahey, you're trying to fill my feet. (fill my shoes)",
"You gotta remember, every kid goes through phrases. (phases)",
"What Julian don't grow won't burn him. (know, hurt)",
"Nice decnals! (decals)",
"I'm just stretched out! (stressed)*",
"I don't need your cherry trees. (charity)*",
"What if he has radies? (rabies)",
"Supply and command. (demand)",
"What comes around is all around (What goes around comes around)",
"What, do you own space? No. Nay-saw does. (NASA)",
"Do unto others as you do unto you. (Do unto others as you would have them do unto you)",
"One day I will go somewhere that is hot, like Majaica or the Dromedary Republic (Jamaica, Dominican Republic)",
"Trinity made a life-ing thing basically out of this chicken. Started with a little eggy thing, and heated it up under these incu-baker things, and it...it was bornt. (living, incubator, born)",
"We'll split 50/50/50. (three ways.)",
"(To Trevor and Cory) Well, I'd like for you two to come with us, but apparently it's clear to see who makes the pants here. (wears the pants)",
"I hate to have to give you an ultimarium (ultimatum)",
"It's me or PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PIio (PI:NAME:<NAME>END_PI and TPI:NAME:<NAME>END_PI)",
"PI:NAME:<NAME>END_PIins! That's what they are, PI:NAME:<NAME>END_PI, fuckin' raykins! (raccoons)",
"I'm not working for J-Roc, that's against my vice principals (principles)",
"Bubbles, I don't want any rich peopleman's food, I want some fuckin' meat that's cooked. (people's)",
"It's survival of the fitness, boys. (fittest)",
"If PI:NAME:<NAME>END_PI thinks he's smartener than me, he's wrong. (smarter)*",
"You gotta do illegal things once in a while, and then maturinate into a better person. (mature)",
"Your thoughts might be better than mine, but I have thoughts going around in my head too, about...different thinkings...about brain things that you can use and...doing different things.",
"Sweet empowered chicken things (sweet and sour chicken)",
"(To PI:NAME:<NAME>END_PI) Take a shower for fuck's sake! You look like a fuckin' hobolo! (hobo)",
"(To PI:NAME:<NAME>END_PI) Why don't you fuck off and go get some hypo-suction! (liposuction)",
"It was my mother's mating name. (maiden name)",
"Holy shit, you got us a lemon-zine? (Limousine)",
"PI:NAME:<NAME>END_PI bornt my baby. (PI:NAME:<NAME>END_PI is the father of PI:NAME:<NAME>END_PI's 2nd child)",
"PI:NAME:<NAME>END_PI, I will make you have a eternity test. (paternity)",
"He's gettin' all frustated. (frustrated)",
"You can go to college and get your little Pf.D, or whatever the fuck it's called! (Ph.D.)",
"Child reports (Child Support)",
"Get us the fuckin' land papers A.S.A.T! (Land papers because he couldn't pronounce 'topographic map', A.S.A.P)",
"I'm fucked over from being electromecuted! (electrocuted)",
"Those them cigarettes in there is our lifes! (are our lives)",
"...it's distraculating my case. (distracting)",
"Amernicans! (Americans)",
"I have responsibles now... (Responsibilities)",
"Well, now we gotta go to the library and get a book on horficulture. (Horticulture)",
"I self-learned myself. (self-taught)"
]
lahey = [
"When you plant shit-seeds, you get shit-weeds.",
"Birds of a shitfeather flock together, PI:NAME:<NAME>END_PI.",
"We're in the eye of a shiticane here, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI's a low-shit system!",
"Shit-storm troopers",
"The shit-apple doesn't fall far from the shit-tree",
"PI:NAME:<NAME>END_PI",
"I'm watching you like a shithawk",
"We're sailing into a shit-typhoon PI:NAME:<NAME>END_PI, we'd better haul in the jib before it gets covered in shit.",
"When you're getting pelted with shitballs, deputy, you gotta get a shit-bat.",
"The shit pool's gettin full, PI:NAME:<NAME>END_PI, time to strain the shit before it overflows. I will not have a Pompeiian catastrophie happening in Sunnyvale.* How dare you involve my daughter in your hemisphere of shit?",
"Your shit-goose is cooked, PI:NAME:<NAME>END_PI",
"Shit-apples never fall far from the shit-tree",
"He's about to enter the shit-tornado to Oz.",
"Do you know what a shit-rope is PI:NAME:<NAME>END_PI? It's a rope covered in shit that criminals try to cling to. Y'see, the shit acts like grease, and the harder you tighten your grip, the more you slide down it.",
"A shit-leopard can't change its spots.",
"We need more shit puppets for our play, PI:NAME:<NAME>END_PI, and we need angry shit puppets but they aren't mad at us. Shit puppets only get angry at other shit puppets",
"PI:NAME:<NAME>END_PI: Cops and dope don't mix, do they Mr. PI:NAME:<NAME>END_PI? Lahey: Like shit and strawberry shortcake PI:NAME:<NAME>END_PI.",
"I live by the golden rule: if you don't cross my shitline I won't cross yours. But when Ray told everybody in the park that I was drinking again, he crossed the goddamn shitline.",
"PI:NAME:<NAME>END_PI: Do you know what a shit barometer is, Bubbles? Measures the shit pressure in the air. You can feel it. Listen, Bubs. You hear that? The sounds of the whispering winds of shit? You can hear it.",
"Do you feel that, PI:NAME:<NAME>END_PI, the way the shit clings to the air? Shit Blizzard.",
"Never Cry Shitwolf.",
"Did you see that PI:NAME:<NAME>END_PI, Goddamn shitapple driving the shitmobile. Nobody else in this park gives a fuck, why should I?",
"PI:NAME:<NAME>END_PI -You know what's at work here, it's shit tectonics, when two shit plates strike and come together under incredible pressure, do you know what happens, Bubbles?",
"Yes I used to drink, PI:NAME:<NAME>END_PI, but I got the shitmonkey off my back for good.",
"You just opened Pandora's Shitbox, PI:NAME:<NAME>END_PI",
"You know what you get when two shit-tectonic plates collide? Shitquakes, PI:NAME:<NAME>END_PI. Shitquakes.",
"The ole shit liner is coming to port, and I'll be there to tie her up.",
"Y'see, PI:NAME:<NAME>END_PI started off as a little shitspark from the ol' shitflint that eventually grew into a shitbonfire, and driven by the winds of his monumental ignorance, grew into a raging shitfirestorm. If I marry PI:NAME:<NAME>END_PI, I'll have total control of Sunnyvale, and then I'll be able to unleash a shitnami tidal wave that will extinguish PI:NAME:<NAME>END_PI and his shitflames forever. And with any luck, he'll drown in the undershit of that wave...shitwaves.",
"TPI:NAME:<NAME>END_PI TPI:NAME:<NAME>END_PI, Shit clock's tickin' Rick.",
"We got the key to shitty city, PI:NAME:<NAME>END_PI, and Julian's the muscular mayor.",
"You boys have loaded up a hair-trigger, double barrelled shitmachinegun, and the barrel's pointing right at your own heads.",
"Shit flowers, PI:NAME:<NAME>END_PI. From a distance they look like ordinary flowers, but when you get right down and stick your nose in them you realize they're shit flowers, and there's a whole fucking bouquet down there right in front of Ray's trailer.",
"Lahey: Shit moths, PI:NAME:<NAME>END_PI. RPI:NAME:<NAME>END_PI: Is that you or the liquor speaking, Mr LaPI:NAME:<NAME>END_PI?",
"HPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI (Lahey adressing Julian)",
"Whenever I'm sober, the boys are careful, they're scared of me cause they know what I'll do. They're cautious, it's hard to catch them. But when I'm drinking, their shitguards are down and they fuck up, but the problem is when I'm drinking, I fuck up too, a lot, Barb. I gotta be drinking, but not drinking, ya see? The only way to do that, is to pretend, I am gonna pretend to be drunk, collect evidence and build a solid case against them. Sober as a judge I'm gonna show up today at the cheeseburger picnic, and I'm gonna pretend to be a drunken idiot. And why? Shitguards, Barb...shitguards.",
"This place is a dump. You have my permission to do whatever you want, any time any place, and you don't have to listen to Pilsbandy Doughboy (Randy) or Team Sexy (the police)"
]
bubbles = [
"I'd like to see that Red Blue Green cocksucker put one of those together fucking duct taping it.",
"PI:NAME:<NAME>END_PI. Did you call PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI too? How about Mr. Slate?",
"I won't tell anyone you have splinters in your lips if you don't tell anyone I have a wooden cock.",
"PI:NAME:<NAME>END_PI: Does that thing really launch, Bubbles? Bubbles: Does the Tin Man have a sheet-metal cock?",
"PI:NAME:<NAME>END_PI, what's a shit hawk? Is it some kind of shitty bird that swoops down and puts poop on you?",
"PI:NAME:<NAME>END_PI, what happened to your fucking eyes? You look like PI:NAME:<NAME>END_PI?",
"(in reference to the Helix song Rock You) I'm not giving anyone a fucking R!",
"PI:NAME:<NAME>END_PI, those laws are there to protect kids, not so goofballs like you can put them in the car with no door on it, and drive around the fuckin' neighbourhood stealin' barbecues!",
"Can I come out now? I think I have a leech on my bird.",
"PI:NAME:<NAME>END_PI, we're both baked. That's why were probably not making any sense.",
"No, he's just a really big kitty, and he's baked!",
"Bubbles: Stealing gas? Why, Cory and Trevor, that's highly illegal, you shouldn't be stealing gas, Cory and Trevor.",
"(Rapping) I got a grey kitty, white one, and a tabby too/ And a big orange guy who put snakes in my shoes/ Mad MC skills, leave ya struck, and I roll with ma kitties, and I'am hard as fuck/ I am down with Plato and Socrates/ And I like to get busy with all the ladies. Grunt, grunt/ sumthin,' sumthin,' sumthin,'/ Grunt/ Up in ma shed, up in ma shed...",
"Holy fuck boys, this shed is like a fucking palace! Indoor plumbing (toilet seat inside), satellite tv, 400 channels, anything I wanna watch, it's right there, space for my kitties, Mobile phone, new technology (holds up an ancient mobile phone), this is the best fucking shed there ever was!",
"Here, Cory-Trevor, Cory-Trevor!",
"PI:NAME:<NAME>END_PI: Can you read, my son? Bubbles: Well, that depends, can you go fuck yourself?",
"Trevor: PI:NAME:<NAME>END_PI, this looks like a pirate gun. Bubbles: Well Trevor, I guess that makes you Long PI:NAME:<NAME>END_PI, then.",
"Green Bastard, from parts unknown (grunts and inhales).",
"Lahey, can you please get the flyin' fuck out of our way!",
"COCK-SUCKER!",
"There's a note pinned to a tree! Diddly-dee!",
"(To Randy re: cheeseburgers) How many did you drive into that big fuckin cheeseburger-locker?",
"Well, when I was a little guy, I always wanted to go up into space, be a space-man. But you gotta be able to see really fuckin' good to do that job. Some guy would take one look at me and say 'Uhhh, sorry sir, you gotta be able to see a little better than you'... I don't give a fuck.",
"Holy sweet flying fuck!"
]
module.exports = (robot) ->
robot.hear /.*(hey bubbles).*/i, (msg) ->
msg.send msg.random bubbles
robot.hear /.*(hey ricky).*/i, (msg) ->
msg.send msg.random ricky
robot.hear /.*(hey j-roc).*/i, (msg) ->
msg.send msg.random jroc
robot.hear /.*(hey lahey).*/i, (msg) ->
msg.send msg.random lahey |
[
{
"context": "e'\n\n orgA = yield Organization.create\n name: 'St. Patrick Center'\n description: 'We do good things.'\n commun",
"end": 497,
"score": 0.9094821214675903,
"start": 479,
"tag": "NAME",
"value": "St. Patrick Center"
},
{
"context": "al'\n orgB = yield Organiz... | fixtures.coffee | evanhuang8/teresa | 0 | #!/usr/bin/env coffee
_ = require 'lodash'
co = require 'co'
faker = require 'faker'
co ->
db = require './src/db'
yield db.client.sync
force: true
Community = db.model 'Community'
Organization = db.model 'Organization'
User = db.model 'User'
Client = db.model 'Client'
Service = db.model 'Service'
community = yield Community.create
name: 'St. Louis CoC'
description: 'St. Louis Continuum of Care'
orgA = yield Organization.create
name: 'St. Patrick Center'
description: 'We do good things.'
communityId: community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Central'
orgB = yield Organization.create
name: 'Mercy Ministries'
description: 'We do good things.'
communityId: community.id
address: '655 Maryville Centre Dr, St. Louis, MO 63141'
lat: 38.644379
lng: -90.495485
tz: 'US/Central'
orgC = yield Organization.create
name: 'Evanston'
description: 'Ahhhhhhhhhh'
communityId: community.id
address: '4476 Barat Hall Dr, St. Louis, MO 63108'
lat: 38.6440
lng: -90.2574
tz: 'US/Central'
userA = yield User.create
email: 'user1@example.com'
password: 'password1'
organizationId: orgA.id
userB = yield User.create
email: 'user2@example.com'
password: 'password2'
organizationId: orgB.id
userC = yield User.create
email: 'user3@example.com'
password: 'password3'
organizationId: orgC.id
hours = []
for i in [0...7]
hours.push
always: true
shelterA = yield Service.create
name: 'St. Patrick Shelters'
type: 'housing'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: orgA.id
shelterB = yield Service.create
name: 'Mercy Shelters'
type: 'job'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: orgB.id
shelterC = yield Service.create
name: 'My Crib'
type: 'shelter'
description: 'Great'
businessHours: hours
maxCapacity: 100
openCapacity: 10
organizationId: orgC.id
clients = []
initials = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'Z']
stages = ['unknown', 'emergent', 'homeless', 'rehab']
for i in [0..101]
clients.push
firstName: faker.name.firstName()
middleName: initials[i % initials.length]
lastName: faker.name.lastName()
phone: faker.phone.phoneNumberFormat()
stage: _.sample stages
yield Client.bulkCreate clients
process.exit()
.catch (err) ->
console.log err.stack
return | 111253 | #!/usr/bin/env coffee
_ = require 'lodash'
co = require 'co'
faker = require 'faker'
co ->
db = require './src/db'
yield db.client.sync
force: true
Community = db.model 'Community'
Organization = db.model 'Organization'
User = db.model 'User'
Client = db.model 'Client'
Service = db.model 'Service'
community = yield Community.create
name: 'St. Louis CoC'
description: 'St. Louis Continuum of Care'
orgA = yield Organization.create
name: '<NAME>'
description: 'We do good things.'
communityId: community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Central'
orgB = yield Organization.create
name: '<NAME>'
description: 'We do good things.'
communityId: community.id
address: '655 Maryville Centre Dr, St. Louis, MO 63141'
lat: 38.644379
lng: -90.495485
tz: 'US/Central'
orgC = yield Organization.create
name: '<NAME>'
description: 'Ahhhhhhhhhh'
communityId: community.id
address: '4476 Barat Hall Dr, St. Louis, MO 63108'
lat: 38.6440
lng: -90.2574
tz: 'US/Central'
userA = yield User.create
email: '<EMAIL>'
password: '<PASSWORD>'
organizationId: orgA.id
userB = yield User.create
email: '<EMAIL>'
password: '<PASSWORD>'
organizationId: orgB.id
userC = yield User.create
email: '<EMAIL>'
password: '<PASSWORD>'
organizationId: orgC.id
hours = []
for i in [0...7]
hours.push
always: true
shelterA = yield Service.create
name: '<NAME>. <NAME>'
type: 'housing'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: orgA.id
shelterB = yield Service.create
name: '<NAME>'
type: 'job'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: orgB.id
shelterC = yield Service.create
name: '<NAME>'
type: 'shelter'
description: 'Great'
businessHours: hours
maxCapacity: 100
openCapacity: 10
organizationId: orgC.id
clients = []
initials = ['<NAME>', '<NAME>', 'C', 'D', 'E', 'F', 'G', 'I', 'Z']
stages = ['unknown', 'emergent', 'homeless', 'rehab']
for i in [0..101]
clients.push
firstName: faker.name.firstName()
middleName: initials[i % initials.length]
lastName: faker.name.lastName()
phone: faker.phone.phoneNumberFormat()
stage: _.sample stages
yield Client.bulkCreate clients
process.exit()
.catch (err) ->
console.log err.stack
return | true | #!/usr/bin/env coffee
_ = require 'lodash'
co = require 'co'
faker = require 'faker'
co ->
db = require './src/db'
yield db.client.sync
force: true
Community = db.model 'Community'
Organization = db.model 'Organization'
User = db.model 'User'
Client = db.model 'Client'
Service = db.model 'Service'
community = yield Community.create
name: 'St. Louis CoC'
description: 'St. Louis Continuum of Care'
orgA = yield Organization.create
name: 'PI:NAME:<NAME>END_PI'
description: 'We do good things.'
communityId: community.id
address: '80 N Tucker Blvd, St. Louis, MO 63101'
lat: 38.633397
lng: -90.19559
tz: 'US/Central'
orgB = yield Organization.create
name: 'PI:NAME:<NAME>END_PI'
description: 'We do good things.'
communityId: community.id
address: '655 Maryville Centre Dr, St. Louis, MO 63141'
lat: 38.644379
lng: -90.495485
tz: 'US/Central'
orgC = yield Organization.create
name: 'PI:NAME:<NAME>END_PI'
description: 'Ahhhhhhhhhh'
communityId: community.id
address: '4476 Barat Hall Dr, St. Louis, MO 63108'
lat: 38.6440
lng: -90.2574
tz: 'US/Central'
userA = yield User.create
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
organizationId: orgA.id
userB = yield User.create
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
organizationId: orgB.id
userC = yield User.create
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
organizationId: orgC.id
hours = []
for i in [0...7]
hours.push
always: true
shelterA = yield Service.create
name: 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI'
type: 'housing'
description: 'Dope crib'
businessHours: hours
maxCapacity: 200
openCapacity: 150
organizationId: orgA.id
shelterB = yield Service.create
name: 'PI:NAME:<NAME>END_PI'
type: 'job'
description: 'Not so much good'
businessHours: hours
maxCapacity: 100
openCapacity: 50
organizationId: orgB.id
shelterC = yield Service.create
name: 'PI:NAME:<NAME>END_PI'
type: 'shelter'
description: 'Great'
businessHours: hours
maxCapacity: 100
openCapacity: 10
organizationId: orgC.id
clients = []
initials = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'C', 'D', 'E', 'F', 'G', 'I', 'Z']
stages = ['unknown', 'emergent', 'homeless', 'rehab']
for i in [0..101]
clients.push
firstName: faker.name.firstName()
middleName: initials[i % initials.length]
lastName: faker.name.lastName()
phone: faker.phone.phoneNumberFormat()
stage: _.sample stages
yield Client.bulkCreate clients
process.exit()
.catch (err) ->
console.log err.stack
return |
[
{
"context": "ary_uuid'\n process.env.OCTOBLU_CANARY_TOKEN = 'canary_token'\n process.env.OCTOBLU_API_HOST = 'http://l",
"end": 510,
"score": 0.8491436243057251,
"start": 498,
"tag": "PASSWORD",
"value": "canary_token"
}
] | test/canary-spec.coffee | octoblu/octoblu-flow-canary | 0 | _ = require 'lodash'
shmock = require 'shmock'
MessageController = require '../src/message-controller'
API_HOST_PORT = 0xdead
TRIGGER_HOST_PORT = 0xbeef
SLACK_HOST_PORT = 0xf00d
describe 'Canary', ->
@timeout 30000
before ->
@DateMock =
now: => @time or 0
setTime: (@time) =>
inc: (delta) => @time += delta
@startTime = Date.now()
@DateMock.setTime @startTime
process.env.OCTOBLU_CANARY_UUID = 'canary_uuid'
process.env.OCTOBLU_CANARY_TOKEN = 'canary_token'
process.env.OCTOBLU_API_HOST = 'http://localhost:' + API_HOST_PORT
process.env.OCTOBLU_TRIGGER_HOST = 'http://localhost:' + TRIGGER_HOST_PORT
process.env.SLACK_CHANNEL_URL = 'http://localhost:' + SLACK_HOST_PORT + '/slackTest'
@CANARY_RESTART_FLOWS_MAX_TIME = process.env.CANARY_RESTART_FLOWS_MAX_TIME = 1000*60
@CANARY_UPDATE_INTERVAL = process.env.CANARY_UPDATE_INTERVAL = 1000*120
@CANARY_HEALTH_CHECK_MAX_DIFF = process.env.CANARY_HEALTH_CHECK_MAX_DIFF = 100
@CANARY_DATA_HISTORY_SIZE = process.env.CANARY_DATA_HISTORY_SIZE = 3
@apiHost = shmock API_HOST_PORT
@triggerHost = shmock TRIGGER_HOST_PORT
@slackHost = shmock SLACK_HOST_PORT
@flows = [
flowId: "flow-a"
name: "trigger flow a"
activated: true
nodes: [
id: "trigger-flow-a"
type: "operation:trigger"
]
,
flowId: "flow-b"
name: "trigger flow b"
nodes: [
id: "trigger-flow-b"
type: "operation:trigger"
]
,
flowId: "flow-c"
name: "something something"
]
@sut = new MessageController Date: @DateMock
@resetFlowTime = (name, time) =>
(@sut.canary.stats.getFlows())[name] = {messageTime:[time]}
after (done) ->
@apiHost.close =>
@triggerHost.close =>
@slackHost.close done
describe '-> canary', ->
it 'should have a message endpoint', ->
expect(@sut.postMessage).to.exist
it 'should have a stats endpoint', ->
expect(@sut.getStats).to.exist
it 'should have a passing endpoint', ->
expect(@sut.getPassing).to.exist
it 'should have a postTriggers function', ->
expect(@sut.canary.postTriggers).to.exist
it 'should have a function for getting current stats', ->
expect(@sut.canary.getStats).to.exist
it 'should have an initial failing state', ->
expect(@sut.canary.getPassing().passing).to.equal false
describe 'when startAllFlows is called', ->
before (done) ->
@getFlows = @apiHost.get('/api/flows').reply(200, @flows)
@startFlowA = @apiHost.post('/api/flows/flow-a/instance').reply(201)
@startFlowB = @apiHost.post('/api/flows/flow-b/instance').reply(201)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(201)
@sut.canary.startAllFlows =>
@DateMock.inc @CANARY_UPDATE_INTERVAL
done()
it 'should have fetched our flows and started them', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowA.isDone).to.be.true
expect(@startFlowB.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
it 'should be in a passing state', ->
expect(@sut.canary.getPassing().passing).to.equal true
describe 'when one of the flows hasn\'t been messaged in awhile', ->
before ->
@resetFlowTime 'flow-a', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
it 'should be in a failing state', ->
expect(@sut.canary.getPassing().passing).to.equal false
describe.only 'and we message them a bunch', ->
before ->
messageCanary = =>
@DateMock.inc @CANARY_UPDATE_INTERVAL
@sut.postMessage {body:fromUuid:'flow-a'}, {end:=>}
@sut.postMessage {body:fromUuid:'flow-b'}, {end:=>}
@sut.postMessage {body:fromUuid:'flow-c'}, {end:=>}
_.times @CANARY_DATA_HISTORY_SIZE+1, messageCanary
it 'should be in a passing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal true
describe 'when postTriggers is called', ->
before (done) ->
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(201)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(201)
@sut.canary.postTriggers done
it 'should have posted to both triggers', ->
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
describe 'when one of the other flows hasn\'t been messaged in awhile', ->
before ->
@resetFlowTime 'flow-c', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
it 'should be in a failing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal false
xdescribe 'when processUpdateInterval is called', ->
before (done) ->
@getFlows = @apiHost.get('/api/flows').reply(200, @flows)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(201)
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(201)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(201)
@slackPost = @slackHost.post('/slackTest').reply(200)
@sut.canary.processUpdateInterval done
it 'should have fetched the flows, restarted the failed flow, and posted to triggers', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
expect(@slackPost.isDone).to.be.true
it 'should have no errors in stats', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(_.isEmpty(@sut.canary.getStats().errors)).to.be.true
xdescribe 'when processUpdateInterval and everything errors', ->
before (done) ->
@resetFlowTime 'flow-c', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
@getFlows = @apiHost.get('/api/flows').reply(401, @flows)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(401)
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(401)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(401)
@slackPost = @slackHost.post('/slackTest').reply(200)
@sut.canary.processUpdateInterval done
it 'should have tried to fetch the flows, restart the failed flow, and post to triggers', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
expect(@slackPost.isDone).to.be.true
it 'should have errors in stats', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getStats().errors?.length).to.equal 4
describe 'when one of the flows is messaged too often', ->
before ->
@resetFlowTime 'flow-a', @DateMock.now()
@resetFlowTime 'flow-b', @DateMock.now()
@resetFlowTime 'flow-c', @DateMock.now()
delete @sut.canary.stats.errors
it 'should initialy be in a passing state', ->
expect(@sut.canary.getPassing().passing).to.equal true
describe 'and we message a flow once', ->
before ->
@DateMock.inc @CANARY_UPDATE_INTERVAL - (@CANARY_HEALTH_CHECK_MAX_DIFF*1.1)
@sut.postMessage {body:fromUuid:'flow-a'}, {end:=>}
it 'should be in a failing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal false
| 110012 | _ = require 'lodash'
shmock = require 'shmock'
MessageController = require '../src/message-controller'
API_HOST_PORT = 0xdead
TRIGGER_HOST_PORT = 0xbeef
SLACK_HOST_PORT = 0xf00d
describe 'Canary', ->
@timeout 30000
before ->
@DateMock =
now: => @time or 0
setTime: (@time) =>
inc: (delta) => @time += delta
@startTime = Date.now()
@DateMock.setTime @startTime
process.env.OCTOBLU_CANARY_UUID = 'canary_uuid'
process.env.OCTOBLU_CANARY_TOKEN = '<PASSWORD>'
process.env.OCTOBLU_API_HOST = 'http://localhost:' + API_HOST_PORT
process.env.OCTOBLU_TRIGGER_HOST = 'http://localhost:' + TRIGGER_HOST_PORT
process.env.SLACK_CHANNEL_URL = 'http://localhost:' + SLACK_HOST_PORT + '/slackTest'
@CANARY_RESTART_FLOWS_MAX_TIME = process.env.CANARY_RESTART_FLOWS_MAX_TIME = 1000*60
@CANARY_UPDATE_INTERVAL = process.env.CANARY_UPDATE_INTERVAL = 1000*120
@CANARY_HEALTH_CHECK_MAX_DIFF = process.env.CANARY_HEALTH_CHECK_MAX_DIFF = 100
@CANARY_DATA_HISTORY_SIZE = process.env.CANARY_DATA_HISTORY_SIZE = 3
@apiHost = shmock API_HOST_PORT
@triggerHost = shmock TRIGGER_HOST_PORT
@slackHost = shmock SLACK_HOST_PORT
@flows = [
flowId: "flow-a"
name: "trigger flow a"
activated: true
nodes: [
id: "trigger-flow-a"
type: "operation:trigger"
]
,
flowId: "flow-b"
name: "trigger flow b"
nodes: [
id: "trigger-flow-b"
type: "operation:trigger"
]
,
flowId: "flow-c"
name: "something something"
]
@sut = new MessageController Date: @DateMock
@resetFlowTime = (name, time) =>
(@sut.canary.stats.getFlows())[name] = {messageTime:[time]}
after (done) ->
@apiHost.close =>
@triggerHost.close =>
@slackHost.close done
describe '-> canary', ->
it 'should have a message endpoint', ->
expect(@sut.postMessage).to.exist
it 'should have a stats endpoint', ->
expect(@sut.getStats).to.exist
it 'should have a passing endpoint', ->
expect(@sut.getPassing).to.exist
it 'should have a postTriggers function', ->
expect(@sut.canary.postTriggers).to.exist
it 'should have a function for getting current stats', ->
expect(@sut.canary.getStats).to.exist
it 'should have an initial failing state', ->
expect(@sut.canary.getPassing().passing).to.equal false
describe 'when startAllFlows is called', ->
before (done) ->
@getFlows = @apiHost.get('/api/flows').reply(200, @flows)
@startFlowA = @apiHost.post('/api/flows/flow-a/instance').reply(201)
@startFlowB = @apiHost.post('/api/flows/flow-b/instance').reply(201)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(201)
@sut.canary.startAllFlows =>
@DateMock.inc @CANARY_UPDATE_INTERVAL
done()
it 'should have fetched our flows and started them', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowA.isDone).to.be.true
expect(@startFlowB.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
it 'should be in a passing state', ->
expect(@sut.canary.getPassing().passing).to.equal true
describe 'when one of the flows hasn\'t been messaged in awhile', ->
before ->
@resetFlowTime 'flow-a', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
it 'should be in a failing state', ->
expect(@sut.canary.getPassing().passing).to.equal false
describe.only 'and we message them a bunch', ->
before ->
messageCanary = =>
@DateMock.inc @CANARY_UPDATE_INTERVAL
@sut.postMessage {body:fromUuid:'flow-a'}, {end:=>}
@sut.postMessage {body:fromUuid:'flow-b'}, {end:=>}
@sut.postMessage {body:fromUuid:'flow-c'}, {end:=>}
_.times @CANARY_DATA_HISTORY_SIZE+1, messageCanary
it 'should be in a passing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal true
describe 'when postTriggers is called', ->
before (done) ->
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(201)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(201)
@sut.canary.postTriggers done
it 'should have posted to both triggers', ->
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
describe 'when one of the other flows hasn\'t been messaged in awhile', ->
before ->
@resetFlowTime 'flow-c', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
it 'should be in a failing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal false
xdescribe 'when processUpdateInterval is called', ->
before (done) ->
@getFlows = @apiHost.get('/api/flows').reply(200, @flows)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(201)
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(201)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(201)
@slackPost = @slackHost.post('/slackTest').reply(200)
@sut.canary.processUpdateInterval done
it 'should have fetched the flows, restarted the failed flow, and posted to triggers', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
expect(@slackPost.isDone).to.be.true
it 'should have no errors in stats', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(_.isEmpty(@sut.canary.getStats().errors)).to.be.true
xdescribe 'when processUpdateInterval and everything errors', ->
before (done) ->
@resetFlowTime 'flow-c', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
@getFlows = @apiHost.get('/api/flows').reply(401, @flows)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(401)
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(401)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(401)
@slackPost = @slackHost.post('/slackTest').reply(200)
@sut.canary.processUpdateInterval done
it 'should have tried to fetch the flows, restart the failed flow, and post to triggers', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
expect(@slackPost.isDone).to.be.true
it 'should have errors in stats', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getStats().errors?.length).to.equal 4
describe 'when one of the flows is messaged too often', ->
before ->
@resetFlowTime 'flow-a', @DateMock.now()
@resetFlowTime 'flow-b', @DateMock.now()
@resetFlowTime 'flow-c', @DateMock.now()
delete @sut.canary.stats.errors
it 'should initialy be in a passing state', ->
expect(@sut.canary.getPassing().passing).to.equal true
describe 'and we message a flow once', ->
before ->
@DateMock.inc @CANARY_UPDATE_INTERVAL - (@CANARY_HEALTH_CHECK_MAX_DIFF*1.1)
@sut.postMessage {body:fromUuid:'flow-a'}, {end:=>}
it 'should be in a failing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal false
| true | _ = require 'lodash'
shmock = require 'shmock'
MessageController = require '../src/message-controller'
API_HOST_PORT = 0xdead
TRIGGER_HOST_PORT = 0xbeef
SLACK_HOST_PORT = 0xf00d
describe 'Canary', ->
@timeout 30000
before ->
@DateMock =
now: => @time or 0
setTime: (@time) =>
inc: (delta) => @time += delta
@startTime = Date.now()
@DateMock.setTime @startTime
process.env.OCTOBLU_CANARY_UUID = 'canary_uuid'
process.env.OCTOBLU_CANARY_TOKEN = 'PI:PASSWORD:<PASSWORD>END_PI'
process.env.OCTOBLU_API_HOST = 'http://localhost:' + API_HOST_PORT
process.env.OCTOBLU_TRIGGER_HOST = 'http://localhost:' + TRIGGER_HOST_PORT
process.env.SLACK_CHANNEL_URL = 'http://localhost:' + SLACK_HOST_PORT + '/slackTest'
@CANARY_RESTART_FLOWS_MAX_TIME = process.env.CANARY_RESTART_FLOWS_MAX_TIME = 1000*60
@CANARY_UPDATE_INTERVAL = process.env.CANARY_UPDATE_INTERVAL = 1000*120
@CANARY_HEALTH_CHECK_MAX_DIFF = process.env.CANARY_HEALTH_CHECK_MAX_DIFF = 100
@CANARY_DATA_HISTORY_SIZE = process.env.CANARY_DATA_HISTORY_SIZE = 3
@apiHost = shmock API_HOST_PORT
@triggerHost = shmock TRIGGER_HOST_PORT
@slackHost = shmock SLACK_HOST_PORT
@flows = [
flowId: "flow-a"
name: "trigger flow a"
activated: true
nodes: [
id: "trigger-flow-a"
type: "operation:trigger"
]
,
flowId: "flow-b"
name: "trigger flow b"
nodes: [
id: "trigger-flow-b"
type: "operation:trigger"
]
,
flowId: "flow-c"
name: "something something"
]
@sut = new MessageController Date: @DateMock
@resetFlowTime = (name, time) =>
(@sut.canary.stats.getFlows())[name] = {messageTime:[time]}
after (done) ->
@apiHost.close =>
@triggerHost.close =>
@slackHost.close done
describe '-> canary', ->
it 'should have a message endpoint', ->
expect(@sut.postMessage).to.exist
it 'should have a stats endpoint', ->
expect(@sut.getStats).to.exist
it 'should have a passing endpoint', ->
expect(@sut.getPassing).to.exist
it 'should have a postTriggers function', ->
expect(@sut.canary.postTriggers).to.exist
it 'should have a function for getting current stats', ->
expect(@sut.canary.getStats).to.exist
it 'should have an initial failing state', ->
expect(@sut.canary.getPassing().passing).to.equal false
describe 'when startAllFlows is called', ->
before (done) ->
@getFlows = @apiHost.get('/api/flows').reply(200, @flows)
@startFlowA = @apiHost.post('/api/flows/flow-a/instance').reply(201)
@startFlowB = @apiHost.post('/api/flows/flow-b/instance').reply(201)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(201)
@sut.canary.startAllFlows =>
@DateMock.inc @CANARY_UPDATE_INTERVAL
done()
it 'should have fetched our flows and started them', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowA.isDone).to.be.true
expect(@startFlowB.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
it 'should be in a passing state', ->
expect(@sut.canary.getPassing().passing).to.equal true
describe 'when one of the flows hasn\'t been messaged in awhile', ->
before ->
@resetFlowTime 'flow-a', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
it 'should be in a failing state', ->
expect(@sut.canary.getPassing().passing).to.equal false
describe.only 'and we message them a bunch', ->
before ->
messageCanary = =>
@DateMock.inc @CANARY_UPDATE_INTERVAL
@sut.postMessage {body:fromUuid:'flow-a'}, {end:=>}
@sut.postMessage {body:fromUuid:'flow-b'}, {end:=>}
@sut.postMessage {body:fromUuid:'flow-c'}, {end:=>}
_.times @CANARY_DATA_HISTORY_SIZE+1, messageCanary
it 'should be in a passing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal true
describe 'when postTriggers is called', ->
before (done) ->
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(201)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(201)
@sut.canary.postTriggers done
it 'should have posted to both triggers', ->
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
describe 'when one of the other flows hasn\'t been messaged in awhile', ->
before ->
@resetFlowTime 'flow-c', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
it 'should be in a failing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal false
xdescribe 'when processUpdateInterval is called', ->
before (done) ->
@getFlows = @apiHost.get('/api/flows').reply(200, @flows)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(201)
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(201)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(201)
@slackPost = @slackHost.post('/slackTest').reply(200)
@sut.canary.processUpdateInterval done
it 'should have fetched the flows, restarted the failed flow, and posted to triggers', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
expect(@slackPost.isDone).to.be.true
it 'should have no errors in stats', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(_.isEmpty(@sut.canary.getStats().errors)).to.be.true
xdescribe 'when processUpdateInterval and everything errors', ->
before (done) ->
@resetFlowTime 'flow-c', @DateMock.now() - @CANARY_UPDATE_INTERVAL*2
@getFlows = @apiHost.get('/api/flows').reply(401, @flows)
@startFlowC = @apiHost.post('/api/flows/flow-c/instance').reply(401)
@triggerAPost = @triggerHost.post('/flows/flow-a/triggers/trigger-flow-a').reply(401)
@triggerBPost = @triggerHost.post('/flows/flow-b/triggers/trigger-flow-b').reply(401)
@slackPost = @slackHost.post('/slackTest').reply(200)
@sut.canary.processUpdateInterval done
it 'should have tried to fetch the flows, restart the failed flow, and post to triggers', ->
expect(@getFlows.isDone).to.be.true
expect(@startFlowC.isDone).to.be.true
expect(@triggerAPost.isDone).to.be.true
expect(@triggerBPost.isDone).to.be.true
expect(@slackPost.isDone).to.be.true
it 'should have errors in stats', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getStats().errors?.length).to.equal 4
describe 'when one of the flows is messaged too often', ->
before ->
@resetFlowTime 'flow-a', @DateMock.now()
@resetFlowTime 'flow-b', @DateMock.now()
@resetFlowTime 'flow-c', @DateMock.now()
delete @sut.canary.stats.errors
it 'should initialy be in a passing state', ->
expect(@sut.canary.getPassing().passing).to.equal true
describe 'and we message a flow once', ->
before ->
@DateMock.inc @CANARY_UPDATE_INTERVAL - (@CANARY_HEALTH_CHECK_MAX_DIFF*1.1)
@sut.postMessage {body:fromUuid:'flow-a'}, {end:=>}
it 'should be in a failing state', ->
# console.log JSON.stringify @sut.canary.getCurrentStats(), null, 2
expect(@sut.canary.getPassing().passing).to.equal false
|
[
{
"context": ">\n\n it 'should have id in had', ->\n id = 'test-id'\n had = Had id:id\n assert.equal had.id,",
"end": 172,
"score": 0.8234405517578125,
"start": 165,
"tag": "USERNAME",
"value": "test-id"
},
{
"context": "e:'null'\n type:'arg'\n ... | test/test-had.coffee | elidoran/had | 1 | assert = require 'assert'
Had = require '../lib'
describe 'test had\'s functions', ->
describe 'test had id', ->
it 'should have id in had', ->
id = 'test-id'
had = Had id:id
assert.equal had.id, id, 'had should have its id'
describe 'test isSuccess', ->
describe 'isSuccess of null', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess null
assert.equal result, false
describe 'isSuccess of undefined', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess undefined
assert.equal result, false
describe 'isSuccess of empty object', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess {}
assert.equal result, true
describe 'isSuccess of non-empty object', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess some:'thing'
assert.equal result, true
describe 'isSuccess of object with had prop', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess had:'test'
assert.equal result, true
describe 'isSuccess of empty array', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess []
assert.equal result, true
describe 'isSuccess of non-empty array', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess ['one']
assert.equal result, true
describe 'isSuccess of true', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess true
assert.equal result, true
describe 'isSuccess of false', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess false
assert.equal result, false
describe 'isSuccess of a had success result, single', ->
it 'should return true', ->
had = Had id:'isSuccess'
successResult = had:'sample name', some:'test'
result = had.isSuccess successResult
assert.equal result, true
describe 'isSuccess of a had success result, multiple', ->
it 'should return true', ->
successResult =
had:'sample name'
some:'test'
previous: [ { had:'sample name', some:'test2' } ]
had = Had id:'isSuccess'
result = had.isSuccess successResult
assert.equal result, true
describe 'isSuccess of a had success+error result', ->
it 'should return false', ->
comboResult =
had:'sample name'
error: had:'sample name', message:'test', type:'test', some:'testy'
previous: [ had:'sample name', success:true, some:'test' ]
had = Had id:'isSuccess'
result = had.isSuccess comboResult
assert.equal result, false
describe 'isSuccess of a had error result, single', ->
it 'should return false', ->
errorResult = had:'sample name', error:'sample error'
had = Had id:'isSuccess'
result = had.isSuccess errorResult
assert.equal result, false
describe 'isSuccess of a had error result, multiple', ->
it 'should return false', ->
errorResult =
had:'sample name'
error: had:'sample name', error:'test', some:'test'
previous: [
had:'sample name', error:'test', some:'test2'
]
had = Had id:'isSuccess'
result = had.isSuccess errorResult
assert.equal result, false
describe 'test nullArg', ->
describe 'with undefined', ->
it 'should fill error content and return true', ->
error =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'test'
had = Had id:'nullArg'
result = had.nullArg 'test', undefined
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with null', ->
it 'should fill error content and return true', ->
error =
had:'nullArg'
error:
message:'null', type:'arg', name:'test'
had = Had id:'nullArg'
result = had.nullArg 'test', null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'twice with undefined', ->
it 'should fill error content and return true', ->
first =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'test1'
second =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'test2'
had = Had id:'nullArg'
result1 = had.nullArg 'test1', undefined
result2 = had.nullArg 'test2', undefined
assert.equal result1, true
assert.equal result2, true
assert.deepEqual had.array.length, 2
assert.deepEqual had.array[0], first
assert.deepEqual had.array[1], second
describe 'with empty string', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', ''
assert.equal result, false
describe 'with non-empty string', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 'string'
assert.equal result, false
describe 'with 0', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 0
assert.equal result, false
describe 'with 1', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 1
assert.equal result, false
describe 'with -1', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', -1
assert.equal result, false
describe 'with empty array', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', []
assert.equal result, false
describe 'with non-empty array', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', [ 'something' ]
assert.equal result, false
describe 'with empty object', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', {}
assert.equal result, false
describe 'with non-empty object', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', { some: 'thing' }
assert.equal result, false
describe 'with Date', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', new Date()
assert.equal result, false
describe 'with Function', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', ->
assert.equal result, false
describe 'test nullProp', ->
describe 'with null object', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
object:true
had = Had id:'nullProp'
result = had.nullProp 'test', null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with undefined object', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
object:true
had = Had id:'nullProp'
result = had.nullProp 'test', undefined
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'without prop', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
had = Had id:'nullProp'
result = had.nullProp 'test', {}
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with null prop value', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
had = Had id:'nullProp'
result = had.nullProp 'test', test:null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with undefined prop value', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
had = Had id:'nullProp'
result = had.nullProp 'test', test:undefined
assert.equal result?, true, 'result should exist'
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with prop value', ->
it 'should return false', ->
had = Had id:'nullProp'
result = had.nullProp 'test', test:'exists'
assert.equal result, false
describe 'test success', ->
describe 'with no options', ->
it 'should return success result', ->
answer = had: 'success', previous:null
had = Had id:'success'
result = had.success()
assert.deepEqual result, answer
describe 'with one option', ->
it 'should return success result with extra option', ->
answer =
had: 'success'
value: test: 'option'
previous: null
had = Had id:'success'
result = had.success test:'option'
assert.deepEqual result, answer
describe 'with an \'error\' property true', ->
it 'returns the success result with an _error_ property', ->
answer =
had: 'success'
value: error: 'test'
previous: null
had = Had id:'success'
result = had.success error:'test'
assert.deepEqual result, answer
describe 'with previous error result to include', ->
it 'should return both results', ->
previousError =
had: 'anotherHad'
error:
message:'previous issue'
type:'something else'
some:'thing'
previous: null
success =
another:'thing'
combinedResult =
had: 'success'
value: success
previous: [ previousError ]
had = Had id:'success'
result = had.success previousError, success
assert.deepEqual result, combinedResult
describe 'with previous success result to include', ->
it 'should return both successes', ->
previousResult =
had: 'anotherHad'
value:
some:'thing'
previous: undefined
# thisResult =
# had: 'success'
# value:
# something:'else'
# previous: undefined
combinedResult =
had: 'success'
value:
something:'else'
previous: [ previousResult ]
had = Had id:'success'
result = had.success previousResult, something:'else'
assert.equal result?, true, 'result should exist'
assert.deepEqual result, combinedResult
describe 'with previous true result to include', ->
it 'should return the one success', ->
thisResult =
had: 'success'
value:
some:'thing'
previous: null
had = Had id:'success'
result = had.success true, thisResult.value
assert.deepEqual result, thisResult
describe 'with previous false result to include', ->
it 'should return the one success', ->
thisResult =
had: 'success'
value:
some:'thing'
previous: null
had = Had id:'success'
result = had.success false, some:'thing'
assert.deepEqual result, thisResult
describe 'test error', ->
describe 'with no options', ->
it 'should return error result', ->
answer =
had:'error'
error:'unknown'
previous: null
had = Had id:'error'
result = had.error()
assert.deepEqual result, answer
describe 'with \'error\' option', ->
it 'should return error result with error option', ->
answer =
had:'error'
error: message:'test'
previous: null
had = Had id:'error'
result = had.error message:'test'
assert.deepEqual result, answer
describe 'with \'type\' option', ->
it 'should return error result with type option', ->
answer =
had:'error'
error: type:'test'
previous: null
had = Had id:'error'
result = had.error type:'test'
assert.deepEqual result, answer
describe 'with \'extra\' option', ->
it 'should return error result with extra option', ->
answer =
had:'error'
error: extra:'test'
previous: null
had = Had id:'error'
result = had.error extra:'test'
assert.deepEqual result, answer
describe 'with \'success\' option', ->
it 'should return error result with _success_ property', ->
answer =
had:'error'
error: success:'test'
previous: null
had = Had id:'error'
result = had.error success:'test'
assert.deepEqual result, answer
describe 'with previous error result to include', ->
it 'should return both errors', ->
previousError =
had: 'anotherHad'
error:
message:'previous issue'
type:'something else'
some:'thing'
previous: null
thisError =
message:'testing'
type:'test'
some:'thing'
combinedError =
had: 'error'
error: thisError
previous: [previousError]
had = Had id:'error'
result = had.error previousError, thisError
assert.deepEqual result, combinedError
describe 'with previous success result to include', ->
it 'should return both errors', ->
previousResult =
had: 'anotherHad'
value:
some:'thing'
previous: null
thisError =
message:'testing'
type:'test'
another:'thing'
combinedResult =
had: 'error'
error: thisError
previous: [previousResult]
had = Had id:'error'
result = had.error previousResult, thisError
assert.deepEqual result, combinedResult
describe 'with previous true result to include', ->
it 'should return the one error', ->
thisError =
had: 'error'
error:
message:'testing'
type:'test'
previous: null
had = Had id:'error'
result = had.error true, message:'testing', type:'test'
assert.deepEqual result, thisError
describe 'with previous false result to include', ->
it 'should return the one error', ->
thisError =
had: 'error'
error:
message:'testing'
type:'test'
previous: null
had = Had id:'error'
result = had.error false, message:'testing', type:'test'
assert.deepEqual result, thisError
describe 'test results', ->
describe 'with no options', ->
it 'should return basic result with only had ID', ->
answer = had:'results'
had = Had id:'results'
result = had.results()
assert.deepEqual result, answer
describe 'with a single override value', ->
it 'should return result with had+override', ->
answer = had:'results', some:'thing'
had = Had id:'results'
result = had.results some:'thing'
assert.deepEqual result, answer
describe 'with error override values', ->
it 'should return result with overridden values', ->
answer =
had:'results'
error:'new'
type:'values'
had = Had id:'results'
result = had.results error:'new', type:'values'
assert.deepEqual result, answer
describe 'with a result to use', ->
it 'should return the result', ->
answer =
had:'results'
error: some:'thing'
previous: null
had = Had id:'results'
had.addError some:'thing'
result = had.results()
assert.deepEqual result, answer
describe 'with two results to use', ->
it 'should return the result', ->
answer =
had:'results'
error: second:'thing'
previous: [
had:'results'
error: first:'thing'
]
had = Had id:'results'
had.addError first:'thing'
had.addError second:'thing'
result = had.results()
assert.deepEqual result, answer
describe 'test addSuccess', ->
it 'with a value', ->
result = [
{
had:'addSuccess'
value:
some:'thing'
}
]
had = Had id:'addSuccess'
had.addSuccess some:'thing'
assert.deepEqual had.array, result
it 'without a value', ->
result = [ had:'addSuccess' ]
had = Had id:'addSuccess'
had.addSuccess()
assert.deepEqual had.array, result
| 20954 | assert = require 'assert'
Had = require '../lib'
describe 'test had\'s functions', ->
describe 'test had id', ->
it 'should have id in had', ->
id = 'test-id'
had = Had id:id
assert.equal had.id, id, 'had should have its id'
describe 'test isSuccess', ->
describe 'isSuccess of null', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess null
assert.equal result, false
describe 'isSuccess of undefined', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess undefined
assert.equal result, false
describe 'isSuccess of empty object', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess {}
assert.equal result, true
describe 'isSuccess of non-empty object', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess some:'thing'
assert.equal result, true
describe 'isSuccess of object with had prop', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess had:'test'
assert.equal result, true
describe 'isSuccess of empty array', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess []
assert.equal result, true
describe 'isSuccess of non-empty array', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess ['one']
assert.equal result, true
describe 'isSuccess of true', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess true
assert.equal result, true
describe 'isSuccess of false', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess false
assert.equal result, false
describe 'isSuccess of a had success result, single', ->
it 'should return true', ->
had = Had id:'isSuccess'
successResult = had:'sample name', some:'test'
result = had.isSuccess successResult
assert.equal result, true
describe 'isSuccess of a had success result, multiple', ->
it 'should return true', ->
successResult =
had:'sample name'
some:'test'
previous: [ { had:'sample name', some:'test2' } ]
had = Had id:'isSuccess'
result = had.isSuccess successResult
assert.equal result, true
describe 'isSuccess of a had success+error result', ->
it 'should return false', ->
comboResult =
had:'sample name'
error: had:'sample name', message:'test', type:'test', some:'testy'
previous: [ had:'sample name', success:true, some:'test' ]
had = Had id:'isSuccess'
result = had.isSuccess comboResult
assert.equal result, false
describe 'isSuccess of a had error result, single', ->
it 'should return false', ->
errorResult = had:'sample name', error:'sample error'
had = Had id:'isSuccess'
result = had.isSuccess errorResult
assert.equal result, false
describe 'isSuccess of a had error result, multiple', ->
it 'should return false', ->
errorResult =
had:'sample name'
error: had:'sample name', error:'test', some:'test'
previous: [
had:'sample name', error:'test', some:'test2'
]
had = Had id:'isSuccess'
result = had.isSuccess errorResult
assert.equal result, false
describe 'test nullArg', ->
describe 'with undefined', ->
it 'should fill error content and return true', ->
error =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'<NAME>'
had = Had id:'nullArg'
result = had.nullArg 'test', undefined
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with null', ->
it 'should fill error content and return true', ->
error =
had:'nullArg'
error:
message:'null', type:'arg', name:'<NAME>'
had = Had id:'nullArg'
result = had.nullArg 'test', null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'twice with undefined', ->
it 'should fill error content and return true', ->
first =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'<NAME>'
second =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'<NAME>'
had = Had id:'nullArg'
result1 = had.nullArg 'test1', undefined
result2 = had.nullArg 'test2', undefined
assert.equal result1, true
assert.equal result2, true
assert.deepEqual had.array.length, 2
assert.deepEqual had.array[0], first
assert.deepEqual had.array[1], second
describe 'with empty string', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', ''
assert.equal result, false
describe 'with non-empty string', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 'string'
assert.equal result, false
describe 'with 0', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 0
assert.equal result, false
describe 'with 1', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 1
assert.equal result, false
describe 'with -1', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', -1
assert.equal result, false
describe 'with empty array', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', []
assert.equal result, false
describe 'with non-empty array', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', [ 'something' ]
assert.equal result, false
describe 'with empty object', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', {}
assert.equal result, false
describe 'with non-empty object', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', { some: 'thing' }
assert.equal result, false
describe 'with Date', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', new Date()
assert.equal result, false
describe 'with Function', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', ->
assert.equal result, false
describe 'test nullProp', ->
describe 'with null object', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'<NAME>'
object:true
had = Had id:'nullProp'
result = had.nullProp 'test', null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with undefined object', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'<NAME>'
object:true
had = Had id:'nullProp'
result = had.nullProp 'test', undefined
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'without prop', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'<NAME>'
had = Had id:'nullProp'
result = had.nullProp 'test', {}
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with null prop value', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'<NAME>'
had = Had id:'nullProp'
result = had.nullProp 'test', test:null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with undefined prop value', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
had = Had id:'nullProp'
result = had.nullProp 'test', test:undefined
assert.equal result?, true, 'result should exist'
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with prop value', ->
it 'should return false', ->
had = Had id:'nullProp'
result = had.nullProp 'test', test:'exists'
assert.equal result, false
describe 'test success', ->
describe 'with no options', ->
it 'should return success result', ->
answer = had: 'success', previous:null
had = Had id:'success'
result = had.success()
assert.deepEqual result, answer
describe 'with one option', ->
it 'should return success result with extra option', ->
answer =
had: 'success'
value: test: 'option'
previous: null
had = Had id:'success'
result = had.success test:'option'
assert.deepEqual result, answer
describe 'with an \'error\' property true', ->
it 'returns the success result with an _error_ property', ->
answer =
had: 'success'
value: error: 'test'
previous: null
had = Had id:'success'
result = had.success error:'test'
assert.deepEqual result, answer
describe 'with previous error result to include', ->
it 'should return both results', ->
previousError =
had: 'anotherHad'
error:
message:'previous issue'
type:'something else'
some:'thing'
previous: null
success =
another:'thing'
combinedResult =
had: 'success'
value: success
previous: [ previousError ]
had = Had id:'success'
result = had.success previousError, success
assert.deepEqual result, combinedResult
describe 'with previous success result to include', ->
it 'should return both successes', ->
previousResult =
had: 'anotherHad'
value:
some:'thing'
previous: undefined
# thisResult =
# had: 'success'
# value:
# something:'else'
# previous: undefined
combinedResult =
had: 'success'
value:
something:'else'
previous: [ previousResult ]
had = Had id:'success'
result = had.success previousResult, something:'else'
assert.equal result?, true, 'result should exist'
assert.deepEqual result, combinedResult
describe 'with previous true result to include', ->
it 'should return the one success', ->
thisResult =
had: 'success'
value:
some:'thing'
previous: null
had = Had id:'success'
result = had.success true, thisResult.value
assert.deepEqual result, thisResult
describe 'with previous false result to include', ->
it 'should return the one success', ->
thisResult =
had: 'success'
value:
some:'thing'
previous: null
had = Had id:'success'
result = had.success false, some:'thing'
assert.deepEqual result, thisResult
describe 'test error', ->
describe 'with no options', ->
it 'should return error result', ->
answer =
had:'error'
error:'unknown'
previous: null
had = Had id:'error'
result = had.error()
assert.deepEqual result, answer
describe 'with \'error\' option', ->
it 'should return error result with error option', ->
answer =
had:'error'
error: message:'test'
previous: null
had = Had id:'error'
result = had.error message:'test'
assert.deepEqual result, answer
describe 'with \'type\' option', ->
it 'should return error result with type option', ->
answer =
had:'error'
error: type:'test'
previous: null
had = Had id:'error'
result = had.error type:'test'
assert.deepEqual result, answer
describe 'with \'extra\' option', ->
it 'should return error result with extra option', ->
answer =
had:'error'
error: extra:'test'
previous: null
had = Had id:'error'
result = had.error extra:'test'
assert.deepEqual result, answer
describe 'with \'success\' option', ->
it 'should return error result with _success_ property', ->
answer =
had:'error'
error: success:'test'
previous: null
had = Had id:'error'
result = had.error success:'test'
assert.deepEqual result, answer
describe 'with previous error result to include', ->
it 'should return both errors', ->
previousError =
had: 'anotherHad'
error:
message:'previous issue'
type:'something else'
some:'thing'
previous: null
thisError =
message:'testing'
type:'test'
some:'thing'
combinedError =
had: 'error'
error: thisError
previous: [previousError]
had = Had id:'error'
result = had.error previousError, thisError
assert.deepEqual result, combinedError
describe 'with previous success result to include', ->
it 'should return both errors', ->
previousResult =
had: 'anotherHad'
value:
some:'thing'
previous: null
thisError =
message:'testing'
type:'test'
another:'thing'
combinedResult =
had: 'error'
error: thisError
previous: [previousResult]
had = Had id:'error'
result = had.error previousResult, thisError
assert.deepEqual result, combinedResult
describe 'with previous true result to include', ->
it 'should return the one error', ->
thisError =
had: 'error'
error:
message:'testing'
type:'test'
previous: null
had = Had id:'error'
result = had.error true, message:'testing', type:'test'
assert.deepEqual result, thisError
describe 'with previous false result to include', ->
it 'should return the one error', ->
thisError =
had: 'error'
error:
message:'testing'
type:'test'
previous: null
had = Had id:'error'
result = had.error false, message:'testing', type:'test'
assert.deepEqual result, thisError
describe 'test results', ->
describe 'with no options', ->
it 'should return basic result with only had ID', ->
answer = had:'results'
had = Had id:'results'
result = had.results()
assert.deepEqual result, answer
describe 'with a single override value', ->
it 'should return result with had+override', ->
answer = had:'results', some:'thing'
had = Had id:'results'
result = had.results some:'thing'
assert.deepEqual result, answer
describe 'with error override values', ->
it 'should return result with overridden values', ->
answer =
had:'results'
error:'new'
type:'values'
had = Had id:'results'
result = had.results error:'new', type:'values'
assert.deepEqual result, answer
describe 'with a result to use', ->
it 'should return the result', ->
answer =
had:'results'
error: some:'thing'
previous: null
had = Had id:'results'
had.addError some:'thing'
result = had.results()
assert.deepEqual result, answer
describe 'with two results to use', ->
it 'should return the result', ->
answer =
had:'results'
error: second:'thing'
previous: [
had:'results'
error: first:'thing'
]
had = Had id:'results'
had.addError first:'thing'
had.addError second:'thing'
result = had.results()
assert.deepEqual result, answer
describe 'test addSuccess', ->
it 'with a value', ->
result = [
{
had:'addSuccess'
value:
some:'thing'
}
]
had = Had id:'addSuccess'
had.addSuccess some:'thing'
assert.deepEqual had.array, result
it 'without a value', ->
result = [ had:'addSuccess' ]
had = Had id:'addSuccess'
had.addSuccess()
assert.deepEqual had.array, result
| true | assert = require 'assert'
Had = require '../lib'
describe 'test had\'s functions', ->
describe 'test had id', ->
it 'should have id in had', ->
id = 'test-id'
had = Had id:id
assert.equal had.id, id, 'had should have its id'
describe 'test isSuccess', ->
describe 'isSuccess of null', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess null
assert.equal result, false
describe 'isSuccess of undefined', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess undefined
assert.equal result, false
describe 'isSuccess of empty object', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess {}
assert.equal result, true
describe 'isSuccess of non-empty object', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess some:'thing'
assert.equal result, true
describe 'isSuccess of object with had prop', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess had:'test'
assert.equal result, true
describe 'isSuccess of empty array', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess []
assert.equal result, true
describe 'isSuccess of non-empty array', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess ['one']
assert.equal result, true
describe 'isSuccess of true', ->
it 'should return true', ->
had = Had id:'isSuccess'
result = had.isSuccess true
assert.equal result, true
describe 'isSuccess of false', ->
it 'should return false', ->
had = Had id:'isSuccess'
result = had.isSuccess false
assert.equal result, false
describe 'isSuccess of a had success result, single', ->
it 'should return true', ->
had = Had id:'isSuccess'
successResult = had:'sample name', some:'test'
result = had.isSuccess successResult
assert.equal result, true
describe 'isSuccess of a had success result, multiple', ->
it 'should return true', ->
successResult =
had:'sample name'
some:'test'
previous: [ { had:'sample name', some:'test2' } ]
had = Had id:'isSuccess'
result = had.isSuccess successResult
assert.equal result, true
describe 'isSuccess of a had success+error result', ->
it 'should return false', ->
comboResult =
had:'sample name'
error: had:'sample name', message:'test', type:'test', some:'testy'
previous: [ had:'sample name', success:true, some:'test' ]
had = Had id:'isSuccess'
result = had.isSuccess comboResult
assert.equal result, false
describe 'isSuccess of a had error result, single', ->
it 'should return false', ->
errorResult = had:'sample name', error:'sample error'
had = Had id:'isSuccess'
result = had.isSuccess errorResult
assert.equal result, false
describe 'isSuccess of a had error result, multiple', ->
it 'should return false', ->
errorResult =
had:'sample name'
error: had:'sample name', error:'test', some:'test'
previous: [
had:'sample name', error:'test', some:'test2'
]
had = Had id:'isSuccess'
result = had.isSuccess errorResult
assert.equal result, false
describe 'test nullArg', ->
describe 'with undefined', ->
it 'should fill error content and return true', ->
error =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'PI:NAME:<NAME>END_PI'
had = Had id:'nullArg'
result = had.nullArg 'test', undefined
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with null', ->
it 'should fill error content and return true', ->
error =
had:'nullArg'
error:
message:'null', type:'arg', name:'PI:NAME:<NAME>END_PI'
had = Had id:'nullArg'
result = had.nullArg 'test', null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'twice with undefined', ->
it 'should fill error content and return true', ->
first =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'PI:NAME:<NAME>END_PI'
second =
had:'nullArg'
error:
message:'null'
type:'arg'
name:'PI:NAME:<NAME>END_PI'
had = Had id:'nullArg'
result1 = had.nullArg 'test1', undefined
result2 = had.nullArg 'test2', undefined
assert.equal result1, true
assert.equal result2, true
assert.deepEqual had.array.length, 2
assert.deepEqual had.array[0], first
assert.deepEqual had.array[1], second
describe 'with empty string', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', ''
assert.equal result, false
describe 'with non-empty string', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 'string'
assert.equal result, false
describe 'with 0', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 0
assert.equal result, false
describe 'with 1', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', 1
assert.equal result, false
describe 'with -1', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', -1
assert.equal result, false
describe 'with empty array', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', []
assert.equal result, false
describe 'with non-empty array', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', [ 'something' ]
assert.equal result, false
describe 'with empty object', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', {}
assert.equal result, false
describe 'with non-empty object', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', { some: 'thing' }
assert.equal result, false
describe 'with Date', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', new Date()
assert.equal result, false
describe 'with Function', ->
it 'should return false', ->
had = Had id:'nullArg'
result = had.nullArg 'test', ->
assert.equal result, false
describe 'test nullProp', ->
describe 'with null object', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'PI:NAME:<NAME>END_PI'
object:true
had = Had id:'nullProp'
result = had.nullProp 'test', null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with undefined object', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'PI:NAME:<NAME>END_PI'
object:true
had = Had id:'nullProp'
result = had.nullProp 'test', undefined
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'without prop', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'PI:NAME:<NAME>END_PI'
had = Had id:'nullProp'
result = had.nullProp 'test', {}
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with null prop value', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'PI:NAME:<NAME>END_PI'
had = Had id:'nullProp'
result = had.nullProp 'test', test:null
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with undefined prop value', ->
it 'should fill error content and return true', ->
error =
had:'nullProp'
error:
message:'null'
type:'prop'
name:'test'
had = Had id:'nullProp'
result = had.nullProp 'test', test:undefined
assert.equal result?, true, 'result should exist'
assert.equal result, true
assert.deepEqual had.array[0], error
describe 'with prop value', ->
it 'should return false', ->
had = Had id:'nullProp'
result = had.nullProp 'test', test:'exists'
assert.equal result, false
describe 'test success', ->
describe 'with no options', ->
it 'should return success result', ->
answer = had: 'success', previous:null
had = Had id:'success'
result = had.success()
assert.deepEqual result, answer
describe 'with one option', ->
it 'should return success result with extra option', ->
answer =
had: 'success'
value: test: 'option'
previous: null
had = Had id:'success'
result = had.success test:'option'
assert.deepEqual result, answer
describe 'with an \'error\' property true', ->
it 'returns the success result with an _error_ property', ->
answer =
had: 'success'
value: error: 'test'
previous: null
had = Had id:'success'
result = had.success error:'test'
assert.deepEqual result, answer
describe 'with previous error result to include', ->
it 'should return both results', ->
previousError =
had: 'anotherHad'
error:
message:'previous issue'
type:'something else'
some:'thing'
previous: null
success =
another:'thing'
combinedResult =
had: 'success'
value: success
previous: [ previousError ]
had = Had id:'success'
result = had.success previousError, success
assert.deepEqual result, combinedResult
describe 'with previous success result to include', ->
it 'should return both successes', ->
previousResult =
had: 'anotherHad'
value:
some:'thing'
previous: undefined
# thisResult =
# had: 'success'
# value:
# something:'else'
# previous: undefined
combinedResult =
had: 'success'
value:
something:'else'
previous: [ previousResult ]
had = Had id:'success'
result = had.success previousResult, something:'else'
assert.equal result?, true, 'result should exist'
assert.deepEqual result, combinedResult
describe 'with previous true result to include', ->
it 'should return the one success', ->
thisResult =
had: 'success'
value:
some:'thing'
previous: null
had = Had id:'success'
result = had.success true, thisResult.value
assert.deepEqual result, thisResult
describe 'with previous false result to include', ->
it 'should return the one success', ->
thisResult =
had: 'success'
value:
some:'thing'
previous: null
had = Had id:'success'
result = had.success false, some:'thing'
assert.deepEqual result, thisResult
describe 'test error', ->
describe 'with no options', ->
it 'should return error result', ->
answer =
had:'error'
error:'unknown'
previous: null
had = Had id:'error'
result = had.error()
assert.deepEqual result, answer
describe 'with \'error\' option', ->
it 'should return error result with error option', ->
answer =
had:'error'
error: message:'test'
previous: null
had = Had id:'error'
result = had.error message:'test'
assert.deepEqual result, answer
describe 'with \'type\' option', ->
it 'should return error result with type option', ->
answer =
had:'error'
error: type:'test'
previous: null
had = Had id:'error'
result = had.error type:'test'
assert.deepEqual result, answer
describe 'with \'extra\' option', ->
it 'should return error result with extra option', ->
answer =
had:'error'
error: extra:'test'
previous: null
had = Had id:'error'
result = had.error extra:'test'
assert.deepEqual result, answer
describe 'with \'success\' option', ->
it 'should return error result with _success_ property', ->
answer =
had:'error'
error: success:'test'
previous: null
had = Had id:'error'
result = had.error success:'test'
assert.deepEqual result, answer
describe 'with previous error result to include', ->
it 'should return both errors', ->
previousError =
had: 'anotherHad'
error:
message:'previous issue'
type:'something else'
some:'thing'
previous: null
thisError =
message:'testing'
type:'test'
some:'thing'
combinedError =
had: 'error'
error: thisError
previous: [previousError]
had = Had id:'error'
result = had.error previousError, thisError
assert.deepEqual result, combinedError
describe 'with previous success result to include', ->
it 'should return both errors', ->
previousResult =
had: 'anotherHad'
value:
some:'thing'
previous: null
thisError =
message:'testing'
type:'test'
another:'thing'
combinedResult =
had: 'error'
error: thisError
previous: [previousResult]
had = Had id:'error'
result = had.error previousResult, thisError
assert.deepEqual result, combinedResult
describe 'with previous true result to include', ->
it 'should return the one error', ->
thisError =
had: 'error'
error:
message:'testing'
type:'test'
previous: null
had = Had id:'error'
result = had.error true, message:'testing', type:'test'
assert.deepEqual result, thisError
describe 'with previous false result to include', ->
it 'should return the one error', ->
thisError =
had: 'error'
error:
message:'testing'
type:'test'
previous: null
had = Had id:'error'
result = had.error false, message:'testing', type:'test'
assert.deepEqual result, thisError
describe 'test results', ->
describe 'with no options', ->
it 'should return basic result with only had ID', ->
answer = had:'results'
had = Had id:'results'
result = had.results()
assert.deepEqual result, answer
describe 'with a single override value', ->
it 'should return result with had+override', ->
answer = had:'results', some:'thing'
had = Had id:'results'
result = had.results some:'thing'
assert.deepEqual result, answer
describe 'with error override values', ->
it 'should return result with overridden values', ->
answer =
had:'results'
error:'new'
type:'values'
had = Had id:'results'
result = had.results error:'new', type:'values'
assert.deepEqual result, answer
describe 'with a result to use', ->
it 'should return the result', ->
answer =
had:'results'
error: some:'thing'
previous: null
had = Had id:'results'
had.addError some:'thing'
result = had.results()
assert.deepEqual result, answer
describe 'with two results to use', ->
it 'should return the result', ->
answer =
had:'results'
error: second:'thing'
previous: [
had:'results'
error: first:'thing'
]
had = Had id:'results'
had.addError first:'thing'
had.addError second:'thing'
result = had.results()
assert.deepEqual result, answer
describe 'test addSuccess', ->
it 'with a value', ->
result = [
{
had:'addSuccess'
value:
some:'thing'
}
]
had = Had id:'addSuccess'
had.addSuccess some:'thing'
assert.deepEqual had.array, result
it 'without a value', ->
result = [ had:'addSuccess' ]
had = Had id:'addSuccess'
had.addSuccess()
assert.deepEqual had.array, result
|
[
{
"context": "r Message Queue Javascript implementation\n(c) 2014 Rob Murray\n@see https://github.com/rob-murray/ui-message-que",
"end": 87,
"score": 0.9998394250869751,
"start": 77,
"tag": "NAME",
"value": "Rob Murray"
},
{
"context": "ation\n(c) 2014 Rob Murray\n@see https://github... | src/UiMessageQueue.coffee | GerHobbelt/ui-message-queue | 0 | ###
UiMessageQueue - a User Message Queue Javascript implementation
(c) 2014 Rob Murray
@see https://github.com/rob-murray/ui-message-queue
UiMessageQueue may be freely distributed under the MIT license
###
# testing helper
root = exports ? window
# Imports
AlertDisplay = root.AlertDisplay || require('../lib/AlertDisplay').AlertDisplay
DomDisplay = root.DomDisplay || require('../lib/DomDisplay').DomDisplay
FifoQueue = root.FifoQueue || require('../lib/FifoQueue').FifoQueue
class root.UiMessageQueue
"use strict"
# default options
# timeout value to display message in milisecs
@DEFAULT_DELAY: 1000
# default string to display when no messages in queue
@DEFAULT_EMPTY_DISPLAY_MESSAGE: ""
# Create new instance with args as options
constructor: (args) ->
throw new Error("Missing arguments. UiMessageQueue requires arguments to run.") if not args
# assign ivars
@_displayer = new AlertDisplay()
@_delay = UiMessageQueue.DEFAULT_DELAY
@_emptyDisplayString = UiMessageQueue.DEFAULT_EMPTY_DISPLAY_MESSAGE
@_messageStack = new FifoQueue()
@_setOptions args
@_triggered = false
# internal; method to set attributes from args passed
_setOptions: (options)->
# Test and assign emptyDisplayString
if options.emptyDisplayString
throw new Error("Invalid argument: emptyDisplayString is not a String") if not (typeof options.emptyDisplayString == "string")
@_emptyDisplayString = options.emptyDisplayString
# Test and assign timeout
if options.delay
throw new Error("Invalid argument: delay is not numeric") if not isFinite options.delay
@_delay = options.delay
if options.outputElementId
try
@_displayer = new DomDisplay(options.outputElementId)
catch e
@_displayer = new AlertDisplay()
# add a message to the queue
push: ( message ) =>
@_messageStack.push message if typeof message == "string"
# only trigger processing if not already done so,
# processing will internally work through the queue
@_processMessageQueue() if @_triggered == false
# internal; delegate display of message to display strategy
_displayMessage: (message) =>
@_displayer.displayMessage message
# internal; grab the first message off the stack, display it
_processMessageQueue: =>
if @_messageStack.hasItems()
self = @
# if the one message in the queue is the first
# addition then display it immediately
if @_messageStack.getCount() == 1 and @_triggered == false
@_displayMessage @_messageStack.getItem()
# pass reference to this into timeout call and set to run with delay
setTimeout ((self) ->
# if there are items in queue then display the next one;
# otherwise it must be the empty string
if self._messageStack.hasItems()
self._displayMessage self._messageStack.getItem()
else
self._displayMessage self._emptyDisplayString
# call this method again
self._processMessageQueue()
), self._delay, this
@_triggered = true
else
# stop processing
@_triggered = false
| 169536 | ###
UiMessageQueue - a User Message Queue Javascript implementation
(c) 2014 <NAME>
@see https://github.com/rob-murray/ui-message-queue
UiMessageQueue may be freely distributed under the MIT license
###
# testing helper
root = exports ? window
# Imports
AlertDisplay = root.AlertDisplay || require('../lib/AlertDisplay').AlertDisplay
DomDisplay = root.DomDisplay || require('../lib/DomDisplay').DomDisplay
FifoQueue = root.FifoQueue || require('../lib/FifoQueue').FifoQueue
class root.UiMessageQueue
"use strict"
# default options
# timeout value to display message in milisecs
@DEFAULT_DELAY: 1000
# default string to display when no messages in queue
@DEFAULT_EMPTY_DISPLAY_MESSAGE: ""
# Create new instance with args as options
constructor: (args) ->
throw new Error("Missing arguments. UiMessageQueue requires arguments to run.") if not args
# assign ivars
@_displayer = new AlertDisplay()
@_delay = UiMessageQueue.DEFAULT_DELAY
@_emptyDisplayString = UiMessageQueue.DEFAULT_EMPTY_DISPLAY_MESSAGE
@_messageStack = new FifoQueue()
@_setOptions args
@_triggered = false
# internal; method to set attributes from args passed
_setOptions: (options)->
# Test and assign emptyDisplayString
if options.emptyDisplayString
throw new Error("Invalid argument: emptyDisplayString is not a String") if not (typeof options.emptyDisplayString == "string")
@_emptyDisplayString = options.emptyDisplayString
# Test and assign timeout
if options.delay
throw new Error("Invalid argument: delay is not numeric") if not isFinite options.delay
@_delay = options.delay
if options.outputElementId
try
@_displayer = new DomDisplay(options.outputElementId)
catch e
@_displayer = new AlertDisplay()
# add a message to the queue
push: ( message ) =>
@_messageStack.push message if typeof message == "string"
# only trigger processing if not already done so,
# processing will internally work through the queue
@_processMessageQueue() if @_triggered == false
# internal; delegate display of message to display strategy
_displayMessage: (message) =>
@_displayer.displayMessage message
# internal; grab the first message off the stack, display it
_processMessageQueue: =>
if @_messageStack.hasItems()
self = @
# if the one message in the queue is the first
# addition then display it immediately
if @_messageStack.getCount() == 1 and @_triggered == false
@_displayMessage @_messageStack.getItem()
# pass reference to this into timeout call and set to run with delay
setTimeout ((self) ->
# if there are items in queue then display the next one;
# otherwise it must be the empty string
if self._messageStack.hasItems()
self._displayMessage self._messageStack.getItem()
else
self._displayMessage self._emptyDisplayString
# call this method again
self._processMessageQueue()
), self._delay, this
@_triggered = true
else
# stop processing
@_triggered = false
| true | ###
UiMessageQueue - a User Message Queue Javascript implementation
(c) 2014 PI:NAME:<NAME>END_PI
@see https://github.com/rob-murray/ui-message-queue
UiMessageQueue may be freely distributed under the MIT license
###
# testing helper
root = exports ? window
# Imports
AlertDisplay = root.AlertDisplay || require('../lib/AlertDisplay').AlertDisplay
DomDisplay = root.DomDisplay || require('../lib/DomDisplay').DomDisplay
FifoQueue = root.FifoQueue || require('../lib/FifoQueue').FifoQueue
class root.UiMessageQueue
"use strict"
# default options
# timeout value to display message in milisecs
@DEFAULT_DELAY: 1000
# default string to display when no messages in queue
@DEFAULT_EMPTY_DISPLAY_MESSAGE: ""
# Create new instance with args as options
constructor: (args) ->
throw new Error("Missing arguments. UiMessageQueue requires arguments to run.") if not args
# assign ivars
@_displayer = new AlertDisplay()
@_delay = UiMessageQueue.DEFAULT_DELAY
@_emptyDisplayString = UiMessageQueue.DEFAULT_EMPTY_DISPLAY_MESSAGE
@_messageStack = new FifoQueue()
@_setOptions args
@_triggered = false
# internal; method to set attributes from args passed
_setOptions: (options)->
# Test and assign emptyDisplayString
if options.emptyDisplayString
throw new Error("Invalid argument: emptyDisplayString is not a String") if not (typeof options.emptyDisplayString == "string")
@_emptyDisplayString = options.emptyDisplayString
# Test and assign timeout
if options.delay
throw new Error("Invalid argument: delay is not numeric") if not isFinite options.delay
@_delay = options.delay
if options.outputElementId
try
@_displayer = new DomDisplay(options.outputElementId)
catch e
@_displayer = new AlertDisplay()
# add a message to the queue
push: ( message ) =>
@_messageStack.push message if typeof message == "string"
# only trigger processing if not already done so,
# processing will internally work through the queue
@_processMessageQueue() if @_triggered == false
# internal; delegate display of message to display strategy
_displayMessage: (message) =>
@_displayer.displayMessage message
# internal; grab the first message off the stack, display it
_processMessageQueue: =>
if @_messageStack.hasItems()
self = @
# if the one message in the queue is the first
# addition then display it immediately
if @_messageStack.getCount() == 1 and @_triggered == false
@_displayMessage @_messageStack.getItem()
# pass reference to this into timeout call and set to run with delay
setTimeout ((self) ->
# if there are items in queue then display the next one;
# otherwise it must be the empty string
if self._messageStack.hasItems()
self._displayMessage self._messageStack.getItem()
else
self._displayMessage self._emptyDisplayString
# call this method again
self._processMessageQueue()
), self._delay, this
@_triggered = true
else
# stop processing
@_triggered = false
|
[
{
"context": " parents\n parentKey = if parent.id? then \"precondition_#{parent.id}\" else parent.key || parent.type\n ",
"end": 4903,
"score": 0.6823287010192871,
"start": 4893,
"tag": "KEY",
"value": "condition_"
},
{
"context": " if (child.preconditions)\n ke... | app/assets/javascripts/models/result.js.coffee | okeefm/bonnie | 0 | class Thorax.Models.Result extends Thorax.Model
initialize: (attrs, options) ->
@population = options.population
@measure = @population.collection.parent
@patient = options.patient
# Provide a deferred that allows usage of a result to be deferred until it's populated
@calculation = $.Deferred()
if @isPopulated() then @calculation.resolve() else @once 'change:rationale', -> @calculation.resolve()
# When a patient changes, is materialized, or is destroyed, we need to respond appropriately
@listenTo @patient, 'change materialize destroy', =>
bonnie.calculator.clearResult(@population, @patient) # Remove the result from the cache
@destroy() # Destroy the result to remove it from any collections
isPopulated: -> @has('rationale')
differenceFromExpected: ->
expected = @patient.getExpectedValue @population
new Thorax.Models.Difference({}, result: this, expected: expected)
specificsRationale: ->
updatedRationale = {}
rationale = @get('rationale')
orCounts = @calculateOrCounts(rationale)
for code in Thorax.Models.Measure.allPopulationCodes
if specifics = @get('finalSpecifics')?[code]
updatedRationale[code] = {}
# get the referenced occurrences in the logic tree using original population code
occurrences = _.uniq @population.getDataCriteriaKeys(@measure.get('population_criteria')[@population.get(code)?.code])
# get the good and bad specifics
occurrenceResults = @checkSpecificsForRationale(specifics, occurrences, @measure.get('data_criteria'))
submeasureCode = @population.get(code)?.code || code
parentMap = @buildParentMap(@measure.get('population_criteria')[submeasureCode])
# check each bad occurrence and remove highlights marking true
for badOccurrence in occurrenceResults.bad
if (rationale[badOccurrence])
updatedRationale[code][badOccurrence] = false
# move up the logic tree to set AND/ORs to false based on the removal of the bad specific's true eval
@updateLogicTree(updatedRationale, rationale, code, badOccurrence, orCounts, parentMap)
# check the good specifics with a negated parent. If there are multiple candidate specifics
# and one is good while the other is bad, the child of the negation will evaluate to true, we want it to
# evaluate to false since if there's a good negation then there's an occurrence for which it evaluated to false
for goodOccurrence in occurrenceResults.good
@updatedNegatedGood(updatedRationale[code], rationale, goodOccurrence, parentMap)
return updatedRationale
updatedRationale: ->
updatedRationale = @specificsRationale()
currentRationale = @get 'rationale'
cleanup = []
for code in @population.populationCriteria() when currentRationale[code]?
for key, value of currentRationale
if _(updatedRationale).has(code) and updatedRationale[code][key] is false then cleanup.push(key)
_(currentRationale).omit(cleanup)
updatedNegatedGood: (updatedRationale, rationale, goodOccurrence, parentMap) ->
parent = parentMap[goodOccurrence]
while parent
if (parent.negation && rationale[goodOccurrence])
updatedRationale[goodOccurrence] = false
return
parent = parentMap["precondition_#{parent.id}"]
# get good and bad specific occurrences referenced in this part of the measure
checkSpecificsForRationale: (finalSpecifics, occurrences, dataCriteriaMap) ->
results = {bad: occurrences, good: []}
# if we dont't have any specifics rows then they are all bad
return results if finalSpecifics.length == 0
results.bad = []
# check for good and bad specifics. Bad will be used to clear out logical true values that are false
# when specifics are applied. Good will be used to fix negations of specific occurrences
for occurrence in occurrences
index = hqmf.SpecificsManager.indexLookup[dataCriteriaMap[occurrence].source_data_criteria]
good = false
# we're good if the occurrence is referenced by ID, Any indicates that we did not use it in the true path, thus it's bad
for row in finalSpecifics
good = true if row[index] != hqmf.SpecificsManager.any
if good then results.good.push(occurrence) else results.bad.push(occurrence)
results
# from each leaf walk up the tree updating the logical statements appropriately to false
updateLogicTree: (updatedRationale, rationale, code, badOccurrence, orCounts, parentMap) ->
parents = parentMap[badOccurrence]
@updateLogicTreeChildren(updatedRationale, rationale, code, parents, orCounts, parentMap)
updateLogicTreeChildren: (updatedRationale, rationale, code, parents, orCounts, parentMap) ->
return unless parents
for parent in parents
parentKey = if parent.id? then "precondition_#{parent.id}" else parent.key || parent.type
# we are negated if the parent is negated and the parent is a precondition. If it's a data criteria, then negation is fine
negated = parent.negation && parent.id?
# do not bubble up negated unless we have no final specifics. If we have no final specifics then we may not have positive statements to bubble up.
if updatedRationale[code][parentKey] != false && (!negated || _.isEmpty(finalSpecifics[code]))
# if this is an OR then remove a true increment since it's a bad true
orCounts[parentKey]-- if orCounts[parentKey]?
# if we're either an AND or we're an OR and the count is zero then switch to false and move up the tree
if ((!orCounts[parentKey]? || orCounts[parentKey] == 0) && (!!rationale[parentKey] == true || rationale[parentKey] == undefined))
updatedRationale[code][parentKey] = false if rationale[parentKey]?
@updateLogicTreeChildren(updatedRationale, rationale, code, parentMap[parentKey], orCounts, parentMap)
buildParentMap: (root) ->
dataCriteriaMap = @measure.get('data_criteria')
parentMap = {}
return parentMap unless root
if root.preconditions?.length > 0
for precondition in root.preconditions
parentMap["precondition_#{precondition.id}"] = (parentMap["precondition_#{precondition.id}"] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(precondition))
else if root.reference?
parentMap[root.reference] = (parentMap[root.reference] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[root.reference]))
else
if root.temporal_references?
for temporal_reference in root.temporal_references
if temporal_reference.reference != 'MeasurePeriod'
parentMap[temporal_reference.reference] = (parentMap[temporal_reference.reference] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[temporal_reference.reference]))
if root.children_criteria
for child in root.children_criteria
parentMap[child] = (parentMap[child] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[child]))
parentMap
mergeParentMaps: (left, right) ->
for key,value of right
if (left[key])
left[key] = left[key].concat right[key]
else
left[key] = right[key]
left
# Or counts are used to know when to turn an OR from green to red. Once we negate all the true ors, we can switch to red
calculateOrCounts: (rationale) ->
orCounts = {}
for code in Thorax.Models.Measure.allPopulationCodes
if populationCriteria = @population.get(code)
_.extend(orCounts, @calculateOrCountsRecursive(rationale, populationCriteria.preconditions))
_.extend(orCounts, @calculateDataCriteriaOrCounts(rationale))
# recursively walk preconditions to count true values for child ORs moving down the tree
calculateOrCountsRecursive: (rationale, preconditions) ->
orCounts = {}
return orCounts unless preconditions? && preconditions.length > 0
for precondition in preconditions
if (precondition.conjunction_code == 'atLeastOneTrue' && !precondition.negation)
trueCount = 0
if precondition.preconditions?.length > 0
for child in precondition.preconditions
if (child.preconditions)
key = "precondition_#{child.id}"
else
key = child.reference
trueCount += 1 if rationale[key]
orCounts["precondition_#{precondition.id}"] = trueCount
_.extend(orCounts, @calculateOrCountsRecursive(rationale, precondition.preconditions))
return orCounts
# walk through data criteria to account for specific occurrences within a UNION
calculateDataCriteriaOrCounts: (rationale) ->
orCounts = {}
for key, dc of @measure.get('data_criteria') when dc.derivation_operator == 'UNION' && key.indexOf('UNION') != -1
for child in dc.children_criteria
orCounts[key] = (orCounts[key] || 0) + 1 if rationale[key]
orCounts
codedEntriesForDataCriteria: (dataCriteriaKey) ->
@get('rationale')[dataCriteriaKey]?['results']
codedEntriesPassingSpecifics: (dataCriteriaKey, populationCriteriaKey) ->
index = hqmf.SpecificsManager.indexLookup[@measure.get('data_criteria')[dataCriteriaKey].source_data_criteria]
goodElements = (row[index] for row in @get('finalSpecifics')[populationCriteriaKey]) if index? and @get('finalSpecifics')?[populationCriteriaKey]?
class Thorax.Collections.Results extends Thorax.Collection
model: Thorax.Models.Result
initialize: (models, options) -> @parent = options?.parent
| 202614 | class Thorax.Models.Result extends Thorax.Model
initialize: (attrs, options) ->
@population = options.population
@measure = @population.collection.parent
@patient = options.patient
# Provide a deferred that allows usage of a result to be deferred until it's populated
@calculation = $.Deferred()
if @isPopulated() then @calculation.resolve() else @once 'change:rationale', -> @calculation.resolve()
# When a patient changes, is materialized, or is destroyed, we need to respond appropriately
@listenTo @patient, 'change materialize destroy', =>
bonnie.calculator.clearResult(@population, @patient) # Remove the result from the cache
@destroy() # Destroy the result to remove it from any collections
isPopulated: -> @has('rationale')
differenceFromExpected: ->
expected = @patient.getExpectedValue @population
new Thorax.Models.Difference({}, result: this, expected: expected)
specificsRationale: ->
updatedRationale = {}
rationale = @get('rationale')
orCounts = @calculateOrCounts(rationale)
for code in Thorax.Models.Measure.allPopulationCodes
if specifics = @get('finalSpecifics')?[code]
updatedRationale[code] = {}
# get the referenced occurrences in the logic tree using original population code
occurrences = _.uniq @population.getDataCriteriaKeys(@measure.get('population_criteria')[@population.get(code)?.code])
# get the good and bad specifics
occurrenceResults = @checkSpecificsForRationale(specifics, occurrences, @measure.get('data_criteria'))
submeasureCode = @population.get(code)?.code || code
parentMap = @buildParentMap(@measure.get('population_criteria')[submeasureCode])
# check each bad occurrence and remove highlights marking true
for badOccurrence in occurrenceResults.bad
if (rationale[badOccurrence])
updatedRationale[code][badOccurrence] = false
# move up the logic tree to set AND/ORs to false based on the removal of the bad specific's true eval
@updateLogicTree(updatedRationale, rationale, code, badOccurrence, orCounts, parentMap)
# check the good specifics with a negated parent. If there are multiple candidate specifics
# and one is good while the other is bad, the child of the negation will evaluate to true, we want it to
# evaluate to false since if there's a good negation then there's an occurrence for which it evaluated to false
for goodOccurrence in occurrenceResults.good
@updatedNegatedGood(updatedRationale[code], rationale, goodOccurrence, parentMap)
return updatedRationale
updatedRationale: ->
updatedRationale = @specificsRationale()
currentRationale = @get 'rationale'
cleanup = []
for code in @population.populationCriteria() when currentRationale[code]?
for key, value of currentRationale
if _(updatedRationale).has(code) and updatedRationale[code][key] is false then cleanup.push(key)
_(currentRationale).omit(cleanup)
updatedNegatedGood: (updatedRationale, rationale, goodOccurrence, parentMap) ->
parent = parentMap[goodOccurrence]
while parent
if (parent.negation && rationale[goodOccurrence])
updatedRationale[goodOccurrence] = false
return
parent = parentMap["precondition_#{parent.id}"]
# get good and bad specific occurrences referenced in this part of the measure
checkSpecificsForRationale: (finalSpecifics, occurrences, dataCriteriaMap) ->
results = {bad: occurrences, good: []}
# if we dont't have any specifics rows then they are all bad
return results if finalSpecifics.length == 0
results.bad = []
# check for good and bad specifics. Bad will be used to clear out logical true values that are false
# when specifics are applied. Good will be used to fix negations of specific occurrences
for occurrence in occurrences
index = hqmf.SpecificsManager.indexLookup[dataCriteriaMap[occurrence].source_data_criteria]
good = false
# we're good if the occurrence is referenced by ID, Any indicates that we did not use it in the true path, thus it's bad
for row in finalSpecifics
good = true if row[index] != hqmf.SpecificsManager.any
if good then results.good.push(occurrence) else results.bad.push(occurrence)
results
# from each leaf walk up the tree updating the logical statements appropriately to false
updateLogicTree: (updatedRationale, rationale, code, badOccurrence, orCounts, parentMap) ->
parents = parentMap[badOccurrence]
@updateLogicTreeChildren(updatedRationale, rationale, code, parents, orCounts, parentMap)
updateLogicTreeChildren: (updatedRationale, rationale, code, parents, orCounts, parentMap) ->
return unless parents
for parent in parents
parentKey = if parent.id? then "pre<KEY>#{parent.id}" else parent.key || parent.type
# we are negated if the parent is negated and the parent is a precondition. If it's a data criteria, then negation is fine
negated = parent.negation && parent.id?
# do not bubble up negated unless we have no final specifics. If we have no final specifics then we may not have positive statements to bubble up.
if updatedRationale[code][parentKey] != false && (!negated || _.isEmpty(finalSpecifics[code]))
# if this is an OR then remove a true increment since it's a bad true
orCounts[parentKey]-- if orCounts[parentKey]?
# if we're either an AND or we're an OR and the count is zero then switch to false and move up the tree
if ((!orCounts[parentKey]? || orCounts[parentKey] == 0) && (!!rationale[parentKey] == true || rationale[parentKey] == undefined))
updatedRationale[code][parentKey] = false if rationale[parentKey]?
@updateLogicTreeChildren(updatedRationale, rationale, code, parentMap[parentKey], orCounts, parentMap)
buildParentMap: (root) ->
dataCriteriaMap = @measure.get('data_criteria')
parentMap = {}
return parentMap unless root
if root.preconditions?.length > 0
for precondition in root.preconditions
parentMap["precondition_#{precondition.id}"] = (parentMap["precondition_#{precondition.id}"] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(precondition))
else if root.reference?
parentMap[root.reference] = (parentMap[root.reference] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[root.reference]))
else
if root.temporal_references?
for temporal_reference in root.temporal_references
if temporal_reference.reference != 'MeasurePeriod'
parentMap[temporal_reference.reference] = (parentMap[temporal_reference.reference] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[temporal_reference.reference]))
if root.children_criteria
for child in root.children_criteria
parentMap[child] = (parentMap[child] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[child]))
parentMap
mergeParentMaps: (left, right) ->
for key,value of right
if (left[key])
left[key] = left[key].concat right[key]
else
left[key] = right[key]
left
# Or counts are used to know when to turn an OR from green to red. Once we negate all the true ors, we can switch to red
calculateOrCounts: (rationale) ->
orCounts = {}
for code in Thorax.Models.Measure.allPopulationCodes
if populationCriteria = @population.get(code)
_.extend(orCounts, @calculateOrCountsRecursive(rationale, populationCriteria.preconditions))
_.extend(orCounts, @calculateDataCriteriaOrCounts(rationale))
# recursively walk preconditions to count true values for child ORs moving down the tree
calculateOrCountsRecursive: (rationale, preconditions) ->
orCounts = {}
return orCounts unless preconditions? && preconditions.length > 0
for precondition in preconditions
if (precondition.conjunction_code == 'atLeastOneTrue' && !precondition.negation)
trueCount = 0
if precondition.preconditions?.length > 0
for child in precondition.preconditions
if (child.preconditions)
key = "pre<KEY>child.<KEY>}"
else
key = child.reference
trueCount += 1 if rationale[key]
orCounts["precondition_#{precondition.id}"] = trueCount
_.extend(orCounts, @calculateOrCountsRecursive(rationale, precondition.preconditions))
return orCounts
# walk through data criteria to account for specific occurrences within a UNION
calculateDataCriteriaOrCounts: (rationale) ->
orCounts = {}
for key, dc of @measure.get('data_criteria') when dc.derivation_operator == 'UNION' && key.indexOf('UNION') != -1
for child in dc.children_criteria
orCounts[key] = (orCounts[key] || 0) + 1 if rationale[key]
orCounts
codedEntriesForDataCriteria: (dataCriteriaKey) ->
@get('rationale')[dataCriteriaKey]?['results']
codedEntriesPassingSpecifics: (dataCriteriaKey, populationCriteriaKey) ->
index = hqmf.SpecificsManager.indexLookup[@measure.get('data_criteria')[dataCriteriaKey].source_data_criteria]
goodElements = (row[index] for row in @get('finalSpecifics')[populationCriteriaKey]) if index? and @get('finalSpecifics')?[populationCriteriaKey]?
class Thorax.Collections.Results extends Thorax.Collection
model: Thorax.Models.Result
initialize: (models, options) -> @parent = options?.parent
| true | class Thorax.Models.Result extends Thorax.Model
initialize: (attrs, options) ->
@population = options.population
@measure = @population.collection.parent
@patient = options.patient
# Provide a deferred that allows usage of a result to be deferred until it's populated
@calculation = $.Deferred()
if @isPopulated() then @calculation.resolve() else @once 'change:rationale', -> @calculation.resolve()
# When a patient changes, is materialized, or is destroyed, we need to respond appropriately
@listenTo @patient, 'change materialize destroy', =>
bonnie.calculator.clearResult(@population, @patient) # Remove the result from the cache
@destroy() # Destroy the result to remove it from any collections
isPopulated: -> @has('rationale')
differenceFromExpected: ->
expected = @patient.getExpectedValue @population
new Thorax.Models.Difference({}, result: this, expected: expected)
specificsRationale: ->
updatedRationale = {}
rationale = @get('rationale')
orCounts = @calculateOrCounts(rationale)
for code in Thorax.Models.Measure.allPopulationCodes
if specifics = @get('finalSpecifics')?[code]
updatedRationale[code] = {}
# get the referenced occurrences in the logic tree using original population code
occurrences = _.uniq @population.getDataCriteriaKeys(@measure.get('population_criteria')[@population.get(code)?.code])
# get the good and bad specifics
occurrenceResults = @checkSpecificsForRationale(specifics, occurrences, @measure.get('data_criteria'))
submeasureCode = @population.get(code)?.code || code
parentMap = @buildParentMap(@measure.get('population_criteria')[submeasureCode])
# check each bad occurrence and remove highlights marking true
for badOccurrence in occurrenceResults.bad
if (rationale[badOccurrence])
updatedRationale[code][badOccurrence] = false
# move up the logic tree to set AND/ORs to false based on the removal of the bad specific's true eval
@updateLogicTree(updatedRationale, rationale, code, badOccurrence, orCounts, parentMap)
# check the good specifics with a negated parent. If there are multiple candidate specifics
# and one is good while the other is bad, the child of the negation will evaluate to true, we want it to
# evaluate to false since if there's a good negation then there's an occurrence for which it evaluated to false
for goodOccurrence in occurrenceResults.good
@updatedNegatedGood(updatedRationale[code], rationale, goodOccurrence, parentMap)
return updatedRationale
updatedRationale: ->
updatedRationale = @specificsRationale()
currentRationale = @get 'rationale'
cleanup = []
for code in @population.populationCriteria() when currentRationale[code]?
for key, value of currentRationale
if _(updatedRationale).has(code) and updatedRationale[code][key] is false then cleanup.push(key)
_(currentRationale).omit(cleanup)
updatedNegatedGood: (updatedRationale, rationale, goodOccurrence, parentMap) ->
parent = parentMap[goodOccurrence]
while parent
if (parent.negation && rationale[goodOccurrence])
updatedRationale[goodOccurrence] = false
return
parent = parentMap["precondition_#{parent.id}"]
# get good and bad specific occurrences referenced in this part of the measure
checkSpecificsForRationale: (finalSpecifics, occurrences, dataCriteriaMap) ->
results = {bad: occurrences, good: []}
# if we dont't have any specifics rows then they are all bad
return results if finalSpecifics.length == 0
results.bad = []
# check for good and bad specifics. Bad will be used to clear out logical true values that are false
# when specifics are applied. Good will be used to fix negations of specific occurrences
for occurrence in occurrences
index = hqmf.SpecificsManager.indexLookup[dataCriteriaMap[occurrence].source_data_criteria]
good = false
# we're good if the occurrence is referenced by ID, Any indicates that we did not use it in the true path, thus it's bad
for row in finalSpecifics
good = true if row[index] != hqmf.SpecificsManager.any
if good then results.good.push(occurrence) else results.bad.push(occurrence)
results
# from each leaf walk up the tree updating the logical statements appropriately to false
updateLogicTree: (updatedRationale, rationale, code, badOccurrence, orCounts, parentMap) ->
parents = parentMap[badOccurrence]
@updateLogicTreeChildren(updatedRationale, rationale, code, parents, orCounts, parentMap)
updateLogicTreeChildren: (updatedRationale, rationale, code, parents, orCounts, parentMap) ->
return unless parents
for parent in parents
parentKey = if parent.id? then "prePI:KEY:<KEY>END_PI#{parent.id}" else parent.key || parent.type
# we are negated if the parent is negated and the parent is a precondition. If it's a data criteria, then negation is fine
negated = parent.negation && parent.id?
# do not bubble up negated unless we have no final specifics. If we have no final specifics then we may not have positive statements to bubble up.
if updatedRationale[code][parentKey] != false && (!negated || _.isEmpty(finalSpecifics[code]))
# if this is an OR then remove a true increment since it's a bad true
orCounts[parentKey]-- if orCounts[parentKey]?
# if we're either an AND or we're an OR and the count is zero then switch to false and move up the tree
if ((!orCounts[parentKey]? || orCounts[parentKey] == 0) && (!!rationale[parentKey] == true || rationale[parentKey] == undefined))
updatedRationale[code][parentKey] = false if rationale[parentKey]?
@updateLogicTreeChildren(updatedRationale, rationale, code, parentMap[parentKey], orCounts, parentMap)
buildParentMap: (root) ->
dataCriteriaMap = @measure.get('data_criteria')
parentMap = {}
return parentMap unless root
if root.preconditions?.length > 0
for precondition in root.preconditions
parentMap["precondition_#{precondition.id}"] = (parentMap["precondition_#{precondition.id}"] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(precondition))
else if root.reference?
parentMap[root.reference] = (parentMap[root.reference] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[root.reference]))
else
if root.temporal_references?
for temporal_reference in root.temporal_references
if temporal_reference.reference != 'MeasurePeriod'
parentMap[temporal_reference.reference] = (parentMap[temporal_reference.reference] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[temporal_reference.reference]))
if root.children_criteria
for child in root.children_criteria
parentMap[child] = (parentMap[child] || []).concat root
@mergeParentMaps(parentMap, @buildParentMap(dataCriteriaMap[child]))
parentMap
mergeParentMaps: (left, right) ->
for key,value of right
if (left[key])
left[key] = left[key].concat right[key]
else
left[key] = right[key]
left
# Or counts are used to know when to turn an OR from green to red. Once we negate all the true ors, we can switch to red
calculateOrCounts: (rationale) ->
orCounts = {}
for code in Thorax.Models.Measure.allPopulationCodes
if populationCriteria = @population.get(code)
_.extend(orCounts, @calculateOrCountsRecursive(rationale, populationCriteria.preconditions))
_.extend(orCounts, @calculateDataCriteriaOrCounts(rationale))
# recursively walk preconditions to count true values for child ORs moving down the tree
calculateOrCountsRecursive: (rationale, preconditions) ->
orCounts = {}
return orCounts unless preconditions? && preconditions.length > 0
for precondition in preconditions
if (precondition.conjunction_code == 'atLeastOneTrue' && !precondition.negation)
trueCount = 0
if precondition.preconditions?.length > 0
for child in precondition.preconditions
if (child.preconditions)
key = "prePI:KEY:<KEY>END_PIchild.PI:KEY:<KEY>END_PI}"
else
key = child.reference
trueCount += 1 if rationale[key]
orCounts["precondition_#{precondition.id}"] = trueCount
_.extend(orCounts, @calculateOrCountsRecursive(rationale, precondition.preconditions))
return orCounts
# walk through data criteria to account for specific occurrences within a UNION
calculateDataCriteriaOrCounts: (rationale) ->
orCounts = {}
for key, dc of @measure.get('data_criteria') when dc.derivation_operator == 'UNION' && key.indexOf('UNION') != -1
for child in dc.children_criteria
orCounts[key] = (orCounts[key] || 0) + 1 if rationale[key]
orCounts
codedEntriesForDataCriteria: (dataCriteriaKey) ->
@get('rationale')[dataCriteriaKey]?['results']
codedEntriesPassingSpecifics: (dataCriteriaKey, populationCriteriaKey) ->
index = hqmf.SpecificsManager.indexLookup[@measure.get('data_criteria')[dataCriteriaKey].source_data_criteria]
goodElements = (row[index] for row in @get('finalSpecifics')[populationCriteriaKey]) if index? and @get('finalSpecifics')?[populationCriteriaKey]?
class Thorax.Collections.Results extends Thorax.Collection
model: Thorax.Models.Result
initialize: (models, options) -> @parent = options?.parent
|
[
{
"context": "its foes. Beware the finishing blow.\n *\n * @name Rogue\n * @physical\n * @dps\n * @hp 70+[level*10]+[con",
"end": 143,
"score": 0.8981744647026062,
"start": 138,
"tag": "NAME",
"value": "Rogue"
},
{
"context": "pecial.__current = 100\n player.special.name = \"... | src/character/classes/Rogue.coffee | sadbear-/IdleLands | 0 |
Class = require "./../base/Class"
`/**
* This class performs many deadly combos on its foes. Beware the finishing blow.
*
* @name Rogue
* @physical
* @dps
* @hp 70+[level*10]+[con*6]
* @mp [level*1]+[int*1]
* @special Stamina (The Rogue gets 100 stamina with which they can use skills that combo their foes.)
* @itemScore con*2 + agi*1.5 + dex*1.5 - int - wis - luck*0.2
* @statPerLevel {str} 2
* @statPerLevel {dex} 4
* @statPerLevel {con} 2
* @statPerLevel {int} 1
* @statPerLevel {wis} 0
* @statPerLevel {agi} 4
* @minDamage 37%
* @category Classes
* @package Player
*/`
class Rogue extends Class
baseHp: 70
baseHpPerLevel: 10
baseHpPerCon: 6
baseMp: 0
baseMpPerLevel: 1
baseMpPerInt: 1
baseConPerLevel: 2
baseDexPerLevel: 4
baseAgiPerLevel: 4
baseStrPerLevel: 2
baseIntPerLevel: 1
baseWisPerLevel: 0
itemScore: (player, item) ->
item.agi*1.4 +
item.dex*1.4 +
item.str*0.3 +
item.con*0.2 -
item.wis*0.8 -
item.int*0.8
physicalAttackChance: -> -40
minDamage: (player) ->
player.calc.damage()*0.37
updateCombo: (spell) ->
@lastComboSkill = spell.baseName
@lastComboSkillTurn = 4
resetCombo: ->
@lastComboSkill = null
@lastComboSkillTurn = 0
events: {}
load: (player) ->
super player
player.special.maximum = 100
player.special.__current = 100
player.special.name = "Stamina"
player.on "combat.battle.start", @events.combatStart = =>
@resetCombo()
player.special.toMaximum()
player.on "combat.round.start", @events.roundStart = =>
player.special.add 2
@lastComboSkillTurn-- if @lastComboSkillTurn > 0
@lastComboSkill = null if @lastComboSkillTurn <= 0
unload: (player) ->
player.special.maximum = 0
player.special.name = ""
player.off "combat.battle.start", @events.combatStart
player.off "combat.round.start", @events.roundStart
module.exports = exports = Rogue
| 191762 |
Class = require "./../base/Class"
`/**
* This class performs many deadly combos on its foes. Beware the finishing blow.
*
* @name <NAME>
* @physical
* @dps
* @hp 70+[level*10]+[con*6]
* @mp [level*1]+[int*1]
* @special Stamina (The Rogue gets 100 stamina with which they can use skills that combo their foes.)
* @itemScore con*2 + agi*1.5 + dex*1.5 - int - wis - luck*0.2
* @statPerLevel {str} 2
* @statPerLevel {dex} 4
* @statPerLevel {con} 2
* @statPerLevel {int} 1
* @statPerLevel {wis} 0
* @statPerLevel {agi} 4
* @minDamage 37%
* @category Classes
* @package Player
*/`
class Rogue extends Class
baseHp: 70
baseHpPerLevel: 10
baseHpPerCon: 6
baseMp: 0
baseMpPerLevel: 1
baseMpPerInt: 1
baseConPerLevel: 2
baseDexPerLevel: 4
baseAgiPerLevel: 4
baseStrPerLevel: 2
baseIntPerLevel: 1
baseWisPerLevel: 0
itemScore: (player, item) ->
item.agi*1.4 +
item.dex*1.4 +
item.str*0.3 +
item.con*0.2 -
item.wis*0.8 -
item.int*0.8
physicalAttackChance: -> -40
minDamage: (player) ->
player.calc.damage()*0.37
updateCombo: (spell) ->
@lastComboSkill = spell.baseName
@lastComboSkillTurn = 4
resetCombo: ->
@lastComboSkill = null
@lastComboSkillTurn = 0
events: {}
load: (player) ->
super player
player.special.maximum = 100
player.special.__current = 100
player.special.name = "<NAME>"
player.on "combat.battle.start", @events.combatStart = =>
@resetCombo()
player.special.toMaximum()
player.on "combat.round.start", @events.roundStart = =>
player.special.add 2
@lastComboSkillTurn-- if @lastComboSkillTurn > 0
@lastComboSkill = null if @lastComboSkillTurn <= 0
unload: (player) ->
player.special.maximum = 0
player.special.name = ""
player.off "combat.battle.start", @events.combatStart
player.off "combat.round.start", @events.roundStart
module.exports = exports = Rogue
| true |
Class = require "./../base/Class"
`/**
* This class performs many deadly combos on its foes. Beware the finishing blow.
*
* @name PI:NAME:<NAME>END_PI
* @physical
* @dps
* @hp 70+[level*10]+[con*6]
* @mp [level*1]+[int*1]
* @special Stamina (The Rogue gets 100 stamina with which they can use skills that combo their foes.)
* @itemScore con*2 + agi*1.5 + dex*1.5 - int - wis - luck*0.2
* @statPerLevel {str} 2
* @statPerLevel {dex} 4
* @statPerLevel {con} 2
* @statPerLevel {int} 1
* @statPerLevel {wis} 0
* @statPerLevel {agi} 4
* @minDamage 37%
* @category Classes
* @package Player
*/`
class Rogue extends Class
baseHp: 70
baseHpPerLevel: 10
baseHpPerCon: 6
baseMp: 0
baseMpPerLevel: 1
baseMpPerInt: 1
baseConPerLevel: 2
baseDexPerLevel: 4
baseAgiPerLevel: 4
baseStrPerLevel: 2
baseIntPerLevel: 1
baseWisPerLevel: 0
itemScore: (player, item) ->
item.agi*1.4 +
item.dex*1.4 +
item.str*0.3 +
item.con*0.2 -
item.wis*0.8 -
item.int*0.8
physicalAttackChance: -> -40
minDamage: (player) ->
player.calc.damage()*0.37
updateCombo: (spell) ->
@lastComboSkill = spell.baseName
@lastComboSkillTurn = 4
resetCombo: ->
@lastComboSkill = null
@lastComboSkillTurn = 0
events: {}
load: (player) ->
super player
player.special.maximum = 100
player.special.__current = 100
player.special.name = "PI:NAME:<NAME>END_PI"
player.on "combat.battle.start", @events.combatStart = =>
@resetCombo()
player.special.toMaximum()
player.on "combat.round.start", @events.roundStart = =>
player.special.add 2
@lastComboSkillTurn-- if @lastComboSkillTurn > 0
@lastComboSkill = null if @lastComboSkillTurn <= 0
unload: (player) ->
player.special.maximum = 0
player.special.name = ""
player.off "combat.battle.start", @events.combatStart
player.off "combat.round.start", @events.roundStart
module.exports = exports = Rogue
|
[
{
"context": "umns.Dribbble extends Columns.FeedColumn\n name: \"Dribbble\"\n width: 2\n thumb: \"img/column-dribble.p",
"end": 60,
"score": 0.806557834148407,
"start": 59,
"tag": "NAME",
"value": "D"
},
{
"context": "dribbble.com/v1/shots?page={PAGENUM}&access_token=74f8fb9f92c1f... | src/columns/dribbble/Dribbble.coffee | jariz/hackertab | 548 | class Columns.Dribbble extends Columns.FeedColumn
name: "Dribbble"
width: 2
thumb: "img/column-dribble.png"
link: "https://dribbble.com"
element: "dribbble-item"
url: "https://api.dribbble.com/v1/shots?page={PAGENUM}&access_token=74f8fb9f92c1f79c4bc3662f708dfdce7cd05c3fc67ac84ae68ff47568b71a1f"
infiniteScroll: true
flex: true
tabbie.register "Dribbble" | 8918 | class Columns.Dribbble extends Columns.FeedColumn
name: "<NAME>ribbble"
width: 2
thumb: "img/column-dribble.png"
link: "https://dribbble.com"
element: "dribbble-item"
url: "https://api.dribbble.com/v1/shots?page={PAGENUM}&access_token=<KEY>"
infiniteScroll: true
flex: true
tabbie.register "Dribbble" | true | class Columns.Dribbble extends Columns.FeedColumn
name: "PI:NAME:<NAME>END_PIribbble"
width: 2
thumb: "img/column-dribble.png"
link: "https://dribbble.com"
element: "dribbble-item"
url: "https://api.dribbble.com/v1/shots?page={PAGENUM}&access_token=PI:KEY:<KEY>END_PI"
infiniteScroll: true
flex: true
tabbie.register "Dribbble" |
[
{
"context": "on't work reliable in phantomjs\n\n\t\t\ttext = \"Hello Koen Bok\"\n\t\t\tstyle = {font:\"20px/1em Menlo\"}\n\n\t\t\t# it \"sho",
"end": 6122,
"score": 0.9957743287086487,
"start": 6114,
"tag": "NAME",
"value": "Koen Bok"
},
{
"context": "uld.equal(true)\n\t\t\tUtils.i... | test/tests/UtilsTest.coffee | HydAu/FramerJS | 0 |
describe "Utils", ->
describe "valueOrDefault", ->
it "should get a value", ->
Utils.valueOrDefault(10, 0).should.equal 10
it "should get the default value", ->
Utils.valueOrDefault(null, 0).should.equal 0
# it "should get the fallback value", ->
# Utils.valueOrDefault(undefined, undefined, 0).should.equal 0
describe "arrayFromArguments", ->
it "should work", ->
f = -> return Utils.arrayFromArguments arguments
f("a").should.eql ["a"]
f("a", "b").should.eql ["a", "b"]
f(["a"]).should.eql ["a"]
f(["a", "b"]).should.eql ["a", "b"]
f("monkey").should.eql ["monkey"]
f(["monkey"]).should.eql ["monkey"]
describe "parseFunction", ->
it "should work without arguments", ->
result = Utils.parseFunction "spring"
result.name.should.equal "spring"
result.args.should.eql []
it "should work with a single argument", ->
result = Utils.parseFunction "spring(100)"
result.name.should.equal "spring"
result.args.should.eql ["100"]
it "should work with multiple arguments", ->
result = Utils.parseFunction "spring(100,50)"
result.name.should.equal "spring"
result.args.should.eql ["100", "50"]
it "should cleanup arguments", ->
result = Utils.parseFunction "spring(100 , 50 )"
result.name.should.equal "spring"
result.args.should.eql ["100", "50"]
describe "arrayNext", ->
it "should work", ->
Utils.arrayNext(["a", "b", "c"], "a").should.equal "b"
Utils.arrayNext(["a", "b", "c"], "b").should.equal "c"
Utils.arrayNext(["a", "b", "c"], "c").should.equal "a"
describe "arrayPrev", ->
it "should work", ->
Utils.arrayPrev(["a", "b", "c"], "a").should.equal "c"
Utils.arrayPrev(["a", "b", "c"], "b").should.equal "a"
Utils.arrayPrev(["a", "b", "c"], "c").should.equal "b"
describe "sizeMax", ->
it "should work", ->
Utils.sizeMax([
{width:100, height:100},
{width:100, height:100},
]).should.eql {width:100, height:100}
Utils.sizeMax([
{width:1000, height:1000},
{width:100, height:100},
]).should.eql {width:1000, height:1000}
describe "pathJoin", ->
it "should work", ->
Utils.pathJoin("test", "monkey").should.equal "test/monkey"
describe "sizeMin", ->
it "should work", ->
Utils.sizeMin([
{width:100, height:100},
{width:100, height:100},
]).should.eql {width:100, height:100}
Utils.sizeMin([
{width:1000, height:1000},
{width:100, height:100},
]).should.eql {width:100, height:100}
describe "points", ->
it "should get points from frame", ->
frame = {x:200, y:-60, width:200, height:200}
points = Utils.pointsFromFrame(frame)
points.length.should.eql 4
points[0].x.should.eql 200
points[1].y.should.eql 140
points[3].y.should.eql -60
it "should get frame from points", ->
points = [{x:200, y:-60}, {x:200, y:140}, {x:400, y:140}, {x:400, y:-60}]
frame = Utils.frameFromPoints(points)
frame.x.should.eql 200
frame.y.should.eql -60
frame.width.should.eql 200
frame.height.should.eql 200
describe "frameMerge", ->
it "should work", ->
compare = (frames, result) ->
frame = Utils.frameMerge frames
for p in ["x", "y", "width", "height"]
frame[p].should.equal result[p], p
compare [
{x:0, y:0, width:100, height:100},
{x:0, y:0, width:100, height:100},
], {x:0, y:0, width:100, height:100}
compare [
{x:0, y:0, width:100, height:100},
{x:0, y:0, width:500, height:500},
], {x:0, y:0, width:500, height:500}
compare [
{x:0, y:0, width:100, height:100},
{x:100, y:100, width:500, height:500},
], {x:0, y:0, width:600, height:600}
compare [
{x:100, y:100, width:100, height:100},
{x:100, y:100, width:500, height:500},
], {x:100, y:100, width:500, height:500}
# Bla bla. This works. Doing a visual comparison is so much easier
# Start the cactus project and go to /test.html
describe "framePointForOrigin", ->
it "should work", ->
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
# describe "domLoadData", (callback) ->
# it "should load data async", (callback) ->
# data = Utils.domLoadData "static/test.txt", (err, data) ->
# data.should.equal "TEST HELLO"
# callback()
# it "should load throw error on nonexisting", (callback) ->
# data = Utils.domLoadData "static/test123.txt", (err, data) ->
# err.should.equal true
# callback()
# describe "domLoadDataSync", ->
# it "should load data async", ->
# data = Utils.domLoadDataSync "static/test.txt"
# data.should.equal "TEST HELLO"
# it "should load throw error on nonexisting", ->
# test = -> Utils.domLoadDataSync("static/nonexisting.txt")
# test.should.throw()
describe "modulate", ->
it "should have the right results", ->
Utils.modulate(0.5, [0, 1], [0, 100]).should.equal 50
Utils.modulate(1, [0, 1], [0, 100]).should.equal 100
Utils.modulate(2, [0, 1], [0, 100], true).should.equal 100
Utils.modulate(2, [0, 1], [0, 100], false).should.equal 200
Utils.modulate(0, [1, 2], [0, 100], true).should.equal 0
Utils.modulate(0, [1, 2], [0, 100], false).should.equal -100
Utils.modulate(0, [1, 2], [100, 0], true).should.equal 100
Utils.modulate(0, [1, 2], [100, 0], false).should.equal 200
describe "clamp", ->
it "should have the right results", ->
Utils.clamp(3, 4, 6).should.equal 4
Utils.clamp(3, 6, 4).should.equal 4
Utils.clamp(5, 6, 4).should.equal 5
Utils.clamp(5, 6, -4).should.equal 5
describe "textSize", ->
it "should have the right text size", ->
# Todo: for some reason these don't work reliable in phantomjs
text = "Hello Koen Bok"
style = {font:"20px/1em Menlo"}
# it "should return the right size", ->
# Utils.textSize(text, style).should.eql({width:168, height:20})
# it "should return the right size with width constraint", ->
# Utils.textSize(text, style, {width:100}).should.eql({width:100, height:40})
# it "should return the right size with height constraint", ->
# Utils.textSize(text, style, {height:100}).should.eql(width:168,height:100)
describe "frameSortByAbsoluteDistance", ->
it "should sort x", ->
layerA = new Layer x:300, y:100
layerB = new Layer x:100, y:100
layerC = new Layer x:200, y:100
Utils.frameSortByAbsoluteDistance({x:0, y:0}, [layerA, layerB, layerC]).should.eql([layerB, layerC, layerA])
it "should sort", ->
layerA = new Layer x:500, y:500
layerB = new Layer x:300, y:300
layerC = new Layer x:100, y:100
Utils.frameSortByAbsoluteDistance({x:0, y:0}, [layerA, layerB, layerC]).should.eql([layerC, layerB, layerA])
describe "inspect", ->
it "should work for strings", ->
Utils.inspect("a").should.equal("\"a\"")
it "should work for booleans", ->
Utils.inspect(true).should.equal("true")
it "should work for numbers", ->
Utils.inspect(12.34).should.equal("12.34")
it "should work for null", ->
Utils.inspect(null).should.equal("null")
it "should work for undefined", ->
Utils.inspect(undefined).should.equal("undefined")
it "should work for arrays", ->
Utils.inspect(["a", 1, ["b", "c"]]).should.equal("[\"a\", 1, [\"b\", \"c\"]]")
it "should work for objects", ->
Utils.inspect({a:1, b:[1, 2, 3]}).should.equal("{a:1, b:[1, 2, 3]}")
it "should work for functions", ->
test = -> return "a"
Utils.inspect(test).should.equal("<Function () { return \"a\"; }>")
it "should work for functions with arguments", ->
test = (a) -> return "a"
Utils.inspect(test).should.equal("<Function (a) { return \"a\"; }>")
it "should work for named functions", ->
# There are no named function in coffee script
`function test(a) { return "a"; }`
Utils.inspect(test).should.equal("<Function test(a) { return \"a\"; }>")
it "should work for long functions", ->
test = ->
its = 1
very = 1
rainy = 1
today = 1
down = 1
here = 1
return "a"
Utils.inspect(test).should.equal("<Function () { var down, here, its, rainy, today, very; its = 1; very = 1; rainy = 1; today = 1; down = 1; here = 1; return \"a\"; }>")
Utils.inspect([test]).should.equal("[<Function () { var down, here, its, rainy, today, very; its =… }>]")
it "should work for classes", ->
class TestClass
constructor: ->
@a = 1
instance = new TestClass
Utils.inspect(instance).should.equal("<TestClass {a:1}>")
it "should work for subclasses", ->
class TestClass
constructor: ->
@a = 1
class SubTestClass extends TestClass
instance = new SubTestClass
Utils.inspect(instance).should.equal("<SubTestClass {a:1}>")
it "should work with Colors", ->
instance = new Color "red"
Utils.inspect(instance).should.equal("<Color \"red\">")
instance = new Color "#28affa"
Utils.inspect(instance).should.equal("<Color \"#28affa\">")
instance = new Color
r: 200
g: 100
b: 20
a: 1
Utils.inspect(instance).should.equal("<Color r:200 g:100 b:20 a:1>")
instance = new Color
h: 200
s: 1
l: .2
a: 1
Utils.inspect(instance).should.equal("<Color h:200 s:1 l:0.2 a:1>")
it "should work with toInspect", ->
class TestClass
toInspect: -> return "Hello"
instance = new TestClass
Utils.inspect(instance).should.equal("Hello")
it "should work with WebKitCSSMatrix", ->
instance = new WebKitCSSMatrix()
Utils.inspect(instance).should.equal("<WebKitCSSMatrix {e:0, m33:1, f:0, m42:0, m44:1, m24:0, m31:0, m32:0, m21:0, m14:0, c:0, m34:0, m13:0, m12:0, m11:1, m41:0, m23:0, b:0, d:1, m22:1, a:1, m43:0}>")
it "should work with HTMLDivElement", ->
instance = document.createElement("div")
Utils.inspect(instance).should.equal("<HTMLDivElement>")
it "should work with HTMLDivElementConstructor", ->
instance = document.createElement("div")
Utils.inspectObjectType(instance.constructor).should.equal("HTMLDivElementConstructor")
Utils.inspect(instance.constructor).should.equal("<HTMLDivElementConstructor>")
it "should work with CSSStyleDeclaration", ->
instance = document.createElement("div")
Utils.inspect(instance.style).should.equal("<CSSStyleDeclaration {}>")
it "should work with LayerDraggable", ->
layer = new Layer
Utils.inspectObjectType(layer.draggable).should.equal("LayerDraggable")
it "should work with a layer on an object", ->
varName = "123"
g = {}
g[varName] = new Layer
Utils.inspect(_.keys(g)).should.equal("[\"123\"]")
it "should work with align", ->
options =
x: Align.center
y: Align.center
Utils.inspect(options).should.equal("{x:Align.center, y:Align.center}")
describe "keyPath", ->
it "should get with single", ->
obj = {foo: "bar"}
Utils.getValueForKeyPath(obj, "foo").should.equal("bar")
it "should get with multipe", ->
obj = {fooA: {fooB: {fooC: "bar"}}}
Utils.getValueForKeyPath(obj, "fooA.fooB.fooC").should.equal("bar")
it "should set with single", ->
obj = {}
Utils.setValueForKeyPath(obj, "foo", "bar")
obj.should.eql({foo: "bar"})
it "should set with multiple", ->
obj = {fooA: {fooB: {}}}
Utils.setValueForKeyPath(obj, "fooA.fooB.fooC", "bar")
obj.should.eql({fooA: {fooB: {fooC: "bar"}}})
describe "isFileUrl", ->
it "should work", ->
Utils.isFileUrl("file:///Users/koen/Desktop/index.html").should.equal(true)
Utils.isFileUrl("http://apple.com/index.html").should.equal(false)
Utils.isFileUrl("https://apple.com/index.html").should.equal(false)
describe "isRelativeUrl", ->
it "should work", ->
Utils.isRelativeUrl("Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("/Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("./Desktop/index.html").should.equal(true)
Utils.isRelativeUrl(".././Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("https://apple.com/index.html").should.equal(false)
describe "isLocalServerUrl", ->
it "should work", ->
Utils.isLocalServerUrl("/Desktop/index.html").should.equal(false)
Utils.isLocalServerUrl("http://localhost/index.html").should.equal(true)
Utils.isLocalServerUrl("http://127.0.0.1/index.html").should.equal(true)
Utils.isLocalServerUrl("https://localhost/index.html").should.equal(true)
Utils.isLocalServerUrl("https://127.0.0.1/index.html").should.equal(true)
Utils.isLocalServerUrl(".././Desktop/index.html").should.equal(false)
Utils.isLocalServerUrl("https://apple.com/index.html").should.equal(false)
describe "isLocalAssetUrl", ->
it "should work", ->
Utils.isLocalAssetUrl("Desktop/index.html", "http://localhost/index.html").should.equal(true)
Utils.isLocalAssetUrl("/Desktop/index.html", "http://localhost/index.html").should.equal(true)
Utils.isLocalAssetUrl("Desktop/index.html", "http://127.0.0.1/index.html").should.equal(true)
Utils.isLocalAssetUrl("Desktop/index.html", "http://apple.com/index.html").should.equal(false)
Utils.isLocalAssetUrl("file:///Desktop/index.html", "http://apple.com/index.html").should.equal(true)
Utils.isLocalAssetUrl("http://apple.com/index.html", "http://127.0.0.1/index.html").should.equal(false)
| 51327 |
describe "Utils", ->
describe "valueOrDefault", ->
it "should get a value", ->
Utils.valueOrDefault(10, 0).should.equal 10
it "should get the default value", ->
Utils.valueOrDefault(null, 0).should.equal 0
# it "should get the fallback value", ->
# Utils.valueOrDefault(undefined, undefined, 0).should.equal 0
describe "arrayFromArguments", ->
it "should work", ->
f = -> return Utils.arrayFromArguments arguments
f("a").should.eql ["a"]
f("a", "b").should.eql ["a", "b"]
f(["a"]).should.eql ["a"]
f(["a", "b"]).should.eql ["a", "b"]
f("monkey").should.eql ["monkey"]
f(["monkey"]).should.eql ["monkey"]
describe "parseFunction", ->
it "should work without arguments", ->
result = Utils.parseFunction "spring"
result.name.should.equal "spring"
result.args.should.eql []
it "should work with a single argument", ->
result = Utils.parseFunction "spring(100)"
result.name.should.equal "spring"
result.args.should.eql ["100"]
it "should work with multiple arguments", ->
result = Utils.parseFunction "spring(100,50)"
result.name.should.equal "spring"
result.args.should.eql ["100", "50"]
it "should cleanup arguments", ->
result = Utils.parseFunction "spring(100 , 50 )"
result.name.should.equal "spring"
result.args.should.eql ["100", "50"]
describe "arrayNext", ->
it "should work", ->
Utils.arrayNext(["a", "b", "c"], "a").should.equal "b"
Utils.arrayNext(["a", "b", "c"], "b").should.equal "c"
Utils.arrayNext(["a", "b", "c"], "c").should.equal "a"
describe "arrayPrev", ->
it "should work", ->
Utils.arrayPrev(["a", "b", "c"], "a").should.equal "c"
Utils.arrayPrev(["a", "b", "c"], "b").should.equal "a"
Utils.arrayPrev(["a", "b", "c"], "c").should.equal "b"
describe "sizeMax", ->
it "should work", ->
Utils.sizeMax([
{width:100, height:100},
{width:100, height:100},
]).should.eql {width:100, height:100}
Utils.sizeMax([
{width:1000, height:1000},
{width:100, height:100},
]).should.eql {width:1000, height:1000}
describe "pathJoin", ->
it "should work", ->
Utils.pathJoin("test", "monkey").should.equal "test/monkey"
describe "sizeMin", ->
it "should work", ->
Utils.sizeMin([
{width:100, height:100},
{width:100, height:100},
]).should.eql {width:100, height:100}
Utils.sizeMin([
{width:1000, height:1000},
{width:100, height:100},
]).should.eql {width:100, height:100}
describe "points", ->
it "should get points from frame", ->
frame = {x:200, y:-60, width:200, height:200}
points = Utils.pointsFromFrame(frame)
points.length.should.eql 4
points[0].x.should.eql 200
points[1].y.should.eql 140
points[3].y.should.eql -60
it "should get frame from points", ->
points = [{x:200, y:-60}, {x:200, y:140}, {x:400, y:140}, {x:400, y:-60}]
frame = Utils.frameFromPoints(points)
frame.x.should.eql 200
frame.y.should.eql -60
frame.width.should.eql 200
frame.height.should.eql 200
describe "frameMerge", ->
it "should work", ->
compare = (frames, result) ->
frame = Utils.frameMerge frames
for p in ["x", "y", "width", "height"]
frame[p].should.equal result[p], p
compare [
{x:0, y:0, width:100, height:100},
{x:0, y:0, width:100, height:100},
], {x:0, y:0, width:100, height:100}
compare [
{x:0, y:0, width:100, height:100},
{x:0, y:0, width:500, height:500},
], {x:0, y:0, width:500, height:500}
compare [
{x:0, y:0, width:100, height:100},
{x:100, y:100, width:500, height:500},
], {x:0, y:0, width:600, height:600}
compare [
{x:100, y:100, width:100, height:100},
{x:100, y:100, width:500, height:500},
], {x:100, y:100, width:500, height:500}
# Bla bla. This works. Doing a visual comparison is so much easier
# Start the cactus project and go to /test.html
describe "framePointForOrigin", ->
it "should work", ->
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
# describe "domLoadData", (callback) ->
# it "should load data async", (callback) ->
# data = Utils.domLoadData "static/test.txt", (err, data) ->
# data.should.equal "TEST HELLO"
# callback()
# it "should load throw error on nonexisting", (callback) ->
# data = Utils.domLoadData "static/test123.txt", (err, data) ->
# err.should.equal true
# callback()
# describe "domLoadDataSync", ->
# it "should load data async", ->
# data = Utils.domLoadDataSync "static/test.txt"
# data.should.equal "TEST HELLO"
# it "should load throw error on nonexisting", ->
# test = -> Utils.domLoadDataSync("static/nonexisting.txt")
# test.should.throw()
describe "modulate", ->
it "should have the right results", ->
Utils.modulate(0.5, [0, 1], [0, 100]).should.equal 50
Utils.modulate(1, [0, 1], [0, 100]).should.equal 100
Utils.modulate(2, [0, 1], [0, 100], true).should.equal 100
Utils.modulate(2, [0, 1], [0, 100], false).should.equal 200
Utils.modulate(0, [1, 2], [0, 100], true).should.equal 0
Utils.modulate(0, [1, 2], [0, 100], false).should.equal -100
Utils.modulate(0, [1, 2], [100, 0], true).should.equal 100
Utils.modulate(0, [1, 2], [100, 0], false).should.equal 200
describe "clamp", ->
it "should have the right results", ->
Utils.clamp(3, 4, 6).should.equal 4
Utils.clamp(3, 6, 4).should.equal 4
Utils.clamp(5, 6, 4).should.equal 5
Utils.clamp(5, 6, -4).should.equal 5
describe "textSize", ->
it "should have the right text size", ->
# Todo: for some reason these don't work reliable in phantomjs
text = "Hello <NAME>"
style = {font:"20px/1em Menlo"}
# it "should return the right size", ->
# Utils.textSize(text, style).should.eql({width:168, height:20})
# it "should return the right size with width constraint", ->
# Utils.textSize(text, style, {width:100}).should.eql({width:100, height:40})
# it "should return the right size with height constraint", ->
# Utils.textSize(text, style, {height:100}).should.eql(width:168,height:100)
describe "frameSortByAbsoluteDistance", ->
it "should sort x", ->
layerA = new Layer x:300, y:100
layerB = new Layer x:100, y:100
layerC = new Layer x:200, y:100
Utils.frameSortByAbsoluteDistance({x:0, y:0}, [layerA, layerB, layerC]).should.eql([layerB, layerC, layerA])
it "should sort", ->
layerA = new Layer x:500, y:500
layerB = new Layer x:300, y:300
layerC = new Layer x:100, y:100
Utils.frameSortByAbsoluteDistance({x:0, y:0}, [layerA, layerB, layerC]).should.eql([layerC, layerB, layerA])
describe "inspect", ->
it "should work for strings", ->
Utils.inspect("a").should.equal("\"a\"")
it "should work for booleans", ->
Utils.inspect(true).should.equal("true")
it "should work for numbers", ->
Utils.inspect(12.34).should.equal("12.34")
it "should work for null", ->
Utils.inspect(null).should.equal("null")
it "should work for undefined", ->
Utils.inspect(undefined).should.equal("undefined")
it "should work for arrays", ->
Utils.inspect(["a", 1, ["b", "c"]]).should.equal("[\"a\", 1, [\"b\", \"c\"]]")
it "should work for objects", ->
Utils.inspect({a:1, b:[1, 2, 3]}).should.equal("{a:1, b:[1, 2, 3]}")
it "should work for functions", ->
test = -> return "a"
Utils.inspect(test).should.equal("<Function () { return \"a\"; }>")
it "should work for functions with arguments", ->
test = (a) -> return "a"
Utils.inspect(test).should.equal("<Function (a) { return \"a\"; }>")
it "should work for named functions", ->
# There are no named function in coffee script
`function test(a) { return "a"; }`
Utils.inspect(test).should.equal("<Function test(a) { return \"a\"; }>")
it "should work for long functions", ->
test = ->
its = 1
very = 1
rainy = 1
today = 1
down = 1
here = 1
return "a"
Utils.inspect(test).should.equal("<Function () { var down, here, its, rainy, today, very; its = 1; very = 1; rainy = 1; today = 1; down = 1; here = 1; return \"a\"; }>")
Utils.inspect([test]).should.equal("[<Function () { var down, here, its, rainy, today, very; its =… }>]")
it "should work for classes", ->
class TestClass
constructor: ->
@a = 1
instance = new TestClass
Utils.inspect(instance).should.equal("<TestClass {a:1}>")
it "should work for subclasses", ->
class TestClass
constructor: ->
@a = 1
class SubTestClass extends TestClass
instance = new SubTestClass
Utils.inspect(instance).should.equal("<SubTestClass {a:1}>")
it "should work with Colors", ->
instance = new Color "red"
Utils.inspect(instance).should.equal("<Color \"red\">")
instance = new Color "#28affa"
Utils.inspect(instance).should.equal("<Color \"#28affa\">")
instance = new Color
r: 200
g: 100
b: 20
a: 1
Utils.inspect(instance).should.equal("<Color r:200 g:100 b:20 a:1>")
instance = new Color
h: 200
s: 1
l: .2
a: 1
Utils.inspect(instance).should.equal("<Color h:200 s:1 l:0.2 a:1>")
it "should work with toInspect", ->
class TestClass
toInspect: -> return "Hello"
instance = new TestClass
Utils.inspect(instance).should.equal("Hello")
it "should work with WebKitCSSMatrix", ->
instance = new WebKitCSSMatrix()
Utils.inspect(instance).should.equal("<WebKitCSSMatrix {e:0, m33:1, f:0, m42:0, m44:1, m24:0, m31:0, m32:0, m21:0, m14:0, c:0, m34:0, m13:0, m12:0, m11:1, m41:0, m23:0, b:0, d:1, m22:1, a:1, m43:0}>")
it "should work with HTMLDivElement", ->
instance = document.createElement("div")
Utils.inspect(instance).should.equal("<HTMLDivElement>")
it "should work with HTMLDivElementConstructor", ->
instance = document.createElement("div")
Utils.inspectObjectType(instance.constructor).should.equal("HTMLDivElementConstructor")
Utils.inspect(instance.constructor).should.equal("<HTMLDivElementConstructor>")
it "should work with CSSStyleDeclaration", ->
instance = document.createElement("div")
Utils.inspect(instance.style).should.equal("<CSSStyleDeclaration {}>")
it "should work with LayerDraggable", ->
layer = new Layer
Utils.inspectObjectType(layer.draggable).should.equal("LayerDraggable")
it "should work with a layer on an object", ->
varName = "123"
g = {}
g[varName] = new Layer
Utils.inspect(_.keys(g)).should.equal("[\"123\"]")
it "should work with align", ->
options =
x: Align.center
y: Align.center
Utils.inspect(options).should.equal("{x:Align.center, y:Align.center}")
describe "keyPath", ->
it "should get with single", ->
obj = {foo: "bar"}
Utils.getValueForKeyPath(obj, "foo").should.equal("bar")
it "should get with multipe", ->
obj = {fooA: {fooB: {fooC: "bar"}}}
Utils.getValueForKeyPath(obj, "fooA.fooB.fooC").should.equal("bar")
it "should set with single", ->
obj = {}
Utils.setValueForKeyPath(obj, "foo", "bar")
obj.should.eql({foo: "bar"})
it "should set with multiple", ->
obj = {fooA: {fooB: {}}}
Utils.setValueForKeyPath(obj, "fooA.fooB.fooC", "bar")
obj.should.eql({fooA: {fooB: {fooC: "bar"}}})
describe "isFileUrl", ->
it "should work", ->
Utils.isFileUrl("file:///Users/koen/Desktop/index.html").should.equal(true)
Utils.isFileUrl("http://apple.com/index.html").should.equal(false)
Utils.isFileUrl("https://apple.com/index.html").should.equal(false)
describe "isRelativeUrl", ->
it "should work", ->
Utils.isRelativeUrl("Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("/Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("./Desktop/index.html").should.equal(true)
Utils.isRelativeUrl(".././Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("https://apple.com/index.html").should.equal(false)
describe "isLocalServerUrl", ->
it "should work", ->
Utils.isLocalServerUrl("/Desktop/index.html").should.equal(false)
Utils.isLocalServerUrl("http://localhost/index.html").should.equal(true)
Utils.isLocalServerUrl("http://127.0.0.1/index.html").should.equal(true)
Utils.isLocalServerUrl("https://localhost/index.html").should.equal(true)
Utils.isLocalServerUrl("https://127.0.0.1/index.html").should.equal(true)
Utils.isLocalServerUrl(".././Desktop/index.html").should.equal(false)
Utils.isLocalServerUrl("https://apple.com/index.html").should.equal(false)
describe "isLocalAssetUrl", ->
it "should work", ->
Utils.isLocalAssetUrl("Desktop/index.html", "http://localhost/index.html").should.equal(true)
Utils.isLocalAssetUrl("/Desktop/index.html", "http://localhost/index.html").should.equal(true)
Utils.isLocalAssetUrl("Desktop/index.html", "http://127.0.0.1/index.html").should.equal(true)
Utils.isLocalAssetUrl("Desktop/index.html", "http://apple.com/index.html").should.equal(false)
Utils.isLocalAssetUrl("file:///Desktop/index.html", "http://apple.com/index.html").should.equal(true)
Utils.isLocalAssetUrl("http://apple.com/index.html", "http://127.0.0.1/index.html").should.equal(false)
| true |
describe "Utils", ->
describe "valueOrDefault", ->
it "should get a value", ->
Utils.valueOrDefault(10, 0).should.equal 10
it "should get the default value", ->
Utils.valueOrDefault(null, 0).should.equal 0
# it "should get the fallback value", ->
# Utils.valueOrDefault(undefined, undefined, 0).should.equal 0
describe "arrayFromArguments", ->
it "should work", ->
f = -> return Utils.arrayFromArguments arguments
f("a").should.eql ["a"]
f("a", "b").should.eql ["a", "b"]
f(["a"]).should.eql ["a"]
f(["a", "b"]).should.eql ["a", "b"]
f("monkey").should.eql ["monkey"]
f(["monkey"]).should.eql ["monkey"]
describe "parseFunction", ->
it "should work without arguments", ->
result = Utils.parseFunction "spring"
result.name.should.equal "spring"
result.args.should.eql []
it "should work with a single argument", ->
result = Utils.parseFunction "spring(100)"
result.name.should.equal "spring"
result.args.should.eql ["100"]
it "should work with multiple arguments", ->
result = Utils.parseFunction "spring(100,50)"
result.name.should.equal "spring"
result.args.should.eql ["100", "50"]
it "should cleanup arguments", ->
result = Utils.parseFunction "spring(100 , 50 )"
result.name.should.equal "spring"
result.args.should.eql ["100", "50"]
describe "arrayNext", ->
it "should work", ->
Utils.arrayNext(["a", "b", "c"], "a").should.equal "b"
Utils.arrayNext(["a", "b", "c"], "b").should.equal "c"
Utils.arrayNext(["a", "b", "c"], "c").should.equal "a"
describe "arrayPrev", ->
it "should work", ->
Utils.arrayPrev(["a", "b", "c"], "a").should.equal "c"
Utils.arrayPrev(["a", "b", "c"], "b").should.equal "a"
Utils.arrayPrev(["a", "b", "c"], "c").should.equal "b"
describe "sizeMax", ->
it "should work", ->
Utils.sizeMax([
{width:100, height:100},
{width:100, height:100},
]).should.eql {width:100, height:100}
Utils.sizeMax([
{width:1000, height:1000},
{width:100, height:100},
]).should.eql {width:1000, height:1000}
describe "pathJoin", ->
it "should work", ->
Utils.pathJoin("test", "monkey").should.equal "test/monkey"
describe "sizeMin", ->
it "should work", ->
Utils.sizeMin([
{width:100, height:100},
{width:100, height:100},
]).should.eql {width:100, height:100}
Utils.sizeMin([
{width:1000, height:1000},
{width:100, height:100},
]).should.eql {width:100, height:100}
describe "points", ->
it "should get points from frame", ->
frame = {x:200, y:-60, width:200, height:200}
points = Utils.pointsFromFrame(frame)
points.length.should.eql 4
points[0].x.should.eql 200
points[1].y.should.eql 140
points[3].y.should.eql -60
it "should get frame from points", ->
points = [{x:200, y:-60}, {x:200, y:140}, {x:400, y:140}, {x:400, y:-60}]
frame = Utils.frameFromPoints(points)
frame.x.should.eql 200
frame.y.should.eql -60
frame.width.should.eql 200
frame.height.should.eql 200
describe "frameMerge", ->
it "should work", ->
compare = (frames, result) ->
frame = Utils.frameMerge frames
for p in ["x", "y", "width", "height"]
frame[p].should.equal result[p], p
compare [
{x:0, y:0, width:100, height:100},
{x:0, y:0, width:100, height:100},
], {x:0, y:0, width:100, height:100}
compare [
{x:0, y:0, width:100, height:100},
{x:0, y:0, width:500, height:500},
], {x:0, y:0, width:500, height:500}
compare [
{x:0, y:0, width:100, height:100},
{x:100, y:100, width:500, height:500},
], {x:0, y:0, width:600, height:600}
compare [
{x:100, y:100, width:100, height:100},
{x:100, y:100, width:500, height:500},
], {x:100, y:100, width:500, height:500}
# Bla bla. This works. Doing a visual comparison is so much easier
# Start the cactus project and go to /test.html
describe "framePointForOrigin", ->
it "should work", ->
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
Utils.framePointForOrigin({x:100, y:100, width:100, height:100}, 0, 0).should.eql(
{x:100, y:100, width:100, height:100})
# describe "domLoadData", (callback) ->
# it "should load data async", (callback) ->
# data = Utils.domLoadData "static/test.txt", (err, data) ->
# data.should.equal "TEST HELLO"
# callback()
# it "should load throw error on nonexisting", (callback) ->
# data = Utils.domLoadData "static/test123.txt", (err, data) ->
# err.should.equal true
# callback()
# describe "domLoadDataSync", ->
# it "should load data async", ->
# data = Utils.domLoadDataSync "static/test.txt"
# data.should.equal "TEST HELLO"
# it "should load throw error on nonexisting", ->
# test = -> Utils.domLoadDataSync("static/nonexisting.txt")
# test.should.throw()
describe "modulate", ->
it "should have the right results", ->
Utils.modulate(0.5, [0, 1], [0, 100]).should.equal 50
Utils.modulate(1, [0, 1], [0, 100]).should.equal 100
Utils.modulate(2, [0, 1], [0, 100], true).should.equal 100
Utils.modulate(2, [0, 1], [0, 100], false).should.equal 200
Utils.modulate(0, [1, 2], [0, 100], true).should.equal 0
Utils.modulate(0, [1, 2], [0, 100], false).should.equal -100
Utils.modulate(0, [1, 2], [100, 0], true).should.equal 100
Utils.modulate(0, [1, 2], [100, 0], false).should.equal 200
describe "clamp", ->
it "should have the right results", ->
Utils.clamp(3, 4, 6).should.equal 4
Utils.clamp(3, 6, 4).should.equal 4
Utils.clamp(5, 6, 4).should.equal 5
Utils.clamp(5, 6, -4).should.equal 5
describe "textSize", ->
it "should have the right text size", ->
# Todo: for some reason these don't work reliable in phantomjs
text = "Hello PI:NAME:<NAME>END_PI"
style = {font:"20px/1em Menlo"}
# it "should return the right size", ->
# Utils.textSize(text, style).should.eql({width:168, height:20})
# it "should return the right size with width constraint", ->
# Utils.textSize(text, style, {width:100}).should.eql({width:100, height:40})
# it "should return the right size with height constraint", ->
# Utils.textSize(text, style, {height:100}).should.eql(width:168,height:100)
describe "frameSortByAbsoluteDistance", ->
it "should sort x", ->
layerA = new Layer x:300, y:100
layerB = new Layer x:100, y:100
layerC = new Layer x:200, y:100
Utils.frameSortByAbsoluteDistance({x:0, y:0}, [layerA, layerB, layerC]).should.eql([layerB, layerC, layerA])
it "should sort", ->
layerA = new Layer x:500, y:500
layerB = new Layer x:300, y:300
layerC = new Layer x:100, y:100
Utils.frameSortByAbsoluteDistance({x:0, y:0}, [layerA, layerB, layerC]).should.eql([layerC, layerB, layerA])
describe "inspect", ->
it "should work for strings", ->
Utils.inspect("a").should.equal("\"a\"")
it "should work for booleans", ->
Utils.inspect(true).should.equal("true")
it "should work for numbers", ->
Utils.inspect(12.34).should.equal("12.34")
it "should work for null", ->
Utils.inspect(null).should.equal("null")
it "should work for undefined", ->
Utils.inspect(undefined).should.equal("undefined")
it "should work for arrays", ->
Utils.inspect(["a", 1, ["b", "c"]]).should.equal("[\"a\", 1, [\"b\", \"c\"]]")
it "should work for objects", ->
Utils.inspect({a:1, b:[1, 2, 3]}).should.equal("{a:1, b:[1, 2, 3]}")
it "should work for functions", ->
test = -> return "a"
Utils.inspect(test).should.equal("<Function () { return \"a\"; }>")
it "should work for functions with arguments", ->
test = (a) -> return "a"
Utils.inspect(test).should.equal("<Function (a) { return \"a\"; }>")
it "should work for named functions", ->
# There are no named function in coffee script
`function test(a) { return "a"; }`
Utils.inspect(test).should.equal("<Function test(a) { return \"a\"; }>")
it "should work for long functions", ->
test = ->
its = 1
very = 1
rainy = 1
today = 1
down = 1
here = 1
return "a"
Utils.inspect(test).should.equal("<Function () { var down, here, its, rainy, today, very; its = 1; very = 1; rainy = 1; today = 1; down = 1; here = 1; return \"a\"; }>")
Utils.inspect([test]).should.equal("[<Function () { var down, here, its, rainy, today, very; its =… }>]")
it "should work for classes", ->
class TestClass
constructor: ->
@a = 1
instance = new TestClass
Utils.inspect(instance).should.equal("<TestClass {a:1}>")
it "should work for subclasses", ->
class TestClass
constructor: ->
@a = 1
class SubTestClass extends TestClass
instance = new SubTestClass
Utils.inspect(instance).should.equal("<SubTestClass {a:1}>")
it "should work with Colors", ->
instance = new Color "red"
Utils.inspect(instance).should.equal("<Color \"red\">")
instance = new Color "#28affa"
Utils.inspect(instance).should.equal("<Color \"#28affa\">")
instance = new Color
r: 200
g: 100
b: 20
a: 1
Utils.inspect(instance).should.equal("<Color r:200 g:100 b:20 a:1>")
instance = new Color
h: 200
s: 1
l: .2
a: 1
Utils.inspect(instance).should.equal("<Color h:200 s:1 l:0.2 a:1>")
it "should work with toInspect", ->
class TestClass
toInspect: -> return "Hello"
instance = new TestClass
Utils.inspect(instance).should.equal("Hello")
it "should work with WebKitCSSMatrix", ->
instance = new WebKitCSSMatrix()
Utils.inspect(instance).should.equal("<WebKitCSSMatrix {e:0, m33:1, f:0, m42:0, m44:1, m24:0, m31:0, m32:0, m21:0, m14:0, c:0, m34:0, m13:0, m12:0, m11:1, m41:0, m23:0, b:0, d:1, m22:1, a:1, m43:0}>")
it "should work with HTMLDivElement", ->
instance = document.createElement("div")
Utils.inspect(instance).should.equal("<HTMLDivElement>")
it "should work with HTMLDivElementConstructor", ->
instance = document.createElement("div")
Utils.inspectObjectType(instance.constructor).should.equal("HTMLDivElementConstructor")
Utils.inspect(instance.constructor).should.equal("<HTMLDivElementConstructor>")
it "should work with CSSStyleDeclaration", ->
instance = document.createElement("div")
Utils.inspect(instance.style).should.equal("<CSSStyleDeclaration {}>")
it "should work with LayerDraggable", ->
layer = new Layer
Utils.inspectObjectType(layer.draggable).should.equal("LayerDraggable")
it "should work with a layer on an object", ->
varName = "123"
g = {}
g[varName] = new Layer
Utils.inspect(_.keys(g)).should.equal("[\"123\"]")
it "should work with align", ->
options =
x: Align.center
y: Align.center
Utils.inspect(options).should.equal("{x:Align.center, y:Align.center}")
describe "keyPath", ->
it "should get with single", ->
obj = {foo: "bar"}
Utils.getValueForKeyPath(obj, "foo").should.equal("bar")
it "should get with multipe", ->
obj = {fooA: {fooB: {fooC: "bar"}}}
Utils.getValueForKeyPath(obj, "fooA.fooB.fooC").should.equal("bar")
it "should set with single", ->
obj = {}
Utils.setValueForKeyPath(obj, "foo", "bar")
obj.should.eql({foo: "bar"})
it "should set with multiple", ->
obj = {fooA: {fooB: {}}}
Utils.setValueForKeyPath(obj, "fooA.fooB.fooC", "bar")
obj.should.eql({fooA: {fooB: {fooC: "bar"}}})
describe "isFileUrl", ->
it "should work", ->
Utils.isFileUrl("file:///Users/koen/Desktop/index.html").should.equal(true)
Utils.isFileUrl("http://apple.com/index.html").should.equal(false)
Utils.isFileUrl("https://apple.com/index.html").should.equal(false)
describe "isRelativeUrl", ->
it "should work", ->
Utils.isRelativeUrl("Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("/Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("./Desktop/index.html").should.equal(true)
Utils.isRelativeUrl(".././Desktop/index.html").should.equal(true)
Utils.isRelativeUrl("https://apple.com/index.html").should.equal(false)
describe "isLocalServerUrl", ->
it "should work", ->
Utils.isLocalServerUrl("/Desktop/index.html").should.equal(false)
Utils.isLocalServerUrl("http://localhost/index.html").should.equal(true)
Utils.isLocalServerUrl("http://127.0.0.1/index.html").should.equal(true)
Utils.isLocalServerUrl("https://localhost/index.html").should.equal(true)
Utils.isLocalServerUrl("https://127.0.0.1/index.html").should.equal(true)
Utils.isLocalServerUrl(".././Desktop/index.html").should.equal(false)
Utils.isLocalServerUrl("https://apple.com/index.html").should.equal(false)
describe "isLocalAssetUrl", ->
it "should work", ->
Utils.isLocalAssetUrl("Desktop/index.html", "http://localhost/index.html").should.equal(true)
Utils.isLocalAssetUrl("/Desktop/index.html", "http://localhost/index.html").should.equal(true)
Utils.isLocalAssetUrl("Desktop/index.html", "http://127.0.0.1/index.html").should.equal(true)
Utils.isLocalAssetUrl("Desktop/index.html", "http://apple.com/index.html").should.equal(false)
Utils.isLocalAssetUrl("file:///Desktop/index.html", "http://apple.com/index.html").should.equal(true)
Utils.isLocalAssetUrl("http://apple.com/index.html", "http://127.0.0.1/index.html").should.equal(false)
|
[
{
"context": "sion on tryerlang.org and return the result\n#\n# By Roberto Aloi (@robertoaloi)\n\nQS = require \"querystring\"\n\nmodul",
"end": 103,
"score": 0.9998766183853149,
"start": 91,
"tag": "NAME",
"value": "Roberto Aloi"
},
{
"context": "lang.org and return the result\n#\n#... | src/scripts/tryerlang.coffee | aroben/hubot-scripts | 0 | # erl <expr> - Evaluate an Erlang Expression on tryerlang.org and return the result
#
# By Roberto Aloi (@robertoaloi)
QS = require "querystring"
module.exports = (robot) ->
robot.respond /(tryerlang|erl) (.*)/i, (msg) ->
expr = msg.match[2]
data = QS.stringify({'expression': expr})
msg.http('http://www.tryerlang.org/api/eval/default/intro')
.post(data) (err, res, body) ->
response = JSON.parse(body)
msg.send response.result
| 189126 | # erl <expr> - Evaluate an Erlang Expression on tryerlang.org and return the result
#
# By <NAME> (@robertoaloi)
QS = require "querystring"
module.exports = (robot) ->
robot.respond /(tryerlang|erl) (.*)/i, (msg) ->
expr = msg.match[2]
data = QS.stringify({'expression': expr})
msg.http('http://www.tryerlang.org/api/eval/default/intro')
.post(data) (err, res, body) ->
response = JSON.parse(body)
msg.send response.result
| true | # erl <expr> - Evaluate an Erlang Expression on tryerlang.org and return the result
#
# By PI:NAME:<NAME>END_PI (@robertoaloi)
QS = require "querystring"
module.exports = (robot) ->
robot.respond /(tryerlang|erl) (.*)/i, (msg) ->
expr = msg.match[2]
data = QS.stringify({'expression': expr})
msg.http('http://www.tryerlang.org/api/eval/default/intro')
.post(data) (err, res, body) ->
response = JSON.parse(body)
msg.send response.result
|
[
{
"context": " foosbot Tip - Get a helpful tip!\n#\n# Author:\n# MartinPetkov\n\nfs = require 'fs'\nts = require 'trueskill'\nsched",
"end": 4080,
"score": 0.9931351542472839,
"start": 4068,
"tag": "NAME",
"value": "MartinPetkov"
},
{
"context": "\nfindPeopleForNextGameRespond = (... | scripts/foosbot.coffee | MartinPetkov/foosbot | 8 | # Description:
# An LCB bot that arranges foosball games
#
# Commands:
# foosbot Games - List currently scheduled games
# foosbot Total games - Return the number of total games
# foosbot Start game - Start a new game, always added to the end of the queue
# foosbot Start game with <p1> [<p2> <p3>] - Start a new game, always added to the end of the queue, with multiple people
# foosbot Find people|players - Ask for people to play in the next game
# foosbot I'm in | Join game - Claim a spot in the next game
# foosbot Add <player_name> - Add a player that may or may not be on LCB to the next game
# foosbot Kick <player_name> - Kick a player from the next game
# foosbot Abandon game - Free up your spot in the next game
# foosbot Cancel game - Cancel the next game
# foosbot Balance game - Balance the next game based on player ranks
# foosbot Shuffle game - Randomly shuffle the players in the next game
# foosbot Find people|players for game <n> - Ask for people to play in the nth game
# foosbot Join game <n> - Claim a spot in the nth game
# foosbot Add <player_name> to game <n> - Add a player that may or may not be on LCB to the nth game
# foosbot Kick <player_name> from game <n> - Kick a player from the nth game
# foosbot Abandon game <n> - Free up your spot in the nth game
# foosbot Cancel game <n> - Cancel the nth game
# foosbot Balance game <n> - Balance the nth game based on player ranks
# foosbot Shuffle game <n> - Randomly shuffle the players in the nth game
# foosbot Finish game <team1_score>-<team2_score> - Finish the next game in order and record the results
# foosbot Rematch - Repair your pride by playing the same game you just lost
# foosbot Go on [a] cleanse - Go on a cleanse, unable to be added to a game
# foosbot Return from cleanse - Return refreshed, ready to take on the champions
# foosbot Retire - Hang up the gloves for good
# foosbot Unretire - Rise up from the ashes of old age and get back to the table
# foosbot Rankings|Leaderboard - Show the leaderboard
# foosbot Rankings|Stats <player1> [<player2> ...] - Show the stats for specific players
# foosbot Top <n> - Show the top n players in the rankings
# foosbot History <player>|me [<numPastGames>|all] - Show a summary of your past games
# foosbot Team history <player>|me <otherPlayer> [<numPastGames>|all] - Show a summary of past games with a specific teammate
# foosbot Rival history <player>|me <otherPlayer> [<numPastGames>|all] - Show a summary of past games against a specific rival
# foosbot Team Stats <playerOne>|me <playerTwo>|me|all - Shows the team stats for two players, or all pairings of <playerOne>
# foosbot The rules - Show the rules we play by
# foosbot Start tournament - Begin a new tournament (cannot run multiple tournaments at once)
# foosbot Start tournament with <n> people - Begin a new tournament with some number of people (must be a power of 2)
# foosbot Cancel tournament - Cancel the currently running tournament (nothing will get saved)
# foosbot Show tournament - Show the current tournament tree
# foosbot Show tournament players - Show all the players involved in the tournament
# foosbot Show tournament teams - Show all the teams involved in the tournament
# foosbot Swap tournament player <current_player> with <new_player> - Replace a player in the tournament (only works with players that had ranks when the tournament was started)
# foosbot Accept tournament players - Confirm the player selection and officially begin the tournament
# foosbot Finish tournament game round <n1> game <n2> <team1_score>-<team2_score> - Finish a game and have the team move on
# foosbot Start betting - Join the betting pool
# foosbot My balance - Ask for your current balance
# foosbot Bet <x.y> on game <n> team (0|1) - Place a bet of <x.y>Ģ (i.e. 5.2) on game <n> for team 0 or 1 (placing again replaces your previous bet)
# foosbot Cancel bet on game <n> - Withdraw your bet for game <n>
# foosbot Tip - Get a helpful tip!
#
# Author:
# MartinPetkov
fs = require 'fs'
ts = require 'trueskill'
schedule = require 'node-schedule'
# Must be a power of 2
_DEFAULT_TOURNAMENT_SIZE = 16
# Betting constants
_STARTING_FOOSCOIN = 30.0
_MATCH_WIN_AMOUNT = 5.0
_HOUSE_PRIZE_BASE = 5.0
# Rules and tips
_THE_RULES = [
"No spinning",
"If someone scores with the first shot, it doesn't count",
"If someone scores by hitting the ball before it reaches the far wall, it doesn't count",
"Any player can score from any position",
"When one team reaches 5 points, both teams switch defense/offense players",
"If a shot goes in but comes out, it counts as long as it made the *dank* sound",
"The last goal cannot be an own goal, it must be scored by the opposing team",
"If unsure whether a goal counts, the team that got scored on makes the call",
"If the ball goes dead anywhere except the far sides, reset to the middle",
"If the ball goes dead on a far side, defense resets it from a corner",
"If the ball flies off the table, reset to the middle",
"If it wasn't organized by foosbot, it's a friendly game and does not affect rankings",
"Everyone has 3 seconds after a drop to call a redrop",
"If a player takes both hands off the handles and clearly stops playing, play is considered paused",
"If you get shut out, you have to crawl under the table"
"Everyone shakes hands at the end of the game, no exceptions",
]
_TIPS = [
"Keep your goalie in the center if you're not sure what to do",
"Take your time and control the ball for a better shot",
"Stagger your players when defending",
"Try not to shoot straight through the center",
"Keep your players the ball is behind them, so you don't block your partner's shot",
"Keep your defenders pointed inwards to make angle shots harder",
"To slapshot, place the bottom of your plam flat out, push forward, then pull up and grab",
"Close the gaps that lead to your net",
"Don't instinctively move your players back when the ball goes past them, you might score on yourself",
"Watch the ball, not the player, don't be fooled by dekes",
"Keep moving! Don't stop and pause just because your opponent did",
"Watch the hands and react to that, they're a tell before the actual move",
"Try to avoid patterns in your movement",
"Try to avoid crossing your goalie and your defenders, that leaves a gap through which to shoot",
"Guard the posts, but try not to linger there",
"Try to control the ball instead of shooting right away",
"Don't move for no reason if you're in a good position",
"Don't panic on slow shots! Concentrate and punish back",
"Keep an eye on your players more than on the ball when it's not in your half",
"Vary your shots, don't do the same thing from the same position over and over",
"Forget mistakes quickly and start thinking about the next play",
"Don't talk too much or you'll get distracted and make a mistake",
]
gamesFile = 'games.json'
finishedGamesFile = 'finishedgames.json'
previousRanksFile = 'previousranks.json'
cleanseFile = 'cleanse.json'
retireesFile = 'retirees.json'
tournamentFile = 'tournament.json'
accountsFile = 'accounts.json'
loadFile = (fileName, initialValue) ->
# Initialize the file if it does not exist
if !(fs.existsSync(fileName))
fs.writeFileSync(fileName, JSON.stringify(initialValue))
return JSON.parse((fs.readFileSync fileName, 'utf8').toString().trim())
saveFile = (fileName, data) ->
fs.writeFileSync(fileName, JSON.stringify(data))
games = loadFile(gamesFile, [])
finishedGames = loadFile(finishedGamesFile, [])
previousRanks = loadFile(previousRanksFile, {})
cleanse = loadFile(cleanseFile, [])
retirees = loadFile(retireesFile, [])
tournament = loadFile(tournamentFile, {'started': false, 'size': _DEFAULT_TOURNAMENT_SIZE})
accounts = loadFile(accountsFile, {})
saveGames = () ->
saveFile(gamesFile, games)
saveFinishedGames = () ->
saveFile(finishedGamesFile, finishedGames)
savePreviousRanks = () ->
saveFile(previousRanksFile, previousRanks)
saveCleanse = () ->
saveFile(cleanseFile, cleanse)
saveRetirees = () ->
saveFile(retireesFile, retirees)
saveTournament = () ->
saveFile(tournamentFile, tournament)
saveAccounts = () ->
saveFile(accountsFile, accounts)
# Date diff calculations
_MS_PER_DAY = 1000 * 60 * 60 * 24
diffDays = (date1, date2) ->
return Math.round((date1 - date2) / _MS_PER_DAY, 0)
# Store list of datetimes of previous plays
_SHAME_MESSAGES = [
"Playing again, huh?",
"Shouldn't you be doing...work?",
"Wow, look at your rank after all these games you've played!",
"You could have finished that ticket in the time you've spent playing foosball today",
"Aren't your hands tired by now?",
"Maybe it's time you took a break from foos",
"Are you /really/ sure you want to keep playing today?",
]
_DEFAULT_SHAME_MESSAGE = "Maximum slack level reached, HR has been notified"
getShameMsg = (res, player, timesPlayed) ->
shameMsg = if timesPlayed >= 10 then _DEFAULT_SHAME_MESSAGE else res.random _SHAME_MESSAGES
return "@#{player} #{shameMsg}"
# Store shame
shameFile = 'shame.json'
shame = JSON.parse((fs.readFileSync shameFile, 'utf8').toString().trim())
for player of shame
shame[player] = shame[player].map (playTime) -> new Date(playTime)
saveShame = () ->
fs.writeFileSync(shameFile, JSON.stringify(shame))
# Shame players who play too much
updateShame = (player) ->
if !(player of shame)
shame[player] = []
now = new Date()
shame[player].push now
saveShame()
shameSlacker = (res, player) ->
player = player.trim().toLowerCase()
if !(player of shame)
return
# Remove all recorded plays older than 1 day and not on the same calendar date
now = new Date()
shame[player] = shame[player].filter (playTime) -> (diffDays(now, playTime) == 0) && (playTime.getDate() == now.getDate())
saveShame()
timesPlayed = shame[player].length
if timesPlayed >= 3
res.send getShameMsg(res, player, timesPlayed)
isUndefined = (myvar) ->
return typeof myvar == 'undefined'
isPowerOfTwo = (mynum) ->
return (Math.log2(mynum) % 1) == 0
rightPad = (s, finalLength) ->
numSpaces = Math.max(0, finalLength - s.length)
return s + ' '.repeat(numSpaces)
customRound = (num, decimals) ->
return Number(Math.round(num+'e'+decimals)+'e-'+decimals);
gamesRespond = (res) ->
# List the games, in groups of 4, with the indices
if games.length <= 0
res.send "No games started"
return
responseLines = []
for game, index in games
gamePlayers = game['players']
team1 = "#{gamePlayers[0]} and #{gamePlayers[1]}"
team2 = "#{gamePlayers[2]} and #{gamePlayers[3]}"
# Calculate bets for each team
team1Bets = 0.0
team2Bets = 0.0
for betterName of game['bets']
bet = game['bets'][betterName]
if bet['team'] == 0
team1Bets += bet['amount']
else
team2Bets += bet['amount']
if team1Bets > 0
team1 += " (#{team1Bets}Ģ bet)"
if team2Bets > 0
team2 += " (#{team2Bets}Ģ bet)"
responseLines.push "Game #{index}:\n#{team1}\nvs.\n#{team2}\n"
res.send responseLines.join('\n')
startGameRespond = (res, startingPlayers) ->
# Create a new group of four, at the end of the games array
captain = res.message.user.name
if captain in cleanse
res.reply "You can't start any games, you're on a cleanse!"
return
if captain in retirees
res.reply "You can't start any games, you're retired!"
return
games.push {
"players": [captain, '_', '_', '_'],
"bets": {}
}
saveGames()
shameSlacker(res, captain)
res.send "New game started"
if !(isUndefined(startingPlayers))
n = games.length - 1
for sp in startingPlayers
joinGameRespond(res, n, sp)
gamesRespond(res)
startGameWithPlayersRespond = (res) ->
startingPlayers = (name.trim() for name in res.match[1].trim().split(' '))
res.send "Starting players: #{startingPlayers}"
startGameRespond(res, startingPlayers)
isInvalidIndex = (gameIndex) ->
return isNaN(gameIndex) || gameIndex < 0 || gameIndex >= games.length
findPeopleForGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
gameStr = if n == 0 then "Next game" else "Game #{n}"
gamePlayers = games[n]['players']
currentPlayers = (player for player in gamePlayers when player != "_")
spotsLeft = 4 - currentPlayers.length
if spotsLeft <= 0
res.send "No spots left in #{gameStr}"
return
# Ask @all who's up for a game, and announce who's currently part of the nth game
currentPlayers = currentPlayers.join(', ')
res.send "@all Who's up for a game? #{gameStr} has #{spotsLeft} spots, current players are #{currentPlayers}"
initOrRetrievePlayerStat = (stats, playerName) ->
if playerName of stats
return stats[playerName]
return {
"gamesPlayed": 0,
"gamesWon": 0,
"winPercentage": 0,
"skill": [25.0, 25.0/3.0],
"rank": 2,
"streak": 0,
"longestWinStreak": 0,
"longestLoseStreak": 0,
}
getStats = () ->
# Return stats for all players, which is a map from player name to object with games played, games won, and win percentage
stats = {}
for finishedGame in finishedGames
t1p1 = finishedGame['team1']['player1']
t1p2 = finishedGame['team1']['player2']
t2p1 = finishedGame['team2']['player1']
t2p2 = finishedGame['team2']['player2']
t1score = finishedGame['team1']['score']
t2score = finishedGame['team2']['score']
allPlayers = [t1p1, t1p2, t2p1, t2p2]
for player in allPlayers
stats[player] = initOrRetrievePlayerStat(stats, player)
stats[player]['gamesPlayed'] += 1
stats[player]['rank'] = 2
winPlayers = []
losePlayers = []
if t1score > t2score
winPlayers = [t1p1, t1p2]
losePlayers = [t2p1, t2p2]
else if t2score > t1score
winPlayers = [t2p1, t2p2]
losePlayers = [t1p1, t1p2]
for wp in winPlayers
stats[wp]['gamesWon'] += 1
stats[wp]['rank'] = 1
# If they were losing until this game, reset them to a 1 win streak
stats[wp]['streak'] = if stats[wp]['streak'] < 0 then 1 else stats[wp]['streak'] + 1
if stats[wp]['streak'] > stats[wp]['longestWinStreak']
stats[wp]['longestWinStreak'] = stats[wp]['streak']
for lp in losePlayers
# If they were winning until this game, reset them to a 1 lose streak
stats[lp]['streak'] = if stats[lp]['streak'] > 0 then -1 else stats[lp]['streak'] - 1
if -stats[lp]['streak'] > stats[lp]['longestLoseStreak']
stats[lp]['longestLoseStreak'] = -stats[lp]['streak']
ts.AdjustPlayers([stats[t1p1], stats[t1p2], stats[t2p1], stats[t2p2]])
for player in Object.keys(stats)
stats[player]['name'] = player
stats[player]['winPercentage'] = customRound((stats[player]['gamesWon'] / stats[player]['gamesPlayed']) * 100, 2)
stats[player]['trueskill'] = stats[player]['skill'][0] - (3 * stats[player]['skill'][1])
return stats
noopFormat = (str) -> return "#{str}"
fixedTwoFormat = (str) -> return "#{str.toFixed(2)}"
trueskillFormat = (str) -> return "#{str.toFixed(5)}"
percentFormat = (str) -> return "#{str}% "
gamesFormat = (str) -> return "#{str} game#{if str == 1 then '' else 's'}"
streakFormat = (str) ->
winning = str > 0
gameStreak = if winning then str else -str
return "#{if winning then ':fire:' else ':poop:'} #{gameStreak} #{if winning then 'won' else 'lost'}"
addColumn = (lines, stats, header, field, formatFunc, isFirstColumn) ->
isIndexColumn = !field
formatFunc = if isUndefined(formatFunc) then noopFormat else formatFunc
# Calculate the longest length, for padding
header = if isIndexColumn then "Rank" else "#{header}"
longestLength = header.length
longestHeaderLength = header.length
for stat, index in stats
fieldValue = if isIndexColumn then "#{index}" else formatFunc(stat[field])
longestLength = Math.max(longestLength, fieldValue.length)
# Convert emojis to a single character
collapsedFieldValue = fieldValue
collapsedFieldValue = collapsedFieldValue.replace /:.*:/g, (txt) -> ':::'
longestHeaderLength = Math.max(longestHeaderLength, collapsedFieldValue.length)
longestLength += 1
longestHeaderLength += 1
# Add the header and the underline
headerLength = longestHeaderLength + 2
lines[0] += rightPad(header, headerLength)
lines[1] += '-'.repeat(headerLength)
# Add the column for each statistic
for stat, index in stats
if isIndexColumn
fieldValue = rightPad("#{index+1}", longestLength)
else
fieldValue = rightPad(formatFunc(stat[field]), longestLength)
if !isFirstColumn
lines[2+index] += "| "
lines[2+index] += "#{fieldValue}"
skillSort = (p1, p2) ->
# High ranks are pushed to the front
if p1['trueskill'] > p2['trueskill']
return -1
if p1['trueskill'] < p2['trueskill']
return 1
# Order by games won next
if p1['gamesWon'] > p2['gamesWon']
return -1
if p1['gamesWon'] < p2['gamesWon']
return 1
# Order by win percentage last
return if p1['winPercentage'] >= p2['winPercentage'] then -1 else 1
getRankings = () ->
# Get the stats for each player
stats = getStats()
# Remove all retirees
for retiree in retirees
if retiree of stats
delete stats[retiree]
# Make a sortable array
rankings = []
for player in Object.keys(stats)
rankings.push stats[player]
# Sort the players based on rank
rankings.sort(skillSort)
for stat, rank in rankings
stat['rank'] = rank + 1
return rankings
rankingsRespond = (res, specificPlayers, topNPlayers) ->
# Get the player rankings
rankings = getRankings()
# Either filter or show topNPlayers players, but not both
if !(isUndefined(specificPlayers))
rankings = rankings.filter (stat) -> stat["name"] in specificPlayers
else if !(isUndefined(topNPlayers))
rankings = rankings.slice(0, topNPlayers)
# Construct the rankings string
responseList = new Array(rankings.length + 2).fill('') # Initialize with empty lines, to add to later
# addColumn(responseList, rankings, "", "", ) # Index column
addColumn(responseList, rankings, "Rank", "rank", noopFormat, true)
addColumn(responseList, rankings, "Player", "name")
addColumn(responseList, rankings, "Trueskill", "trueskill", trueskillFormat)
addColumn(responseList, rankings, "Win %", "winPercentage", percentFormat)
addColumn(responseList, rankings, "Won", "gamesWon")
addColumn(responseList, rankings, "Played", "gamesPlayed")
addColumn(responseList, rankings, "Streak", "streak", streakFormat)
addColumn(responseList, rankings, "Longest Win Streak", "longestWinStreak", gamesFormat)
addColumn(responseList, rankings, "Longest Lose Streak", "longestLoseStreak", gamesFormat)
res.send responseList.join('\n')
rankingsForPlayersRespond = (res) ->
players = (name.trim() for name in res.match[1].trim().split(' '))
rankingsRespond(res, players)
topNRankingsRespond = (res) ->
n = res.match[1].trim()
rankingsRespond(res, undefined, n)
resetPreviousRankings = (res) ->
rankings = getRankings()
for player, rank in rankings
previousRanks[player['name']] = rank + 1
savePreviousRanks()
showChangedRankings = (res, p1, p2, p3, p4) ->
rankChanges = "Rank changes:\n"
rankings = getRankings()
for p in [p1,p2,p3,p4]
curRank = getRank(p, rankings) + 1
if p of previousRanks
prevRank = previousRanks[p]
rankDiff = prevRank - curRank
prefix = if rankDiff < 0 then '' else if rankDiff == 0 then '=' else '+'
else
rankDiff = curRank
prefix = '~'
rankChanges += "#{prefix}#{rankDiff} -> #{curRank} #{p}\n"
resetPreviousRankings(res)
res.send rankChanges
rankSort = (p1,p2) ->
# Negative rank means the player isn't ranked
if p1['rank'] < 0
return -1
if p2['rank'] < 0
return 1
# A low rank is better than a high rank
return if p1['rank'] <= p2['rank'] then -1 else 1
getRank = (playerName, rankings) ->
for player, rank in rankings
if player['name'] == playerName
return rank
# If the player is new, they should be considered worse than anyone
return Infinity
balancePlayers = (game) ->
# Get the player rankings, which are sorted correctly
rankings = getRankings()
# Balance based on rank
playersWithRanks = game.map (player) -> {"name": player, "rank": getRank(player, rankings)}
playersWithRanks.sort(rankSort)
# Update the game
game[0] = playersWithRanks[0]["name"]
game[1] = playersWithRanks[3]["name"]
game[2] = playersWithRanks[1]["name"]
game[3] = playersWithRanks[2]["name"]
shufflePlayers = (n) ->
# Simply rotate the last 3 players left
game = games[n]["players"]
games[n]["players"] = [game[0]].concat(game.slice(2).concat(game[1]))
joinGameRespond = (res, n, playerName) ->
newPlayer = if isUndefined(playerName) then res.message.user.name else playerName
if newPlayer in cleanse
if isUndefined(playerName)
res.reply "You can't join any games, you're on a cleanse!"
else
res.send "#{newPlayer} cannot join games, they are on a cleanse!"
return
if newPlayer in retirees
if isUndefined(playerName)
res.reply "You can't join any games, you're retired!"
else
res.send "#{newPlayer} cannot join games, they are retired!"
return
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
any = if !any then false else true
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
shameSlacker(res, newPlayer)
gameStr = if n == 0 then "Next game" else "Game #{n}"
gamePlayers = games[n]['players']
if gamePlayers.indexOf(newPlayer) >= 0
res.send "You're already part of that game!"
return
# Add yourself to the nth game
for player, index in gamePlayers
if player == '_'
gamePlayers[index] = newPlayer
res.send "#{newPlayer} joined #{gameStr}!"
if gamePlayers.indexOf('_') < 0
balancePlayers(gamePlayers)
teamOneWinRate = getTeamStats(gamePlayers[0], gamePlayers[1])[gamePlayers[1]]["winPercentage"]
teamTwoWinRate = getTeamStats(gamePlayers[2], gamePlayers[3])[gamePlayers[3]]["winPercentage"]
teamsStr = "@#{gamePlayers[0]} and @#{gamePlayers[1]} (#{teamOneWinRate}%)\n"
teamsStr += "vs.\n"
teamsStr += "@#{gamePlayers[2]} and @#{gamePlayers[3]} (#{teamTwoWinRate}%)"
res.send "#{gameStr} is ready to go! Teams:\n#{teamsStr}"
saveGames()
return
# Cannot join if full
res.send "No spots in #{gameStr}"
abandonGameRespond = (res, n, playerName) ->
senderPlayer = if isUndefined(playerName) then res.message.user.name else playerName
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
gamePlayers = games[n]['players']
playerIndex = gamePlayers.indexOf(senderPlayer)
if playerIndex < 0
res.send "#{senderPlayer} is not part of Game #{n}"
return
# Return any bets placed on that game
returnBets(res, n)
gamePlayers[playerIndex] = '_'
saveGames()
# Abandon the nth game, freeing your spot in it
remainingPlayers = [(player for player in gamePlayers when player != "_")].join(', ')
res.send "#{senderPlayer} abandoned game #{n}. Remaining players: #{remainingPlayers}"
gamesRespond(res)
cancelGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
# Return any bets placed on that game
returnBets(res, n)
games.splice(n, 1)
saveGames()
# Cancel the nth game
res.send "Game #{n} cancelled"
gamesRespond(res)
findPeopleForNextGameRespond = (res) ->
# Ask @all who's up for a game, and announce who's currently part of the next upcoming game
findPeopleForGameRespond(res, 0)
joinNextGameRespond = (res) ->
# Add yourself to the next game
# Cannot join if full
joinGameRespond(res, 0)
abandonNextGameRespond = (res) ->
# Abandon the next upcoming game, freeing your spot in it
abandonGameRespond(res, 0)
cancelNextGameRespond = (res) ->
# Cancel the next upcoming game
cancelGameRespond(res, 0)
addToGameRespond = (res, n) ->
# Add a player to the nth game
playerName = res.match[1].trim()
n = if isUndefined(n) then parseInt(res.match[2].trim(), 10) else n
joinGameRespond(res, n, playerName)
addToNextGameRespond = (res) ->
# Add yourself to the next game
# Cannot join if full
addToGameRespond(res, 0)
kickFromGameRespond = (res, n) ->
# Kick a player from the nth game
playerName = res.match[1].trim()
n = if isUndefined(n) then parseInt(res.match[2].trim(), 10) else n
abandonGameRespond(res, n, playerName)
kickFromNextGameRespond = (res) ->
# Kick a player from the next game
kickFromGameRespond(res, 0)
balanceGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
balancePlayers(games[n]['players'])
saveGames()
gamesRespond(res)
res.send "Game #{n} balanced based on rank"
balanceNextGameRespond = (res) ->
balanceGameRespond(res, 0)
shuffleGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
shufflePlayers(n)
returnBets(res, n)
saveGames()
gamesRespond(res)
res.send "Game #{n} shuffled"
shuffleNextGameRespond = (res) ->
shuffleGameRespond(res, 0)
finishGameRespond = (res) ->
if games.length <= 0
res.send "No games are being played at the moment"
return
game = games[0]
gamePlayers = game['players']
if gamePlayers.indexOf('_') >= 0
res.send "Next game isn't ready to go yet!"
return
result = res.match[1].trim().split('-')
t1score = parseInt(result[0], 10)
t2score = parseInt(result[1], 10)
t1p1 = gamePlayers[0].trim().toLowerCase()
t1p2 = gamePlayers[1].trim().toLowerCase()
t2p1 = gamePlayers[2].trim().toLowerCase()
t2p2 = gamePlayers[3].trim().toLowerCase()
oldStats = getStats()
# The following is the format for game results
resultDetails = {
'team1': {
'player1': t1p1,
'player2': t1p2,
'score': t1score
},
'team2': {
'player1': t2p1,
'player2': t2p2,
'score': t2score
}
}
for player in [t1p1,t1p2,t2p1,t2p2]
updateShame(player)
if !(player of oldStats)
oldStats[player] = {
'trueskill': 0.0
}
# Record the scores and save them
finishedGames.push resultDetails
# Return the bets to the bet winners
winningTeam = if t1score > t2score then 0 else 1
betWinners = []
betWinnersTotalPool = 0
prizePool = 0
for betterName of game['bets']
if game['bets'][betterName]['team'] == winningTeam
betWinnersTotalPool += game['bets'][betterName]['amount']
# Return the winner's bet, but don't announce it
accounts[betterName] += game['bets'][betterName]['amount']
betWinners.push(betterName)
else
prizePool += game['bets'][betterName]['amount']
# Give extra money from the house, based on trueskill
winningTeamPlayers = if t1score > t2score then [t1p1,t1p2] else [t2p1,t2p2]
losingTeamPlayers = if t1score > t2score then [t2p1,t2p2] else [t1p1,t1p2]
winningTeamTrueskill = oldStats[losingTeamPlayers[0]]['trueskill'] + oldStats[losingTeamPlayers[1]]['trueskill']
losingTeamTrueskill = oldStats[winningTeamPlayers[0]]['trueskill'] + oldStats[winningTeamPlayers[1]]['trueskill']
housePrizeProportion = winningTeamTrueskill / losingTeamTrueskill
housePrize = customRound(housePrizeProportion * _HOUSE_PRIZE_BASE, 2)
if betWinners.length > 0
for betWinner in betWinners
if betWinner of accounts
# Award the house prize
accounts[betWinner] += housePrize
res.send "@#{betWinner} won #{housePrize}Ģ from the house!"
# Distribute the prize pool from the losers
if prizePool > 0
# Determine how much this winner should get, proportional to what they bet
proportion = customRound(game['bets'][betWinner]['amount'] / betWinnersTotalPool, 4)
betWinAmount = customRound(prizePool * proportion, 4)
accounts[betWinner] += betWinAmount
res.send "@#{betWinner} won #{betWinAmount}Ģ from betting!"
# Award a prize to the winners of the match, equal to the number of goals scored
matchWinners = if t1score > t2score then [t1p1,t1p2] else [t2p1,t2p2]
matchWinnersScore = if t1score > t2score then t1score else t2score
matchLosersScore = if t1score > t2score then t2score else t1score
matchWinAmount = Math.abs(t1score - t2score)
# Give more if the trueskill difference is larger
matchWinAmount += housePrizeProportion * 2 * matchWinAmount
# Determine how much of the opposing prize pool to give, with the goals as a percentage
if prizePool > 0
matchWinAmount += prizePool * (matchWinnersScore / 100.0)
# Double the win amount in case of a shutout
if matchLosersScore == 0
matchWinAmount = matchWinAmount * 2
res.send "Double fooscoins for a shutout win!"
res.send "https://media.giphy.com/media/gtakVlnStZUbe/giphy.gif"
for matchWinner in matchWinners
if matchWinner of accounts
accounts[matchWinner] += matchWinAmount
res.send "@#{matchWinner} won #{matchWinAmount}Ģ!"
saveAccounts()
saveFinishedGames()
# Show changed rankings since last time
showChangedRankings(res, t1p1, t1p2, t2p1, t2p2)
# Remove the game from the list
games.splice(0,1)
saveGames()
res.send "Results saved"
theRulesRespond = (res) ->
res.send _THE_RULES.map((rule, i) -> "#{i+1}. #{rule}").join('\n')
tipRespond = (res) ->
res.send res.random _TIPS
goOnACleanseRespond = (res) ->
senderName = res.message.user.name
if !(senderName in cleanse)
cleanse.push senderName
saveCleanse()
res.reply "You are now on a cleanse. Stay away from the foosball table, and relax :palm_tree:"
returnFromCleanseRespond = (res) ->
senderName = res.message.user.name
if !(senderName in cleanse)
res.reply "You are not on a cleanse, go play some foos!"
return
cleanse.splice(cleanse.indexOf(senderName), 1)
saveCleanse()
res.reply "Welcome back! Now go kick some ass"
initTeamStat = (stats, playerName) ->
stats[playerName] = {
"wins": 0,
"losses": 0,
"ties": 0,
"goalsFor": 0,
"goalsAgainst": 0,
"winPercentage": 0,
"avgGoalsFor": 0,
"avgGoalsAgainst": 0
}
getTeamStats = (playerOneName, playerTwoName) ->
# Allow getting stats for all team pairings by providing "all" as the playerTwoName
# The keys of the return dictionary are the names of the other team member
stats = {}
playerOneName = playerOneName.toLowerCase()
playerTwoName = playerTwoName.toLowerCase()
# Make sure the partner has the default stats
if !(playerTwoName == 'all')
initTeamStat(stats, playerTwoName)
for finishedGame in finishedGames
teamOne = [finishedGame["team1"]["player1"], finishedGame["team1"]["player2"]]
teamTwo = [finishedGame["team2"]["player1"], finishedGame["team2"]["player2"]]
if playerOneName in teamOne && (playerTwoName == 'all' || playerTwoName in teamOne)
myTeam = finishedGame["team1"]
otherTeam = finishedGame["team2"]
else if playerOneName in teamTwo && (playerTwoName == 'all' || playerTwoName in teamTwo)
myTeam = finishedGame["team2"]
otherTeam = finishedGame["team1"]
else
continue
# Get the partner's name
partnerName = if myTeam["player1"] == playerOneName then myTeam["player2"] else myTeam["player1"]
if !(partnerName of stats)
initTeamStat(stats, partnerName)
partnerStats = stats[partnerName]
if myTeam["score"] > otherTeam["score"]
partnerStats["wins"] += 1
else if myTeam["score"] == otherTeam["score"]
partnerStats["ties"] += 1
else
partnerStats["losses"] += 1
partnerStats["goalsFor"] += myTeam["score"]
partnerStats["goalsAgainst"] += otherTeam["score"]
# Extra Stats
for partnerName of stats
partnerStats = stats[partnerName]
gamesPlayed = partnerStats["wins"] + partnerStats["losses"] + partnerStats["ties"]
if gamesPlayed > 0
partnerStats["winPercentage"] = ((partnerStats["wins"] / gamesPlayed) * 100).toFixed(2)
partnerStats["avgGoalsFor"] = partnerStats["goalsFor"] / gamesPlayed
partnerStats["avgGoalsAgainst"] = partnerStats["goalsAgainst"] / gamesPlayed
return stats
teamStatsRespond = (res) ->
playerOneName = if res.match[1] == 'me' then res.message.user.name else res.match[1].trim().toLowerCase()
playerTwoName = if res.match[2] == 'me' then res.message.user.name else res.match[2].trim().toLowerCase()
if playerOneName == playerTwoName
res.send "Player one and player two cannot be the same."
return
teamStats = getTeamStats(playerOneName, playerTwoName)
# Build the response of stats for all team pairings
response = ''
for partnerName of teamStats
partnerStats = teamStats[partnerName]
responseList = new Array(3).fill('')
addColumn(responseList, [partnerStats], "Win", "wins", noopFormat, true)
addColumn(responseList, [partnerStats], "Loss", "losses")
addColumn(responseList, [partnerStats], "Tie", "ties")
addColumn(responseList, [partnerStats], "Avg. Goals For", "avgGoalsFor", fixedTwoFormat)
addColumn(responseList, [partnerStats], "Avg. Goals Against", "avgGoalsAgainst", fixedTwoFormat)
addColumn(responseList, [partnerStats], "Win Rate", "winPercentage", percentFormat)
response += "Team: #{playerOneName} and #{partnerName}\n"
response += responseList.join("\n")
response += "\n\n\n"
res.send response
historyMeRespond = (res) ->
me = res.match[1] == 'me'
playerName = if me then res.message.user.name else res.match[1].trim().toLowerCase()
numPastGames = if isUndefined(res.match[2]) then 5 else res.match[2].trim()
historyRespond(res, me, numPastGames, playerName)
multiHistoryRespond = (res, rivals) ->
me = res.match[1] == 'me'
playerName = if me then res.message.user.name else res.match[1].trim().toLowerCase()
otherPlayerName = res.match[2].trim().toLowerCase()
numPastGames = if isUndefined(res.match[3]) then 5 else res.match[3].trim()
historyRespond(res, me, numPastGames, playerName, otherPlayerName, rivals)
teamHistoryRespond = (res) ->
multiHistoryRespond(res, false)
rivalHistoryRespond = (res) ->
multiHistoryRespond(res, true)
historyRespond = (res, me, numPastGames, playerName, otherPlayerName, rivals) ->
gamesFound = 0
pastGames = []
if !(numPastGames == 'all')
numPastGames = parseInt(numPastGames, 10)
# Collect the last n games
for i in [finishedGames.length-1..0] by -1
fgame = finishedGames[i]
fgPlayers = [fgame["team1"]["player1"], fgame["team1"]["player2"], fgame["team2"]["player1"], fgame["team2"]["player2"]]
keepGame = false
if isUndefined(otherPlayerName)
# Single-player history
if playerName in fgPlayers
keepGame = true
else
# Team history
fgTeam1 = [fgame["team1"]["player1"], fgame["team1"]["player2"]]
fgTeam2 = [fgame["team2"]["player1"], fgame["team2"]["player2"]]
if rivals
keepGame = ((playerName in fgTeam1) && (otherPlayerName in fgTeam2)) || ((playerName in fgTeam2) && (otherPlayerName in fgTeam1))
else
keepGame = ((playerName in fgTeam1) && (otherPlayerName in fgTeam1)) || ((playerName in fgTeam2) && (otherPlayerName in fgTeam2))
if keepGame
pastGames.unshift(fgame)
gamesFound += 1
if numPastGames != 'all' && gamesFound >= numPastGames
break
pronoun = "#{playerName}'s"
together = ""
if !isUndefined(otherPlayerName)
pronoun = "#{playerName} and #{otherPlayerName}'s"
together = if rivals then " against each other" else " together"
gamesWon = 0
title = "#{pronoun} last #{numPastGames} games#{together}:"
strGames = ""
for pg, i in pastGames
score = '\t'
team1 = [pg["team1"]["player1"], pg["team1"]["player2"]]
team2 = [pg["team2"]["player1"], pg["team2"]["player2"]]
thisTeam = team1
thisTeamScore = pg['team1']['score']
otherTeamScore = pg['team2']['score']
if playerName in team2
thisTeam = team2
thisTeamScore = pg['team2']['score']
otherTeamScore = pg['team1']['score']
if thisTeamScore > otherTeamScore
gamesWon += 1
score = process.env.WIN_EMOJI
if otherTeamScore == 0
score += process.env.SHUTOUT_EMOJI
else if otherTeamScore == 8
score += process.env.CLOSE_WIN_EMOJI
score += '\t'
else if thisTeamScore == 0
score = process.env.NO_GOALS_EMOJI + '\t'
else if thisTeamScore == 8
score = process.env.CLOSE_LOSS_EMOJI + '\t'
score += "#{thisTeamScore}-#{otherTeamScore}"
if playerName == pg['team1']['player1']
teams = [pg['team1']['player1'], pg['team1']['player2'], pg['team2']['player1'], pg['team2']['player2']]
else if playerName == pg['team1']['player2']
teams = [pg['team1']['player2'], pg['team1']['player1'], pg['team2']['player1'], pg['team2']['player2']]
else if playerName == pg['team2']['player1']
teams = [pg['team2']['player1'], pg['team2']['player2'], pg['team1']['player1'], pg['team1']['player2']]
else
teams = [pg['team2']['player2'], pg['team2']['player1'], pg['team1']['player1'], pg['team1']['player2']]
strGames += "\n#{score}\t#{teams[0]} and #{teams[1]} vs. #{teams[2]} and #{teams[3]}"
strGames = title + "\nK-D ratio: #{gamesWon}-#{gamesFound-gamesWon}\n" + strGames
res.send strGames
totalGamesRespond = (res) ->
res.send finishedGames.length
rematchRespond = (res) ->
playerName = res.message.user.name.trim().toLowerCase()
for i in [finishedGames.length-1..0] by -1
fgame = finishedGames[i]
fgamePlayers = [fgame["team1"]["player1"], fgame["team1"]["player2"], fgame["team2"]["player1"], fgame["team2"]["player2"]]
if playerName in fgamePlayers
res.send "Rematch called by #{playerName}!"
startingPlayers = fgamePlayers.filter (name) -> name != playerName
startGameRespond(res, startingPlayers)
return
res.send "Nothing to rematch, you haven't played any previous games"
# Tournament responders
startTournamentWithNPeopleRespond = (res) ->
tournamentSize = parseInt(res.match[1].trim(), 10)
if !isPowerOfTwo(tournamentSize)
res.send "The number of must be a power of 2, and #{tournamentSize} is not!"
return
if tournamentSize < 4
res.send "You need at least 4 people to start a tournament!"
return
tournament['size'] = tournamentSize
startTournamentRespond(res)
startTournamentRespond = (res) ->
# Initialize the game with the top 16 players
# Save all players and their ranks at that time
# Create teams by pairing 1-16, 2-15, etc.
if tournament['started']
res.send 'Tournament has already been started! Please cancel the current one if you wish to start a new one.'
return
tournament = {
'allPlayers': [],
'tournamentPlayers': [],
'tournamentTeams': [],
'allGames': [],
'accepted': false,
'started': true,
'size': tournament['size'],
}
# Get all players
tournament['allPlayers'] = getRankings()
if tournament['allPlayers'].length < tournament['size']
res.send "Not enough players to start tournament. Have: #{tournament['allPlayers'].length}; Need: #{tournament['size']}"
return
# Choose the top tournament['size'] players to participate
tournament['tournamentPlayers'] = tournament['allPlayers'].slice(0, tournament['size'])
prepareAndDistributeTournamentTeams()
saveTournament()
res.send 'Tournament started!'
showTournamentRespond(res)
prepareTournamentGames = () ->
# Clear the games
tournament['allGames'] = []
# Prepare games with log_2(tournament['size']/2) rounds
numRounds = Math.log2(tournament['size']/2)
for r in [numRounds-1..0] by -1
firstRound = false
if tournament['allGames'].length <= 0
firstRound = true
topTeam = true
gameRound = []
numGamesInRound = Math.pow(2, r)
for g in [0..numGamesInRound-1]
previousGames = false
if !firstRound
previousGames = [(2 * g), (2 * g) + 1]
nextGame = if numGamesInRound == 1 then false else Math.floor(g/2)
gameRound.push {
'previousGames': previousGames,
'nextGame': nextGame,
'team1': false,
'team2': false,
'finalScore': false,
'finished': false,
'topTeam': topTeam,
}
# Make sure teams display correctly
topTeam = !topTeam
tournament['allGames'].push gameRound
prepareAndDistributeTournamentTeams = () ->
# Prepare the games first
prepareTournamentGames()
# Make teams by pairing 1-16, 2-15, etc.
for i in [0..(tournament['size']/2)-1]
tournament['tournamentTeams'][i] = [
tournament['tournamentPlayers'][i]['name'],
tournament['tournamentPlayers'][tournament['size'] - 1 - i]['name'],
]
# Populate the first round with players, alternating between placing at the top or bottom of the bracket
i = 0
teamsDistributed = 0
bracketSideTop = true
for team in tournament['tournamentTeams']
if bracketSideTop
game = tournament['allGames'][0][i]
else
game = tournament['allGames'][0][tournament['allGames'][0].length - 1 - i]
if !game['team1']
game['team1'] = team
else
game['team2'] = team
teamsDistributed += 1
if teamsDistributed == 4
teamsDistributed = 0
i += 1
bracketSideTop = !bracketSideTop
cancelTournamentRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Empty out the object containing the tournament info
tournament = {'started': false, 'size': _DEFAULT_TOURNAMENT_SIZE}
saveTournament()
res.send "Tournament cancelled"
showTournamentRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Print the tournament tree, in the following format
# -------------|
# goofy, daffy |
# |
# [9-1]|--------------|
# | goofy, daffy |
# mick, minnie | |
# -------------| |
# [9-3]|--- goofy, daffy
# -------------| |
# pluto, don | |
# | pluto, don |
# [2-9]|--------------|
# |
# noob, mike |
# -------------|
startingLine = 0
width = 6
betweenGamesWidth = 2
numStartingGames = tournament['allGames'][0].length
numLines = (numStartingGames * width) + ((numStartingGames - 1) * betweenGamesWidth)
# Add one "column" for each round
strTree = new Array(numLines + 2).fill('') # Initialize with empty lines, to add to later
for gameRound in tournament['allGames']
longestLineLength = 7
for game in gameRound
if game['team1']
longestLineLength = Math.max(longestLineLength, "#{game['team1']}".length + 7)
if game['team2']
longestLineLength = Math.max(longestLineLength, "#{game['team2']}".length + 7)
# Draw each of the games
numGames = gameRound.length
currentLine = startingLine
for i in [0..numGames-1]
game = gameRound[i]
gameStartingLine = currentLine
# Draw the two lines on the top and bottom of the game
strTree[currentLine] += '-'.repeat(longestLineLength)
currentLine += width
strTree[currentLine] += '-'.repeat(longestLineLength)
# Draw the team names in the
currentLine = gameStartingLine + 1
if game['team1']
teamStr = " #{game['team1']}"
strTree[currentLine] += teamStr + ' '.repeat(longestLineLength - teamStr.length)
currentLine += width - 2
if game['team2']
teamStr = " #{game['team2']}"
strTree[currentLine] += teamStr + ' '.repeat(longestLineLength - teamStr.length)
# Draw the score in the middle
currentLine = gameStartingLine
currentLine += (width/2)
score = if game['finalScore'] then game['finalScore'] else '?-?'
score = "[#{score}]"
strTree[currentLine] += ' '.repeat(longestLineLength - score.length)
strTree[currentLine] += score
# Add the vertical lines
currentLine = gameStartingLine
while currentLine <= gameStartingLine+width
if !(/(]|-|\w)$/.test(strTree[currentLine].trim()))
strTree[currentLine] += ' '.repeat(longestLineLength)
strTree[currentLine] += '|'
currentLine += 1
if i < (numGames - 1)
endLine = (currentLine + betweenGamesWidth - 1)
while currentLine < endLine
strTree[currentLine] += ' '.repeat(longestLineLength+1)
currentLine += 1
# Update where to start drawing the next round
startingLine = startingLine + (width/2)
width += betweenGamesWidth
betweenGamesWidth = width
# Draw the final winner line
winrar = '?'
finalGame = tournament['allGames'][tournament['allGames'].length-1][0]
if finalGame['finished']
score = finalGame['finalScore'].split('-')
t1score = parseInt(score[0], 10)
t2score = parseInt(score[1], 10)
if t1score > t2score
winrar = "#{finalGame['team1']}"
else
winrar = "#{finalGame['team2']}"
strTree[startingLine] += "--- :trophy: #{winrar}"
res.send strTree.join('\n')
showTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# List all the players currently in the tournament and their ranks at the time of joining
strPlayers = ['Rank:\tName:']
for player in tournament['tournamentPlayers']
strPlayers.push "#{player.rank}\t#{player.name}"
res.send strPlayers.join('\n')
showTournamentTeamsRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# List all the teams currently in the tournament
strTeams = []
for t, i in tournament['tournamentTeams']
strTeams.push "Team #{i}:\n#{t[0]}, #{t[1]}"
res.send strTeams.join('\n\n')
swapTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Try to swap two players
# If players have been accepted, error out
if tournament['playersAccepted']
res.send 'Tournament players have been accepted, you can\'t make modifications anymore!'
return
p1Name = res.match[1].trim().toLowerCase()
p2Name = res.match[2].trim().toLowerCase()
# If the second player didn't exist when the tournament was started, error out
p2 = false
for p in tournament['allPlayers']
if p['name'] == p2Name
p2 = p
break
if !p2
res.send "Player \"#{p2Name}\" did not exist when the tournament was started!"
return
# If the first player isn't in the tournament, error out
p1Index = false
for i in [0..tournament['tournamentPlayers'].length-1]
if tournament['tournamentPlayers'][i]['name'] == p1Name
p1Index = i
# If the second player is already in the tournament, error out
if tournament['tournamentPlayers'][i]['name'] == p2Name
res.send "Player \"#{p2Name}\" is already in the tournament!"
return
if !p1Index
res.send "Player \"#{p1Name}\" is not in the tournament!"
return
tournament['tournamentPlayers'][p1Index] = p2
# Sort the players by the new rank
tournament['tournamentPlayers'] = tournament['tournamentPlayers'].sort(rankSort)
prepareAndDistributeTournamentTeams()
saveTournament()
res.send "Successfully swapped \"#{p1Name}\" with \"#{p2Name}\". Teams have been rebalanced."
acceptTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Freeze the players
tournament['playersAccepted'] = true
saveTournament()
res.send 'Players accepted, tournament is ready to go!'
isInvalidGenericIndex = (genericIndex, maxLength) ->
return isNaN(genericIndex) || genericIndex < 0 || genericIndex >= maxLength
finishTournamentGameRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
roundNum = parseInt(res.match[1].trim(), 10)
gameNum = parseInt(res.match[2].trim(), 10)
score = res.match[3].trim().split('-')
t1score = parseInt(score[0], 10)
t2score = parseInt(score[1], 10)
# Finish a game, as indicated in the tree diagram
# If players have not been accepted, error out
if !tournament['playersAccepted']
res.send 'Tournament players have not been accepted yet!'
return
# If the game does not exist, error out
if isInvalidGenericIndex(roundNum, tournament['allGames'].length)
res.send "Invalid round #{roundNum}"
return
gameRound = tournament['allGames'][roundNum]
if isInvalidGenericIndex(gameNum, gameRound.length)
res.send "Invalid game #{gameNum} in round #{roundNum}"
return
game = gameRound[gameNum]
# If the game does not have both teams yet, error out
if !game['team1'] || !game['team2']
res.send "Game #{gameNum} in round #{roundNum} isn't ready to go yet!"
return
# If the game has been finished already, error out
if game['finished']
res.send "Game #{gameNum} in round #{roundNum} has already finished!"
return
# If the game is even, error out
if t1score == t2score
res.send "Cannot finish a tournament game with an even score, someone must lose"
return
# Finish the game and record the score
game['finished'] = true
game['finalScore'] = "#{t1score}-#{t2score}"
# Determine the winner
winrar = game['team2']
losar = game['team1']
strScore = "#{t2score}-#{t1score}"
if t1score > t2score
winrar = game['team1']
losar = game['team2']
strScore = "#{t1score}-#{t2score}"
if game['nextGame'] == false
# If the game finished is the final game, print out a congratulatory message and fanfare, crowning the champions
res.send "Tournament is over! Congratulations to the champions!"
res.send ":trophy::trophy::trophy: #{winrar} :trophy::trophy::trophy:"
else
# Add the team to the next game
nextGame = tournament['allGames'][roundNum+1][game['nextGame']]
if game['topTeam']
nextGame['team1'] = winrar
else
nextGame['team2'] = winrar
res.send "Finished game #{gameNum} in round #{roundNum}! #{winrar} beat #{losar} with a score of #{strScore}"
showTournamentRespond(res)
saveTournament()
retireRespond = (res) ->
retiree = res.message.user.name.trim().toLowerCase()
if retiree in retirees
res.send "You've already retired, you can't double retire!"
return
retirees.push retiree
saveRetirees()
res.send "#{retiree} has permanently retired!"
unretireRespond = (res) ->
retiree = res.message.user.name.trim().toLowerCase()
if !(retiree in retirees)
res.send "You're still kicking"
return
retirees.splice(retirees.indexOf(retiree), 1)
saveRetirees()
res.send "#{retiree} is back in the action!"
# Betting commands
startBettingRespond = (res) ->
highRoller = res.message.user.name.trim().toLowerCase()
if highRoller of accounts
res.send "You have already bought in, you can't buy in again"
return
accounts[highRoller] = _STARTING_FOOSCOIN
saveAccounts()
res.send "#{highRoller} bought in! They start with #{_STARTING_FOOSCOIN}Ģ"
myBalanceRespond = (res) ->
me = res.message.user.name.trim().toLowerCase()
# Error out if person has not bought in yet
if !(me of accounts)
res.send 'You have not bought in yet!'
return
balance = customRound(accounts[me], 4)
res.send "@#{me}, you have #{balance}Ģ"
betRespond = (res) ->
better = res.message.user.name.trim().toLowerCase()
betAmount = parseFloat(res.match[1].trim(), 10)
n = parseInt(res.match[2].trim(), 10)
teamToBetOn = parseInt(res.match[3].trim(), 10)
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
game = games[n]
if game['players'].indexOf(better) >= 0
res.send "You can't bet on a game you're playing in!"
return
if !(better of accounts)
res.send "You have not bought in yet!"
return
# Temporarily bring back the previous bet, then restore it if there are insufficient funds
currentBetAmount = if better of game['bets'] then game['bets'][better]['amount'] else 0
accounts[better] += currentBetAmount
if accounts[better] < betAmount
accounts[better] -= currentBetAmount
res.send "You can't bet #{betAmount}Ģ, you only have #{accounts[better]}Ģ!"
return
# Place the bet, taking it out of the better's account
accounts[better] -= betAmount
game['bets'][better] = {
'amount': betAmount,
'team': teamToBetOn
}
sliceIndex = teamToBetOn * 2
teamMembers = game['players'].slice(sliceIndex, sliceIndex + 2)
saveAccounts()
saveGames()
res.send "#{better} bet #{betAmount}Ģ on game #{n} for #{teamMembers}! They have #{accounts[better]}Ģ left"
cancelBetRespond = (res) ->
better = res.message.user.name.trim().toLowerCase()
n = parseInt(res.match[1].trim(), 10)
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
game = games[n]
if !(better of game['bets'])
res.send "You have not placed a bet on game #{n}"
return
if !(better of accounts)
res.send "You couldn't have place a bet on game #{n}, you haven't bought in yet!"
return
accounts[better] += game['bets'][better]['amount']
delete game['bets'][better]
saveAccounts()
saveGames()
res.send "#{better} cancelled bet on game #{n}, they have #{accounts[better]}Ģ left"
returnBets = (res, n) ->
game = games[n]
if Object.keys(game['bets']).length < 1
return
for betterName of game['bets']
if betterName of accounts
accounts[betterName] += game['bets'][betterName]['amount']
res.send "#{betterName} got #{game['bets'][betterName]['amount']}Ģ back, they have #{accounts[betterName]}Ģ left"
game['bets'] = {}
saveAccounts()
saveGames()
res.send "All bets returned for game #{n}"
tipOfTheDaySend = (robot) ->
return () ->
topd = 'Here is your Tip Of The Day™!\n\n'
randomTip = _TIPS[Math.round(Math.random() * (_TIPS.length - 1))]
topd += randomTip
robot.send room: process.env.FOOSBALL_ROOM_ID, topd
module.exports = (robot) ->
robot.respond /games/i, gamesRespond
robot.respond /total games/i, totalGamesRespond
robot.respond /find (?:people|players) for game (\d+)/i, findPeopleForGameRespond
robot.respond /join game (\d+)/i, joinGameRespond
robot.respond /add (\w+) to game (\d+)/i, addToGameRespond
robot.respond /kick (\w+) from game (\d+)/i, kickFromGameRespond
robot.respond /abandon game (\d+)/i, abandonGameRespond
robot.respond /cancel game (\d+)/i, cancelGameRespond
robot.respond /balance game (\d+)/i, balanceGameRespond
robot.respond /shuffle game (\d+)/i, shuffleGameRespond
robot.respond /start game$/i, startGameRespond
robot.respond /start game(?: with)?(( \w+){1,3})$/i, startGameWithPlayersRespond
robot.respond /find people$|find players$/i, findPeopleForNextGameRespond
robot.respond /i'm in/i, joinNextGameRespond
robot.respond /join game$/i, joinNextGameRespond
robot.respond /add (\w+)$/i, addToNextGameRespond
robot.respond /kick (\w+)$/i, kickFromNextGameRespond
robot.respond /abandon game$/i, abandonNextGameRespond
robot.respond /cancel game$/i, cancelNextGameRespond
robot.respond /balance game$/i, balanceNextGameRespond
robot.respond /shuffle game$/i, shuffleNextGameRespond
robot.respond /rematch/i, rematchRespond
robot.respond /finish game +(\d-\d)$/i, finishGameRespond
robot.respond /(rankings|leaderboard)$/i, rankingsRespond
robot.respond /(?:stats|rankings)(( \w+)+)$/i, rankingsForPlayersRespond
robot.respond /top (\d+).*$/i, topNRankingsRespond
robot.respond /reset previous rankings$/i, resetPreviousRankings
robot.respond /history (\w+) ?(\d+|all)?$/i, historyMeRespond
robot.respond /team history (\w+) (\w+) ?(\d+|all)?$/i, teamHistoryRespond
robot.respond /rival history (\w+) (\w+) ?(\d+|all)?$/i, rivalHistoryRespond
robot.respond /team stats (\w+) (\w+)$/i, teamStatsRespond
robot.respond /go on (a )?cleanse$/i, goOnACleanseRespond
robot.respond /return from cleanse$/i, returnFromCleanseRespond
robot.respond /retire/i, retireRespond
robot.respond /unretire/i, unretireRespond
# Tournament commands
robot.respond /start tournament$/i, startTournamentRespond
robot.respond /start tournament with (\d+) people/i, startTournamentWithNPeopleRespond
robot.respond /cancel tournament/i, cancelTournamentRespond
robot.respond /show tournament$/i, showTournamentRespond
robot.respond /show tournament players/i, showTournamentPlayersRespond
robot.respond /show tournament teams/i, showTournamentTeamsRespond
robot.respond /swap tournament player (\w+) with (\w+)/i, swapTournamentPlayersRespond
robot.respond /accept tournament players/i, acceptTournamentPlayersRespond
robot.respond /finish tournament game round (\d+) game (\d+) (\d-\d)/i, finishTournamentGameRespond
# Betting commands
robot.respond /start betting/i, startBettingRespond
robot.respond /(my )?balance$/i, myBalanceRespond
robot.respond /bet (\d+\.\d+) on game (\d+) team ([01])/i, betRespond
robot.respond /cancel bet on game (\d+)/i, cancelBetRespond
# Helpful stuff
robot.respond /the rules/i, theRulesRespond
robot.respond /tip/i, tipRespond
schedule.scheduleJob "0 30 11 * * 1-5", tipOfTheDaySend(robot)
| 181618 | # Description:
# An LCB bot that arranges foosball games
#
# Commands:
# foosbot Games - List currently scheduled games
# foosbot Total games - Return the number of total games
# foosbot Start game - Start a new game, always added to the end of the queue
# foosbot Start game with <p1> [<p2> <p3>] - Start a new game, always added to the end of the queue, with multiple people
# foosbot Find people|players - Ask for people to play in the next game
# foosbot I'm in | Join game - Claim a spot in the next game
# foosbot Add <player_name> - Add a player that may or may not be on LCB to the next game
# foosbot Kick <player_name> - Kick a player from the next game
# foosbot Abandon game - Free up your spot in the next game
# foosbot Cancel game - Cancel the next game
# foosbot Balance game - Balance the next game based on player ranks
# foosbot Shuffle game - Randomly shuffle the players in the next game
# foosbot Find people|players for game <n> - Ask for people to play in the nth game
# foosbot Join game <n> - Claim a spot in the nth game
# foosbot Add <player_name> to game <n> - Add a player that may or may not be on LCB to the nth game
# foosbot Kick <player_name> from game <n> - Kick a player from the nth game
# foosbot Abandon game <n> - Free up your spot in the nth game
# foosbot Cancel game <n> - Cancel the nth game
# foosbot Balance game <n> - Balance the nth game based on player ranks
# foosbot Shuffle game <n> - Randomly shuffle the players in the nth game
# foosbot Finish game <team1_score>-<team2_score> - Finish the next game in order and record the results
# foosbot Rematch - Repair your pride by playing the same game you just lost
# foosbot Go on [a] cleanse - Go on a cleanse, unable to be added to a game
# foosbot Return from cleanse - Return refreshed, ready to take on the champions
# foosbot Retire - Hang up the gloves for good
# foosbot Unretire - Rise up from the ashes of old age and get back to the table
# foosbot Rankings|Leaderboard - Show the leaderboard
# foosbot Rankings|Stats <player1> [<player2> ...] - Show the stats for specific players
# foosbot Top <n> - Show the top n players in the rankings
# foosbot History <player>|me [<numPastGames>|all] - Show a summary of your past games
# foosbot Team history <player>|me <otherPlayer> [<numPastGames>|all] - Show a summary of past games with a specific teammate
# foosbot Rival history <player>|me <otherPlayer> [<numPastGames>|all] - Show a summary of past games against a specific rival
# foosbot Team Stats <playerOne>|me <playerTwo>|me|all - Shows the team stats for two players, or all pairings of <playerOne>
# foosbot The rules - Show the rules we play by
# foosbot Start tournament - Begin a new tournament (cannot run multiple tournaments at once)
# foosbot Start tournament with <n> people - Begin a new tournament with some number of people (must be a power of 2)
# foosbot Cancel tournament - Cancel the currently running tournament (nothing will get saved)
# foosbot Show tournament - Show the current tournament tree
# foosbot Show tournament players - Show all the players involved in the tournament
# foosbot Show tournament teams - Show all the teams involved in the tournament
# foosbot Swap tournament player <current_player> with <new_player> - Replace a player in the tournament (only works with players that had ranks when the tournament was started)
# foosbot Accept tournament players - Confirm the player selection and officially begin the tournament
# foosbot Finish tournament game round <n1> game <n2> <team1_score>-<team2_score> - Finish a game and have the team move on
# foosbot Start betting - Join the betting pool
# foosbot My balance - Ask for your current balance
# foosbot Bet <x.y> on game <n> team (0|1) - Place a bet of <x.y>Ģ (i.e. 5.2) on game <n> for team 0 or 1 (placing again replaces your previous bet)
# foosbot Cancel bet on game <n> - Withdraw your bet for game <n>
# foosbot Tip - Get a helpful tip!
#
# Author:
# <NAME>
fs = require 'fs'
ts = require 'trueskill'
schedule = require 'node-schedule'
# Must be a power of 2
_DEFAULT_TOURNAMENT_SIZE = 16
# Betting constants
_STARTING_FOOSCOIN = 30.0
_MATCH_WIN_AMOUNT = 5.0
_HOUSE_PRIZE_BASE = 5.0
# Rules and tips
_THE_RULES = [
"No spinning",
"If someone scores with the first shot, it doesn't count",
"If someone scores by hitting the ball before it reaches the far wall, it doesn't count",
"Any player can score from any position",
"When one team reaches 5 points, both teams switch defense/offense players",
"If a shot goes in but comes out, it counts as long as it made the *dank* sound",
"The last goal cannot be an own goal, it must be scored by the opposing team",
"If unsure whether a goal counts, the team that got scored on makes the call",
"If the ball goes dead anywhere except the far sides, reset to the middle",
"If the ball goes dead on a far side, defense resets it from a corner",
"If the ball flies off the table, reset to the middle",
"If it wasn't organized by foosbot, it's a friendly game and does not affect rankings",
"Everyone has 3 seconds after a drop to call a redrop",
"If a player takes both hands off the handles and clearly stops playing, play is considered paused",
"If you get shut out, you have to crawl under the table"
"Everyone shakes hands at the end of the game, no exceptions",
]
_TIPS = [
"Keep your goalie in the center if you're not sure what to do",
"Take your time and control the ball for a better shot",
"Stagger your players when defending",
"Try not to shoot straight through the center",
"Keep your players the ball is behind them, so you don't block your partner's shot",
"Keep your defenders pointed inwards to make angle shots harder",
"To slapshot, place the bottom of your plam flat out, push forward, then pull up and grab",
"Close the gaps that lead to your net",
"Don't instinctively move your players back when the ball goes past them, you might score on yourself",
"Watch the ball, not the player, don't be fooled by dekes",
"Keep moving! Don't stop and pause just because your opponent did",
"Watch the hands and react to that, they're a tell before the actual move",
"Try to avoid patterns in your movement",
"Try to avoid crossing your goalie and your defenders, that leaves a gap through which to shoot",
"Guard the posts, but try not to linger there",
"Try to control the ball instead of shooting right away",
"Don't move for no reason if you're in a good position",
"Don't panic on slow shots! Concentrate and punish back",
"Keep an eye on your players more than on the ball when it's not in your half",
"Vary your shots, don't do the same thing from the same position over and over",
"Forget mistakes quickly and start thinking about the next play",
"Don't talk too much or you'll get distracted and make a mistake",
]
gamesFile = 'games.json'
finishedGamesFile = 'finishedgames.json'
previousRanksFile = 'previousranks.json'
cleanseFile = 'cleanse.json'
retireesFile = 'retirees.json'
tournamentFile = 'tournament.json'
accountsFile = 'accounts.json'
loadFile = (fileName, initialValue) ->
# Initialize the file if it does not exist
if !(fs.existsSync(fileName))
fs.writeFileSync(fileName, JSON.stringify(initialValue))
return JSON.parse((fs.readFileSync fileName, 'utf8').toString().trim())
saveFile = (fileName, data) ->
fs.writeFileSync(fileName, JSON.stringify(data))
games = loadFile(gamesFile, [])
finishedGames = loadFile(finishedGamesFile, [])
previousRanks = loadFile(previousRanksFile, {})
cleanse = loadFile(cleanseFile, [])
retirees = loadFile(retireesFile, [])
tournament = loadFile(tournamentFile, {'started': false, 'size': _DEFAULT_TOURNAMENT_SIZE})
accounts = loadFile(accountsFile, {})
saveGames = () ->
saveFile(gamesFile, games)
saveFinishedGames = () ->
saveFile(finishedGamesFile, finishedGames)
savePreviousRanks = () ->
saveFile(previousRanksFile, previousRanks)
saveCleanse = () ->
saveFile(cleanseFile, cleanse)
saveRetirees = () ->
saveFile(retireesFile, retirees)
saveTournament = () ->
saveFile(tournamentFile, tournament)
saveAccounts = () ->
saveFile(accountsFile, accounts)
# Date diff calculations
_MS_PER_DAY = 1000 * 60 * 60 * 24
diffDays = (date1, date2) ->
return Math.round((date1 - date2) / _MS_PER_DAY, 0)
# Store list of datetimes of previous plays
_SHAME_MESSAGES = [
"Playing again, huh?",
"Shouldn't you be doing...work?",
"Wow, look at your rank after all these games you've played!",
"You could have finished that ticket in the time you've spent playing foosball today",
"Aren't your hands tired by now?",
"Maybe it's time you took a break from foos",
"Are you /really/ sure you want to keep playing today?",
]
_DEFAULT_SHAME_MESSAGE = "Maximum slack level reached, HR has been notified"
getShameMsg = (res, player, timesPlayed) ->
shameMsg = if timesPlayed >= 10 then _DEFAULT_SHAME_MESSAGE else res.random _SHAME_MESSAGES
return "@#{player} #{shameMsg}"
# Store shame
shameFile = 'shame.json'
shame = JSON.parse((fs.readFileSync shameFile, 'utf8').toString().trim())
for player of shame
shame[player] = shame[player].map (playTime) -> new Date(playTime)
saveShame = () ->
fs.writeFileSync(shameFile, JSON.stringify(shame))
# Shame players who play too much
updateShame = (player) ->
if !(player of shame)
shame[player] = []
now = new Date()
shame[player].push now
saveShame()
shameSlacker = (res, player) ->
player = player.trim().toLowerCase()
if !(player of shame)
return
# Remove all recorded plays older than 1 day and not on the same calendar date
now = new Date()
shame[player] = shame[player].filter (playTime) -> (diffDays(now, playTime) == 0) && (playTime.getDate() == now.getDate())
saveShame()
timesPlayed = shame[player].length
if timesPlayed >= 3
res.send getShameMsg(res, player, timesPlayed)
isUndefined = (myvar) ->
return typeof myvar == 'undefined'
isPowerOfTwo = (mynum) ->
return (Math.log2(mynum) % 1) == 0
rightPad = (s, finalLength) ->
numSpaces = Math.max(0, finalLength - s.length)
return s + ' '.repeat(numSpaces)
customRound = (num, decimals) ->
return Number(Math.round(num+'e'+decimals)+'e-'+decimals);
gamesRespond = (res) ->
# List the games, in groups of 4, with the indices
if games.length <= 0
res.send "No games started"
return
responseLines = []
for game, index in games
gamePlayers = game['players']
team1 = "#{gamePlayers[0]} and #{gamePlayers[1]}"
team2 = "#{gamePlayers[2]} and #{gamePlayers[3]}"
# Calculate bets for each team
team1Bets = 0.0
team2Bets = 0.0
for betterName of game['bets']
bet = game['bets'][betterName]
if bet['team'] == 0
team1Bets += bet['amount']
else
team2Bets += bet['amount']
if team1Bets > 0
team1 += " (#{team1Bets}Ģ bet)"
if team2Bets > 0
team2 += " (#{team2Bets}Ģ bet)"
responseLines.push "Game #{index}:\n#{team1}\nvs.\n#{team2}\n"
res.send responseLines.join('\n')
startGameRespond = (res, startingPlayers) ->
# Create a new group of four, at the end of the games array
captain = res.message.user.name
if captain in cleanse
res.reply "You can't start any games, you're on a cleanse!"
return
if captain in retirees
res.reply "You can't start any games, you're retired!"
return
games.push {
"players": [captain, '_', '_', '_'],
"bets": {}
}
saveGames()
shameSlacker(res, captain)
res.send "New game started"
if !(isUndefined(startingPlayers))
n = games.length - 1
for sp in startingPlayers
joinGameRespond(res, n, sp)
gamesRespond(res)
startGameWithPlayersRespond = (res) ->
startingPlayers = (name.trim() for name in res.match[1].trim().split(' '))
res.send "Starting players: #{startingPlayers}"
startGameRespond(res, startingPlayers)
isInvalidIndex = (gameIndex) ->
return isNaN(gameIndex) || gameIndex < 0 || gameIndex >= games.length
findPeopleForGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
gameStr = if n == 0 then "Next game" else "Game #{n}"
gamePlayers = games[n]['players']
currentPlayers = (player for player in gamePlayers when player != "_")
spotsLeft = 4 - currentPlayers.length
if spotsLeft <= 0
res.send "No spots left in #{gameStr}"
return
# Ask @all who's up for a game, and announce who's currently part of the nth game
currentPlayers = currentPlayers.join(', ')
res.send "@all Who's up for a game? #{gameStr} has #{spotsLeft} spots, current players are #{currentPlayers}"
initOrRetrievePlayerStat = (stats, playerName) ->
if playerName of stats
return stats[playerName]
return {
"gamesPlayed": 0,
"gamesWon": 0,
"winPercentage": 0,
"skill": [25.0, 25.0/3.0],
"rank": 2,
"streak": 0,
"longestWinStreak": 0,
"longestLoseStreak": 0,
}
getStats = () ->
# Return stats for all players, which is a map from player name to object with games played, games won, and win percentage
stats = {}
for finishedGame in finishedGames
t1p1 = finishedGame['team1']['player1']
t1p2 = finishedGame['team1']['player2']
t2p1 = finishedGame['team2']['player1']
t2p2 = finishedGame['team2']['player2']
t1score = finishedGame['team1']['score']
t2score = finishedGame['team2']['score']
allPlayers = [t1p1, t1p2, t2p1, t2p2]
for player in allPlayers
stats[player] = initOrRetrievePlayerStat(stats, player)
stats[player]['gamesPlayed'] += 1
stats[player]['rank'] = 2
winPlayers = []
losePlayers = []
if t1score > t2score
winPlayers = [t1p1, t1p2]
losePlayers = [t2p1, t2p2]
else if t2score > t1score
winPlayers = [t2p1, t2p2]
losePlayers = [t1p1, t1p2]
for wp in winPlayers
stats[wp]['gamesWon'] += 1
stats[wp]['rank'] = 1
# If they were losing until this game, reset them to a 1 win streak
stats[wp]['streak'] = if stats[wp]['streak'] < 0 then 1 else stats[wp]['streak'] + 1
if stats[wp]['streak'] > stats[wp]['longestWinStreak']
stats[wp]['longestWinStreak'] = stats[wp]['streak']
for lp in losePlayers
# If they were winning until this game, reset them to a 1 lose streak
stats[lp]['streak'] = if stats[lp]['streak'] > 0 then -1 else stats[lp]['streak'] - 1
if -stats[lp]['streak'] > stats[lp]['longestLoseStreak']
stats[lp]['longestLoseStreak'] = -stats[lp]['streak']
ts.AdjustPlayers([stats[t1p1], stats[t1p2], stats[t2p1], stats[t2p2]])
for player in Object.keys(stats)
stats[player]['name'] = player
stats[player]['winPercentage'] = customRound((stats[player]['gamesWon'] / stats[player]['gamesPlayed']) * 100, 2)
stats[player]['trueskill'] = stats[player]['skill'][0] - (3 * stats[player]['skill'][1])
return stats
noopFormat = (str) -> return "#{str}"
fixedTwoFormat = (str) -> return "#{str.toFixed(2)}"
trueskillFormat = (str) -> return "#{str.toFixed(5)}"
percentFormat = (str) -> return "#{str}% "
gamesFormat = (str) -> return "#{str} game#{if str == 1 then '' else 's'}"
streakFormat = (str) ->
winning = str > 0
gameStreak = if winning then str else -str
return "#{if winning then ':fire:' else ':poop:'} #{gameStreak} #{if winning then 'won' else 'lost'}"
addColumn = (lines, stats, header, field, formatFunc, isFirstColumn) ->
isIndexColumn = !field
formatFunc = if isUndefined(formatFunc) then noopFormat else formatFunc
# Calculate the longest length, for padding
header = if isIndexColumn then "Rank" else "#{header}"
longestLength = header.length
longestHeaderLength = header.length
for stat, index in stats
fieldValue = if isIndexColumn then "#{index}" else formatFunc(stat[field])
longestLength = Math.max(longestLength, fieldValue.length)
# Convert emojis to a single character
collapsedFieldValue = fieldValue
collapsedFieldValue = collapsedFieldValue.replace /:.*:/g, (txt) -> ':::'
longestHeaderLength = Math.max(longestHeaderLength, collapsedFieldValue.length)
longestLength += 1
longestHeaderLength += 1
# Add the header and the underline
headerLength = longestHeaderLength + 2
lines[0] += rightPad(header, headerLength)
lines[1] += '-'.repeat(headerLength)
# Add the column for each statistic
for stat, index in stats
if isIndexColumn
fieldValue = rightPad("#{index+1}", longestLength)
else
fieldValue = rightPad(formatFunc(stat[field]), longestLength)
if !isFirstColumn
lines[2+index] += "| "
lines[2+index] += "#{fieldValue}"
skillSort = (p1, p2) ->
# High ranks are pushed to the front
if p1['trueskill'] > p2['trueskill']
return -1
if p1['trueskill'] < p2['trueskill']
return 1
# Order by games won next
if p1['gamesWon'] > p2['gamesWon']
return -1
if p1['gamesWon'] < p2['gamesWon']
return 1
# Order by win percentage last
return if p1['winPercentage'] >= p2['winPercentage'] then -1 else 1
getRankings = () ->
# Get the stats for each player
stats = getStats()
# Remove all retirees
for retiree in retirees
if retiree of stats
delete stats[retiree]
# Make a sortable array
rankings = []
for player in Object.keys(stats)
rankings.push stats[player]
# Sort the players based on rank
rankings.sort(skillSort)
for stat, rank in rankings
stat['rank'] = rank + 1
return rankings
rankingsRespond = (res, specificPlayers, topNPlayers) ->
# Get the player rankings
rankings = getRankings()
# Either filter or show topNPlayers players, but not both
if !(isUndefined(specificPlayers))
rankings = rankings.filter (stat) -> stat["name"] in specificPlayers
else if !(isUndefined(topNPlayers))
rankings = rankings.slice(0, topNPlayers)
# Construct the rankings string
responseList = new Array(rankings.length + 2).fill('') # Initialize with empty lines, to add to later
# addColumn(responseList, rankings, "", "", ) # Index column
addColumn(responseList, rankings, "Rank", "rank", noopFormat, true)
addColumn(responseList, rankings, "Player", "name")
addColumn(responseList, rankings, "Trueskill", "trueskill", trueskillFormat)
addColumn(responseList, rankings, "Win %", "winPercentage", percentFormat)
addColumn(responseList, rankings, "Won", "gamesWon")
addColumn(responseList, rankings, "Played", "gamesPlayed")
addColumn(responseList, rankings, "Streak", "streak", streakFormat)
addColumn(responseList, rankings, "Longest Win Streak", "longestWinStreak", gamesFormat)
addColumn(responseList, rankings, "Longest Lose Streak", "longestLoseStreak", gamesFormat)
res.send responseList.join('\n')
rankingsForPlayersRespond = (res) ->
players = (name.trim() for name in res.match[1].trim().split(' '))
rankingsRespond(res, players)
topNRankingsRespond = (res) ->
n = res.match[1].trim()
rankingsRespond(res, undefined, n)
resetPreviousRankings = (res) ->
rankings = getRankings()
for player, rank in rankings
previousRanks[player['name']] = rank + 1
savePreviousRanks()
showChangedRankings = (res, p1, p2, p3, p4) ->
rankChanges = "Rank changes:\n"
rankings = getRankings()
for p in [p1,p2,p3,p4]
curRank = getRank(p, rankings) + 1
if p of previousRanks
prevRank = previousRanks[p]
rankDiff = prevRank - curRank
prefix = if rankDiff < 0 then '' else if rankDiff == 0 then '=' else '+'
else
rankDiff = curRank
prefix = '~'
rankChanges += "#{prefix}#{rankDiff} -> #{curRank} #{p}\n"
resetPreviousRankings(res)
res.send rankChanges
rankSort = (p1,p2) ->
# Negative rank means the player isn't ranked
if p1['rank'] < 0
return -1
if p2['rank'] < 0
return 1
# A low rank is better than a high rank
return if p1['rank'] <= p2['rank'] then -1 else 1
getRank = (playerName, rankings) ->
for player, rank in rankings
if player['name'] == playerName
return rank
# If the player is new, they should be considered worse than anyone
return Infinity
balancePlayers = (game) ->
# Get the player rankings, which are sorted correctly
rankings = getRankings()
# Balance based on rank
playersWithRanks = game.map (player) -> {"name": player, "rank": getRank(player, rankings)}
playersWithRanks.sort(rankSort)
# Update the game
game[0] = playersWithRanks[0]["name"]
game[1] = playersWithRanks[3]["name"]
game[2] = playersWithRanks[1]["name"]
game[3] = playersWithRanks[2]["name"]
shufflePlayers = (n) ->
# Simply rotate the last 3 players left
game = games[n]["players"]
games[n]["players"] = [game[0]].concat(game.slice(2).concat(game[1]))
joinGameRespond = (res, n, playerName) ->
newPlayer = if isUndefined(playerName) then res.message.user.name else playerName
if newPlayer in cleanse
if isUndefined(playerName)
res.reply "You can't join any games, you're on a cleanse!"
else
res.send "#{newPlayer} cannot join games, they are on a cleanse!"
return
if newPlayer in retirees
if isUndefined(playerName)
res.reply "You can't join any games, you're retired!"
else
res.send "#{newPlayer} cannot join games, they are retired!"
return
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
any = if !any then false else true
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
shameSlacker(res, newPlayer)
gameStr = if n == 0 then "Next game" else "Game #{n}"
gamePlayers = games[n]['players']
if gamePlayers.indexOf(newPlayer) >= 0
res.send "You're already part of that game!"
return
# Add yourself to the nth game
for player, index in gamePlayers
if player == '_'
gamePlayers[index] = newPlayer
res.send "#{newPlayer} joined #{gameStr}!"
if gamePlayers.indexOf('_') < 0
balancePlayers(gamePlayers)
teamOneWinRate = getTeamStats(gamePlayers[0], gamePlayers[1])[gamePlayers[1]]["winPercentage"]
teamTwoWinRate = getTeamStats(gamePlayers[2], gamePlayers[3])[gamePlayers[3]]["winPercentage"]
teamsStr = "@#{gamePlayers[0]} and @#{gamePlayers[1]} (#{teamOneWinRate}%)\n"
teamsStr += "vs.\n"
teamsStr += "@#{gamePlayers[2]} and @#{gamePlayers[3]} (#{teamTwoWinRate}%)"
res.send "#{gameStr} is ready to go! Teams:\n#{teamsStr}"
saveGames()
return
# Cannot join if full
res.send "No spots in #{gameStr}"
abandonGameRespond = (res, n, playerName) ->
senderPlayer = if isUndefined(playerName) then res.message.user.name else playerName
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
gamePlayers = games[n]['players']
playerIndex = gamePlayers.indexOf(senderPlayer)
if playerIndex < 0
res.send "#{senderPlayer} is not part of Game #{n}"
return
# Return any bets placed on that game
returnBets(res, n)
gamePlayers[playerIndex] = '_'
saveGames()
# Abandon the nth game, freeing your spot in it
remainingPlayers = [(player for player in gamePlayers when player != "_")].join(', ')
res.send "#{senderPlayer} abandoned game #{n}. Remaining players: #{remainingPlayers}"
gamesRespond(res)
cancelGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
# Return any bets placed on that game
returnBets(res, n)
games.splice(n, 1)
saveGames()
# Cancel the nth game
res.send "Game #{n} cancelled"
gamesRespond(res)
findPeopleForNextGameRespond = (res) ->
# Ask @all who's up for a game, and announce who's currently part of the next upcoming game
findPeopleForGameRespond(res, 0)
joinNextGameRespond = (res) ->
# Add yourself to the next game
# Cannot join if full
joinGameRespond(res, 0)
abandonNextGameRespond = (res) ->
# Abandon the next upcoming game, freeing your spot in it
abandonGameRespond(res, 0)
cancelNextGameRespond = (res) ->
# Cancel the next upcoming game
cancelGameRespond(res, 0)
addToGameRespond = (res, n) ->
# Add a player to the nth game
playerName = res.match[1].trim()
n = if isUndefined(n) then parseInt(res.match[2].trim(), 10) else n
joinGameRespond(res, n, playerName)
addToNextGameRespond = (res) ->
# Add yourself to the next game
# Cannot join if full
addToGameRespond(res, 0)
kickFromGameRespond = (res, n) ->
# Kick a player from the nth game
playerName = res.match[1].trim()
n = if isUndefined(n) then parseInt(res.match[2].trim(), 10) else n
abandonGameRespond(res, n, playerName)
kickFromNextGameRespond = (res) ->
# Kick a player from the next game
kickFromGameRespond(res, 0)
balanceGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
balancePlayers(games[n]['players'])
saveGames()
gamesRespond(res)
res.send "Game #{n} balanced based on rank"
balanceNextGameRespond = (res) ->
balanceGameRespond(res, 0)
shuffleGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
shufflePlayers(n)
returnBets(res, n)
saveGames()
gamesRespond(res)
res.send "Game #{n} shuffled"
shuffleNextGameRespond = (res) ->
shuffleGameRespond(res, 0)
finishGameRespond = (res) ->
if games.length <= 0
res.send "No games are being played at the moment"
return
game = games[0]
gamePlayers = game['players']
if gamePlayers.indexOf('_') >= 0
res.send "Next game isn't ready to go yet!"
return
result = res.match[1].trim().split('-')
t1score = parseInt(result[0], 10)
t2score = parseInt(result[1], 10)
t1p1 = gamePlayers[0].trim().toLowerCase()
t1p2 = gamePlayers[1].trim().toLowerCase()
t2p1 = gamePlayers[2].trim().toLowerCase()
t2p2 = gamePlayers[3].trim().toLowerCase()
oldStats = getStats()
# The following is the format for game results
resultDetails = {
'team1': {
'player1': t1p1,
'player2': t1p2,
'score': t1score
},
'team2': {
'player1': t2p1,
'player2': t2p2,
'score': t2score
}
}
for player in [t1p1,t1p2,t2p1,t2p2]
updateShame(player)
if !(player of oldStats)
oldStats[player] = {
'trueskill': 0.0
}
# Record the scores and save them
finishedGames.push resultDetails
# Return the bets to the bet winners
winningTeam = if t1score > t2score then 0 else 1
betWinners = []
betWinnersTotalPool = 0
prizePool = 0
for betterName of game['bets']
if game['bets'][betterName]['team'] == winningTeam
betWinnersTotalPool += game['bets'][betterName]['amount']
# Return the winner's bet, but don't announce it
accounts[betterName] += game['bets'][betterName]['amount']
betWinners.push(betterName)
else
prizePool += game['bets'][betterName]['amount']
# Give extra money from the house, based on trueskill
winningTeamPlayers = if t1score > t2score then [t1p1,t1p2] else [t2p1,t2p2]
losingTeamPlayers = if t1score > t2score then [t2p1,t2p2] else [t1p1,t1p2]
winningTeamTrueskill = oldStats[losingTeamPlayers[0]]['trueskill'] + oldStats[losingTeamPlayers[1]]['trueskill']
losingTeamTrueskill = oldStats[winningTeamPlayers[0]]['trueskill'] + oldStats[winningTeamPlayers[1]]['trueskill']
housePrizeProportion = winningTeamTrueskill / losingTeamTrueskill
housePrize = customRound(housePrizeProportion * _HOUSE_PRIZE_BASE, 2)
if betWinners.length > 0
for betWinner in betWinners
if betWinner of accounts
# Award the house prize
accounts[betWinner] += housePrize
res.send "@#{betWinner} won #{housePrize}Ģ from the house!"
# Distribute the prize pool from the losers
if prizePool > 0
# Determine how much this winner should get, proportional to what they bet
proportion = customRound(game['bets'][betWinner]['amount'] / betWinnersTotalPool, 4)
betWinAmount = customRound(prizePool * proportion, 4)
accounts[betWinner] += betWinAmount
res.send "@#{betWinner} won #{betWinAmount}Ģ from betting!"
# Award a prize to the winners of the match, equal to the number of goals scored
matchWinners = if t1score > t2score then [t1p1,t1p2] else [t2p1,t2p2]
matchWinnersScore = if t1score > t2score then t1score else t2score
matchLosersScore = if t1score > t2score then t2score else t1score
matchWinAmount = Math.abs(t1score - t2score)
# Give more if the trueskill difference is larger
matchWinAmount += housePrizeProportion * 2 * matchWinAmount
# Determine how much of the opposing prize pool to give, with the goals as a percentage
if prizePool > 0
matchWinAmount += prizePool * (matchWinnersScore / 100.0)
# Double the win amount in case of a shutout
if matchLosersScore == 0
matchWinAmount = matchWinAmount * 2
res.send "Double fooscoins for a shutout win!"
res.send "https://media.giphy.com/media/gtakVlnStZUbe/giphy.gif"
for matchWinner in matchWinners
if matchWinner of accounts
accounts[matchWinner] += matchWinAmount
res.send "@#{matchWinner} won #{matchWinAmount}Ģ!"
saveAccounts()
saveFinishedGames()
# Show changed rankings since last time
showChangedRankings(res, t1p1, t1p2, t2p1, t2p2)
# Remove the game from the list
games.splice(0,1)
saveGames()
res.send "Results saved"
theRulesRespond = (res) ->
res.send _THE_RULES.map((rule, i) -> "#{i+1}. #{rule}").join('\n')
tipRespond = (res) ->
res.send res.random _TIPS
goOnACleanseRespond = (res) ->
senderName = res.message.user.name
if !(senderName in cleanse)
cleanse.push senderName
saveCleanse()
res.reply "You are now on a cleanse. Stay away from the foosball table, and relax :palm_tree:"
returnFromCleanseRespond = (res) ->
senderName = res.message.user.name
if !(senderName in cleanse)
res.reply "You are not on a cleanse, go play some foos!"
return
cleanse.splice(cleanse.indexOf(senderName), 1)
saveCleanse()
res.reply "Welcome back! Now go kick some ass"
initTeamStat = (stats, playerName) ->
stats[playerName] = {
"wins": 0,
"losses": 0,
"ties": 0,
"goalsFor": 0,
"goalsAgainst": 0,
"winPercentage": 0,
"avgGoalsFor": 0,
"avgGoalsAgainst": 0
}
getTeamStats = (playerOneName, playerTwoName) ->
# Allow getting stats for all team pairings by providing "all" as the playerTwoName
# The keys of the return dictionary are the names of the other team member
stats = {}
playerOneName = playerOneName.toLowerCase()
playerTwoName = playerTwoName.toLowerCase()
# Make sure the partner has the default stats
if !(playerTwoName == 'all')
initTeamStat(stats, playerTwoName)
for finishedGame in finishedGames
teamOne = [finishedGame["team1"]["player1"], finishedGame["team1"]["player2"]]
teamTwo = [finishedGame["team2"]["player1"], finishedGame["team2"]["player2"]]
if playerOneName in teamOne && (playerTwoName == 'all' || playerTwoName in teamOne)
myTeam = finishedGame["team1"]
otherTeam = finishedGame["team2"]
else if playerOneName in teamTwo && (playerTwoName == 'all' || playerTwoName in teamTwo)
myTeam = finishedGame["team2"]
otherTeam = finishedGame["team1"]
else
continue
# Get the partner's name
partnerName = if myTeam["player1"] == playerOneName then myTeam["player2"] else myTeam["player1"]
if !(partnerName of stats)
initTeamStat(stats, partnerName)
partnerStats = stats[partnerName]
if myTeam["score"] > otherTeam["score"]
partnerStats["wins"] += 1
else if myTeam["score"] == otherTeam["score"]
partnerStats["ties"] += 1
else
partnerStats["losses"] += 1
partnerStats["goalsFor"] += myTeam["score"]
partnerStats["goalsAgainst"] += otherTeam["score"]
# Extra Stats
for partnerName of stats
partnerStats = stats[partnerName]
gamesPlayed = partnerStats["wins"] + partnerStats["losses"] + partnerStats["ties"]
if gamesPlayed > 0
partnerStats["winPercentage"] = ((partnerStats["wins"] / gamesPlayed) * 100).toFixed(2)
partnerStats["avgGoalsFor"] = partnerStats["goalsFor"] / gamesPlayed
partnerStats["avgGoalsAgainst"] = partnerStats["goalsAgainst"] / gamesPlayed
return stats
teamStatsRespond = (res) ->
playerOneName = if res.match[1] == 'me' then res.message.user.name else res.match[1].trim().toLowerCase()
playerTwoName = if res.match[2] == 'me' then res.message.user.name else res.match[2].trim().toLowerCase()
if playerOneName == playerTwoName
res.send "Player one and player two cannot be the same."
return
teamStats = getTeamStats(playerOneName, playerTwoName)
# Build the response of stats for all team pairings
response = ''
for partnerName of teamStats
partnerStats = teamStats[partnerName]
responseList = new Array(3).fill('')
addColumn(responseList, [partnerStats], "Win", "wins", noopFormat, true)
addColumn(responseList, [partnerStats], "Loss", "losses")
addColumn(responseList, [partnerStats], "Tie", "ties")
addColumn(responseList, [partnerStats], "Avg. Goals For", "avgGoalsFor", fixedTwoFormat)
addColumn(responseList, [partnerStats], "Avg. Goals Against", "avgGoalsAgainst", fixedTwoFormat)
addColumn(responseList, [partnerStats], "Win Rate", "winPercentage", percentFormat)
response += "Team: #{playerOneName} and #{partnerName}\n"
response += responseList.join("\n")
response += "\n\n\n"
res.send response
historyMeRespond = (res) ->
me = res.match[1] == 'me'
playerName = if me then res.message.user.name else res.match[1].trim().toLowerCase()
numPastGames = if isUndefined(res.match[2]) then 5 else res.match[2].trim()
historyRespond(res, me, numPastGames, playerName)
multiHistoryRespond = (res, rivals) ->
me = res.match[1] == 'me'
playerName = if me then res.message.user.name else res.match[1].trim().toLowerCase()
otherPlayerName = res.match[2].trim().toLowerCase()
numPastGames = if isUndefined(res.match[3]) then 5 else res.match[3].trim()
historyRespond(res, me, numPastGames, playerName, otherPlayerName, rivals)
teamHistoryRespond = (res) ->
multiHistoryRespond(res, false)
rivalHistoryRespond = (res) ->
multiHistoryRespond(res, true)
historyRespond = (res, me, numPastGames, playerName, otherPlayerName, rivals) ->
gamesFound = 0
pastGames = []
if !(numPastGames == 'all')
numPastGames = parseInt(numPastGames, 10)
# Collect the last n games
for i in [finishedGames.length-1..0] by -1
fgame = finishedGames[i]
fgPlayers = [fgame["team1"]["player1"], fgame["team1"]["player2"], fgame["team2"]["player1"], fgame["team2"]["player2"]]
keepGame = false
if isUndefined(otherPlayerName)
# Single-player history
if playerName in fgPlayers
keepGame = true
else
# Team history
fgTeam1 = [fgame["team1"]["player1"], fgame["team1"]["player2"]]
fgTeam2 = [fgame["team2"]["player1"], fgame["team2"]["player2"]]
if rivals
keepGame = ((playerName in fgTeam1) && (otherPlayerName in fgTeam2)) || ((playerName in fgTeam2) && (otherPlayerName in fgTeam1))
else
keepGame = ((playerName in fgTeam1) && (otherPlayerName in fgTeam1)) || ((playerName in fgTeam2) && (otherPlayerName in fgTeam2))
if keepGame
pastGames.unshift(fgame)
gamesFound += 1
if numPastGames != 'all' && gamesFound >= numPastGames
break
pronoun = "#{playerName}'s"
together = ""
if !isUndefined(otherPlayerName)
pronoun = "#{playerName} and #{otherPlayerName}'s"
together = if rivals then " against each other" else " together"
gamesWon = 0
title = "#{pronoun} last #{numPastGames} games#{together}:"
strGames = ""
for pg, i in pastGames
score = '\t'
team1 = [pg["team1"]["player1"], pg["team1"]["player2"]]
team2 = [pg["team2"]["player1"], pg["team2"]["player2"]]
thisTeam = team1
thisTeamScore = pg['team1']['score']
otherTeamScore = pg['team2']['score']
if playerName in team2
thisTeam = team2
thisTeamScore = pg['team2']['score']
otherTeamScore = pg['team1']['score']
if thisTeamScore > otherTeamScore
gamesWon += 1
score = process.env.WIN_EMOJI
if otherTeamScore == 0
score += process.env.SHUTOUT_EMOJI
else if otherTeamScore == 8
score += process.env.CLOSE_WIN_EMOJI
score += '\t'
else if thisTeamScore == 0
score = process.env.NO_GOALS_EMOJI + '\t'
else if thisTeamScore == 8
score = process.env.CLOSE_LOSS_EMOJI + '\t'
score += "#{thisTeamScore}-#{otherTeamScore}"
if playerName == pg['team1']['player1']
teams = [pg['team1']['player1'], pg['team1']['player2'], pg['team2']['player1'], pg['team2']['player2']]
else if playerName == pg['team1']['player2']
teams = [pg['team1']['player2'], pg['team1']['player1'], pg['team2']['player1'], pg['team2']['player2']]
else if playerName == pg['team2']['player1']
teams = [pg['team2']['player1'], pg['team2']['player2'], pg['team1']['player1'], pg['team1']['player2']]
else
teams = [pg['team2']['player2'], pg['team2']['player1'], pg['team1']['player1'], pg['team1']['player2']]
strGames += "\n#{score}\t#{teams[0]} and #{teams[1]} vs. #{teams[2]} and #{teams[3]}"
strGames = title + "\nK-D ratio: #{gamesWon}-#{gamesFound-gamesWon}\n" + strGames
res.send strGames
totalGamesRespond = (res) ->
res.send finishedGames.length
rematchRespond = (res) ->
playerName = res.message.user.name.trim().toLowerCase()
for i in [finishedGames.length-1..0] by -1
fgame = finishedGames[i]
fgamePlayers = [fgame["team1"]["player1"], fgame["team1"]["player2"], fgame["team2"]["player1"], fgame["team2"]["player2"]]
if playerName in fgamePlayers
res.send "Rematch called by #{playerName}!"
startingPlayers = fgamePlayers.filter (name) -> name != playerName
startGameRespond(res, startingPlayers)
return
res.send "Nothing to rematch, you haven't played any previous games"
# Tournament responders
startTournamentWithNPeopleRespond = (res) ->
tournamentSize = parseInt(res.match[1].trim(), 10)
if !isPowerOfTwo(tournamentSize)
res.send "The number of must be a power of 2, and #{tournamentSize} is not!"
return
if tournamentSize < 4
res.send "You need at least 4 people to start a tournament!"
return
tournament['size'] = tournamentSize
startTournamentRespond(res)
startTournamentRespond = (res) ->
# Initialize the game with the top 16 players
# Save all players and their ranks at that time
# Create teams by pairing 1-16, 2-15, etc.
if tournament['started']
res.send 'Tournament has already been started! Please cancel the current one if you wish to start a new one.'
return
tournament = {
'allPlayers': [],
'tournamentPlayers': [],
'tournamentTeams': [],
'allGames': [],
'accepted': false,
'started': true,
'size': tournament['size'],
}
# Get all players
tournament['allPlayers'] = getRankings()
if tournament['allPlayers'].length < tournament['size']
res.send "Not enough players to start tournament. Have: #{tournament['allPlayers'].length}; Need: #{tournament['size']}"
return
# Choose the top tournament['size'] players to participate
tournament['tournamentPlayers'] = tournament['allPlayers'].slice(0, tournament['size'])
prepareAndDistributeTournamentTeams()
saveTournament()
res.send 'Tournament started!'
showTournamentRespond(res)
prepareTournamentGames = () ->
# Clear the games
tournament['allGames'] = []
# Prepare games with log_2(tournament['size']/2) rounds
numRounds = Math.log2(tournament['size']/2)
for r in [numRounds-1..0] by -1
firstRound = false
if tournament['allGames'].length <= 0
firstRound = true
topTeam = true
gameRound = []
numGamesInRound = Math.pow(2, r)
for g in [0..numGamesInRound-1]
previousGames = false
if !firstRound
previousGames = [(2 * g), (2 * g) + 1]
nextGame = if numGamesInRound == 1 then false else Math.floor(g/2)
gameRound.push {
'previousGames': previousGames,
'nextGame': nextGame,
'team1': false,
'team2': false,
'finalScore': false,
'finished': false,
'topTeam': topTeam,
}
# Make sure teams display correctly
topTeam = !topTeam
tournament['allGames'].push gameRound
prepareAndDistributeTournamentTeams = () ->
# Prepare the games first
prepareTournamentGames()
# Make teams by pairing 1-16, 2-15, etc.
for i in [0..(tournament['size']/2)-1]
tournament['tournamentTeams'][i] = [
tournament['tournamentPlayers'][i]['name'],
tournament['tournamentPlayers'][tournament['size'] - 1 - i]['name'],
]
# Populate the first round with players, alternating between placing at the top or bottom of the bracket
i = 0
teamsDistributed = 0
bracketSideTop = true
for team in tournament['tournamentTeams']
if bracketSideTop
game = tournament['allGames'][0][i]
else
game = tournament['allGames'][0][tournament['allGames'][0].length - 1 - i]
if !game['team1']
game['team1'] = team
else
game['team2'] = team
teamsDistributed += 1
if teamsDistributed == 4
teamsDistributed = 0
i += 1
bracketSideTop = !bracketSideTop
cancelTournamentRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Empty out the object containing the tournament info
tournament = {'started': false, 'size': _DEFAULT_TOURNAMENT_SIZE}
saveTournament()
res.send "Tournament cancelled"
showTournamentRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Print the tournament tree, in the following format
# -------------|
# goofy, daffy |
# |
# [9-1]|--------------|
# | goofy, daffy |
# <NAME> | |
# -------------| |
# [9-3]|--- goofy, daffy
# -------------| |
# pluto, don | |
# | pluto, don |
# [2-9]|--------------|
# |
# noob, mike |
# -------------|
startingLine = 0
width = 6
betweenGamesWidth = 2
numStartingGames = tournament['allGames'][0].length
numLines = (numStartingGames * width) + ((numStartingGames - 1) * betweenGamesWidth)
# Add one "column" for each round
strTree = new Array(numLines + 2).fill('') # Initialize with empty lines, to add to later
for gameRound in tournament['allGames']
longestLineLength = 7
for game in gameRound
if game['team1']
longestLineLength = Math.max(longestLineLength, "#{game['team1']}".length + 7)
if game['team2']
longestLineLength = Math.max(longestLineLength, "#{game['team2']}".length + 7)
# Draw each of the games
numGames = gameRound.length
currentLine = startingLine
for i in [0..numGames-1]
game = gameRound[i]
gameStartingLine = currentLine
# Draw the two lines on the top and bottom of the game
strTree[currentLine] += '-'.repeat(longestLineLength)
currentLine += width
strTree[currentLine] += '-'.repeat(longestLineLength)
# Draw the team names in the
currentLine = gameStartingLine + 1
if game['team1']
teamStr = " #{game['team1']}"
strTree[currentLine] += teamStr + ' '.repeat(longestLineLength - teamStr.length)
currentLine += width - 2
if game['team2']
teamStr = " #{game['team2']}"
strTree[currentLine] += teamStr + ' '.repeat(longestLineLength - teamStr.length)
# Draw the score in the middle
currentLine = gameStartingLine
currentLine += (width/2)
score = if game['finalScore'] then game['finalScore'] else '?-?'
score = "[#{score}]"
strTree[currentLine] += ' '.repeat(longestLineLength - score.length)
strTree[currentLine] += score
# Add the vertical lines
currentLine = gameStartingLine
while currentLine <= gameStartingLine+width
if !(/(]|-|\w)$/.test(strTree[currentLine].trim()))
strTree[currentLine] += ' '.repeat(longestLineLength)
strTree[currentLine] += '|'
currentLine += 1
if i < (numGames - 1)
endLine = (currentLine + betweenGamesWidth - 1)
while currentLine < endLine
strTree[currentLine] += ' '.repeat(longestLineLength+1)
currentLine += 1
# Update where to start drawing the next round
startingLine = startingLine + (width/2)
width += betweenGamesWidth
betweenGamesWidth = width
# Draw the final winner line
winrar = '?'
finalGame = tournament['allGames'][tournament['allGames'].length-1][0]
if finalGame['finished']
score = finalGame['finalScore'].split('-')
t1score = parseInt(score[0], 10)
t2score = parseInt(score[1], 10)
if t1score > t2score
winrar = "#{finalGame['team1']}"
else
winrar = "#{finalGame['team2']}"
strTree[startingLine] += "--- :trophy: #{winrar}"
res.send strTree.join('\n')
showTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# List all the players currently in the tournament and their ranks at the time of joining
strPlayers = ['Rank:\tName:']
for player in tournament['tournamentPlayers']
strPlayers.push "#{player.rank}\t#{player.name}"
res.send strPlayers.join('\n')
showTournamentTeamsRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# List all the teams currently in the tournament
strTeams = []
for t, i in tournament['tournamentTeams']
strTeams.push "Team #{i}:\n#{t[0]}, #{t[1]}"
res.send strTeams.join('\n\n')
swapTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Try to swap two players
# If players have been accepted, error out
if tournament['playersAccepted']
res.send 'Tournament players have been accepted, you can\'t make modifications anymore!'
return
p1Name = res.match[1].trim().toLowerCase()
p2Name = res.match[2].trim().toLowerCase()
# If the second player didn't exist when the tournament was started, error out
p2 = false
for p in tournament['allPlayers']
if p['name'] == p2Name
p2 = p
break
if !p2
res.send "Player \"#{p2Name}\" did not exist when the tournament was started!"
return
# If the first player isn't in the tournament, error out
p1Index = false
for i in [0..tournament['tournamentPlayers'].length-1]
if tournament['tournamentPlayers'][i]['name'] == p1Name
p1Index = i
# If the second player is already in the tournament, error out
if tournament['tournamentPlayers'][i]['name'] == p2Name
res.send "Player \"#{p2Name}\" is already in the tournament!"
return
if !p1Index
res.send "Player \"#{p1Name}\" is not in the tournament!"
return
tournament['tournamentPlayers'][p1Index] = p2
# Sort the players by the new rank
tournament['tournamentPlayers'] = tournament['tournamentPlayers'].sort(rankSort)
prepareAndDistributeTournamentTeams()
saveTournament()
res.send "Successfully swapped \"#{p1Name}\" with \"#{p2Name}\". Teams have been rebalanced."
acceptTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Freeze the players
tournament['playersAccepted'] = true
saveTournament()
res.send 'Players accepted, tournament is ready to go!'
isInvalidGenericIndex = (genericIndex, maxLength) ->
return isNaN(genericIndex) || genericIndex < 0 || genericIndex >= maxLength
finishTournamentGameRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
roundNum = parseInt(res.match[1].trim(), 10)
gameNum = parseInt(res.match[2].trim(), 10)
score = res.match[3].trim().split('-')
t1score = parseInt(score[0], 10)
t2score = parseInt(score[1], 10)
# Finish a game, as indicated in the tree diagram
# If players have not been accepted, error out
if !tournament['playersAccepted']
res.send 'Tournament players have not been accepted yet!'
return
# If the game does not exist, error out
if isInvalidGenericIndex(roundNum, tournament['allGames'].length)
res.send "Invalid round #{roundNum}"
return
gameRound = tournament['allGames'][roundNum]
if isInvalidGenericIndex(gameNum, gameRound.length)
res.send "Invalid game #{gameNum} in round #{roundNum}"
return
game = gameRound[gameNum]
# If the game does not have both teams yet, error out
if !game['team1'] || !game['team2']
res.send "Game #{gameNum} in round #{roundNum} isn't ready to go yet!"
return
# If the game has been finished already, error out
if game['finished']
res.send "Game #{gameNum} in round #{roundNum} has already finished!"
return
# If the game is even, error out
if t1score == t2score
res.send "Cannot finish a tournament game with an even score, someone must lose"
return
# Finish the game and record the score
game['finished'] = true
game['finalScore'] = "#{t1score}-#{t2score}"
# Determine the winner
winrar = game['team2']
losar = game['team1']
strScore = "#{t2score}-#{t1score}"
if t1score > t2score
winrar = game['team1']
losar = game['team2']
strScore = "#{t1score}-#{t2score}"
if game['nextGame'] == false
# If the game finished is the final game, print out a congratulatory message and fanfare, crowning the champions
res.send "Tournament is over! Congratulations to the champions!"
res.send ":trophy::trophy::trophy: #{winrar} :trophy::trophy::trophy:"
else
# Add the team to the next game
nextGame = tournament['allGames'][roundNum+1][game['nextGame']]
if game['topTeam']
nextGame['team1'] = winrar
else
nextGame['team2'] = winrar
res.send "Finished game #{gameNum} in round #{roundNum}! #{winrar} beat #{losar} with a score of #{strScore}"
showTournamentRespond(res)
saveTournament()
retireRespond = (res) ->
retiree = res.message.user.name.trim().toLowerCase()
if retiree in retirees
res.send "You've already retired, you can't double retire!"
return
retirees.push retiree
saveRetirees()
res.send "#{retiree} has permanently retired!"
unretireRespond = (res) ->
retiree = res.message.user.name.trim().toLowerCase()
if !(retiree in retirees)
res.send "You're still kicking"
return
retirees.splice(retirees.indexOf(retiree), 1)
saveRetirees()
res.send "#{retiree} is back in the action!"
# Betting commands
startBettingRespond = (res) ->
highRoller = res.message.user.name.trim().toLowerCase()
if highRoller of accounts
res.send "You have already bought in, you can't buy in again"
return
accounts[highRoller] = _STARTING_FOOSCOIN
saveAccounts()
res.send "#{highRoller} bought in! They start with #{_STARTING_FOOSCOIN}Ģ"
myBalanceRespond = (res) ->
me = res.message.user.name.trim().toLowerCase()
# Error out if person has not bought in yet
if !(me of accounts)
res.send 'You have not bought in yet!'
return
balance = customRound(accounts[me], 4)
res.send "@#{me}, you have #{balance}Ģ"
betRespond = (res) ->
better = res.message.user.name.trim().toLowerCase()
betAmount = parseFloat(res.match[1].trim(), 10)
n = parseInt(res.match[2].trim(), 10)
teamToBetOn = parseInt(res.match[3].trim(), 10)
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
game = games[n]
if game['players'].indexOf(better) >= 0
res.send "You can't bet on a game you're playing in!"
return
if !(better of accounts)
res.send "You have not bought in yet!"
return
# Temporarily bring back the previous bet, then restore it if there are insufficient funds
currentBetAmount = if better of game['bets'] then game['bets'][better]['amount'] else 0
accounts[better] += currentBetAmount
if accounts[better] < betAmount
accounts[better] -= currentBetAmount
res.send "You can't bet #{betAmount}Ģ, you only have #{accounts[better]}Ģ!"
return
# Place the bet, taking it out of the better's account
accounts[better] -= betAmount
game['bets'][better] = {
'amount': betAmount,
'team': teamToBetOn
}
sliceIndex = teamToBetOn * 2
teamMembers = game['players'].slice(sliceIndex, sliceIndex + 2)
saveAccounts()
saveGames()
res.send "#{better} bet #{betAmount}Ģ on game #{n} for #{teamMembers}! They have #{accounts[better]}Ģ left"
cancelBetRespond = (res) ->
better = res.message.user.name.trim().toLowerCase()
n = parseInt(res.match[1].trim(), 10)
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
game = games[n]
if !(better of game['bets'])
res.send "You have not placed a bet on game #{n}"
return
if !(better of accounts)
res.send "You couldn't have place a bet on game #{n}, you haven't bought in yet!"
return
accounts[better] += game['bets'][better]['amount']
delete game['bets'][better]
saveAccounts()
saveGames()
res.send "#{better} cancelled bet on game #{n}, they have #{accounts[better]}Ģ left"
returnBets = (res, n) ->
game = games[n]
if Object.keys(game['bets']).length < 1
return
for betterName of game['bets']
if betterName of accounts
accounts[betterName] += game['bets'][betterName]['amount']
res.send "#{betterName} got #{game['bets'][betterName]['amount']}Ģ back, they have #{accounts[betterName]}Ģ left"
game['bets'] = {}
saveAccounts()
saveGames()
res.send "All bets returned for game #{n}"
tipOfTheDaySend = (robot) ->
return () ->
topd = 'Here is your Tip Of The Day™!\n\n'
randomTip = _TIPS[Math.round(Math.random() * (_TIPS.length - 1))]
topd += randomTip
robot.send room: process.env.FOOSBALL_ROOM_ID, topd
module.exports = (robot) ->
robot.respond /games/i, gamesRespond
robot.respond /total games/i, totalGamesRespond
robot.respond /find (?:people|players) for game (\d+)/i, findPeopleForGameRespond
robot.respond /join game (\d+)/i, joinGameRespond
robot.respond /add (\w+) to game (\d+)/i, addToGameRespond
robot.respond /kick (\w+) from game (\d+)/i, kickFromGameRespond
robot.respond /abandon game (\d+)/i, abandonGameRespond
robot.respond /cancel game (\d+)/i, cancelGameRespond
robot.respond /balance game (\d+)/i, balanceGameRespond
robot.respond /shuffle game (\d+)/i, shuffleGameRespond
robot.respond /start game$/i, startGameRespond
robot.respond /start game(?: with)?(( \w+){1,3})$/i, startGameWithPlayersRespond
robot.respond /find people$|find players$/i, findPeopleForNextGameRespond
robot.respond /i'm in/i, joinNextGameRespond
robot.respond /join game$/i, joinNextGameRespond
robot.respond /add (\w+)$/i, addToNextGameRespond
robot.respond /kick (\w+)$/i, kickFromNextGameRespond
robot.respond /abandon game$/i, abandonNextGameRespond
robot.respond /cancel game$/i, cancelNextGameRespond
robot.respond /balance game$/i, balanceNextGameRespond
robot.respond /shuffle game$/i, shuffleNextGameRespond
robot.respond /rematch/i, rematchRespond
robot.respond /finish game +(\d-\d)$/i, finishGameRespond
robot.respond /(rankings|leaderboard)$/i, rankingsRespond
robot.respond /(?:stats|rankings)(( \w+)+)$/i, rankingsForPlayersRespond
robot.respond /top (\d+).*$/i, topNRankingsRespond
robot.respond /reset previous rankings$/i, resetPreviousRankings
robot.respond /history (\w+) ?(\d+|all)?$/i, historyMeRespond
robot.respond /team history (\w+) (\w+) ?(\d+|all)?$/i, teamHistoryRespond
robot.respond /rival history (\w+) (\w+) ?(\d+|all)?$/i, rivalHistoryRespond
robot.respond /team stats (\w+) (\w+)$/i, teamStatsRespond
robot.respond /go on (a )?cleanse$/i, goOnACleanseRespond
robot.respond /return from cleanse$/i, returnFromCleanseRespond
robot.respond /retire/i, retireRespond
robot.respond /unretire/i, unretireRespond
# Tournament commands
robot.respond /start tournament$/i, startTournamentRespond
robot.respond /start tournament with (\d+) people/i, startTournamentWithNPeopleRespond
robot.respond /cancel tournament/i, cancelTournamentRespond
robot.respond /show tournament$/i, showTournamentRespond
robot.respond /show tournament players/i, showTournamentPlayersRespond
robot.respond /show tournament teams/i, showTournamentTeamsRespond
robot.respond /swap tournament player (\w+) with (\w+)/i, swapTournamentPlayersRespond
robot.respond /accept tournament players/i, acceptTournamentPlayersRespond
robot.respond /finish tournament game round (\d+) game (\d+) (\d-\d)/i, finishTournamentGameRespond
# Betting commands
robot.respond /start betting/i, startBettingRespond
robot.respond /(my )?balance$/i, myBalanceRespond
robot.respond /bet (\d+\.\d+) on game (\d+) team ([01])/i, betRespond
robot.respond /cancel bet on game (\d+)/i, cancelBetRespond
# Helpful stuff
robot.respond /the rules/i, theRulesRespond
robot.respond /tip/i, tipRespond
schedule.scheduleJob "0 30 11 * * 1-5", tipOfTheDaySend(robot)
| true | # Description:
# An LCB bot that arranges foosball games
#
# Commands:
# foosbot Games - List currently scheduled games
# foosbot Total games - Return the number of total games
# foosbot Start game - Start a new game, always added to the end of the queue
# foosbot Start game with <p1> [<p2> <p3>] - Start a new game, always added to the end of the queue, with multiple people
# foosbot Find people|players - Ask for people to play in the next game
# foosbot I'm in | Join game - Claim a spot in the next game
# foosbot Add <player_name> - Add a player that may or may not be on LCB to the next game
# foosbot Kick <player_name> - Kick a player from the next game
# foosbot Abandon game - Free up your spot in the next game
# foosbot Cancel game - Cancel the next game
# foosbot Balance game - Balance the next game based on player ranks
# foosbot Shuffle game - Randomly shuffle the players in the next game
# foosbot Find people|players for game <n> - Ask for people to play in the nth game
# foosbot Join game <n> - Claim a spot in the nth game
# foosbot Add <player_name> to game <n> - Add a player that may or may not be on LCB to the nth game
# foosbot Kick <player_name> from game <n> - Kick a player from the nth game
# foosbot Abandon game <n> - Free up your spot in the nth game
# foosbot Cancel game <n> - Cancel the nth game
# foosbot Balance game <n> - Balance the nth game based on player ranks
# foosbot Shuffle game <n> - Randomly shuffle the players in the nth game
# foosbot Finish game <team1_score>-<team2_score> - Finish the next game in order and record the results
# foosbot Rematch - Repair your pride by playing the same game you just lost
# foosbot Go on [a] cleanse - Go on a cleanse, unable to be added to a game
# foosbot Return from cleanse - Return refreshed, ready to take on the champions
# foosbot Retire - Hang up the gloves for good
# foosbot Unretire - Rise up from the ashes of old age and get back to the table
# foosbot Rankings|Leaderboard - Show the leaderboard
# foosbot Rankings|Stats <player1> [<player2> ...] - Show the stats for specific players
# foosbot Top <n> - Show the top n players in the rankings
# foosbot History <player>|me [<numPastGames>|all] - Show a summary of your past games
# foosbot Team history <player>|me <otherPlayer> [<numPastGames>|all] - Show a summary of past games with a specific teammate
# foosbot Rival history <player>|me <otherPlayer> [<numPastGames>|all] - Show a summary of past games against a specific rival
# foosbot Team Stats <playerOne>|me <playerTwo>|me|all - Shows the team stats for two players, or all pairings of <playerOne>
# foosbot The rules - Show the rules we play by
# foosbot Start tournament - Begin a new tournament (cannot run multiple tournaments at once)
# foosbot Start tournament with <n> people - Begin a new tournament with some number of people (must be a power of 2)
# foosbot Cancel tournament - Cancel the currently running tournament (nothing will get saved)
# foosbot Show tournament - Show the current tournament tree
# foosbot Show tournament players - Show all the players involved in the tournament
# foosbot Show tournament teams - Show all the teams involved in the tournament
# foosbot Swap tournament player <current_player> with <new_player> - Replace a player in the tournament (only works with players that had ranks when the tournament was started)
# foosbot Accept tournament players - Confirm the player selection and officially begin the tournament
# foosbot Finish tournament game round <n1> game <n2> <team1_score>-<team2_score> - Finish a game and have the team move on
# foosbot Start betting - Join the betting pool
# foosbot My balance - Ask for your current balance
# foosbot Bet <x.y> on game <n> team (0|1) - Place a bet of <x.y>Ģ (i.e. 5.2) on game <n> for team 0 or 1 (placing again replaces your previous bet)
# foosbot Cancel bet on game <n> - Withdraw your bet for game <n>
# foosbot Tip - Get a helpful tip!
#
# Author:
# PI:NAME:<NAME>END_PI
fs = require 'fs'
ts = require 'trueskill'
schedule = require 'node-schedule'
# Must be a power of 2
_DEFAULT_TOURNAMENT_SIZE = 16
# Betting constants
_STARTING_FOOSCOIN = 30.0
_MATCH_WIN_AMOUNT = 5.0
_HOUSE_PRIZE_BASE = 5.0
# Rules and tips
_THE_RULES = [
"No spinning",
"If someone scores with the first shot, it doesn't count",
"If someone scores by hitting the ball before it reaches the far wall, it doesn't count",
"Any player can score from any position",
"When one team reaches 5 points, both teams switch defense/offense players",
"If a shot goes in but comes out, it counts as long as it made the *dank* sound",
"The last goal cannot be an own goal, it must be scored by the opposing team",
"If unsure whether a goal counts, the team that got scored on makes the call",
"If the ball goes dead anywhere except the far sides, reset to the middle",
"If the ball goes dead on a far side, defense resets it from a corner",
"If the ball flies off the table, reset to the middle",
"If it wasn't organized by foosbot, it's a friendly game and does not affect rankings",
"Everyone has 3 seconds after a drop to call a redrop",
"If a player takes both hands off the handles and clearly stops playing, play is considered paused",
"If you get shut out, you have to crawl under the table"
"Everyone shakes hands at the end of the game, no exceptions",
]
_TIPS = [
"Keep your goalie in the center if you're not sure what to do",
"Take your time and control the ball for a better shot",
"Stagger your players when defending",
"Try not to shoot straight through the center",
"Keep your players the ball is behind them, so you don't block your partner's shot",
"Keep your defenders pointed inwards to make angle shots harder",
"To slapshot, place the bottom of your plam flat out, push forward, then pull up and grab",
"Close the gaps that lead to your net",
"Don't instinctively move your players back when the ball goes past them, you might score on yourself",
"Watch the ball, not the player, don't be fooled by dekes",
"Keep moving! Don't stop and pause just because your opponent did",
"Watch the hands and react to that, they're a tell before the actual move",
"Try to avoid patterns in your movement",
"Try to avoid crossing your goalie and your defenders, that leaves a gap through which to shoot",
"Guard the posts, but try not to linger there",
"Try to control the ball instead of shooting right away",
"Don't move for no reason if you're in a good position",
"Don't panic on slow shots! Concentrate and punish back",
"Keep an eye on your players more than on the ball when it's not in your half",
"Vary your shots, don't do the same thing from the same position over and over",
"Forget mistakes quickly and start thinking about the next play",
"Don't talk too much or you'll get distracted and make a mistake",
]
gamesFile = 'games.json'
finishedGamesFile = 'finishedgames.json'
previousRanksFile = 'previousranks.json'
cleanseFile = 'cleanse.json'
retireesFile = 'retirees.json'
tournamentFile = 'tournament.json'
accountsFile = 'accounts.json'
loadFile = (fileName, initialValue) ->
# Initialize the file if it does not exist
if !(fs.existsSync(fileName))
fs.writeFileSync(fileName, JSON.stringify(initialValue))
return JSON.parse((fs.readFileSync fileName, 'utf8').toString().trim())
saveFile = (fileName, data) ->
fs.writeFileSync(fileName, JSON.stringify(data))
games = loadFile(gamesFile, [])
finishedGames = loadFile(finishedGamesFile, [])
previousRanks = loadFile(previousRanksFile, {})
cleanse = loadFile(cleanseFile, [])
retirees = loadFile(retireesFile, [])
tournament = loadFile(tournamentFile, {'started': false, 'size': _DEFAULT_TOURNAMENT_SIZE})
accounts = loadFile(accountsFile, {})
saveGames = () ->
saveFile(gamesFile, games)
saveFinishedGames = () ->
saveFile(finishedGamesFile, finishedGames)
savePreviousRanks = () ->
saveFile(previousRanksFile, previousRanks)
saveCleanse = () ->
saveFile(cleanseFile, cleanse)
saveRetirees = () ->
saveFile(retireesFile, retirees)
saveTournament = () ->
saveFile(tournamentFile, tournament)
saveAccounts = () ->
saveFile(accountsFile, accounts)
# Date diff calculations
_MS_PER_DAY = 1000 * 60 * 60 * 24
diffDays = (date1, date2) ->
return Math.round((date1 - date2) / _MS_PER_DAY, 0)
# Store list of datetimes of previous plays
_SHAME_MESSAGES = [
"Playing again, huh?",
"Shouldn't you be doing...work?",
"Wow, look at your rank after all these games you've played!",
"You could have finished that ticket in the time you've spent playing foosball today",
"Aren't your hands tired by now?",
"Maybe it's time you took a break from foos",
"Are you /really/ sure you want to keep playing today?",
]
_DEFAULT_SHAME_MESSAGE = "Maximum slack level reached, HR has been notified"
getShameMsg = (res, player, timesPlayed) ->
shameMsg = if timesPlayed >= 10 then _DEFAULT_SHAME_MESSAGE else res.random _SHAME_MESSAGES
return "@#{player} #{shameMsg}"
# Store shame
shameFile = 'shame.json'
shame = JSON.parse((fs.readFileSync shameFile, 'utf8').toString().trim())
for player of shame
shame[player] = shame[player].map (playTime) -> new Date(playTime)
saveShame = () ->
fs.writeFileSync(shameFile, JSON.stringify(shame))
# Shame players who play too much
updateShame = (player) ->
if !(player of shame)
shame[player] = []
now = new Date()
shame[player].push now
saveShame()
shameSlacker = (res, player) ->
player = player.trim().toLowerCase()
if !(player of shame)
return
# Remove all recorded plays older than 1 day and not on the same calendar date
now = new Date()
shame[player] = shame[player].filter (playTime) -> (diffDays(now, playTime) == 0) && (playTime.getDate() == now.getDate())
saveShame()
timesPlayed = shame[player].length
if timesPlayed >= 3
res.send getShameMsg(res, player, timesPlayed)
isUndefined = (myvar) ->
return typeof myvar == 'undefined'
isPowerOfTwo = (mynum) ->
return (Math.log2(mynum) % 1) == 0
rightPad = (s, finalLength) ->
numSpaces = Math.max(0, finalLength - s.length)
return s + ' '.repeat(numSpaces)
customRound = (num, decimals) ->
return Number(Math.round(num+'e'+decimals)+'e-'+decimals);
gamesRespond = (res) ->
# List the games, in groups of 4, with the indices
if games.length <= 0
res.send "No games started"
return
responseLines = []
for game, index in games
gamePlayers = game['players']
team1 = "#{gamePlayers[0]} and #{gamePlayers[1]}"
team2 = "#{gamePlayers[2]} and #{gamePlayers[3]}"
# Calculate bets for each team
team1Bets = 0.0
team2Bets = 0.0
for betterName of game['bets']
bet = game['bets'][betterName]
if bet['team'] == 0
team1Bets += bet['amount']
else
team2Bets += bet['amount']
if team1Bets > 0
team1 += " (#{team1Bets}Ģ bet)"
if team2Bets > 0
team2 += " (#{team2Bets}Ģ bet)"
responseLines.push "Game #{index}:\n#{team1}\nvs.\n#{team2}\n"
res.send responseLines.join('\n')
startGameRespond = (res, startingPlayers) ->
# Create a new group of four, at the end of the games array
captain = res.message.user.name
if captain in cleanse
res.reply "You can't start any games, you're on a cleanse!"
return
if captain in retirees
res.reply "You can't start any games, you're retired!"
return
games.push {
"players": [captain, '_', '_', '_'],
"bets": {}
}
saveGames()
shameSlacker(res, captain)
res.send "New game started"
if !(isUndefined(startingPlayers))
n = games.length - 1
for sp in startingPlayers
joinGameRespond(res, n, sp)
gamesRespond(res)
startGameWithPlayersRespond = (res) ->
startingPlayers = (name.trim() for name in res.match[1].trim().split(' '))
res.send "Starting players: #{startingPlayers}"
startGameRespond(res, startingPlayers)
isInvalidIndex = (gameIndex) ->
return isNaN(gameIndex) || gameIndex < 0 || gameIndex >= games.length
findPeopleForGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
gameStr = if n == 0 then "Next game" else "Game #{n}"
gamePlayers = games[n]['players']
currentPlayers = (player for player in gamePlayers when player != "_")
spotsLeft = 4 - currentPlayers.length
if spotsLeft <= 0
res.send "No spots left in #{gameStr}"
return
# Ask @all who's up for a game, and announce who's currently part of the nth game
currentPlayers = currentPlayers.join(', ')
res.send "@all Who's up for a game? #{gameStr} has #{spotsLeft} spots, current players are #{currentPlayers}"
initOrRetrievePlayerStat = (stats, playerName) ->
if playerName of stats
return stats[playerName]
return {
"gamesPlayed": 0,
"gamesWon": 0,
"winPercentage": 0,
"skill": [25.0, 25.0/3.0],
"rank": 2,
"streak": 0,
"longestWinStreak": 0,
"longestLoseStreak": 0,
}
getStats = () ->
# Return stats for all players, which is a map from player name to object with games played, games won, and win percentage
stats = {}
for finishedGame in finishedGames
t1p1 = finishedGame['team1']['player1']
t1p2 = finishedGame['team1']['player2']
t2p1 = finishedGame['team2']['player1']
t2p2 = finishedGame['team2']['player2']
t1score = finishedGame['team1']['score']
t2score = finishedGame['team2']['score']
allPlayers = [t1p1, t1p2, t2p1, t2p2]
for player in allPlayers
stats[player] = initOrRetrievePlayerStat(stats, player)
stats[player]['gamesPlayed'] += 1
stats[player]['rank'] = 2
winPlayers = []
losePlayers = []
if t1score > t2score
winPlayers = [t1p1, t1p2]
losePlayers = [t2p1, t2p2]
else if t2score > t1score
winPlayers = [t2p1, t2p2]
losePlayers = [t1p1, t1p2]
for wp in winPlayers
stats[wp]['gamesWon'] += 1
stats[wp]['rank'] = 1
# If they were losing until this game, reset them to a 1 win streak
stats[wp]['streak'] = if stats[wp]['streak'] < 0 then 1 else stats[wp]['streak'] + 1
if stats[wp]['streak'] > stats[wp]['longestWinStreak']
stats[wp]['longestWinStreak'] = stats[wp]['streak']
for lp in losePlayers
# If they were winning until this game, reset them to a 1 lose streak
stats[lp]['streak'] = if stats[lp]['streak'] > 0 then -1 else stats[lp]['streak'] - 1
if -stats[lp]['streak'] > stats[lp]['longestLoseStreak']
stats[lp]['longestLoseStreak'] = -stats[lp]['streak']
ts.AdjustPlayers([stats[t1p1], stats[t1p2], stats[t2p1], stats[t2p2]])
for player in Object.keys(stats)
stats[player]['name'] = player
stats[player]['winPercentage'] = customRound((stats[player]['gamesWon'] / stats[player]['gamesPlayed']) * 100, 2)
stats[player]['trueskill'] = stats[player]['skill'][0] - (3 * stats[player]['skill'][1])
return stats
noopFormat = (str) -> return "#{str}"
fixedTwoFormat = (str) -> return "#{str.toFixed(2)}"
trueskillFormat = (str) -> return "#{str.toFixed(5)}"
percentFormat = (str) -> return "#{str}% "
gamesFormat = (str) -> return "#{str} game#{if str == 1 then '' else 's'}"
streakFormat = (str) ->
winning = str > 0
gameStreak = if winning then str else -str
return "#{if winning then ':fire:' else ':poop:'} #{gameStreak} #{if winning then 'won' else 'lost'}"
addColumn = (lines, stats, header, field, formatFunc, isFirstColumn) ->
isIndexColumn = !field
formatFunc = if isUndefined(formatFunc) then noopFormat else formatFunc
# Calculate the longest length, for padding
header = if isIndexColumn then "Rank" else "#{header}"
longestLength = header.length
longestHeaderLength = header.length
for stat, index in stats
fieldValue = if isIndexColumn then "#{index}" else formatFunc(stat[field])
longestLength = Math.max(longestLength, fieldValue.length)
# Convert emojis to a single character
collapsedFieldValue = fieldValue
collapsedFieldValue = collapsedFieldValue.replace /:.*:/g, (txt) -> ':::'
longestHeaderLength = Math.max(longestHeaderLength, collapsedFieldValue.length)
longestLength += 1
longestHeaderLength += 1
# Add the header and the underline
headerLength = longestHeaderLength + 2
lines[0] += rightPad(header, headerLength)
lines[1] += '-'.repeat(headerLength)
# Add the column for each statistic
for stat, index in stats
if isIndexColumn
fieldValue = rightPad("#{index+1}", longestLength)
else
fieldValue = rightPad(formatFunc(stat[field]), longestLength)
if !isFirstColumn
lines[2+index] += "| "
lines[2+index] += "#{fieldValue}"
skillSort = (p1, p2) ->
# High ranks are pushed to the front
if p1['trueskill'] > p2['trueskill']
return -1
if p1['trueskill'] < p2['trueskill']
return 1
# Order by games won next
if p1['gamesWon'] > p2['gamesWon']
return -1
if p1['gamesWon'] < p2['gamesWon']
return 1
# Order by win percentage last
return if p1['winPercentage'] >= p2['winPercentage'] then -1 else 1
getRankings = () ->
# Get the stats for each player
stats = getStats()
# Remove all retirees
for retiree in retirees
if retiree of stats
delete stats[retiree]
# Make a sortable array
rankings = []
for player in Object.keys(stats)
rankings.push stats[player]
# Sort the players based on rank
rankings.sort(skillSort)
for stat, rank in rankings
stat['rank'] = rank + 1
return rankings
rankingsRespond = (res, specificPlayers, topNPlayers) ->
# Get the player rankings
rankings = getRankings()
# Either filter or show topNPlayers players, but not both
if !(isUndefined(specificPlayers))
rankings = rankings.filter (stat) -> stat["name"] in specificPlayers
else if !(isUndefined(topNPlayers))
rankings = rankings.slice(0, topNPlayers)
# Construct the rankings string
responseList = new Array(rankings.length + 2).fill('') # Initialize with empty lines, to add to later
# addColumn(responseList, rankings, "", "", ) # Index column
addColumn(responseList, rankings, "Rank", "rank", noopFormat, true)
addColumn(responseList, rankings, "Player", "name")
addColumn(responseList, rankings, "Trueskill", "trueskill", trueskillFormat)
addColumn(responseList, rankings, "Win %", "winPercentage", percentFormat)
addColumn(responseList, rankings, "Won", "gamesWon")
addColumn(responseList, rankings, "Played", "gamesPlayed")
addColumn(responseList, rankings, "Streak", "streak", streakFormat)
addColumn(responseList, rankings, "Longest Win Streak", "longestWinStreak", gamesFormat)
addColumn(responseList, rankings, "Longest Lose Streak", "longestLoseStreak", gamesFormat)
res.send responseList.join('\n')
rankingsForPlayersRespond = (res) ->
players = (name.trim() for name in res.match[1].trim().split(' '))
rankingsRespond(res, players)
topNRankingsRespond = (res) ->
n = res.match[1].trim()
rankingsRespond(res, undefined, n)
resetPreviousRankings = (res) ->
rankings = getRankings()
for player, rank in rankings
previousRanks[player['name']] = rank + 1
savePreviousRanks()
showChangedRankings = (res, p1, p2, p3, p4) ->
rankChanges = "Rank changes:\n"
rankings = getRankings()
for p in [p1,p2,p3,p4]
curRank = getRank(p, rankings) + 1
if p of previousRanks
prevRank = previousRanks[p]
rankDiff = prevRank - curRank
prefix = if rankDiff < 0 then '' else if rankDiff == 0 then '=' else '+'
else
rankDiff = curRank
prefix = '~'
rankChanges += "#{prefix}#{rankDiff} -> #{curRank} #{p}\n"
resetPreviousRankings(res)
res.send rankChanges
rankSort = (p1,p2) ->
# Negative rank means the player isn't ranked
if p1['rank'] < 0
return -1
if p2['rank'] < 0
return 1
# A low rank is better than a high rank
return if p1['rank'] <= p2['rank'] then -1 else 1
getRank = (playerName, rankings) ->
for player, rank in rankings
if player['name'] == playerName
return rank
# If the player is new, they should be considered worse than anyone
return Infinity
balancePlayers = (game) ->
# Get the player rankings, which are sorted correctly
rankings = getRankings()
# Balance based on rank
playersWithRanks = game.map (player) -> {"name": player, "rank": getRank(player, rankings)}
playersWithRanks.sort(rankSort)
# Update the game
game[0] = playersWithRanks[0]["name"]
game[1] = playersWithRanks[3]["name"]
game[2] = playersWithRanks[1]["name"]
game[3] = playersWithRanks[2]["name"]
shufflePlayers = (n) ->
# Simply rotate the last 3 players left
game = games[n]["players"]
games[n]["players"] = [game[0]].concat(game.slice(2).concat(game[1]))
joinGameRespond = (res, n, playerName) ->
newPlayer = if isUndefined(playerName) then res.message.user.name else playerName
if newPlayer in cleanse
if isUndefined(playerName)
res.reply "You can't join any games, you're on a cleanse!"
else
res.send "#{newPlayer} cannot join games, they are on a cleanse!"
return
if newPlayer in retirees
if isUndefined(playerName)
res.reply "You can't join any games, you're retired!"
else
res.send "#{newPlayer} cannot join games, they are retired!"
return
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
any = if !any then false else true
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
shameSlacker(res, newPlayer)
gameStr = if n == 0 then "Next game" else "Game #{n}"
gamePlayers = games[n]['players']
if gamePlayers.indexOf(newPlayer) >= 0
res.send "You're already part of that game!"
return
# Add yourself to the nth game
for player, index in gamePlayers
if player == '_'
gamePlayers[index] = newPlayer
res.send "#{newPlayer} joined #{gameStr}!"
if gamePlayers.indexOf('_') < 0
balancePlayers(gamePlayers)
teamOneWinRate = getTeamStats(gamePlayers[0], gamePlayers[1])[gamePlayers[1]]["winPercentage"]
teamTwoWinRate = getTeamStats(gamePlayers[2], gamePlayers[3])[gamePlayers[3]]["winPercentage"]
teamsStr = "@#{gamePlayers[0]} and @#{gamePlayers[1]} (#{teamOneWinRate}%)\n"
teamsStr += "vs.\n"
teamsStr += "@#{gamePlayers[2]} and @#{gamePlayers[3]} (#{teamTwoWinRate}%)"
res.send "#{gameStr} is ready to go! Teams:\n#{teamsStr}"
saveGames()
return
# Cannot join if full
res.send "No spots in #{gameStr}"
abandonGameRespond = (res, n, playerName) ->
senderPlayer = if isUndefined(playerName) then res.message.user.name else playerName
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
gamePlayers = games[n]['players']
playerIndex = gamePlayers.indexOf(senderPlayer)
if playerIndex < 0
res.send "#{senderPlayer} is not part of Game #{n}"
return
# Return any bets placed on that game
returnBets(res, n)
gamePlayers[playerIndex] = '_'
saveGames()
# Abandon the nth game, freeing your spot in it
remainingPlayers = [(player for player in gamePlayers when player != "_")].join(', ')
res.send "#{senderPlayer} abandoned game #{n}. Remaining players: #{remainingPlayers}"
gamesRespond(res)
cancelGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
# Return any bets placed on that game
returnBets(res, n)
games.splice(n, 1)
saveGames()
# Cancel the nth game
res.send "Game #{n} cancelled"
gamesRespond(res)
findPeopleForNextGameRespond = (res) ->
# Ask @all who's up for a game, and announce who's currently part of the next upcoming game
findPeopleForGameRespond(res, 0)
joinNextGameRespond = (res) ->
# Add yourself to the next game
# Cannot join if full
joinGameRespond(res, 0)
abandonNextGameRespond = (res) ->
# Abandon the next upcoming game, freeing your spot in it
abandonGameRespond(res, 0)
cancelNextGameRespond = (res) ->
# Cancel the next upcoming game
cancelGameRespond(res, 0)
addToGameRespond = (res, n) ->
# Add a player to the nth game
playerName = res.match[1].trim()
n = if isUndefined(n) then parseInt(res.match[2].trim(), 10) else n
joinGameRespond(res, n, playerName)
addToNextGameRespond = (res) ->
# Add yourself to the next game
# Cannot join if full
addToGameRespond(res, 0)
kickFromGameRespond = (res, n) ->
# Kick a player from the nth game
playerName = res.match[1].trim()
n = if isUndefined(n) then parseInt(res.match[2].trim(), 10) else n
abandonGameRespond(res, n, playerName)
kickFromNextGameRespond = (res) ->
# Kick a player from the next game
kickFromGameRespond(res, 0)
balanceGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
balancePlayers(games[n]['players'])
saveGames()
gamesRespond(res)
res.send "Game #{n} balanced based on rank"
balanceNextGameRespond = (res) ->
balanceGameRespond(res, 0)
shuffleGameRespond = (res, n) ->
n = if isUndefined(n) then parseInt(res.match[1].trim(), 10) else n
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
shufflePlayers(n)
returnBets(res, n)
saveGames()
gamesRespond(res)
res.send "Game #{n} shuffled"
shuffleNextGameRespond = (res) ->
shuffleGameRespond(res, 0)
finishGameRespond = (res) ->
if games.length <= 0
res.send "No games are being played at the moment"
return
game = games[0]
gamePlayers = game['players']
if gamePlayers.indexOf('_') >= 0
res.send "Next game isn't ready to go yet!"
return
result = res.match[1].trim().split('-')
t1score = parseInt(result[0], 10)
t2score = parseInt(result[1], 10)
t1p1 = gamePlayers[0].trim().toLowerCase()
t1p2 = gamePlayers[1].trim().toLowerCase()
t2p1 = gamePlayers[2].trim().toLowerCase()
t2p2 = gamePlayers[3].trim().toLowerCase()
oldStats = getStats()
# The following is the format for game results
resultDetails = {
'team1': {
'player1': t1p1,
'player2': t1p2,
'score': t1score
},
'team2': {
'player1': t2p1,
'player2': t2p2,
'score': t2score
}
}
for player in [t1p1,t1p2,t2p1,t2p2]
updateShame(player)
if !(player of oldStats)
oldStats[player] = {
'trueskill': 0.0
}
# Record the scores and save them
finishedGames.push resultDetails
# Return the bets to the bet winners
winningTeam = if t1score > t2score then 0 else 1
betWinners = []
betWinnersTotalPool = 0
prizePool = 0
for betterName of game['bets']
if game['bets'][betterName]['team'] == winningTeam
betWinnersTotalPool += game['bets'][betterName]['amount']
# Return the winner's bet, but don't announce it
accounts[betterName] += game['bets'][betterName]['amount']
betWinners.push(betterName)
else
prizePool += game['bets'][betterName]['amount']
# Give extra money from the house, based on trueskill
winningTeamPlayers = if t1score > t2score then [t1p1,t1p2] else [t2p1,t2p2]
losingTeamPlayers = if t1score > t2score then [t2p1,t2p2] else [t1p1,t1p2]
winningTeamTrueskill = oldStats[losingTeamPlayers[0]]['trueskill'] + oldStats[losingTeamPlayers[1]]['trueskill']
losingTeamTrueskill = oldStats[winningTeamPlayers[0]]['trueskill'] + oldStats[winningTeamPlayers[1]]['trueskill']
housePrizeProportion = winningTeamTrueskill / losingTeamTrueskill
housePrize = customRound(housePrizeProportion * _HOUSE_PRIZE_BASE, 2)
if betWinners.length > 0
for betWinner in betWinners
if betWinner of accounts
# Award the house prize
accounts[betWinner] += housePrize
res.send "@#{betWinner} won #{housePrize}Ģ from the house!"
# Distribute the prize pool from the losers
if prizePool > 0
# Determine how much this winner should get, proportional to what they bet
proportion = customRound(game['bets'][betWinner]['amount'] / betWinnersTotalPool, 4)
betWinAmount = customRound(prizePool * proportion, 4)
accounts[betWinner] += betWinAmount
res.send "@#{betWinner} won #{betWinAmount}Ģ from betting!"
# Award a prize to the winners of the match, equal to the number of goals scored
matchWinners = if t1score > t2score then [t1p1,t1p2] else [t2p1,t2p2]
matchWinnersScore = if t1score > t2score then t1score else t2score
matchLosersScore = if t1score > t2score then t2score else t1score
matchWinAmount = Math.abs(t1score - t2score)
# Give more if the trueskill difference is larger
matchWinAmount += housePrizeProportion * 2 * matchWinAmount
# Determine how much of the opposing prize pool to give, with the goals as a percentage
if prizePool > 0
matchWinAmount += prizePool * (matchWinnersScore / 100.0)
# Double the win amount in case of a shutout
if matchLosersScore == 0
matchWinAmount = matchWinAmount * 2
res.send "Double fooscoins for a shutout win!"
res.send "https://media.giphy.com/media/gtakVlnStZUbe/giphy.gif"
for matchWinner in matchWinners
if matchWinner of accounts
accounts[matchWinner] += matchWinAmount
res.send "@#{matchWinner} won #{matchWinAmount}Ģ!"
saveAccounts()
saveFinishedGames()
# Show changed rankings since last time
showChangedRankings(res, t1p1, t1p2, t2p1, t2p2)
# Remove the game from the list
games.splice(0,1)
saveGames()
res.send "Results saved"
theRulesRespond = (res) ->
res.send _THE_RULES.map((rule, i) -> "#{i+1}. #{rule}").join('\n')
tipRespond = (res) ->
res.send res.random _TIPS
goOnACleanseRespond = (res) ->
senderName = res.message.user.name
if !(senderName in cleanse)
cleanse.push senderName
saveCleanse()
res.reply "You are now on a cleanse. Stay away from the foosball table, and relax :palm_tree:"
returnFromCleanseRespond = (res) ->
senderName = res.message.user.name
if !(senderName in cleanse)
res.reply "You are not on a cleanse, go play some foos!"
return
cleanse.splice(cleanse.indexOf(senderName), 1)
saveCleanse()
res.reply "Welcome back! Now go kick some ass"
initTeamStat = (stats, playerName) ->
stats[playerName] = {
"wins": 0,
"losses": 0,
"ties": 0,
"goalsFor": 0,
"goalsAgainst": 0,
"winPercentage": 0,
"avgGoalsFor": 0,
"avgGoalsAgainst": 0
}
getTeamStats = (playerOneName, playerTwoName) ->
# Allow getting stats for all team pairings by providing "all" as the playerTwoName
# The keys of the return dictionary are the names of the other team member
stats = {}
playerOneName = playerOneName.toLowerCase()
playerTwoName = playerTwoName.toLowerCase()
# Make sure the partner has the default stats
if !(playerTwoName == 'all')
initTeamStat(stats, playerTwoName)
for finishedGame in finishedGames
teamOne = [finishedGame["team1"]["player1"], finishedGame["team1"]["player2"]]
teamTwo = [finishedGame["team2"]["player1"], finishedGame["team2"]["player2"]]
if playerOneName in teamOne && (playerTwoName == 'all' || playerTwoName in teamOne)
myTeam = finishedGame["team1"]
otherTeam = finishedGame["team2"]
else if playerOneName in teamTwo && (playerTwoName == 'all' || playerTwoName in teamTwo)
myTeam = finishedGame["team2"]
otherTeam = finishedGame["team1"]
else
continue
# Get the partner's name
partnerName = if myTeam["player1"] == playerOneName then myTeam["player2"] else myTeam["player1"]
if !(partnerName of stats)
initTeamStat(stats, partnerName)
partnerStats = stats[partnerName]
if myTeam["score"] > otherTeam["score"]
partnerStats["wins"] += 1
else if myTeam["score"] == otherTeam["score"]
partnerStats["ties"] += 1
else
partnerStats["losses"] += 1
partnerStats["goalsFor"] += myTeam["score"]
partnerStats["goalsAgainst"] += otherTeam["score"]
# Extra Stats
for partnerName of stats
partnerStats = stats[partnerName]
gamesPlayed = partnerStats["wins"] + partnerStats["losses"] + partnerStats["ties"]
if gamesPlayed > 0
partnerStats["winPercentage"] = ((partnerStats["wins"] / gamesPlayed) * 100).toFixed(2)
partnerStats["avgGoalsFor"] = partnerStats["goalsFor"] / gamesPlayed
partnerStats["avgGoalsAgainst"] = partnerStats["goalsAgainst"] / gamesPlayed
return stats
teamStatsRespond = (res) ->
playerOneName = if res.match[1] == 'me' then res.message.user.name else res.match[1].trim().toLowerCase()
playerTwoName = if res.match[2] == 'me' then res.message.user.name else res.match[2].trim().toLowerCase()
if playerOneName == playerTwoName
res.send "Player one and player two cannot be the same."
return
teamStats = getTeamStats(playerOneName, playerTwoName)
# Build the response of stats for all team pairings
response = ''
for partnerName of teamStats
partnerStats = teamStats[partnerName]
responseList = new Array(3).fill('')
addColumn(responseList, [partnerStats], "Win", "wins", noopFormat, true)
addColumn(responseList, [partnerStats], "Loss", "losses")
addColumn(responseList, [partnerStats], "Tie", "ties")
addColumn(responseList, [partnerStats], "Avg. Goals For", "avgGoalsFor", fixedTwoFormat)
addColumn(responseList, [partnerStats], "Avg. Goals Against", "avgGoalsAgainst", fixedTwoFormat)
addColumn(responseList, [partnerStats], "Win Rate", "winPercentage", percentFormat)
response += "Team: #{playerOneName} and #{partnerName}\n"
response += responseList.join("\n")
response += "\n\n\n"
res.send response
historyMeRespond = (res) ->
me = res.match[1] == 'me'
playerName = if me then res.message.user.name else res.match[1].trim().toLowerCase()
numPastGames = if isUndefined(res.match[2]) then 5 else res.match[2].trim()
historyRespond(res, me, numPastGames, playerName)
multiHistoryRespond = (res, rivals) ->
me = res.match[1] == 'me'
playerName = if me then res.message.user.name else res.match[1].trim().toLowerCase()
otherPlayerName = res.match[2].trim().toLowerCase()
numPastGames = if isUndefined(res.match[3]) then 5 else res.match[3].trim()
historyRespond(res, me, numPastGames, playerName, otherPlayerName, rivals)
teamHistoryRespond = (res) ->
multiHistoryRespond(res, false)
rivalHistoryRespond = (res) ->
multiHistoryRespond(res, true)
historyRespond = (res, me, numPastGames, playerName, otherPlayerName, rivals) ->
gamesFound = 0
pastGames = []
if !(numPastGames == 'all')
numPastGames = parseInt(numPastGames, 10)
# Collect the last n games
for i in [finishedGames.length-1..0] by -1
fgame = finishedGames[i]
fgPlayers = [fgame["team1"]["player1"], fgame["team1"]["player2"], fgame["team2"]["player1"], fgame["team2"]["player2"]]
keepGame = false
if isUndefined(otherPlayerName)
# Single-player history
if playerName in fgPlayers
keepGame = true
else
# Team history
fgTeam1 = [fgame["team1"]["player1"], fgame["team1"]["player2"]]
fgTeam2 = [fgame["team2"]["player1"], fgame["team2"]["player2"]]
if rivals
keepGame = ((playerName in fgTeam1) && (otherPlayerName in fgTeam2)) || ((playerName in fgTeam2) && (otherPlayerName in fgTeam1))
else
keepGame = ((playerName in fgTeam1) && (otherPlayerName in fgTeam1)) || ((playerName in fgTeam2) && (otherPlayerName in fgTeam2))
if keepGame
pastGames.unshift(fgame)
gamesFound += 1
if numPastGames != 'all' && gamesFound >= numPastGames
break
pronoun = "#{playerName}'s"
together = ""
if !isUndefined(otherPlayerName)
pronoun = "#{playerName} and #{otherPlayerName}'s"
together = if rivals then " against each other" else " together"
gamesWon = 0
title = "#{pronoun} last #{numPastGames} games#{together}:"
strGames = ""
for pg, i in pastGames
score = '\t'
team1 = [pg["team1"]["player1"], pg["team1"]["player2"]]
team2 = [pg["team2"]["player1"], pg["team2"]["player2"]]
thisTeam = team1
thisTeamScore = pg['team1']['score']
otherTeamScore = pg['team2']['score']
if playerName in team2
thisTeam = team2
thisTeamScore = pg['team2']['score']
otherTeamScore = pg['team1']['score']
if thisTeamScore > otherTeamScore
gamesWon += 1
score = process.env.WIN_EMOJI
if otherTeamScore == 0
score += process.env.SHUTOUT_EMOJI
else if otherTeamScore == 8
score += process.env.CLOSE_WIN_EMOJI
score += '\t'
else if thisTeamScore == 0
score = process.env.NO_GOALS_EMOJI + '\t'
else if thisTeamScore == 8
score = process.env.CLOSE_LOSS_EMOJI + '\t'
score += "#{thisTeamScore}-#{otherTeamScore}"
if playerName == pg['team1']['player1']
teams = [pg['team1']['player1'], pg['team1']['player2'], pg['team2']['player1'], pg['team2']['player2']]
else if playerName == pg['team1']['player2']
teams = [pg['team1']['player2'], pg['team1']['player1'], pg['team2']['player1'], pg['team2']['player2']]
else if playerName == pg['team2']['player1']
teams = [pg['team2']['player1'], pg['team2']['player2'], pg['team1']['player1'], pg['team1']['player2']]
else
teams = [pg['team2']['player2'], pg['team2']['player1'], pg['team1']['player1'], pg['team1']['player2']]
strGames += "\n#{score}\t#{teams[0]} and #{teams[1]} vs. #{teams[2]} and #{teams[3]}"
strGames = title + "\nK-D ratio: #{gamesWon}-#{gamesFound-gamesWon}\n" + strGames
res.send strGames
totalGamesRespond = (res) ->
res.send finishedGames.length
rematchRespond = (res) ->
playerName = res.message.user.name.trim().toLowerCase()
for i in [finishedGames.length-1..0] by -1
fgame = finishedGames[i]
fgamePlayers = [fgame["team1"]["player1"], fgame["team1"]["player2"], fgame["team2"]["player1"], fgame["team2"]["player2"]]
if playerName in fgamePlayers
res.send "Rematch called by #{playerName}!"
startingPlayers = fgamePlayers.filter (name) -> name != playerName
startGameRespond(res, startingPlayers)
return
res.send "Nothing to rematch, you haven't played any previous games"
# Tournament responders
startTournamentWithNPeopleRespond = (res) ->
tournamentSize = parseInt(res.match[1].trim(), 10)
if !isPowerOfTwo(tournamentSize)
res.send "The number of must be a power of 2, and #{tournamentSize} is not!"
return
if tournamentSize < 4
res.send "You need at least 4 people to start a tournament!"
return
tournament['size'] = tournamentSize
startTournamentRespond(res)
startTournamentRespond = (res) ->
# Initialize the game with the top 16 players
# Save all players and their ranks at that time
# Create teams by pairing 1-16, 2-15, etc.
if tournament['started']
res.send 'Tournament has already been started! Please cancel the current one if you wish to start a new one.'
return
tournament = {
'allPlayers': [],
'tournamentPlayers': [],
'tournamentTeams': [],
'allGames': [],
'accepted': false,
'started': true,
'size': tournament['size'],
}
# Get all players
tournament['allPlayers'] = getRankings()
if tournament['allPlayers'].length < tournament['size']
res.send "Not enough players to start tournament. Have: #{tournament['allPlayers'].length}; Need: #{tournament['size']}"
return
# Choose the top tournament['size'] players to participate
tournament['tournamentPlayers'] = tournament['allPlayers'].slice(0, tournament['size'])
prepareAndDistributeTournamentTeams()
saveTournament()
res.send 'Tournament started!'
showTournamentRespond(res)
prepareTournamentGames = () ->
# Clear the games
tournament['allGames'] = []
# Prepare games with log_2(tournament['size']/2) rounds
numRounds = Math.log2(tournament['size']/2)
for r in [numRounds-1..0] by -1
firstRound = false
if tournament['allGames'].length <= 0
firstRound = true
topTeam = true
gameRound = []
numGamesInRound = Math.pow(2, r)
for g in [0..numGamesInRound-1]
previousGames = false
if !firstRound
previousGames = [(2 * g), (2 * g) + 1]
nextGame = if numGamesInRound == 1 then false else Math.floor(g/2)
gameRound.push {
'previousGames': previousGames,
'nextGame': nextGame,
'team1': false,
'team2': false,
'finalScore': false,
'finished': false,
'topTeam': topTeam,
}
# Make sure teams display correctly
topTeam = !topTeam
tournament['allGames'].push gameRound
prepareAndDistributeTournamentTeams = () ->
# Prepare the games first
prepareTournamentGames()
# Make teams by pairing 1-16, 2-15, etc.
for i in [0..(tournament['size']/2)-1]
tournament['tournamentTeams'][i] = [
tournament['tournamentPlayers'][i]['name'],
tournament['tournamentPlayers'][tournament['size'] - 1 - i]['name'],
]
# Populate the first round with players, alternating between placing at the top or bottom of the bracket
i = 0
teamsDistributed = 0
bracketSideTop = true
for team in tournament['tournamentTeams']
if bracketSideTop
game = tournament['allGames'][0][i]
else
game = tournament['allGames'][0][tournament['allGames'][0].length - 1 - i]
if !game['team1']
game['team1'] = team
else
game['team2'] = team
teamsDistributed += 1
if teamsDistributed == 4
teamsDistributed = 0
i += 1
bracketSideTop = !bracketSideTop
cancelTournamentRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Empty out the object containing the tournament info
tournament = {'started': false, 'size': _DEFAULT_TOURNAMENT_SIZE}
saveTournament()
res.send "Tournament cancelled"
showTournamentRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Print the tournament tree, in the following format
# -------------|
# goofy, daffy |
# |
# [9-1]|--------------|
# | goofy, daffy |
# PI:NAME:<NAME>END_PI | |
# -------------| |
# [9-3]|--- goofy, daffy
# -------------| |
# pluto, don | |
# | pluto, don |
# [2-9]|--------------|
# |
# noob, mike |
# -------------|
startingLine = 0
width = 6
betweenGamesWidth = 2
numStartingGames = tournament['allGames'][0].length
numLines = (numStartingGames * width) + ((numStartingGames - 1) * betweenGamesWidth)
# Add one "column" for each round
strTree = new Array(numLines + 2).fill('') # Initialize with empty lines, to add to later
for gameRound in tournament['allGames']
longestLineLength = 7
for game in gameRound
if game['team1']
longestLineLength = Math.max(longestLineLength, "#{game['team1']}".length + 7)
if game['team2']
longestLineLength = Math.max(longestLineLength, "#{game['team2']}".length + 7)
# Draw each of the games
numGames = gameRound.length
currentLine = startingLine
for i in [0..numGames-1]
game = gameRound[i]
gameStartingLine = currentLine
# Draw the two lines on the top and bottom of the game
strTree[currentLine] += '-'.repeat(longestLineLength)
currentLine += width
strTree[currentLine] += '-'.repeat(longestLineLength)
# Draw the team names in the
currentLine = gameStartingLine + 1
if game['team1']
teamStr = " #{game['team1']}"
strTree[currentLine] += teamStr + ' '.repeat(longestLineLength - teamStr.length)
currentLine += width - 2
if game['team2']
teamStr = " #{game['team2']}"
strTree[currentLine] += teamStr + ' '.repeat(longestLineLength - teamStr.length)
# Draw the score in the middle
currentLine = gameStartingLine
currentLine += (width/2)
score = if game['finalScore'] then game['finalScore'] else '?-?'
score = "[#{score}]"
strTree[currentLine] += ' '.repeat(longestLineLength - score.length)
strTree[currentLine] += score
# Add the vertical lines
currentLine = gameStartingLine
while currentLine <= gameStartingLine+width
if !(/(]|-|\w)$/.test(strTree[currentLine].trim()))
strTree[currentLine] += ' '.repeat(longestLineLength)
strTree[currentLine] += '|'
currentLine += 1
if i < (numGames - 1)
endLine = (currentLine + betweenGamesWidth - 1)
while currentLine < endLine
strTree[currentLine] += ' '.repeat(longestLineLength+1)
currentLine += 1
# Update where to start drawing the next round
startingLine = startingLine + (width/2)
width += betweenGamesWidth
betweenGamesWidth = width
# Draw the final winner line
winrar = '?'
finalGame = tournament['allGames'][tournament['allGames'].length-1][0]
if finalGame['finished']
score = finalGame['finalScore'].split('-')
t1score = parseInt(score[0], 10)
t2score = parseInt(score[1], 10)
if t1score > t2score
winrar = "#{finalGame['team1']}"
else
winrar = "#{finalGame['team2']}"
strTree[startingLine] += "--- :trophy: #{winrar}"
res.send strTree.join('\n')
showTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# List all the players currently in the tournament and their ranks at the time of joining
strPlayers = ['Rank:\tName:']
for player in tournament['tournamentPlayers']
strPlayers.push "#{player.rank}\t#{player.name}"
res.send strPlayers.join('\n')
showTournamentTeamsRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# List all the teams currently in the tournament
strTeams = []
for t, i in tournament['tournamentTeams']
strTeams.push "Team #{i}:\n#{t[0]}, #{t[1]}"
res.send strTeams.join('\n\n')
swapTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Try to swap two players
# If players have been accepted, error out
if tournament['playersAccepted']
res.send 'Tournament players have been accepted, you can\'t make modifications anymore!'
return
p1Name = res.match[1].trim().toLowerCase()
p2Name = res.match[2].trim().toLowerCase()
# If the second player didn't exist when the tournament was started, error out
p2 = false
for p in tournament['allPlayers']
if p['name'] == p2Name
p2 = p
break
if !p2
res.send "Player \"#{p2Name}\" did not exist when the tournament was started!"
return
# If the first player isn't in the tournament, error out
p1Index = false
for i in [0..tournament['tournamentPlayers'].length-1]
if tournament['tournamentPlayers'][i]['name'] == p1Name
p1Index = i
# If the second player is already in the tournament, error out
if tournament['tournamentPlayers'][i]['name'] == p2Name
res.send "Player \"#{p2Name}\" is already in the tournament!"
return
if !p1Index
res.send "Player \"#{p1Name}\" is not in the tournament!"
return
tournament['tournamentPlayers'][p1Index] = p2
# Sort the players by the new rank
tournament['tournamentPlayers'] = tournament['tournamentPlayers'].sort(rankSort)
prepareAndDistributeTournamentTeams()
saveTournament()
res.send "Successfully swapped \"#{p1Name}\" with \"#{p2Name}\". Teams have been rebalanced."
acceptTournamentPlayersRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
# Freeze the players
tournament['playersAccepted'] = true
saveTournament()
res.send 'Players accepted, tournament is ready to go!'
isInvalidGenericIndex = (genericIndex, maxLength) ->
return isNaN(genericIndex) || genericIndex < 0 || genericIndex >= maxLength
finishTournamentGameRespond = (res) ->
if !tournament['started']
res.send 'Tournament not started yet!'
return
roundNum = parseInt(res.match[1].trim(), 10)
gameNum = parseInt(res.match[2].trim(), 10)
score = res.match[3].trim().split('-')
t1score = parseInt(score[0], 10)
t2score = parseInt(score[1], 10)
# Finish a game, as indicated in the tree diagram
# If players have not been accepted, error out
if !tournament['playersAccepted']
res.send 'Tournament players have not been accepted yet!'
return
# If the game does not exist, error out
if isInvalidGenericIndex(roundNum, tournament['allGames'].length)
res.send "Invalid round #{roundNum}"
return
gameRound = tournament['allGames'][roundNum]
if isInvalidGenericIndex(gameNum, gameRound.length)
res.send "Invalid game #{gameNum} in round #{roundNum}"
return
game = gameRound[gameNum]
# If the game does not have both teams yet, error out
if !game['team1'] || !game['team2']
res.send "Game #{gameNum} in round #{roundNum} isn't ready to go yet!"
return
# If the game has been finished already, error out
if game['finished']
res.send "Game #{gameNum} in round #{roundNum} has already finished!"
return
# If the game is even, error out
if t1score == t2score
res.send "Cannot finish a tournament game with an even score, someone must lose"
return
# Finish the game and record the score
game['finished'] = true
game['finalScore'] = "#{t1score}-#{t2score}"
# Determine the winner
winrar = game['team2']
losar = game['team1']
strScore = "#{t2score}-#{t1score}"
if t1score > t2score
winrar = game['team1']
losar = game['team2']
strScore = "#{t1score}-#{t2score}"
if game['nextGame'] == false
# If the game finished is the final game, print out a congratulatory message and fanfare, crowning the champions
res.send "Tournament is over! Congratulations to the champions!"
res.send ":trophy::trophy::trophy: #{winrar} :trophy::trophy::trophy:"
else
# Add the team to the next game
nextGame = tournament['allGames'][roundNum+1][game['nextGame']]
if game['topTeam']
nextGame['team1'] = winrar
else
nextGame['team2'] = winrar
res.send "Finished game #{gameNum} in round #{roundNum}! #{winrar} beat #{losar} with a score of #{strScore}"
showTournamentRespond(res)
saveTournament()
retireRespond = (res) ->
retiree = res.message.user.name.trim().toLowerCase()
if retiree in retirees
res.send "You've already retired, you can't double retire!"
return
retirees.push retiree
saveRetirees()
res.send "#{retiree} has permanently retired!"
unretireRespond = (res) ->
retiree = res.message.user.name.trim().toLowerCase()
if !(retiree in retirees)
res.send "You're still kicking"
return
retirees.splice(retirees.indexOf(retiree), 1)
saveRetirees()
res.send "#{retiree} is back in the action!"
# Betting commands
startBettingRespond = (res) ->
highRoller = res.message.user.name.trim().toLowerCase()
if highRoller of accounts
res.send "You have already bought in, you can't buy in again"
return
accounts[highRoller] = _STARTING_FOOSCOIN
saveAccounts()
res.send "#{highRoller} bought in! They start with #{_STARTING_FOOSCOIN}Ģ"
myBalanceRespond = (res) ->
me = res.message.user.name.trim().toLowerCase()
# Error out if person has not bought in yet
if !(me of accounts)
res.send 'You have not bought in yet!'
return
balance = customRound(accounts[me], 4)
res.send "@#{me}, you have #{balance}Ģ"
betRespond = (res) ->
better = res.message.user.name.trim().toLowerCase()
betAmount = parseFloat(res.match[1].trim(), 10)
n = parseInt(res.match[2].trim(), 10)
teamToBetOn = parseInt(res.match[3].trim(), 10)
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
game = games[n]
if game['players'].indexOf(better) >= 0
res.send "You can't bet on a game you're playing in!"
return
if !(better of accounts)
res.send "You have not bought in yet!"
return
# Temporarily bring back the previous bet, then restore it if there are insufficient funds
currentBetAmount = if better of game['bets'] then game['bets'][better]['amount'] else 0
accounts[better] += currentBetAmount
if accounts[better] < betAmount
accounts[better] -= currentBetAmount
res.send "You can't bet #{betAmount}Ģ, you only have #{accounts[better]}Ģ!"
return
# Place the bet, taking it out of the better's account
accounts[better] -= betAmount
game['bets'][better] = {
'amount': betAmount,
'team': teamToBetOn
}
sliceIndex = teamToBetOn * 2
teamMembers = game['players'].slice(sliceIndex, sliceIndex + 2)
saveAccounts()
saveGames()
res.send "#{better} bet #{betAmount}Ģ on game #{n} for #{teamMembers}! They have #{accounts[better]}Ģ left"
cancelBetRespond = (res) ->
better = res.message.user.name.trim().toLowerCase()
n = parseInt(res.match[1].trim(), 10)
if isInvalidIndex(n)
res.send "Invalid game index #{n}"
return
game = games[n]
if !(better of game['bets'])
res.send "You have not placed a bet on game #{n}"
return
if !(better of accounts)
res.send "You couldn't have place a bet on game #{n}, you haven't bought in yet!"
return
accounts[better] += game['bets'][better]['amount']
delete game['bets'][better]
saveAccounts()
saveGames()
res.send "#{better} cancelled bet on game #{n}, they have #{accounts[better]}Ģ left"
returnBets = (res, n) ->
game = games[n]
if Object.keys(game['bets']).length < 1
return
for betterName of game['bets']
if betterName of accounts
accounts[betterName] += game['bets'][betterName]['amount']
res.send "#{betterName} got #{game['bets'][betterName]['amount']}Ģ back, they have #{accounts[betterName]}Ģ left"
game['bets'] = {}
saveAccounts()
saveGames()
res.send "All bets returned for game #{n}"
tipOfTheDaySend = (robot) ->
return () ->
topd = 'Here is your Tip Of The Day™!\n\n'
randomTip = _TIPS[Math.round(Math.random() * (_TIPS.length - 1))]
topd += randomTip
robot.send room: process.env.FOOSBALL_ROOM_ID, topd
module.exports = (robot) ->
robot.respond /games/i, gamesRespond
robot.respond /total games/i, totalGamesRespond
robot.respond /find (?:people|players) for game (\d+)/i, findPeopleForGameRespond
robot.respond /join game (\d+)/i, joinGameRespond
robot.respond /add (\w+) to game (\d+)/i, addToGameRespond
robot.respond /kick (\w+) from game (\d+)/i, kickFromGameRespond
robot.respond /abandon game (\d+)/i, abandonGameRespond
robot.respond /cancel game (\d+)/i, cancelGameRespond
robot.respond /balance game (\d+)/i, balanceGameRespond
robot.respond /shuffle game (\d+)/i, shuffleGameRespond
robot.respond /start game$/i, startGameRespond
robot.respond /start game(?: with)?(( \w+){1,3})$/i, startGameWithPlayersRespond
robot.respond /find people$|find players$/i, findPeopleForNextGameRespond
robot.respond /i'm in/i, joinNextGameRespond
robot.respond /join game$/i, joinNextGameRespond
robot.respond /add (\w+)$/i, addToNextGameRespond
robot.respond /kick (\w+)$/i, kickFromNextGameRespond
robot.respond /abandon game$/i, abandonNextGameRespond
robot.respond /cancel game$/i, cancelNextGameRespond
robot.respond /balance game$/i, balanceNextGameRespond
robot.respond /shuffle game$/i, shuffleNextGameRespond
robot.respond /rematch/i, rematchRespond
robot.respond /finish game +(\d-\d)$/i, finishGameRespond
robot.respond /(rankings|leaderboard)$/i, rankingsRespond
robot.respond /(?:stats|rankings)(( \w+)+)$/i, rankingsForPlayersRespond
robot.respond /top (\d+).*$/i, topNRankingsRespond
robot.respond /reset previous rankings$/i, resetPreviousRankings
robot.respond /history (\w+) ?(\d+|all)?$/i, historyMeRespond
robot.respond /team history (\w+) (\w+) ?(\d+|all)?$/i, teamHistoryRespond
robot.respond /rival history (\w+) (\w+) ?(\d+|all)?$/i, rivalHistoryRespond
robot.respond /team stats (\w+) (\w+)$/i, teamStatsRespond
robot.respond /go on (a )?cleanse$/i, goOnACleanseRespond
robot.respond /return from cleanse$/i, returnFromCleanseRespond
robot.respond /retire/i, retireRespond
robot.respond /unretire/i, unretireRespond
# Tournament commands
robot.respond /start tournament$/i, startTournamentRespond
robot.respond /start tournament with (\d+) people/i, startTournamentWithNPeopleRespond
robot.respond /cancel tournament/i, cancelTournamentRespond
robot.respond /show tournament$/i, showTournamentRespond
robot.respond /show tournament players/i, showTournamentPlayersRespond
robot.respond /show tournament teams/i, showTournamentTeamsRespond
robot.respond /swap tournament player (\w+) with (\w+)/i, swapTournamentPlayersRespond
robot.respond /accept tournament players/i, acceptTournamentPlayersRespond
robot.respond /finish tournament game round (\d+) game (\d+) (\d-\d)/i, finishTournamentGameRespond
# Betting commands
robot.respond /start betting/i, startBettingRespond
robot.respond /(my )?balance$/i, myBalanceRespond
robot.respond /bet (\d+\.\d+) on game (\d+) team ([01])/i, betRespond
robot.respond /cancel bet on game (\d+)/i, cancelBetRespond
# Helpful stuff
robot.respond /the rules/i, theRulesRespond
robot.respond /tip/i, tipRespond
schedule.scheduleJob "0 30 11 * * 1-5", tipOfTheDaySend(robot)
|
[
{
"context": "s.String, length: 5}\n\n\n\np = new Person\np.setName 'asdf'\np.setAge 23\np.setValues [1, 2, 3]\np.setAddress [",
"end": 297,
"score": 0.8193228840827942,
"start": 293,
"tag": "USERNAME",
"value": "asdf"
},
{
"context": " ->\n class JSPeople\n constructor: ->\n @nam... | tests/test_struct.coffee | chethiya/lds | 57 | LDS = require './lds'
Person = LDS.Struct "Person",
{property: 'name', type: LDS.Types.String, length: 1}
{property: 'age', type: LDS.Types.Int16}
{property: 'values', type: LDS.Types.Int32, length: 5}
{property: 'address', type: LDS.Types.String, length: 5}
p = new Person
p.setName 'asdf'
p.setAge 23
p.setValues [1, 2, 3]
p.setAddress ["No. 123", "Street 1", "Street 2", ""]
p.setAddress "3 - thrid", 3
str = new LDS.String "4-fourth"
p.setAddress str, 4, on
str.release()
console.log p.get()
console.log p.getAddress 2
str = p.getAddress 0, on
console.log str.toString()
str.release()
p2 = new Person
p2.copyFrom p
console.log p2.get()
test_struct = (n) ->
console.time 'time_struct'
arr = new Array 5
people = []
for i in [0...n]
p = new Person
p.copyFrom p2
for j in [0...5]
arr[j] = "#{i}-#{j}"
p.setAddress arr
people.push p
console.timeEnd 'time_struct'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, people[p].get().address
test_array = (n) ->
console.time 'time_array'
arr = new Array 5
people = new LDS.Array Person, n
instance = people.get 0
for i in [0...n]
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
instance.next()
console.timeEnd 'time_array'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_arraylist = (n) ->
console.time 'time_arraylist'
arr = new Array 5
people = new LDS.ArrayList Person, n
instance = people.get 0
for i in [0...n]
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
if not instance.next()
instance = people.get i+1, instance
console.timeEnd 'time_arraylist'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_arraylist_add = (n) ->
console.time 'time_arraylist_add'
arr = new Array 5
people = new LDS.ArrayList Person
for i in [0...n]
instance = people.add instance
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
console.timeEnd 'time_arraylist_add'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_js = (n) ->
class JSPeople
constructor: ->
@name = "asdf"
@age = 23
@values = [1, 2, 3, 0, 0]
@address = ["No. 123", "Street 1", "Street 2", '', null]
console.time 'time_js'
people = []
for i in [0...n]
p = new JSPeople
for j in [0...5]
p.address[j] = "#{i}-#{j}"
people.push p
console.timeEnd 'time_js'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, people[p].address
run = (n) ->
#test_array n
#test_struct n
test_js n
test_arraylist n
test_arraylist_add n
run 30
| 156079 | LDS = require './lds'
Person = LDS.Struct "Person",
{property: 'name', type: LDS.Types.String, length: 1}
{property: 'age', type: LDS.Types.Int16}
{property: 'values', type: LDS.Types.Int32, length: 5}
{property: 'address', type: LDS.Types.String, length: 5}
p = new Person
p.setName 'asdf'
p.setAge 23
p.setValues [1, 2, 3]
p.setAddress ["No. 123", "Street 1", "Street 2", ""]
p.setAddress "3 - thrid", 3
str = new LDS.String "4-fourth"
p.setAddress str, 4, on
str.release()
console.log p.get()
console.log p.getAddress 2
str = p.getAddress 0, on
console.log str.toString()
str.release()
p2 = new Person
p2.copyFrom p
console.log p2.get()
test_struct = (n) ->
console.time 'time_struct'
arr = new Array 5
people = []
for i in [0...n]
p = new Person
p.copyFrom p2
for j in [0...5]
arr[j] = "#{i}-#{j}"
p.setAddress arr
people.push p
console.timeEnd 'time_struct'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, people[p].get().address
test_array = (n) ->
console.time 'time_array'
arr = new Array 5
people = new LDS.Array Person, n
instance = people.get 0
for i in [0...n]
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
instance.next()
console.timeEnd 'time_array'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_arraylist = (n) ->
console.time 'time_arraylist'
arr = new Array 5
people = new LDS.ArrayList Person, n
instance = people.get 0
for i in [0...n]
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
if not instance.next()
instance = people.get i+1, instance
console.timeEnd 'time_arraylist'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_arraylist_add = (n) ->
console.time 'time_arraylist_add'
arr = new Array 5
people = new LDS.ArrayList Person
for i in [0...n]
instance = people.add instance
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
console.timeEnd 'time_arraylist_add'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_js = (n) ->
class JSPeople
constructor: ->
@name = "<NAME>"
@age = 23
@values = [1, 2, 3, 0, 0]
@address = ["No. 123", "Street 1", "Street 2", '', null]
console.time 'time_js'
people = []
for i in [0...n]
p = new JSPeople
for j in [0...5]
p.address[j] = "#{i}-#{j}"
people.push p
console.timeEnd 'time_js'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, people[p].address
run = (n) ->
#test_array n
#test_struct n
test_js n
test_arraylist n
test_arraylist_add n
run 30
| true | LDS = require './lds'
Person = LDS.Struct "Person",
{property: 'name', type: LDS.Types.String, length: 1}
{property: 'age', type: LDS.Types.Int16}
{property: 'values', type: LDS.Types.Int32, length: 5}
{property: 'address', type: LDS.Types.String, length: 5}
p = new Person
p.setName 'asdf'
p.setAge 23
p.setValues [1, 2, 3]
p.setAddress ["No. 123", "Street 1", "Street 2", ""]
p.setAddress "3 - thrid", 3
str = new LDS.String "4-fourth"
p.setAddress str, 4, on
str.release()
console.log p.get()
console.log p.getAddress 2
str = p.getAddress 0, on
console.log str.toString()
str.release()
p2 = new Person
p2.copyFrom p
console.log p2.get()
test_struct = (n) ->
console.time 'time_struct'
arr = new Array 5
people = []
for i in [0...n]
p = new Person
p.copyFrom p2
for j in [0...5]
arr[j] = "#{i}-#{j}"
p.setAddress arr
people.push p
console.timeEnd 'time_struct'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, people[p].get().address
test_array = (n) ->
console.time 'time_array'
arr = new Array 5
people = new LDS.Array Person, n
instance = people.get 0
for i in [0...n]
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
instance.next()
console.timeEnd 'time_array'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_arraylist = (n) ->
console.time 'time_arraylist'
arr = new Array 5
people = new LDS.ArrayList Person, n
instance = people.get 0
for i in [0...n]
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
if not instance.next()
instance = people.get i+1, instance
console.timeEnd 'time_arraylist'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_arraylist_add = (n) ->
console.time 'time_arraylist_add'
arr = new Array 5
people = new LDS.ArrayList Person
for i in [0...n]
instance = people.add instance
instance.copyFrom p2
for j in [0...5]
#arr[j] = "#{i}-#{j}"
instance.setAddress "#{i}-#{j}", j
#instance.setAddress arr
console.timeEnd 'time_arraylist_add'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, (people.get p, instance).getAddress()
test_js = (n) ->
class JSPeople
constructor: ->
@name = "PI:NAME:<NAME>END_PI"
@age = 23
@values = [1, 2, 3, 0, 0]
@address = ["No. 123", "Street 1", "Street 2", '', null]
console.time 'time_js'
people = []
for i in [0...n]
p = new JSPeople
for j in [0...5]
p.address[j] = "#{i}-#{j}"
people.push p
console.timeEnd 'time_js'
console.log 'created'
for i in [0...10]
p = (Math.floor Math.random()*n) % n
console.log p, people[p].address
run = (n) ->
#test_array n
#test_struct n
test_js n
test_arraylist n
test_arraylist_add n
run 30
|
[
{
"context": "Click message.id\n $.div\n key: message.id\n className: cx\n 'outline': yes\n ",
"end": 564,
"score": 0.7400900721549988,
"start": 562,
"tag": "KEY",
"value": "id"
}
] | source/app/thread-list.coffee | Cumulo/sync-chat | 1 |
React = require 'react'
AppMessage = require './message'
orders = require '../util/orders'
report = require '../report'
addons = require '../util/addons'
$ = React.DOM
cx = addons.cx
module.exports = React.createFactory React.createClass
displayName: 'thread-list'
propTypes:
user: React.PropTypes.object
onMessageClick: (messageId) ->
report.alterThread messageId
renderMessages: ->
@props.data.concat()
.sort orders.timeReverse
.map (message) =>
onClick = => @onMessageClick message.id
$.div
key: message.id
className: cx
'outline': yes
'is-inside': message.id is @props.user.thread
onClick: onClick,
AppMessage key: message.id, data: message
render: ->
$.div className: 'thread-list',
@renderMessages() | 127918 |
React = require 'react'
AppMessage = require './message'
orders = require '../util/orders'
report = require '../report'
addons = require '../util/addons'
$ = React.DOM
cx = addons.cx
module.exports = React.createFactory React.createClass
displayName: 'thread-list'
propTypes:
user: React.PropTypes.object
onMessageClick: (messageId) ->
report.alterThread messageId
renderMessages: ->
@props.data.concat()
.sort orders.timeReverse
.map (message) =>
onClick = => @onMessageClick message.id
$.div
key: message.<KEY>
className: cx
'outline': yes
'is-inside': message.id is @props.user.thread
onClick: onClick,
AppMessage key: message.id, data: message
render: ->
$.div className: 'thread-list',
@renderMessages() | true |
React = require 'react'
AppMessage = require './message'
orders = require '../util/orders'
report = require '../report'
addons = require '../util/addons'
$ = React.DOM
cx = addons.cx
module.exports = React.createFactory React.createClass
displayName: 'thread-list'
propTypes:
user: React.PropTypes.object
onMessageClick: (messageId) ->
report.alterThread messageId
renderMessages: ->
@props.data.concat()
.sort orders.timeReverse
.map (message) =>
onClick = => @onMessageClick message.id
$.div
key: message.PI:KEY:<KEY>END_PI
className: cx
'outline': yes
'is-inside': message.id is @props.user.thread
onClick: onClick,
AppMessage key: message.id, data: message
render: ->
$.div className: 'thread-list',
@renderMessages() |
[
{
"context": " ship: 'Firespray-31'\n pilot: 'Boba Fett (Scum)'\n upgrades: [\n ]\n ",
"end": 495,
"score": 0.9996955990791321,
"start": 486,
"tag": "NAME",
"value": "Boba Fett"
},
{
"context": " ship: 'Firespray-31'\n pil... | tests/test_wave_6.coffee | CrazyVulcan/xwing | 100 | common = require './common'
common.setup()
casper.test.begin "Scum Faction Tab", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.assertTotalPoints(test, '#scum-builder', 0)
.run ->
test.done()
casper.test.begin "Cross-faction Ships", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'Firespray-31'
pilot: 'Boba Fett (Scum)'
upgrades: [
]
}
# TODO: add pilots from HWK, Y-Wing, Z-95
])
common.assertTotalPoints(test, '#scum-builder', 39)
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'Firespray-31'
pilot: 'Boba Fett'
upgrades: [
]
}
])
common.assertTotalPoints(test, '#empire-builder', 39)
common.removeShip('#empire-builder', 1)
common.openScumBuilder()
common.removeShip('#scum-builder', 1)
.run ->
test.done()
casper.test.begin "Virago title", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'StarViper'
pilot: 'Black Sun Enforcer'
upgrades: [
]
}
{
ship: 'StarViper'
pilot: 'Prince Xizor'
upgrades: [
]
}
])
.then ->
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 4}", "StarVipers do not have System upgrades by default"
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 5}", "StarVipers do not have Illicit upgrades by default"
# Low PS ships cannot take Virago title
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", 'Virago')
common.setPilot('#scum-builder', 1, 'Black Sun Vigo')
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", 'Virago')
# High PS ships can take Virago title
common.addUpgrade("#scum-builder", 2, 3, 'Virago')
common.addUpgrade("#scum-builder", 2, 5, 'Accuracy Corrector')
common.addUpgrade("#scum-builder", 2, 6, 'Inertial Dampeners')
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
.run ->
test.done()
casper.test.begin "Heavy Scyk title", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Cannon)'
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Missile)'
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Torpedo)'
]
}
])
.then ->
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", "Scyk fighters do not have cannon, missile, or torpedo upgrades by default"
# Cannons only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 2, 3}", "Ion Pulse Missiles")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 2, 3}", "Ion Torpedoes")
common.addUpgrade('#scum-builder', 2, 3, 'Ion Cannon')
# Missiles only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 3, 3}", "Ion Cannon")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 3, 3}", "Ion Torpedoes")
common.addUpgrade('#scum-builder', 3, 3, 'Ion Pulse Missiles')
# Torpedoes only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 4, 3}", "Ion Cannon")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 4, 3}", "Ion Pulse Missiles")
common.addUpgrade('#scum-builder', 4, 3, 'Ion Torpedoes')
.run ->
test.done()
| 65097 | common = require './common'
common.setup()
casper.test.begin "Scum Faction Tab", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.assertTotalPoints(test, '#scum-builder', 0)
.run ->
test.done()
casper.test.begin "Cross-faction Ships", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'Firespray-31'
pilot: '<NAME> (Scum)'
upgrades: [
]
}
# TODO: add pilots from HWK, Y-Wing, Z-95
])
common.assertTotalPoints(test, '#scum-builder', 39)
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'Firespray-31'
pilot: '<NAME>'
upgrades: [
]
}
])
common.assertTotalPoints(test, '#empire-builder', 39)
common.removeShip('#empire-builder', 1)
common.openScumBuilder()
common.removeShip('#scum-builder', 1)
.run ->
test.done()
casper.test.begin "Virago title", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'StarViper'
pilot: 'Black Sun Enforcer'
upgrades: [
]
}
{
ship: 'StarViper'
pilot: '<NAME>'
upgrades: [
]
}
])
.then ->
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 4}", "StarVipers do not have System upgrades by default"
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 5}", "StarVipers do not have Illicit upgrades by default"
# Low PS ships cannot take Virago title
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", 'Virago')
common.setPilot('#scum-builder', 1, 'Black Sun Vigo')
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", 'Virago')
# High PS ships can take Virago title
common.addUpgrade("#scum-builder", 2, 3, 'Virago')
common.addUpgrade("#scum-builder", 2, 5, 'Accuracy Corrector')
common.addUpgrade("#scum-builder", 2, 6, 'Inertial Dampeners')
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
.run ->
test.done()
casper.test.begin "Heavy Scyk title", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Cannon)'
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Missile)'
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Torpedo)'
]
}
])
.then ->
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", "Scyk fighters do not have cannon, missile, or torpedo upgrades by default"
# Cannons only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 2, 3}", "Ion Pulse Missiles")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 2, 3}", "Ion Torpedoes")
common.addUpgrade('#scum-builder', 2, 3, 'Ion Cannon')
# Missiles only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 3, 3}", "Ion Cannon")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 3, 3}", "Ion Torpedoes")
common.addUpgrade('#scum-builder', 3, 3, 'Ion Pulse Missiles')
# Torpedoes only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 4, 3}", "Ion Cannon")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 4, 3}", "Ion Pulse Missiles")
common.addUpgrade('#scum-builder', 4, 3, 'Ion Torpedoes')
.run ->
test.done()
| true | common = require './common'
common.setup()
casper.test.begin "Scum Faction Tab", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.assertTotalPoints(test, '#scum-builder', 0)
.run ->
test.done()
casper.test.begin "Cross-faction Ships", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'Firespray-31'
pilot: 'PI:NAME:<NAME>END_PI (Scum)'
upgrades: [
]
}
# TODO: add pilots from HWK, Y-Wing, Z-95
])
common.assertTotalPoints(test, '#scum-builder', 39)
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'Firespray-31'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
]
}
])
common.assertTotalPoints(test, '#empire-builder', 39)
common.removeShip('#empire-builder', 1)
common.openScumBuilder()
common.removeShip('#scum-builder', 1)
.run ->
test.done()
casper.test.begin "Virago title", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'StarViper'
pilot: 'Black Sun Enforcer'
upgrades: [
]
}
{
ship: 'StarViper'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
]
}
])
.then ->
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 4}", "StarVipers do not have System upgrades by default"
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 5}", "StarVipers do not have Illicit upgrades by default"
# Low PS ships cannot take Virago title
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", 'Virago')
common.setPilot('#scum-builder', 1, 'Black Sun Vigo')
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", 'Virago')
# High PS ships can take Virago title
common.addUpgrade("#scum-builder", 2, 3, 'Virago')
common.addUpgrade("#scum-builder", 2, 5, 'Accuracy Corrector')
common.addUpgrade("#scum-builder", 2, 6, 'Inertial Dampeners')
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
.run ->
test.done()
casper.test.begin "Heavy Scyk title", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Cannon)'
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Missile)'
]
}
{
ship: 'M3-A Interceptor'
pilot: 'Cartel Spacer'
upgrades: [
'"Heavy Scyk" Interceptor (Torpedo)'
]
}
])
.then ->
test.assertDoesntExist "#scum-builder #{common.selectorForUpgradeIndex 1, 3}", "Scyk fighters do not have cannon, missile, or torpedo upgrades by default"
# Cannons only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 2, 3}", "Ion Pulse Missiles")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 2, 3}", "Ion Torpedoes")
common.addUpgrade('#scum-builder', 2, 3, 'Ion Cannon')
# Missiles only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 3, 3}", "Ion Cannon")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 3, 3}", "Ion Torpedoes")
common.addUpgrade('#scum-builder', 3, 3, 'Ion Pulse Missiles')
# Torpedoes only
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 4, 3}", "Ion Cannon")
common.assertNoMatch(test, "#scum-builder #{common.selectorForUpgradeIndex 4, 3}", "Ion Pulse Missiles")
common.addUpgrade('#scum-builder', 4, 3, 'Ion Torpedoes')
.run ->
test.done()
|
[
{
"context": " opening:\n \"\"\"\n I am Sam.\n Sam I am.\n Do you like gr",
"end": 2215,
"score": 0.9995996952056885,
"start": 2212,
"tag": "NAME",
"value": "Sam"
},
{
"context": "\n \"\"\"\n I am Sam.\n ... | Prototype Flower Charter/node_modules/string-table/spec/stringTable_spec.coffee | yubro/yubro.github.io | 2 | require('colors')
stringTable = require('../stringTable.js')
describe 'stringTable', ->
juxtapose = (left, right, indentation) ->
[leftRows, rightRows] = [left.split('\n'), right.split('\n')]
leftWidth = leftRows[0].length
output = for i in [0...Math.max(leftRows.length, rightRows.length)]
[
pad(leftRows[i] || '', leftWidth),
rightRows[i] || ''
].join(indent(indentation))
output.join('\n')
indent = (indentation) ->
new Array(indentation + 1).join(' ')
pad = (str, width) ->
return str + indent(width - str.length)
beforeEach ->
this.addMatchers
toMatchTable: (expectedTable) ->
this.message = ->
"""
Expected these tables to match:
#{juxtapose(this.actual, expectedTable, 5)}
"""
this.actual == expectedTable
describe 'create', ->
it 'makes a nicely formatted table from a list of objects', ->
objects = [{ foo: 1, bar: 2 }, { foo: 3, bar: 4 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| foo | bar |
-------------
| 1 | 2 |
| 3 | 4 |
"""
)
it 'aligns strings to the left, other values to the right', ->
objects = [{ foo: 'a', bar: 1 }, { foo: 'b', bar: 2 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| foo | bar |
-------------
| a | 1 |
| b | 2 |
"""
)
it 'aligns headings the same as their values', ->
objects = [{ a: 'foo', b: 100 }, { a: 'bar', b: 200 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| a | b |
-------------
| foo | 100 |
| bar | 200 |
"""
)
it 'resizes rows to fit multiline strings', ->
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am Sam.
Sam I am.
Do you like green eggs and ham?
"""
}
]
expect(stringTable.create(books, { rowSeparator: '-' })).toMatchTable(
"""
| title | opening |
--------------------------------------------------------
| The Cat in the Hat | The sun did not shine. |
| | It was too wet to play. |
| | So we sat in the house |
| | All that cold, cold, wet day. |
--------------------------------------------------------
| Green Eggs and Ham | I am Sam. |
| | Sam I am. |
| | Do you like green eggs and ham? |
"""
)
describe 'customization', ->
objects = [
{ a: 'app', b: 'bow', c: 'cow' },
{ a: 'arc', b: 'bra', c: 'cap' }
]
it 'allows you to specify which column headings to include', ->
expect(stringTable.create(objects, { headers: ['a', 'c'] })).toMatchTable(
"""
| a | c |
-------------
| app | cow |
| arc | cap |
"""
)
it 'provides the option of capitalizing column headings', ->
things = [
{ foo: 'app', bar: 'bow' },
{ foo: 'arc', bar: 'bra' }
]
expect(stringTable.create(things, { capitalizeHeaders: true })).toMatchTable(
"""
| Foo | Bar |
-------------
| app | bow |
| arc | bra |
"""
)
it 'allows you to specify custom outer and inner borders', ->
options =
outerBorder: '||'
innerBorder: '*'
expect(stringTable.create(objects, options)).toMatchTable(
"""
|| a * b * c ||
---------------------
|| app * bow * cow ||
|| arc * bra * cap ||
"""
)
it 'allows you to specify a row separator', ->
expect(stringTable.create(objects, { rowSeparator: ':' })).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | cow |
:::::::::::::::::::
| arc | bra | cap |
"""
)
it 'allows the row separator to be multiple characters', ->
expect(stringTable.create(objects, { rowSeparator: '+-*/' })).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | cow |
+-*/+-*/+-*/+-*/+-*
| arc | bra | cap |
"""
)
it 'allows you to specify a custom header separator', ->
expect(stringTable.create(objects, { headerSeparator: 'x' })).toMatchTable(
"""
| a | b | c |
xxxxxxxxxxxxxxxxxxx
| app | bow | cow |
| arc | bra | cap |
"""
)
it 'allows you to specify a custom formatter for each column', ->
options =
formatters:
c: (value) -> value.toUpperCase()
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | COW |
| arc | bra | CAP |
"""
)
describe 'when receiving a { value, format } object as formatter output', ->
users = [
{ name: 'Dan', gender: 'M', age: 29 },
{ name: 'Adam', gender: 'M', age: 31 },
{ name: 'Lauren', gender: 'F', age: 33 }
]
it 'applies no formatting if none is given', ->
options =
formatters:
gender: (value) ->
value: value
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| Dan | M | 29 |
| Adam | M | 31 |
| Lauren | F | 33 |
"""
)
it 'applies colors, if specified', ->
options =
formatters:
gender: (value) ->
value: value
format:
color: if value == 'M' then 'cyan' else 'magenta'
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| Dan | #{'M'.cyan} | 29 |
| Adam | #{'M'.cyan} | 31 |
| Lauren | #{'F'.magenta} | 33 |
"""
)
it 'applies alignment, if specified', ->
options =
formatters:
gender: (value) ->
value: value
format:
alignment: 'right'
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| Dan | M | 29 |
| Adam | M | 31 |
| Lauren | F | 33 |
"""
)
it 'applies alignment to multi-line values as well', ->
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am Sam.
Sam I am.
Do you like green eggs and ham?
"""
}
]
options =
formatters:
opening: (value) ->
value: value
format:
alignment: 'right'
headerSeparator: '='
rowSeparator: '-'
expect(stringTable.create(books, options)).toMatchTable(
"""
| title | opening |
========================================================
| The Cat in the Hat | The sun did not shine. |
| | It was too wet to play. |
| | So we sat in the house |
| | All that cold, cold, wet day. |
--------------------------------------------------------
| Green Eggs and Ham | I am Sam. |
| | Sam I am. |
| | Do you like green eggs and ham? |
"""
)
it 'allows you to specify a custom formatter for a given type', ->
numbers = [
{ name: 'one', value: 1 },
{ name: 'two', value: 2 },
{ name: 'three', value: 3 }
]
options =
typeFormatters:
number: (value) -> value.toFixed(2)
expect(stringTable.create(numbers, options)).toMatchTable(
"""
| name | value |
-----------------
| one | 1.00 |
| two | 2.00 |
| three | 3.00 |
"""
)
it 'passes both value and column header to custom type formatters', ->
people = [
{ firstName: 'Dan', lastName: 'Tao', middleInitial: 'L' },
{ firstName: 'Joe', lastName: 'Schmoe', middleInitial: 'K' },
{ firstName: 'Johnny', lastName: 'Public', middleInitial: 'Q' }
]
options =
typeFormatters:
string: (value, heading) ->
if heading.match(/Name$/) then value.toUpperCase() else value.toLowerCase()
expect(stringTable.create(people, options)).toMatchTable(
"""
| firstName | lastName | middleInitial |
----------------------------------------
| DAN | TAO | l |
| JOE | SCHMOE | k |
| JOHNNY | PUBLIC | q |
"""
)
it 'gives precedence to a column-specific formatter before a type formatter', ->
options =
formatters:
b: (value) -> value.toUpperCase(),
typeFormatters:
string: (value) -> value.substring(0, 2)
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
-----------------
| ap | BOW | co |
| ar | BRA | ca |
"""
)
it 'by default, outputs the strings "null" and "undefined" for null an undefined', ->
objects[0].a = null
objects[0].b = undefined
options =
formatters:
a: (value) -> value
b: (value) -> value
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
--------------------------
| null | undefined | cow |
| arc | bra | cap |
"""
)
it 'can adjust column widths for colored output', ->
require('colors')
palette = [
{ name: 'success', color: 'green'.green },
{ name: 'info', color: 'blue'.blue },
{ name: 'warning', color: 'yellow'.yellow },
{ name: 'danger', color: 'red'.red }
]
expect(stringTable.create(palette)).toMatchTable(
"""
| name | color |
--------------------
| success | #{'green'.green} |
| info | #{'blue'.blue} |
| warning | #{'yellow'.yellow} |
| danger | #{'red'.red} |
"""
)
| 115069 | require('colors')
stringTable = require('../stringTable.js')
describe 'stringTable', ->
juxtapose = (left, right, indentation) ->
[leftRows, rightRows] = [left.split('\n'), right.split('\n')]
leftWidth = leftRows[0].length
output = for i in [0...Math.max(leftRows.length, rightRows.length)]
[
pad(leftRows[i] || '', leftWidth),
rightRows[i] || ''
].join(indent(indentation))
output.join('\n')
indent = (indentation) ->
new Array(indentation + 1).join(' ')
pad = (str, width) ->
return str + indent(width - str.length)
beforeEach ->
this.addMatchers
toMatchTable: (expectedTable) ->
this.message = ->
"""
Expected these tables to match:
#{juxtapose(this.actual, expectedTable, 5)}
"""
this.actual == expectedTable
describe 'create', ->
it 'makes a nicely formatted table from a list of objects', ->
objects = [{ foo: 1, bar: 2 }, { foo: 3, bar: 4 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| foo | bar |
-------------
| 1 | 2 |
| 3 | 4 |
"""
)
it 'aligns strings to the left, other values to the right', ->
objects = [{ foo: 'a', bar: 1 }, { foo: 'b', bar: 2 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| foo | bar |
-------------
| a | 1 |
| b | 2 |
"""
)
it 'aligns headings the same as their values', ->
objects = [{ a: 'foo', b: 100 }, { a: 'bar', b: 200 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| a | b |
-------------
| foo | 100 |
| bar | 200 |
"""
)
it 'resizes rows to fit multiline strings', ->
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am <NAME>.
<NAME> I am.
Do you like green eggs and ham?
"""
}
]
expect(stringTable.create(books, { rowSeparator: '-' })).toMatchTable(
"""
| title | opening |
--------------------------------------------------------
| The Cat in the Hat | The sun did not shine. |
| | It was too wet to play. |
| | So we sat in the house |
| | All that cold, cold, wet day. |
--------------------------------------------------------
| Green Eggs and Ham | I am <NAME>. |
| | <NAME> am. |
| | Do you like green eggs and ham? |
"""
)
describe 'customization', ->
objects = [
{ a: 'app', b: 'bow', c: 'cow' },
{ a: 'arc', b: 'bra', c: 'cap' }
]
it 'allows you to specify which column headings to include', ->
expect(stringTable.create(objects, { headers: ['a', 'c'] })).toMatchTable(
"""
| a | c |
-------------
| app | cow |
| arc | cap |
"""
)
it 'provides the option of capitalizing column headings', ->
things = [
{ foo: 'app', bar: 'bow' },
{ foo: 'arc', bar: 'bra' }
]
expect(stringTable.create(things, { capitalizeHeaders: true })).toMatchTable(
"""
| Foo | Bar |
-------------
| app | bow |
| arc | bra |
"""
)
it 'allows you to specify custom outer and inner borders', ->
options =
outerBorder: '||'
innerBorder: '*'
expect(stringTable.create(objects, options)).toMatchTable(
"""
|| a * b * c ||
---------------------
|| app * bow * cow ||
|| arc * bra * cap ||
"""
)
it 'allows you to specify a row separator', ->
expect(stringTable.create(objects, { rowSeparator: ':' })).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | cow |
:::::::::::::::::::
| arc | bra | cap |
"""
)
it 'allows the row separator to be multiple characters', ->
expect(stringTable.create(objects, { rowSeparator: '+-*/' })).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | cow |
+-*/+-*/+-*/+-*/+-*
| arc | bra | cap |
"""
)
it 'allows you to specify a custom header separator', ->
expect(stringTable.create(objects, { headerSeparator: 'x' })).toMatchTable(
"""
| a | b | c |
xxxxxxxxxxxxxxxxxxx
| app | bow | cow |
| arc | bra | cap |
"""
)
it 'allows you to specify a custom formatter for each column', ->
options =
formatters:
c: (value) -> value.toUpperCase()
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | COW |
| arc | bra | CAP |
"""
)
describe 'when receiving a { value, format } object as formatter output', ->
users = [
{ name: '<NAME>', gender: 'M', age: 29 },
{ name: '<NAME>', gender: 'M', age: 31 },
{ name: '<NAME>', gender: 'F', age: 33 }
]
it 'applies no formatting if none is given', ->
options =
formatters:
gender: (value) ->
value: value
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| <NAME> | M | 29 |
| <NAME> | M | 31 |
| <NAME>uren | F | 33 |
"""
)
it 'applies colors, if specified', ->
options =
formatters:
gender: (value) ->
value: value
format:
color: if value == 'M' then 'cyan' else 'magenta'
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| <NAME> | #{'M'.cyan} | 29 |
| <NAME> | #{'M'.cyan} | 31 |
| <NAME> | #{'F'.magenta} | 33 |
"""
)
it 'applies alignment, if specified', ->
options =
formatters:
gender: (value) ->
value: value
format:
alignment: 'right'
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| <NAME> | M | 29 |
| <NAME> | M | 31 |
| <NAME> | F | 33 |
"""
)
it 'applies alignment to multi-line values as well', ->
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am <NAME>.
<NAME> am.
Do you like green eggs and ham?
"""
}
]
options =
formatters:
opening: (value) ->
value: value
format:
alignment: 'right'
headerSeparator: '='
rowSeparator: '-'
expect(stringTable.create(books, options)).toMatchTable(
"""
| title | opening |
========================================================
| The Cat in the Hat | The sun did not shine. |
| | It was too wet to play. |
| | So we sat in the house |
| | All that cold, cold, wet day. |
--------------------------------------------------------
| Green Eggs and Ham | I am <NAME>. |
| | <NAME> I am. |
| | Do you like green eggs and ham? |
"""
)
it 'allows you to specify a custom formatter for a given type', ->
numbers = [
{ name: 'one', value: 1 },
{ name: 'two', value: 2 },
{ name: 'three', value: 3 }
]
options =
typeFormatters:
number: (value) -> value.toFixed(2)
expect(stringTable.create(numbers, options)).toMatchTable(
"""
| name | value |
-----------------
| one | 1.00 |
| two | 2.00 |
| three | 3.00 |
"""
)
it 'passes both value and column header to custom type formatters', ->
people = [
{ firstName: '<NAME>', lastName: '<NAME>', middleInitial: 'L' },
{ firstName: '<NAME>', lastName: '<NAME>', middleInitial: 'K' },
{ firstName: '<NAME>', lastName: 'Public', middleInitial: 'Q' }
]
options =
typeFormatters:
string: (value, heading) ->
if heading.match(/Name$/) then value.toUpperCase() else value.toLowerCase()
expect(stringTable.create(people, options)).toMatchTable(
"""
| firstName | lastName | middleInitial |
----------------------------------------
| <NAME> | TAO | l |
| JOE | SCHMOE | k |
| JOHNNY | PUBLIC | q |
"""
)
it 'gives precedence to a column-specific formatter before a type formatter', ->
options =
formatters:
b: (value) -> value.toUpperCase(),
typeFormatters:
string: (value) -> value.substring(0, 2)
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
-----------------
| ap | BOW | co |
| ar | BRA | ca |
"""
)
it 'by default, outputs the strings "null" and "undefined" for null an undefined', ->
objects[0].a = null
objects[0].b = undefined
options =
formatters:
a: (value) -> value
b: (value) -> value
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
--------------------------
| null | undefined | cow |
| arc | bra | cap |
"""
)
it 'can adjust column widths for colored output', ->
require('colors')
palette = [
{ name: 'success', color: 'green'.green },
{ name: 'info', color: 'blue'.blue },
{ name: 'warning', color: 'yellow'.yellow },
{ name: 'danger', color: 'red'.red }
]
expect(stringTable.create(palette)).toMatchTable(
"""
| name | color |
--------------------
| success | #{'green'.green} |
| info | #{'blue'.blue} |
| warning | #{'yellow'.yellow} |
| danger | #{'red'.red} |
"""
)
| true | require('colors')
stringTable = require('../stringTable.js')
describe 'stringTable', ->
juxtapose = (left, right, indentation) ->
[leftRows, rightRows] = [left.split('\n'), right.split('\n')]
leftWidth = leftRows[0].length
output = for i in [0...Math.max(leftRows.length, rightRows.length)]
[
pad(leftRows[i] || '', leftWidth),
rightRows[i] || ''
].join(indent(indentation))
output.join('\n')
indent = (indentation) ->
new Array(indentation + 1).join(' ')
pad = (str, width) ->
return str + indent(width - str.length)
beforeEach ->
this.addMatchers
toMatchTable: (expectedTable) ->
this.message = ->
"""
Expected these tables to match:
#{juxtapose(this.actual, expectedTable, 5)}
"""
this.actual == expectedTable
describe 'create', ->
it 'makes a nicely formatted table from a list of objects', ->
objects = [{ foo: 1, bar: 2 }, { foo: 3, bar: 4 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| foo | bar |
-------------
| 1 | 2 |
| 3 | 4 |
"""
)
it 'aligns strings to the left, other values to the right', ->
objects = [{ foo: 'a', bar: 1 }, { foo: 'b', bar: 2 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| foo | bar |
-------------
| a | 1 |
| b | 2 |
"""
)
it 'aligns headings the same as their values', ->
objects = [{ a: 'foo', b: 100 }, { a: 'bar', b: 200 }]
expect(stringTable.create(objects)).toMatchTable(
"""
| a | b |
-------------
| foo | 100 |
| bar | 200 |
"""
)
it 'resizes rows to fit multiline strings', ->
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI I am.
Do you like green eggs and ham?
"""
}
]
expect(stringTable.create(books, { rowSeparator: '-' })).toMatchTable(
"""
| title | opening |
--------------------------------------------------------
| The Cat in the Hat | The sun did not shine. |
| | It was too wet to play. |
| | So we sat in the house |
| | All that cold, cold, wet day. |
--------------------------------------------------------
| Green Eggs and Ham | I am PI:NAME:<NAME>END_PI. |
| | PI:NAME:<NAME>END_PI am. |
| | Do you like green eggs and ham? |
"""
)
describe 'customization', ->
objects = [
{ a: 'app', b: 'bow', c: 'cow' },
{ a: 'arc', b: 'bra', c: 'cap' }
]
it 'allows you to specify which column headings to include', ->
expect(stringTable.create(objects, { headers: ['a', 'c'] })).toMatchTable(
"""
| a | c |
-------------
| app | cow |
| arc | cap |
"""
)
it 'provides the option of capitalizing column headings', ->
things = [
{ foo: 'app', bar: 'bow' },
{ foo: 'arc', bar: 'bra' }
]
expect(stringTable.create(things, { capitalizeHeaders: true })).toMatchTable(
"""
| Foo | Bar |
-------------
| app | bow |
| arc | bra |
"""
)
it 'allows you to specify custom outer and inner borders', ->
options =
outerBorder: '||'
innerBorder: '*'
expect(stringTable.create(objects, options)).toMatchTable(
"""
|| a * b * c ||
---------------------
|| app * bow * cow ||
|| arc * bra * cap ||
"""
)
it 'allows you to specify a row separator', ->
expect(stringTable.create(objects, { rowSeparator: ':' })).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | cow |
:::::::::::::::::::
| arc | bra | cap |
"""
)
it 'allows the row separator to be multiple characters', ->
expect(stringTable.create(objects, { rowSeparator: '+-*/' })).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | cow |
+-*/+-*/+-*/+-*/+-*
| arc | bra | cap |
"""
)
it 'allows you to specify a custom header separator', ->
expect(stringTable.create(objects, { headerSeparator: 'x' })).toMatchTable(
"""
| a | b | c |
xxxxxxxxxxxxxxxxxxx
| app | bow | cow |
| arc | bra | cap |
"""
)
it 'allows you to specify a custom formatter for each column', ->
options =
formatters:
c: (value) -> value.toUpperCase()
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
-------------------
| app | bow | COW |
| arc | bra | CAP |
"""
)
describe 'when receiving a { value, format } object as formatter output', ->
users = [
{ name: 'PI:NAME:<NAME>END_PI', gender: 'M', age: 29 },
{ name: 'PI:NAME:<NAME>END_PI', gender: 'M', age: 31 },
{ name: 'PI:NAME:<NAME>END_PI', gender: 'F', age: 33 }
]
it 'applies no formatting if none is given', ->
options =
formatters:
gender: (value) ->
value: value
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| PI:NAME:<NAME>END_PI | M | 29 |
| PI:NAME:<NAME>END_PI | M | 31 |
| PI:NAME:<NAME>END_PIuren | F | 33 |
"""
)
it 'applies colors, if specified', ->
options =
formatters:
gender: (value) ->
value: value
format:
color: if value == 'M' then 'cyan' else 'magenta'
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| PI:NAME:<NAME>END_PI | #{'M'.cyan} | 29 |
| PI:NAME:<NAME>END_PI | #{'M'.cyan} | 31 |
| PI:NAME:<NAME>END_PI | #{'F'.magenta} | 33 |
"""
)
it 'applies alignment, if specified', ->
options =
formatters:
gender: (value) ->
value: value
format:
alignment: 'right'
expect(stringTable.create(users, options)).toMatchTable(
"""
| name | gender | age |
-------------------------
| PI:NAME:<NAME>END_PI | M | 29 |
| PI:NAME:<NAME>END_PI | M | 31 |
| PI:NAME:<NAME>END_PI | F | 33 |
"""
)
it 'applies alignment to multi-line values as well', ->
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI am.
Do you like green eggs and ham?
"""
}
]
options =
formatters:
opening: (value) ->
value: value
format:
alignment: 'right'
headerSeparator: '='
rowSeparator: '-'
expect(stringTable.create(books, options)).toMatchTable(
"""
| title | opening |
========================================================
| The Cat in the Hat | The sun did not shine. |
| | It was too wet to play. |
| | So we sat in the house |
| | All that cold, cold, wet day. |
--------------------------------------------------------
| Green Eggs and Ham | I am PI:NAME:<NAME>END_PI. |
| | PI:NAME:<NAME>END_PI I am. |
| | Do you like green eggs and ham? |
"""
)
it 'allows you to specify a custom formatter for a given type', ->
numbers = [
{ name: 'one', value: 1 },
{ name: 'two', value: 2 },
{ name: 'three', value: 3 }
]
options =
typeFormatters:
number: (value) -> value.toFixed(2)
expect(stringTable.create(numbers, options)).toMatchTable(
"""
| name | value |
-----------------
| one | 1.00 |
| two | 2.00 |
| three | 3.00 |
"""
)
it 'passes both value and column header to custom type formatters', ->
people = [
{ firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI', middleInitial: 'L' },
{ firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI', middleInitial: 'K' },
{ firstName: 'PI:NAME:<NAME>END_PI', lastName: 'Public', middleInitial: 'Q' }
]
options =
typeFormatters:
string: (value, heading) ->
if heading.match(/Name$/) then value.toUpperCase() else value.toLowerCase()
expect(stringTable.create(people, options)).toMatchTable(
"""
| firstName | lastName | middleInitial |
----------------------------------------
| PI:NAME:<NAME>END_PI | TAO | l |
| JOE | SCHMOE | k |
| JOHNNY | PUBLIC | q |
"""
)
it 'gives precedence to a column-specific formatter before a type formatter', ->
options =
formatters:
b: (value) -> value.toUpperCase(),
typeFormatters:
string: (value) -> value.substring(0, 2)
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
-----------------
| ap | BOW | co |
| ar | BRA | ca |
"""
)
it 'by default, outputs the strings "null" and "undefined" for null an undefined', ->
objects[0].a = null
objects[0].b = undefined
options =
formatters:
a: (value) -> value
b: (value) -> value
expect(stringTable.create(objects, options)).toMatchTable(
"""
| a | b | c |
--------------------------
| null | undefined | cow |
| arc | bra | cap |
"""
)
it 'can adjust column widths for colored output', ->
require('colors')
palette = [
{ name: 'success', color: 'green'.green },
{ name: 'info', color: 'blue'.blue },
{ name: 'warning', color: 'yellow'.yellow },
{ name: 'danger', color: 'red'.red }
]
expect(stringTable.create(palette)).toMatchTable(
"""
| name | color |
--------------------
| success | #{'green'.green} |
| info | #{'blue'.blue} |
| warning | #{'yellow'.yellow} |
| danger | #{'red'.red} |
"""
)
|
[
{
"context": "\texpect(isValid([Object, null], {id: 1234, name: \"Smith\"})).toBe(true)\n\texpect(isValid([Object, null], nu",
"end": 1251,
"score": 0.9974228143692017,
"start": 1246,
"tag": "NAME",
"value": "Smith"
},
{
"context": "xpect(isValid([UserType, null], {id: 1234, name: \"... | tests/isValid/union.coffee | laurentpayot/rflow | 19 | import {isValid} from '../../dist'
test "return true if the value is one of the given strings, false otherwise", ->
expect(isValid(["foo", "bar"], "foo")).toBe(true)
expect(isValid(["foo", "bar"], "bar")).toBe(true)
expect(isValid(["foo", "bar"], "baz")).toBe(false)
expect(isValid(["foo", "bar"], Array)).toBe(false)
test "return true if the value is one of the given strings, false otherwise", ->
expect(isValid([1, 2], 1)).toBe(true)
expect(isValid([1, 2], 2)).toBe(true)
expect(isValid([1, 2], 3)).toBe(false)
expect(isValid([1, 2], Array)).toBe(false)
test "return true for a string or a number value, false otherwise", ->
expect(isValid([String, Number], "foo")).toBe(true)
expect(isValid([String, Number], 1234)).toBe(true)
expect(isValid([String, Number], null)).toBe(false)
expect(isValid([String, Number], {})).toBe(false)
expect(isValid([Object, Number], new Date())).toBe(false)
test "return true for a string or null value, false otherwise", ->
expect(isValid([String, null], "foo")).toBe(true)
expect(isValid([String, null], null)).toBe(true)
expect(isValid([String, null], 1234)).toBe(false)
test "return true for an object or null value, false otherwise", ->
expect(isValid([Object, null], {id: 1234, name: "Smith"})).toBe(true)
expect(isValid([Object, null], null)).toBe(true)
expect(isValid([Object, null], "foo")).toBe(false)
test "return true for an object type or null value, false otherwise", ->
UserType =
id: Number
name: String
expect(isValid([UserType, null], {id: 1234, name: "Smith"})).toBe(true)
expect(isValid([UserType, null], null)).toBe(true)
expect(isValid([UserType, null], "foo")).toBe(false)
| 170430 | import {isValid} from '../../dist'
test "return true if the value is one of the given strings, false otherwise", ->
expect(isValid(["foo", "bar"], "foo")).toBe(true)
expect(isValid(["foo", "bar"], "bar")).toBe(true)
expect(isValid(["foo", "bar"], "baz")).toBe(false)
expect(isValid(["foo", "bar"], Array)).toBe(false)
test "return true if the value is one of the given strings, false otherwise", ->
expect(isValid([1, 2], 1)).toBe(true)
expect(isValid([1, 2], 2)).toBe(true)
expect(isValid([1, 2], 3)).toBe(false)
expect(isValid([1, 2], Array)).toBe(false)
test "return true for a string or a number value, false otherwise", ->
expect(isValid([String, Number], "foo")).toBe(true)
expect(isValid([String, Number], 1234)).toBe(true)
expect(isValid([String, Number], null)).toBe(false)
expect(isValid([String, Number], {})).toBe(false)
expect(isValid([Object, Number], new Date())).toBe(false)
test "return true for a string or null value, false otherwise", ->
expect(isValid([String, null], "foo")).toBe(true)
expect(isValid([String, null], null)).toBe(true)
expect(isValid([String, null], 1234)).toBe(false)
test "return true for an object or null value, false otherwise", ->
expect(isValid([Object, null], {id: 1234, name: "<NAME>"})).toBe(true)
expect(isValid([Object, null], null)).toBe(true)
expect(isValid([Object, null], "foo")).toBe(false)
test "return true for an object type or null value, false otherwise", ->
UserType =
id: Number
name: String
expect(isValid([UserType, null], {id: 1234, name: "<NAME>"})).toBe(true)
expect(isValid([UserType, null], null)).toBe(true)
expect(isValid([UserType, null], "foo")).toBe(false)
| true | import {isValid} from '../../dist'
test "return true if the value is one of the given strings, false otherwise", ->
expect(isValid(["foo", "bar"], "foo")).toBe(true)
expect(isValid(["foo", "bar"], "bar")).toBe(true)
expect(isValid(["foo", "bar"], "baz")).toBe(false)
expect(isValid(["foo", "bar"], Array)).toBe(false)
test "return true if the value is one of the given strings, false otherwise", ->
expect(isValid([1, 2], 1)).toBe(true)
expect(isValid([1, 2], 2)).toBe(true)
expect(isValid([1, 2], 3)).toBe(false)
expect(isValid([1, 2], Array)).toBe(false)
test "return true for a string or a number value, false otherwise", ->
expect(isValid([String, Number], "foo")).toBe(true)
expect(isValid([String, Number], 1234)).toBe(true)
expect(isValid([String, Number], null)).toBe(false)
expect(isValid([String, Number], {})).toBe(false)
expect(isValid([Object, Number], new Date())).toBe(false)
test "return true for a string or null value, false otherwise", ->
expect(isValid([String, null], "foo")).toBe(true)
expect(isValid([String, null], null)).toBe(true)
expect(isValid([String, null], 1234)).toBe(false)
test "return true for an object or null value, false otherwise", ->
expect(isValid([Object, null], {id: 1234, name: "PI:NAME:<NAME>END_PI"})).toBe(true)
expect(isValid([Object, null], null)).toBe(true)
expect(isValid([Object, null], "foo")).toBe(false)
test "return true for an object type or null value, false otherwise", ->
UserType =
id: Number
name: String
expect(isValid([UserType, null], {id: 1234, name: "PI:NAME:<NAME>END_PI"})).toBe(true)
expect(isValid([UserType, null], null)).toBe(true)
expect(isValid([UserType, null], "foo")).toBe(false)
|
[
{
"context": "###\nAuthor: Jamis Buck <jamis@jamisbuck.org>\nLicense: Public domain, bab",
"end": 22,
"score": 0.9998846054077148,
"start": 12,
"tag": "NAME",
"value": "Jamis Buck"
},
{
"context": "###\nAuthor: Jamis Buck <jamis@jamisbuck.org>\nLicense: Public domain, baby. Knock you... | data/coffeescript/c93c11918cf18fff284e2fabea9d5663_widget.coffee | maxim5/code-inspector | 5 | ###
Author: Jamis Buck <jamis@jamisbuck.org>
License: Public domain, baby. Knock yourself out.
The original CoffeeScript sources are always available on GitHub:
http://github.com/jamis/csmazes
###
Maze.createWidget = (algorithm, width, height, options) ->
options ?= {}
updateWalls = (maze, x, y, classes) ->
classes.push "e" if maze.isEast(x, y)
classes.push "w" if maze.isWest(x, y)
classes.push "s" if maze.isSouth(x, y)
classes.push "n" if maze.isNorth(x, y)
classes.push "u" if maze.isUnder(x, y)
ACTIONS =
AldousBroder: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
else if not maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
GrowingTree: (maze, x, y, classes) ->
if not maze.isBlank(x, y)
if maze.algorithm.inQueue(x, y)
classes.push "f"
else
classes.push "in"
updateWalls maze, x, y, classes
GrowingBinaryTree: (maze, x, y, classes) ->
ACTIONS.GrowingTree(maze, x, y, classes)
HuntAndKill: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
unless maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
Prim: (maze, x, y, classes) ->
if maze.algorithm.isFrontier(x, y)
classes.push "f"
else if maze.algorithm.isInside(x, y)
classes.push "in"
updateWalls maze, x, y, classes
RecursiveBacktracker: (maze, x, y, classes) ->
if maze.algorithm.isStack(x, y)
classes.push "f"
else
classes.push "in"
updateWalls maze, x, y, classes
RecursiveDivision: (maze, x, y, classes) ->
updateWalls(maze, x, y, classes)
Wilson: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
updateWalls maze, x, y, classes
else if not maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
else if maze.algorithm.isVisited(x, y)
classes.push "f"
Houston: (maze, x, y, classes) ->
if maze.algorithm.worker.isVisited?
ACTIONS.Wilson(maze, x, y, classes)
else
ACTIONS.AldousBroder(maze, x, y, classes)
default: (maze, x, y, classes) ->
unless maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
updateCallback = (maze, x, y) ->
classes = []
(ACTIONS[algorithm] || ACTIONS.default)(maze, x, y, classes)
cell = document.getElementById("#{maze.element.id}_y#{y}x#{x}")
cell.className = classes.join(" ")
eventCallback = (maze, x, y) ->
maze.element.mazePause() if maze.element.quickStep
id = options.id || algorithm.toLowerCase()
options.interval ?= 50
mazeClass = "maze"
mazeClass += " " + options.class if options.class
gridClass = "grid"
gridClass += " invert" if options.wallwise
gridClass += " padded" if options.padded
if options.watch ? true
watch = "<a id='#{id}_watch' href='#' onclick='document.getElementById(\"#{id}\").mazeQuickStep(); return false;'>Watch</a>"
else
watch = ""
html = """
<div id="#{id}" class="#{mazeClass}">
<div id="#{id}_grid" class="#{gridClass}"></div>
<div class="operations">
<a id="#{id}_reset" href="#" onclick="document.getElementById('#{id}').mazeReset(); return false;">Reset</a>
<a id="#{id}_step" href="#" onclick="document.getElementById('#{id}').mazeStep(); return false;">Step</a>
#{watch}
<a id="#{id}_run" href="#" onclick="document.getElementById('#{id}').mazeRun(); return false;">Run</a>
</div>
</div>
"""
document.write html
element = document.getElementById(id)
element.addClassName = (el, name) ->
classNames = el.className.split(" ")
for className in classNames
return if className == name
el.className += " " + name
element.removeClassName = (el, name) ->
if el.className.length > 0
classNames = el.className.split(" ")
el.className = ""
for className in classNames
if className != name
el.className += " " if el.className.length > 0
el.className += className
element.mazePause = ->
if @mazeStepInterval?
clearInterval @mazeStepInterval
@mazeStepInterval = null
@quickStep = false
return true
element.mazeRun = ->
unless @mazePause()
@mazeStepInterval = setInterval((=> @mazeStep()), options.interval)
element.mazeStep = ->
unless @maze.step()
@mazePause()
@addClassName document.getElementById("#{@id}_step"), "disabled"
@addClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@addClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeQuickStep = ->
@quickStep = true
@mazeRun()
element.mazeReset = ->
@mazePause()
if typeof options.input == "function"
value = options.input()
else
value = options.input
@maze = new Maze(width, height, Maze.Algorithms[algorithm], {
seed: options.seed,
rng: options.rng, input: value, weave: options.weave, weaveMode: options.weaveMode,
weaveDensity: options.weaveDensity
})
@maze.element = this
@maze.onUpdate(updateCallback)
@maze.onEvent(eventCallback)
grid = ""
for y in [0...@maze.height]
row_id = "#{@id}_y#{y}"
grid += "<div class='row' id='#{row_id}'>"
for x in [0...@maze.width]
grid += "<div id='#{row_id}x#{x}'>"
if options.padded
grid += "<div class='np'></div>"
grid += "<div class='wp'></div>"
grid += "<div class='ep'></div>"
grid += "<div class='sp'></div>"
grid += "<div class='c'></div>"
grid += "</div>"
grid += "</div>"
gridElement = document.getElementById("#{@id}_grid")
gridElement.innerHTML = grid
@removeClassName document.getElementById("#{@id}_step"), "disabled"
@removeClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@removeClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeReset()
Maze.createCanvasWidget = (algorithm, width, height, options) ->
options ?= {}
styles = options.styles ? {}
styles.blank ?= "#ccc"
styles.f ?= "#faa"
styles.a ?= "#faa"
styles.b ?= "#afa"
styles.in ?= "#fff"
styles.cursor ?= "#7f7"
styles.wall ?= "#000"
COLORS =
AldousBroder: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
GrowingTree: (maze, x, y) ->
if not maze.isBlank(x, y)
if maze.algorithm.inQueue(x, y)
styles.f
else
styles.in
GrowingBinaryTree: (maze, x, y) ->
COLORS.GrowingTree(maze, x, y)
HuntAndKill: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
Prim: (maze, x, y) ->
if maze.algorithm.isFrontier(x, y)
styles.f
else if maze.algorithm.isInside(x, y)
styles.in
RecursiveBacktracker: (maze, x, y) ->
if maze.algorithm.isStack(x, y)
styles.f
else if not maze.isBlank(x, y)
styles.in
RecursiveDivision: (maze, x, y) ->
# nothing to do here--no fill styles!
Wilson: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
else if maze.algorithm.isVisited(x, y)
styles.f
Houston: (maze, x, y) ->
if maze.algorithm.worker?
if maze.algorithm.worker.isVisited?
COLORS.Wilson(maze, x, y)
else
COLORS.AldousBroder(maze, x, y)
BlobbyDivision: (maze, x, y) ->
switch maze.algorithm.stateAt(x, y)
when "blank" then styles.blank
when "in" then styles.in
when "active" then styles.f
when "a" then styles.a
when "b" then styles.b
default: (maze, x, y) ->
unless maze.isBlank(x, y)
styles.in
drawLine = (ctx, x1, y1, x2, y2) ->
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
drawCell = (maze, x, y) ->
px = x * maze.cellWidth
py = y * maze.cellHeight
wmpx = if x == 0 then px + 0.5 else px - 0.5
nmpy = if y == 0 then py + 0.5 else py - 0.5
empx = px - 0.5
smpy = py - 0.5
colors = COLORS[algorithm] || COLORS.default
color = colors(maze, x, y)
color ?= (if options.wallwise then styles.in else styles.blank)
maze.context.fillStyle = color
maze.context.fillRect(px, py, maze.cellWidth, maze.cellHeight)
maze.context.beginPath()
# west && options.wallwise || !west && !options.wallwise
# -> same as testing equality
if maze.isWest(x, y) == options.wallwise?
drawLine(maze.context, wmpx, py, wmpx, py+maze.cellHeight)
if maze.isEast(x, y) == options.wallwise?
drawLine(maze.context, empx + maze.cellWidth, py, empx + maze.cellWidth, py+maze.cellHeight)
if maze.isNorth(x, y) == options.wallwise?
drawLine(maze.context, px, nmpy, px+maze.cellWidth, nmpy)
if maze.isSouth(x, y) == options.wallwise?
drawLine(maze.context, px, smpy + maze.cellHeight, px+maze.cellWidth, smpy + maze.cellHeight)
maze.context.closePath()
maze.context.stroke()
drawCellPadded = (maze, x, y) ->
px1 = x * maze.cellWidth
px2 = px1 + maze.insetWidth - 0.5
px4 = px1 + maze.cellWidth - 0.5
px3 = px4 - maze.insetWidth
py1 = y * maze.cellHeight
py2 = py1 + maze.insetHeight - 0.5
py4 = py1 + maze.cellHeight - 0.5
py3 = py4 - maze.insetHeight
px1 = if x == 0 then px1 + 0.5 else px1 - 0.5
py1 = if y == 0 then py1 + 0.5 else py1 - 0.5
colors = COLORS[algorithm] || COLORS.default
color = colors(maze, x, y)
color ?= (if options.wallwise then styles.in else styles.blank)
maze.context.fillStyle = color
maze.context.fillRect(px2-0.5, py2-0.5, px3-px2+1, py3-py2+1)
maze.context.beginPath()
if maze.isWest(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px1-0.5, py2-0.5, px2-px1+1, py3-py2+1)
drawLine(maze.context, px1-1, py2, px2, py2)
drawLine(maze.context, px1-1, py3, px2, py3)
if !maze.isWest(x, y)
drawLine(maze.context, px2, py2, px2, py3)
if maze.isEast(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px3-0.5, py2-0.5, px4-px3+1, py3-py2+1)
drawLine(maze.context, px3, py2, px4+1, py2)
drawLine(maze.context, px3, py3, px4+1, py3)
if !maze.isEast(x, y)
drawLine(maze.context, px3, py2, px3, py3)
if maze.isNorth(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px2-0.5, py1-0.5, px3-px2+1, py2-py1+1)
drawLine(maze.context, px2, py1-1, px2, py2)
drawLine(maze.context, px3, py1-1, px3, py2)
if !maze.isNorth(x, y)
drawLine(maze.context, px2, py2, px3, py2)
if maze.isSouth(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px2-0.5, py3-0.5, px3-px2+1, py4-py3+1)
drawLine(maze.context, px2, py3, px2, py4+1)
drawLine(maze.context, px3, py3, px3, py4+1)
if !maze.isSouth(x, y)
drawLine(maze.context, px2, py3, px3, py3)
maze.context.closePath()
maze.context.stroke()
drawMaze = (maze) ->
for row in [0...maze.height] by 1
for col in [0...maze.width] by 1
if options.padded
drawCellPadded(maze, col, row)
else
drawCell(maze, col, row)
updateCallback = (maze, x, y) ->
if options.padded
drawCellPadded(maze, x, y)
else
drawCell(maze, x, y)
eventCallback = (maze, x, y) ->
maze.element.mazePause() if maze.element.quickStep
id = options.id || algorithm.toLowerCase()
options.interval ?= 50
mazeClass = "maze"
mazeClass += " " + options.class if options.class
gridClass = "grid"
gridClass += " invert" if options.wallwise
gridClass += " padded" if options.padded
if options.watch ? true
watch = "<a id='#{id}_watch' href='#' onclick='document.getElementById(\"#{id}\").mazeQuickStep(); return false;'>Watch</a>"
else
watch = ""
html = """
<div id="#{id}" class="#{mazeClass}">
<canvas id="#{id}_canvas" width="210" height="210" class="#{gridClass}"></canvas>
<div class="operations">
<a id="#{id}_reset" href="#" onclick="document.getElementById('#{id}').mazeReset(); return false;">Reset</a>
<a id="#{id}_step" href="#" onclick="document.getElementById('#{id}').mazeStep(); return false;">Step</a>
#{watch}
<a id="#{id}_run" href="#" onclick="document.getElementById('#{id}').mazeRun(); return false;">Run</a>
</div>
</div>
"""
document.write html
element = document.getElementById(id)
element.addClassName = (el, name) ->
classNames = el.className.split(" ")
for className in classNames
return if className == name
el.className += " " + name
element.removeClassName = (el, name) ->
if el.className.length > 0
classNames = el.className.split(" ")
el.className = ""
for className in classNames
if className != name
el.className += " " if el.className.length > 0
el.className += className
element.mazePause = ->
if @mazeStepInterval?
clearInterval @mazeStepInterval
@mazeStepInterval = null
@quickStep = false
return true
element.mazeRun = ->
unless @mazePause()
@mazeStepInterval = setInterval((=> @mazeStep()), options.interval)
element.mazeStep = ->
unless @maze.step()
@mazePause()
@addClassName document.getElementById("#{@id}_step"), "disabled"
@addClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@addClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeQuickStep = ->
@quickStep = true
@mazeRun()
element.mazeReset = ->
@mazePause()
if typeof options.input == "function"
value = options.input()
else
value = options.input
if typeof options.threshold == "function"
threshold = options.threshold()
else
threshold = options.threshold
growSpeed = Math.round(Math.sqrt(width * height))
wallSpeed = Math.round((if width < height then width else height) / 2)
@maze = new Maze(width, height, Maze.Algorithms[algorithm], {
seed: options.seed,
rng: options.rng, input: value, weave: options.weave, weaveMode: options.weaveMode,
weaveDensity: options.weaveDensity, threshold: threshold,
growSpeed: growSpeed, wallSpeed: wallSpeed
})
canvas = document.getElementById("#{@id}_canvas")
@maze.element = this
@maze.canvas = canvas
@maze.context = canvas.getContext('2d')
@maze.cellWidth = Math.floor(canvas.width / @maze.width)
@maze.cellHeight = Math.floor(canvas.height / @maze.height)
if options.padded
inset = options.inset ? 0.1
@maze.insetWidth = Math.ceil(inset * @maze.cellWidth)
@maze.insetHeight = Math.ceil(inset * @maze.cellHeight)
@maze.onUpdate(updateCallback)
@maze.onEvent(eventCallback)
@maze.context.clearRect(0, 0, canvas.width, canvas.height)
@removeClassName document.getElementById("#{@id}_step"), "disabled"
@removeClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@removeClassName document.getElementById("#{@id}_run"), "disabled"
drawMaze(@maze)
element.mazeReset()
| 107135 | ###
Author: <NAME> <<EMAIL>>
License: Public domain, baby. Knock yourself out.
The original CoffeeScript sources are always available on GitHub:
http://github.com/jamis/csmazes
###
Maze.createWidget = (algorithm, width, height, options) ->
options ?= {}
updateWalls = (maze, x, y, classes) ->
classes.push "e" if maze.isEast(x, y)
classes.push "w" if maze.isWest(x, y)
classes.push "s" if maze.isSouth(x, y)
classes.push "n" if maze.isNorth(x, y)
classes.push "u" if maze.isUnder(x, y)
ACTIONS =
AldousBroder: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
else if not maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
GrowingTree: (maze, x, y, classes) ->
if not maze.isBlank(x, y)
if maze.algorithm.inQueue(x, y)
classes.push "f"
else
classes.push "in"
updateWalls maze, x, y, classes
GrowingBinaryTree: (maze, x, y, classes) ->
ACTIONS.GrowingTree(maze, x, y, classes)
HuntAndKill: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
unless maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
Prim: (maze, x, y, classes) ->
if maze.algorithm.isFrontier(x, y)
classes.push "f"
else if maze.algorithm.isInside(x, y)
classes.push "in"
updateWalls maze, x, y, classes
RecursiveBacktracker: (maze, x, y, classes) ->
if maze.algorithm.isStack(x, y)
classes.push "f"
else
classes.push "in"
updateWalls maze, x, y, classes
RecursiveDivision: (maze, x, y, classes) ->
updateWalls(maze, x, y, classes)
<NAME>son: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
updateWalls maze, x, y, classes
else if not maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
else if maze.algorithm.isVisited(x, y)
classes.push "f"
Houston: (maze, x, y, classes) ->
if maze.algorithm.worker.isVisited?
ACTIONS.Wilson(maze, x, y, classes)
else
ACTIONS.AldousBroder(maze, x, y, classes)
default: (maze, x, y, classes) ->
unless maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
updateCallback = (maze, x, y) ->
classes = []
(ACTIONS[algorithm] || ACTIONS.default)(maze, x, y, classes)
cell = document.getElementById("#{maze.element.id}_y#{y}x#{x}")
cell.className = classes.join(" ")
eventCallback = (maze, x, y) ->
maze.element.mazePause() if maze.element.quickStep
id = options.id || algorithm.toLowerCase()
options.interval ?= 50
mazeClass = "maze"
mazeClass += " " + options.class if options.class
gridClass = "grid"
gridClass += " invert" if options.wallwise
gridClass += " padded" if options.padded
if options.watch ? true
watch = "<a id='#{id}_watch' href='#' onclick='document.getElementById(\"#{id}\").mazeQuickStep(); return false;'>Watch</a>"
else
watch = ""
html = """
<div id="#{id}" class="#{mazeClass}">
<div id="#{id}_grid" class="#{gridClass}"></div>
<div class="operations">
<a id="#{id}_reset" href="#" onclick="document.getElementById('#{id}').mazeReset(); return false;">Reset</a>
<a id="#{id}_step" href="#" onclick="document.getElementById('#{id}').mazeStep(); return false;">Step</a>
#{watch}
<a id="#{id}_run" href="#" onclick="document.getElementById('#{id}').mazeRun(); return false;">Run</a>
</div>
</div>
"""
document.write html
element = document.getElementById(id)
element.addClassName = (el, name) ->
classNames = el.className.split(" ")
for className in classNames
return if className == name
el.className += " " + name
element.removeClassName = (el, name) ->
if el.className.length > 0
classNames = el.className.split(" ")
el.className = ""
for className in classNames
if className != name
el.className += " " if el.className.length > 0
el.className += className
element.mazePause = ->
if @mazeStepInterval?
clearInterval @mazeStepInterval
@mazeStepInterval = null
@quickStep = false
return true
element.mazeRun = ->
unless @mazePause()
@mazeStepInterval = setInterval((=> @mazeStep()), options.interval)
element.mazeStep = ->
unless @maze.step()
@mazePause()
@addClassName document.getElementById("#{@id}_step"), "disabled"
@addClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@addClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeQuickStep = ->
@quickStep = true
@mazeRun()
element.mazeReset = ->
@mazePause()
if typeof options.input == "function"
value = options.input()
else
value = options.input
@maze = new Maze(width, height, Maze.Algorithms[algorithm], {
seed: options.seed,
rng: options.rng, input: value, weave: options.weave, weaveMode: options.weaveMode,
weaveDensity: options.weaveDensity
})
@maze.element = this
@maze.onUpdate(updateCallback)
@maze.onEvent(eventCallback)
grid = ""
for y in [0...@maze.height]
row_id = "#{@id}_y#{y}"
grid += "<div class='row' id='#{row_id}'>"
for x in [0...@maze.width]
grid += "<div id='#{row_id}x#{x}'>"
if options.padded
grid += "<div class='np'></div>"
grid += "<div class='wp'></div>"
grid += "<div class='ep'></div>"
grid += "<div class='sp'></div>"
grid += "<div class='c'></div>"
grid += "</div>"
grid += "</div>"
gridElement = document.getElementById("#{@id}_grid")
gridElement.innerHTML = grid
@removeClassName document.getElementById("#{@id}_step"), "disabled"
@removeClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@removeClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeReset()
Maze.createCanvasWidget = (algorithm, width, height, options) ->
options ?= {}
styles = options.styles ? {}
styles.blank ?= "#ccc"
styles.f ?= "#faa"
styles.a ?= "#faa"
styles.b ?= "#afa"
styles.in ?= "#fff"
styles.cursor ?= "#7f7"
styles.wall ?= "#000"
COLORS =
AldousBroder: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
GrowingTree: (maze, x, y) ->
if not maze.isBlank(x, y)
if maze.algorithm.inQueue(x, y)
styles.f
else
styles.in
GrowingBinaryTree: (maze, x, y) ->
COLORS.GrowingTree(maze, x, y)
HuntAndKill: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
Prim: (maze, x, y) ->
if maze.algorithm.isFrontier(x, y)
styles.f
else if maze.algorithm.isInside(x, y)
styles.in
RecursiveBacktracker: (maze, x, y) ->
if maze.algorithm.isStack(x, y)
styles.f
else if not maze.isBlank(x, y)
styles.in
RecursiveDivision: (maze, x, y) ->
# nothing to do here--no fill styles!
<NAME>: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
else if maze.algorithm.isVisited(x, y)
styles.f
Houston: (maze, x, y) ->
if maze.algorithm.worker?
if maze.algorithm.worker.isVisited?
COLORS.Wilson(maze, x, y)
else
COLORS.AldousBroder(maze, x, y)
BlobbyDivision: (maze, x, y) ->
switch maze.algorithm.stateAt(x, y)
when "blank" then styles.blank
when "in" then styles.in
when "active" then styles.f
when "a" then styles.a
when "b" then styles.b
default: (maze, x, y) ->
unless maze.isBlank(x, y)
styles.in
drawLine = (ctx, x1, y1, x2, y2) ->
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
drawCell = (maze, x, y) ->
px = x * maze.cellWidth
py = y * maze.cellHeight
wmpx = if x == 0 then px + 0.5 else px - 0.5
nmpy = if y == 0 then py + 0.5 else py - 0.5
empx = px - 0.5
smpy = py - 0.5
colors = COLORS[algorithm] || COLORS.default
color = colors(maze, x, y)
color ?= (if options.wallwise then styles.in else styles.blank)
maze.context.fillStyle = color
maze.context.fillRect(px, py, maze.cellWidth, maze.cellHeight)
maze.context.beginPath()
# west && options.wallwise || !west && !options.wallwise
# -> same as testing equality
if maze.isWest(x, y) == options.wallwise?
drawLine(maze.context, wmpx, py, wmpx, py+maze.cellHeight)
if maze.isEast(x, y) == options.wallwise?
drawLine(maze.context, empx + maze.cellWidth, py, empx + maze.cellWidth, py+maze.cellHeight)
if maze.isNorth(x, y) == options.wallwise?
drawLine(maze.context, px, nmpy, px+maze.cellWidth, nmpy)
if maze.isSouth(x, y) == options.wallwise?
drawLine(maze.context, px, smpy + maze.cellHeight, px+maze.cellWidth, smpy + maze.cellHeight)
maze.context.closePath()
maze.context.stroke()
drawCellPadded = (maze, x, y) ->
px1 = x * maze.cellWidth
px2 = px1 + maze.insetWidth - 0.5
px4 = px1 + maze.cellWidth - 0.5
px3 = px4 - maze.insetWidth
py1 = y * maze.cellHeight
py2 = py1 + maze.insetHeight - 0.5
py4 = py1 + maze.cellHeight - 0.5
py3 = py4 - maze.insetHeight
px1 = if x == 0 then px1 + 0.5 else px1 - 0.5
py1 = if y == 0 then py1 + 0.5 else py1 - 0.5
colors = COLORS[algorithm] || COLORS.default
color = colors(maze, x, y)
color ?= (if options.wallwise then styles.in else styles.blank)
maze.context.fillStyle = color
maze.context.fillRect(px2-0.5, py2-0.5, px3-px2+1, py3-py2+1)
maze.context.beginPath()
if maze.isWest(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px1-0.5, py2-0.5, px2-px1+1, py3-py2+1)
drawLine(maze.context, px1-1, py2, px2, py2)
drawLine(maze.context, px1-1, py3, px2, py3)
if !maze.isWest(x, y)
drawLine(maze.context, px2, py2, px2, py3)
if maze.isEast(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px3-0.5, py2-0.5, px4-px3+1, py3-py2+1)
drawLine(maze.context, px3, py2, px4+1, py2)
drawLine(maze.context, px3, py3, px4+1, py3)
if !maze.isEast(x, y)
drawLine(maze.context, px3, py2, px3, py3)
if maze.isNorth(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px2-0.5, py1-0.5, px3-px2+1, py2-py1+1)
drawLine(maze.context, px2, py1-1, px2, py2)
drawLine(maze.context, px3, py1-1, px3, py2)
if !maze.isNorth(x, y)
drawLine(maze.context, px2, py2, px3, py2)
if maze.isSouth(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px2-0.5, py3-0.5, px3-px2+1, py4-py3+1)
drawLine(maze.context, px2, py3, px2, py4+1)
drawLine(maze.context, px3, py3, px3, py4+1)
if !maze.isSouth(x, y)
drawLine(maze.context, px2, py3, px3, py3)
maze.context.closePath()
maze.context.stroke()
drawMaze = (maze) ->
for row in [0...maze.height] by 1
for col in [0...maze.width] by 1
if options.padded
drawCellPadded(maze, col, row)
else
drawCell(maze, col, row)
updateCallback = (maze, x, y) ->
if options.padded
drawCellPadded(maze, x, y)
else
drawCell(maze, x, y)
eventCallback = (maze, x, y) ->
maze.element.mazePause() if maze.element.quickStep
id = options.id || algorithm.toLowerCase()
options.interval ?= 50
mazeClass = "maze"
mazeClass += " " + options.class if options.class
gridClass = "grid"
gridClass += " invert" if options.wallwise
gridClass += " padded" if options.padded
if options.watch ? true
watch = "<a id='#{id}_watch' href='#' onclick='document.getElementById(\"#{id}\").mazeQuickStep(); return false;'>Watch</a>"
else
watch = ""
html = """
<div id="#{id}" class="#{mazeClass}">
<canvas id="#{id}_canvas" width="210" height="210" class="#{gridClass}"></canvas>
<div class="operations">
<a id="#{id}_reset" href="#" onclick="document.getElementById('#{id}').mazeReset(); return false;">Reset</a>
<a id="#{id}_step" href="#" onclick="document.getElementById('#{id}').mazeStep(); return false;">Step</a>
#{watch}
<a id="#{id}_run" href="#" onclick="document.getElementById('#{id}').mazeRun(); return false;">Run</a>
</div>
</div>
"""
document.write html
element = document.getElementById(id)
element.addClassName = (el, name) ->
classNames = el.className.split(" ")
for className in classNames
return if className == name
el.className += " " + name
element.removeClassName = (el, name) ->
if el.className.length > 0
classNames = el.className.split(" ")
el.className = ""
for className in classNames
if className != name
el.className += " " if el.className.length > 0
el.className += className
element.mazePause = ->
if @mazeStepInterval?
clearInterval @mazeStepInterval
@mazeStepInterval = null
@quickStep = false
return true
element.mazeRun = ->
unless @mazePause()
@mazeStepInterval = setInterval((=> @mazeStep()), options.interval)
element.mazeStep = ->
unless @maze.step()
@mazePause()
@addClassName document.getElementById("#{@id}_step"), "disabled"
@addClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@addClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeQuickStep = ->
@quickStep = true
@mazeRun()
element.mazeReset = ->
@mazePause()
if typeof options.input == "function"
value = options.input()
else
value = options.input
if typeof options.threshold == "function"
threshold = options.threshold()
else
threshold = options.threshold
growSpeed = Math.round(Math.sqrt(width * height))
wallSpeed = Math.round((if width < height then width else height) / 2)
@maze = new Maze(width, height, Maze.Algorithms[algorithm], {
seed: options.seed,
rng: options.rng, input: value, weave: options.weave, weaveMode: options.weaveMode,
weaveDensity: options.weaveDensity, threshold: threshold,
growSpeed: growSpeed, wallSpeed: wallSpeed
})
canvas = document.getElementById("#{@id}_canvas")
@maze.element = this
@maze.canvas = canvas
@maze.context = canvas.getContext('2d')
@maze.cellWidth = Math.floor(canvas.width / @maze.width)
@maze.cellHeight = Math.floor(canvas.height / @maze.height)
if options.padded
inset = options.inset ? 0.1
@maze.insetWidth = Math.ceil(inset * @maze.cellWidth)
@maze.insetHeight = Math.ceil(inset * @maze.cellHeight)
@maze.onUpdate(updateCallback)
@maze.onEvent(eventCallback)
@maze.context.clearRect(0, 0, canvas.width, canvas.height)
@removeClassName document.getElementById("#{@id}_step"), "disabled"
@removeClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@removeClassName document.getElementById("#{@id}_run"), "disabled"
drawMaze(@maze)
element.mazeReset()
| true | ###
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
License: Public domain, baby. Knock yourself out.
The original CoffeeScript sources are always available on GitHub:
http://github.com/jamis/csmazes
###
Maze.createWidget = (algorithm, width, height, options) ->
options ?= {}
updateWalls = (maze, x, y, classes) ->
classes.push "e" if maze.isEast(x, y)
classes.push "w" if maze.isWest(x, y)
classes.push "s" if maze.isSouth(x, y)
classes.push "n" if maze.isNorth(x, y)
classes.push "u" if maze.isUnder(x, y)
ACTIONS =
AldousBroder: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
else if not maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
GrowingTree: (maze, x, y, classes) ->
if not maze.isBlank(x, y)
if maze.algorithm.inQueue(x, y)
classes.push "f"
else
classes.push "in"
updateWalls maze, x, y, classes
GrowingBinaryTree: (maze, x, y, classes) ->
ACTIONS.GrowingTree(maze, x, y, classes)
HuntAndKill: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
unless maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
Prim: (maze, x, y, classes) ->
if maze.algorithm.isFrontier(x, y)
classes.push "f"
else if maze.algorithm.isInside(x, y)
classes.push "in"
updateWalls maze, x, y, classes
RecursiveBacktracker: (maze, x, y, classes) ->
if maze.algorithm.isStack(x, y)
classes.push "f"
else
classes.push "in"
updateWalls maze, x, y, classes
RecursiveDivision: (maze, x, y, classes) ->
updateWalls(maze, x, y, classes)
PI:NAME:<NAME>END_PIson: (maze, x, y, classes) ->
if maze.algorithm.isCurrent(x, y)
classes.push "cursor"
updateWalls maze, x, y, classes
else if not maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
else if maze.algorithm.isVisited(x, y)
classes.push "f"
Houston: (maze, x, y, classes) ->
if maze.algorithm.worker.isVisited?
ACTIONS.Wilson(maze, x, y, classes)
else
ACTIONS.AldousBroder(maze, x, y, classes)
default: (maze, x, y, classes) ->
unless maze.isBlank(x, y)
classes.push "in"
updateWalls maze, x, y, classes
updateCallback = (maze, x, y) ->
classes = []
(ACTIONS[algorithm] || ACTIONS.default)(maze, x, y, classes)
cell = document.getElementById("#{maze.element.id}_y#{y}x#{x}")
cell.className = classes.join(" ")
eventCallback = (maze, x, y) ->
maze.element.mazePause() if maze.element.quickStep
id = options.id || algorithm.toLowerCase()
options.interval ?= 50
mazeClass = "maze"
mazeClass += " " + options.class if options.class
gridClass = "grid"
gridClass += " invert" if options.wallwise
gridClass += " padded" if options.padded
if options.watch ? true
watch = "<a id='#{id}_watch' href='#' onclick='document.getElementById(\"#{id}\").mazeQuickStep(); return false;'>Watch</a>"
else
watch = ""
html = """
<div id="#{id}" class="#{mazeClass}">
<div id="#{id}_grid" class="#{gridClass}"></div>
<div class="operations">
<a id="#{id}_reset" href="#" onclick="document.getElementById('#{id}').mazeReset(); return false;">Reset</a>
<a id="#{id}_step" href="#" onclick="document.getElementById('#{id}').mazeStep(); return false;">Step</a>
#{watch}
<a id="#{id}_run" href="#" onclick="document.getElementById('#{id}').mazeRun(); return false;">Run</a>
</div>
</div>
"""
document.write html
element = document.getElementById(id)
element.addClassName = (el, name) ->
classNames = el.className.split(" ")
for className in classNames
return if className == name
el.className += " " + name
element.removeClassName = (el, name) ->
if el.className.length > 0
classNames = el.className.split(" ")
el.className = ""
for className in classNames
if className != name
el.className += " " if el.className.length > 0
el.className += className
element.mazePause = ->
if @mazeStepInterval?
clearInterval @mazeStepInterval
@mazeStepInterval = null
@quickStep = false
return true
element.mazeRun = ->
unless @mazePause()
@mazeStepInterval = setInterval((=> @mazeStep()), options.interval)
element.mazeStep = ->
unless @maze.step()
@mazePause()
@addClassName document.getElementById("#{@id}_step"), "disabled"
@addClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@addClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeQuickStep = ->
@quickStep = true
@mazeRun()
element.mazeReset = ->
@mazePause()
if typeof options.input == "function"
value = options.input()
else
value = options.input
@maze = new Maze(width, height, Maze.Algorithms[algorithm], {
seed: options.seed,
rng: options.rng, input: value, weave: options.weave, weaveMode: options.weaveMode,
weaveDensity: options.weaveDensity
})
@maze.element = this
@maze.onUpdate(updateCallback)
@maze.onEvent(eventCallback)
grid = ""
for y in [0...@maze.height]
row_id = "#{@id}_y#{y}"
grid += "<div class='row' id='#{row_id}'>"
for x in [0...@maze.width]
grid += "<div id='#{row_id}x#{x}'>"
if options.padded
grid += "<div class='np'></div>"
grid += "<div class='wp'></div>"
grid += "<div class='ep'></div>"
grid += "<div class='sp'></div>"
grid += "<div class='c'></div>"
grid += "</div>"
grid += "</div>"
gridElement = document.getElementById("#{@id}_grid")
gridElement.innerHTML = grid
@removeClassName document.getElementById("#{@id}_step"), "disabled"
@removeClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@removeClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeReset()
Maze.createCanvasWidget = (algorithm, width, height, options) ->
options ?= {}
styles = options.styles ? {}
styles.blank ?= "#ccc"
styles.f ?= "#faa"
styles.a ?= "#faa"
styles.b ?= "#afa"
styles.in ?= "#fff"
styles.cursor ?= "#7f7"
styles.wall ?= "#000"
COLORS =
AldousBroder: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
GrowingTree: (maze, x, y) ->
if not maze.isBlank(x, y)
if maze.algorithm.inQueue(x, y)
styles.f
else
styles.in
GrowingBinaryTree: (maze, x, y) ->
COLORS.GrowingTree(maze, x, y)
HuntAndKill: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
Prim: (maze, x, y) ->
if maze.algorithm.isFrontier(x, y)
styles.f
else if maze.algorithm.isInside(x, y)
styles.in
RecursiveBacktracker: (maze, x, y) ->
if maze.algorithm.isStack(x, y)
styles.f
else if not maze.isBlank(x, y)
styles.in
RecursiveDivision: (maze, x, y) ->
# nothing to do here--no fill styles!
PI:NAME:<NAME>END_PI: (maze, x, y) ->
if maze.algorithm.isCurrent(x, y)
styles.cursor
else if not maze.isBlank(x, y)
styles.in
else if maze.algorithm.isVisited(x, y)
styles.f
Houston: (maze, x, y) ->
if maze.algorithm.worker?
if maze.algorithm.worker.isVisited?
COLORS.Wilson(maze, x, y)
else
COLORS.AldousBroder(maze, x, y)
BlobbyDivision: (maze, x, y) ->
switch maze.algorithm.stateAt(x, y)
when "blank" then styles.blank
when "in" then styles.in
when "active" then styles.f
when "a" then styles.a
when "b" then styles.b
default: (maze, x, y) ->
unless maze.isBlank(x, y)
styles.in
drawLine = (ctx, x1, y1, x2, y2) ->
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
drawCell = (maze, x, y) ->
px = x * maze.cellWidth
py = y * maze.cellHeight
wmpx = if x == 0 then px + 0.5 else px - 0.5
nmpy = if y == 0 then py + 0.5 else py - 0.5
empx = px - 0.5
smpy = py - 0.5
colors = COLORS[algorithm] || COLORS.default
color = colors(maze, x, y)
color ?= (if options.wallwise then styles.in else styles.blank)
maze.context.fillStyle = color
maze.context.fillRect(px, py, maze.cellWidth, maze.cellHeight)
maze.context.beginPath()
# west && options.wallwise || !west && !options.wallwise
# -> same as testing equality
if maze.isWest(x, y) == options.wallwise?
drawLine(maze.context, wmpx, py, wmpx, py+maze.cellHeight)
if maze.isEast(x, y) == options.wallwise?
drawLine(maze.context, empx + maze.cellWidth, py, empx + maze.cellWidth, py+maze.cellHeight)
if maze.isNorth(x, y) == options.wallwise?
drawLine(maze.context, px, nmpy, px+maze.cellWidth, nmpy)
if maze.isSouth(x, y) == options.wallwise?
drawLine(maze.context, px, smpy + maze.cellHeight, px+maze.cellWidth, smpy + maze.cellHeight)
maze.context.closePath()
maze.context.stroke()
drawCellPadded = (maze, x, y) ->
px1 = x * maze.cellWidth
px2 = px1 + maze.insetWidth - 0.5
px4 = px1 + maze.cellWidth - 0.5
px3 = px4 - maze.insetWidth
py1 = y * maze.cellHeight
py2 = py1 + maze.insetHeight - 0.5
py4 = py1 + maze.cellHeight - 0.5
py3 = py4 - maze.insetHeight
px1 = if x == 0 then px1 + 0.5 else px1 - 0.5
py1 = if y == 0 then py1 + 0.5 else py1 - 0.5
colors = COLORS[algorithm] || COLORS.default
color = colors(maze, x, y)
color ?= (if options.wallwise then styles.in else styles.blank)
maze.context.fillStyle = color
maze.context.fillRect(px2-0.5, py2-0.5, px3-px2+1, py3-py2+1)
maze.context.beginPath()
if maze.isWest(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px1-0.5, py2-0.5, px2-px1+1, py3-py2+1)
drawLine(maze.context, px1-1, py2, px2, py2)
drawLine(maze.context, px1-1, py3, px2, py3)
if !maze.isWest(x, y)
drawLine(maze.context, px2, py2, px2, py3)
if maze.isEast(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px3-0.5, py2-0.5, px4-px3+1, py3-py2+1)
drawLine(maze.context, px3, py2, px4+1, py2)
drawLine(maze.context, px3, py3, px4+1, py3)
if !maze.isEast(x, y)
drawLine(maze.context, px3, py2, px3, py3)
if maze.isNorth(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px2-0.5, py1-0.5, px3-px2+1, py2-py1+1)
drawLine(maze.context, px2, py1-1, px2, py2)
drawLine(maze.context, px3, py1-1, px3, py2)
if !maze.isNorth(x, y)
drawLine(maze.context, px2, py2, px3, py2)
if maze.isSouth(x, y) || maze.isUnder(x, y)
maze.context.fillRect(px2-0.5, py3-0.5, px3-px2+1, py4-py3+1)
drawLine(maze.context, px2, py3, px2, py4+1)
drawLine(maze.context, px3, py3, px3, py4+1)
if !maze.isSouth(x, y)
drawLine(maze.context, px2, py3, px3, py3)
maze.context.closePath()
maze.context.stroke()
drawMaze = (maze) ->
for row in [0...maze.height] by 1
for col in [0...maze.width] by 1
if options.padded
drawCellPadded(maze, col, row)
else
drawCell(maze, col, row)
updateCallback = (maze, x, y) ->
if options.padded
drawCellPadded(maze, x, y)
else
drawCell(maze, x, y)
eventCallback = (maze, x, y) ->
maze.element.mazePause() if maze.element.quickStep
id = options.id || algorithm.toLowerCase()
options.interval ?= 50
mazeClass = "maze"
mazeClass += " " + options.class if options.class
gridClass = "grid"
gridClass += " invert" if options.wallwise
gridClass += " padded" if options.padded
if options.watch ? true
watch = "<a id='#{id}_watch' href='#' onclick='document.getElementById(\"#{id}\").mazeQuickStep(); return false;'>Watch</a>"
else
watch = ""
html = """
<div id="#{id}" class="#{mazeClass}">
<canvas id="#{id}_canvas" width="210" height="210" class="#{gridClass}"></canvas>
<div class="operations">
<a id="#{id}_reset" href="#" onclick="document.getElementById('#{id}').mazeReset(); return false;">Reset</a>
<a id="#{id}_step" href="#" onclick="document.getElementById('#{id}').mazeStep(); return false;">Step</a>
#{watch}
<a id="#{id}_run" href="#" onclick="document.getElementById('#{id}').mazeRun(); return false;">Run</a>
</div>
</div>
"""
document.write html
element = document.getElementById(id)
element.addClassName = (el, name) ->
classNames = el.className.split(" ")
for className in classNames
return if className == name
el.className += " " + name
element.removeClassName = (el, name) ->
if el.className.length > 0
classNames = el.className.split(" ")
el.className = ""
for className in classNames
if className != name
el.className += " " if el.className.length > 0
el.className += className
element.mazePause = ->
if @mazeStepInterval?
clearInterval @mazeStepInterval
@mazeStepInterval = null
@quickStep = false
return true
element.mazeRun = ->
unless @mazePause()
@mazeStepInterval = setInterval((=> @mazeStep()), options.interval)
element.mazeStep = ->
unless @maze.step()
@mazePause()
@addClassName document.getElementById("#{@id}_step"), "disabled"
@addClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@addClassName document.getElementById("#{@id}_run"), "disabled"
element.mazeQuickStep = ->
@quickStep = true
@mazeRun()
element.mazeReset = ->
@mazePause()
if typeof options.input == "function"
value = options.input()
else
value = options.input
if typeof options.threshold == "function"
threshold = options.threshold()
else
threshold = options.threshold
growSpeed = Math.round(Math.sqrt(width * height))
wallSpeed = Math.round((if width < height then width else height) / 2)
@maze = new Maze(width, height, Maze.Algorithms[algorithm], {
seed: options.seed,
rng: options.rng, input: value, weave: options.weave, weaveMode: options.weaveMode,
weaveDensity: options.weaveDensity, threshold: threshold,
growSpeed: growSpeed, wallSpeed: wallSpeed
})
canvas = document.getElementById("#{@id}_canvas")
@maze.element = this
@maze.canvas = canvas
@maze.context = canvas.getContext('2d')
@maze.cellWidth = Math.floor(canvas.width / @maze.width)
@maze.cellHeight = Math.floor(canvas.height / @maze.height)
if options.padded
inset = options.inset ? 0.1
@maze.insetWidth = Math.ceil(inset * @maze.cellWidth)
@maze.insetHeight = Math.ceil(inset * @maze.cellHeight)
@maze.onUpdate(updateCallback)
@maze.onEvent(eventCallback)
@maze.context.clearRect(0, 0, canvas.width, canvas.height)
@removeClassName document.getElementById("#{@id}_step"), "disabled"
@removeClassName document.getElementById("#{@id}_watch"), "disabled" if options.watch ? true
@removeClassName document.getElementById("#{@id}_run"), "disabled"
drawMaze(@maze)
element.mazeReset()
|
[
{
"context": "ue.coffee: Github issue class\n#\n# Copyright © 2013 Josh Priestley. All rights reserved\n#\n\n# Initiate class\nclass Is",
"end": 72,
"score": 0.9993950724601746,
"start": 58,
"tag": "NAME",
"value": "Josh Priestley"
},
{
"context": "e cb null, b, h\n\n # Delete a com... | src/octonode/issue.coffee | silverbux/octonode2 | 0 | #
# issue.coffee: Github issue class
#
# Copyright © 2013 Josh Priestley. All rights reserved
#
# Initiate class
class Issue
constructor: (@repo, @number, @client) ->
# Get a single issue
# '/repos/pksunkara/hub/issues/37' GET
info: (cb) ->
@client.get "/repos/#{@repo}/issues/#{@number}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Issue info error")) else cb null, b, h
# Edit an issue for a repository
# '/repos/pksunkara/hub/issues/37' PATCH
update: (obj, cb) ->
@client.patch "/repos/#{@repo}/issues/#{@number}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Issue update error")) else cb null, b, h
# List comments on an issue
# '/repos/pksunkara/hub/issues/37/comments' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
comments: (params..., cb) ->
@client.get "/repos/" + @repo + "/issues/" + @number + "/comments", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error('Issue Comments error')) else cb null, b, h
# Create a comment
# '/repos/pksunkara/hub/issues/37/comments' POST
createComment: (comment, cb) ->
@client.post "/repos/#{@repo}/issues/#{@number}/comments", comment, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error('Issue createComment error')) else cb null, b, h
# Edit a comment
# '/repos/pksunkara/hub/issues/comments/3' PATCH
updateComment: (id, comment, cb) ->
@client.patch "/repos/#{@repo}/issues/comments/#{id}", comment, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error('Issue updateComment error')) else cb null, b, h
# Delete a comment
# '/repos/pksunkara/hub/issues/comments/3' DELETE
deleteComment: (id) ->
@client.del "/repos/#{@repo}/issues/comments/#{id}", {}, (err, s, b, h) =>
return cb(err) if err
if s isnt 204 then cb(new Error("Issue deleteComment error")) else cb null, b, h
# Export module
module.exports = Issue
| 63418 | #
# issue.coffee: Github issue class
#
# Copyright © 2013 <NAME>. All rights reserved
#
# Initiate class
class Issue
constructor: (@repo, @number, @client) ->
# Get a single issue
# '/repos/pksunkara/hub/issues/37' GET
info: (cb) ->
@client.get "/repos/#{@repo}/issues/#{@number}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Issue info error")) else cb null, b, h
# Edit an issue for a repository
# '/repos/pksunkara/hub/issues/37' PATCH
update: (obj, cb) ->
@client.patch "/repos/#{@repo}/issues/#{@number}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Issue update error")) else cb null, b, h
# List comments on an issue
# '/repos/pksunkara/hub/issues/37/comments' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
comments: (params..., cb) ->
@client.get "/repos/" + @repo + "/issues/" + @number + "/comments", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error('Issue Comments error')) else cb null, b, h
# Create a comment
# '/repos/pksunkara/hub/issues/37/comments' POST
createComment: (comment, cb) ->
@client.post "/repos/#{@repo}/issues/#{@number}/comments", comment, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error('Issue createComment error')) else cb null, b, h
# Edit a comment
# '/repos/pksunkara/hub/issues/comments/3' PATCH
updateComment: (id, comment, cb) ->
@client.patch "/repos/#{@repo}/issues/comments/#{id}", comment, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error('Issue updateComment error')) else cb null, b, h
# Delete a comment
# '/repos/pksunkara/hub/issues/comments/3' DELETE
deleteComment: (id) ->
@client.del "/repos/#{@repo}/issues/comments/#{id}", {}, (err, s, b, h) =>
return cb(err) if err
if s isnt 204 then cb(new Error("Issue deleteComment error")) else cb null, b, h
# Export module
module.exports = Issue
| true | #
# issue.coffee: Github issue class
#
# Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved
#
# Initiate class
class Issue
constructor: (@repo, @number, @client) ->
# Get a single issue
# '/repos/pksunkara/hub/issues/37' GET
info: (cb) ->
@client.get "/repos/#{@repo}/issues/#{@number}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Issue info error")) else cb null, b, h
# Edit an issue for a repository
# '/repos/pksunkara/hub/issues/37' PATCH
update: (obj, cb) ->
@client.patch "/repos/#{@repo}/issues/#{@number}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Issue update error")) else cb null, b, h
# List comments on an issue
# '/repos/pksunkara/hub/issues/37/comments' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
comments: (params..., cb) ->
@client.get "/repos/" + @repo + "/issues/" + @number + "/comments", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error('Issue Comments error')) else cb null, b, h
# Create a comment
# '/repos/pksunkara/hub/issues/37/comments' POST
createComment: (comment, cb) ->
@client.post "/repos/#{@repo}/issues/#{@number}/comments", comment, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error('Issue createComment error')) else cb null, b, h
# Edit a comment
# '/repos/pksunkara/hub/issues/comments/3' PATCH
updateComment: (id, comment, cb) ->
@client.patch "/repos/#{@repo}/issues/comments/#{id}", comment, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error('Issue updateComment error')) else cb null, b, h
# Delete a comment
# '/repos/pksunkara/hub/issues/comments/3' DELETE
deleteComment: (id) ->
@client.del "/repos/#{@repo}/issues/comments/#{id}", {}, (err, s, b, h) =>
return cb(err) if err
if s isnt 204 then cb(new Error("Issue deleteComment error")) else cb null, b, h
# Export module
module.exports = Issue
|
[
{
"context": "# Mobster\n# Sean Canton (@SeanCanton)\n# Chris Scott(@CyberStrike)\n# Emerg",
"end": 23,
"score": 0.9998853802680969,
"start": 12,
"tag": "NAME",
"value": "Sean Canton"
},
{
"context": "# Mobster\n# Sean Canton (@SeanCanton)\n# Chris Scott(@CyberStrike)\n# Emerge Hack ... | js/app.coffee | eighteyes/mobster | 0 | # Mobster
# Sean Canton (@SeanCanton)
# Chris Scott(@CyberStrike)
# Emerge Hack 2014
## Google Map Init
map = {}
@coordinates = {}
@user = {}
# Geolocation
navigator.geolocation.getCurrentPosition (data) =>
@coordinates = data.coords
console.log(
"Accuracy: " + @coordinates.accuracy
"Altitude: " + @coordinates.altitude
"Altitude Accuracy: " + @coordinates.altitudeAccuracy
"Heading: " + @coordinates.heading
"Latitude: " + @coordinates.latitude
"Longitude: " + @coordinates.longitude
"Speed: " + @coordinates.speed)
userId = 12
@user = {
userId: userId,
userName: "webUser",
lon: @coordinates.longitude,
lat: @coordinates.latitude
}
console.log("user", @user)
# Init
socket.emit('init', @user)
# Start Maps
@googlemaps = ->
console.log 'hello'
# Geolocation
navigator.geolocation.getCurrentPosition (data) =>
@coordinates = data.coords
console.log(
"Accuracy: " + @coordinates.accuracy
"Altitude: " + @coordinates.altitude
"Altitude Accuracy: " + @coordinates.altitudeAccuracy
"Heading: " + @coordinates.heading
"Latitude: " + @coordinates.latitude
"Longitude: " + @coordinates.longitude
"Speed: " + @coordinates.speed)
#Configure Maps
@myLatlng = new google.maps.LatLng(@coordinates.latitude, @coordinates.longitude)
mapOptions =
center: @myLatlng
zoom: 13
styles: @Midnight_Commander
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
marker = new google.maps.Marker(
position: @myLatlng,
animation: google.maps.Animation.DROP,
map: map)
#Resize Listener
google.maps.event.addDomListener window, "resize", ->
center = map.getCenter()
google.maps.event.trigger map, "resize"
map.setCenter @myLatlng
$(document).ready => @googlemaps()
$('.testbtn').click ()->
contentString =
'<div id="content">'+'<div id="siteNotice">'+'</div>'+
'<h1 id="firstHeading" class="firstHeading">Test Player</h1>'+
'<div id="bodyContent">'+
'<p>Test Content </p>' +
'</div>'+'</div>'
infowindow = new google.maps.InfoWindow(content: contentString)
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude - 0.01, coordinates.longitude - 0.01)
animation: google.maps.Animation.DROP,
map: map
title: "Test Player"
)
google.maps.event.addListener marker, "click", ->
console.log marker
infowindow.open map, marker
###
Socket.io
###
socket = io.connect('107.170.141.208')
#navigator.geolocation.getCurrentPosition (data) =>
# window.pos = data.coords
# New User
socket.emit("update", user)
socket.on 'newUser', (data)->
console.log('NewUser', data)
console.log data.lat, data.lon
latlng = new google.maps.LatLng(data.lat, data.lon)
@player2 = new google.maps.Marker(
position: latlng,
map: map
)
# Send Msg
$('#msg').keypress (e)->
if e.which == 13
socket.emit 'chat',
userName: 'webUser'
msg: $('#msg').val()
$('#msg').val('')
$('#chat p').last().focus()
socket.on 'chat', (data)->
console.log("chat", data)
$('#chat').append($('<p>', {text: data.msg}))
$('#update').click ()->
console.log(user)
socket.emit( 'update', user)
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude - 0.01, coordinates.longitude - 0.01)
animation: google.maps.Animation.DROP,
map: map
)
# Update
socket.on 'update', (data)->
console.log('update', data)
console.log data.lat, data.lon
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude, coordinates.longitude)
animation: google.maps.Animation.DROP,
map: map
)
i = 0
socket.on 'init', (data)->
users = data
while i < users.length
users[i]
users[i].location[0].lat
users[i].location[0].lon
console.log users[i].location[0].lat, users[i].location[0].lon
latlng = new google.maps.LatLng(users[i].location[0].lat, users[i].location[0].lon)
users[i].userId = new google.maps.Marker(
position: latlng
animation: google.maps.Animation.DROP
)
users[i].userId.setMap(map)
i++
## Push Menu
$menuButton = $('.navbar-toggle')
$menuLeft = $('.menu-left')
$menuRight = $('.menu-right')
$body = $('body')
$el = $(this)
$menuButton.click ->
$el.toggleClass "active"
$body.toggleClass " menu-push-toleft"
$('#overlay').toggleClass "overlay"
$menuRight.toggleClass "menu-open"
$('#overlay').click ->
$menuButton.removeClass "active"
$body.removeClass "menu-push-toleft"
$body.removeClass "menu-push-toright"
$menuRight.removeClass "menu-open"
$menuLeft.removeClass "menu-open"
$('#overlay').removeClass "overlay"
$('.navbar-toggle').removeClass('disabled')
| 18118 | # Mobster
# <NAME> (@SeanCanton)
# <NAME>(@CyberStrike)
# Emerge Hack 2014
## Google Map Init
map = {}
@coordinates = {}
@user = {}
# Geolocation
navigator.geolocation.getCurrentPosition (data) =>
@coordinates = data.coords
console.log(
"Accuracy: " + @coordinates.accuracy
"Altitude: " + @coordinates.altitude
"Altitude Accuracy: " + @coordinates.altitudeAccuracy
"Heading: " + @coordinates.heading
"Latitude: " + @coordinates.latitude
"Longitude: " + @coordinates.longitude
"Speed: " + @coordinates.speed)
userId = 12
@user = {
userId: userId,
userName: "webUser",
lon: @coordinates.longitude,
lat: @coordinates.latitude
}
console.log("user", @user)
# Init
socket.emit('init', @user)
# Start Maps
@googlemaps = ->
console.log 'hello'
# Geolocation
navigator.geolocation.getCurrentPosition (data) =>
@coordinates = data.coords
console.log(
"Accuracy: " + @coordinates.accuracy
"Altitude: " + @coordinates.altitude
"Altitude Accuracy: " + @coordinates.altitudeAccuracy
"Heading: " + @coordinates.heading
"Latitude: " + @coordinates.latitude
"Longitude: " + @coordinates.longitude
"Speed: " + @coordinates.speed)
#Configure Maps
@myLatlng = new google.maps.LatLng(@coordinates.latitude, @coordinates.longitude)
mapOptions =
center: @myLatlng
zoom: 13
styles: @Midnight_Commander
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
marker = new google.maps.Marker(
position: @myLatlng,
animation: google.maps.Animation.DROP,
map: map)
#Resize Listener
google.maps.event.addDomListener window, "resize", ->
center = map.getCenter()
google.maps.event.trigger map, "resize"
map.setCenter @myLatlng
$(document).ready => @googlemaps()
$('.testbtn').click ()->
contentString =
'<div id="content">'+'<div id="siteNotice">'+'</div>'+
'<h1 id="firstHeading" class="firstHeading">Test Player</h1>'+
'<div id="bodyContent">'+
'<p>Test Content </p>' +
'</div>'+'</div>'
infowindow = new google.maps.InfoWindow(content: contentString)
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude - 0.01, coordinates.longitude - 0.01)
animation: google.maps.Animation.DROP,
map: map
title: "Test Player"
)
google.maps.event.addListener marker, "click", ->
console.log marker
infowindow.open map, marker
###
Socket.io
###
socket = io.connect('192.168.127.12')
#navigator.geolocation.getCurrentPosition (data) =>
# window.pos = data.coords
# New User
socket.emit("update", user)
socket.on 'newUser', (data)->
console.log('NewUser', data)
console.log data.lat, data.lon
latlng = new google.maps.LatLng(data.lat, data.lon)
@player2 = new google.maps.Marker(
position: latlng,
map: map
)
# Send Msg
$('#msg').keypress (e)->
if e.which == 13
socket.emit 'chat',
userName: 'webUser'
msg: $('#msg').val()
$('#msg').val('')
$('#chat p').last().focus()
socket.on 'chat', (data)->
console.log("chat", data)
$('#chat').append($('<p>', {text: data.msg}))
$('#update').click ()->
console.log(user)
socket.emit( 'update', user)
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude - 0.01, coordinates.longitude - 0.01)
animation: google.maps.Animation.DROP,
map: map
)
# Update
socket.on 'update', (data)->
console.log('update', data)
console.log data.lat, data.lon
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude, coordinates.longitude)
animation: google.maps.Animation.DROP,
map: map
)
i = 0
socket.on 'init', (data)->
users = data
while i < users.length
users[i]
users[i].location[0].lat
users[i].location[0].lon
console.log users[i].location[0].lat, users[i].location[0].lon
latlng = new google.maps.LatLng(users[i].location[0].lat, users[i].location[0].lon)
users[i].userId = new google.maps.Marker(
position: latlng
animation: google.maps.Animation.DROP
)
users[i].userId.setMap(map)
i++
## Push Menu
$menuButton = $('.navbar-toggle')
$menuLeft = $('.menu-left')
$menuRight = $('.menu-right')
$body = $('body')
$el = $(this)
$menuButton.click ->
$el.toggleClass "active"
$body.toggleClass " menu-push-toleft"
$('#overlay').toggleClass "overlay"
$menuRight.toggleClass "menu-open"
$('#overlay').click ->
$menuButton.removeClass "active"
$body.removeClass "menu-push-toleft"
$body.removeClass "menu-push-toright"
$menuRight.removeClass "menu-open"
$menuLeft.removeClass "menu-open"
$('#overlay').removeClass "overlay"
$('.navbar-toggle').removeClass('disabled')
| true | # Mobster
# PI:NAME:<NAME>END_PI (@SeanCanton)
# PI:NAME:<NAME>END_PI(@CyberStrike)
# Emerge Hack 2014
## Google Map Init
map = {}
@coordinates = {}
@user = {}
# Geolocation
navigator.geolocation.getCurrentPosition (data) =>
@coordinates = data.coords
console.log(
"Accuracy: " + @coordinates.accuracy
"Altitude: " + @coordinates.altitude
"Altitude Accuracy: " + @coordinates.altitudeAccuracy
"Heading: " + @coordinates.heading
"Latitude: " + @coordinates.latitude
"Longitude: " + @coordinates.longitude
"Speed: " + @coordinates.speed)
userId = 12
@user = {
userId: userId,
userName: "webUser",
lon: @coordinates.longitude,
lat: @coordinates.latitude
}
console.log("user", @user)
# Init
socket.emit('init', @user)
# Start Maps
@googlemaps = ->
console.log 'hello'
# Geolocation
navigator.geolocation.getCurrentPosition (data) =>
@coordinates = data.coords
console.log(
"Accuracy: " + @coordinates.accuracy
"Altitude: " + @coordinates.altitude
"Altitude Accuracy: " + @coordinates.altitudeAccuracy
"Heading: " + @coordinates.heading
"Latitude: " + @coordinates.latitude
"Longitude: " + @coordinates.longitude
"Speed: " + @coordinates.speed)
#Configure Maps
@myLatlng = new google.maps.LatLng(@coordinates.latitude, @coordinates.longitude)
mapOptions =
center: @myLatlng
zoom: 13
styles: @Midnight_Commander
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
marker = new google.maps.Marker(
position: @myLatlng,
animation: google.maps.Animation.DROP,
map: map)
#Resize Listener
google.maps.event.addDomListener window, "resize", ->
center = map.getCenter()
google.maps.event.trigger map, "resize"
map.setCenter @myLatlng
$(document).ready => @googlemaps()
$('.testbtn').click ()->
contentString =
'<div id="content">'+'<div id="siteNotice">'+'</div>'+
'<h1 id="firstHeading" class="firstHeading">Test Player</h1>'+
'<div id="bodyContent">'+
'<p>Test Content </p>' +
'</div>'+'</div>'
infowindow = new google.maps.InfoWindow(content: contentString)
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude - 0.01, coordinates.longitude - 0.01)
animation: google.maps.Animation.DROP,
map: map
title: "Test Player"
)
google.maps.event.addListener marker, "click", ->
console.log marker
infowindow.open map, marker
###
Socket.io
###
socket = io.connect('PI:IP_ADDRESS:192.168.127.12END_PI')
#navigator.geolocation.getCurrentPosition (data) =>
# window.pos = data.coords
# New User
socket.emit("update", user)
socket.on 'newUser', (data)->
console.log('NewUser', data)
console.log data.lat, data.lon
latlng = new google.maps.LatLng(data.lat, data.lon)
@player2 = new google.maps.Marker(
position: latlng,
map: map
)
# Send Msg
$('#msg').keypress (e)->
if e.which == 13
socket.emit 'chat',
userName: 'webUser'
msg: $('#msg').val()
$('#msg').val('')
$('#chat p').last().focus()
socket.on 'chat', (data)->
console.log("chat", data)
$('#chat').append($('<p>', {text: data.msg}))
$('#update').click ()->
console.log(user)
socket.emit( 'update', user)
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude - 0.01, coordinates.longitude - 0.01)
animation: google.maps.Animation.DROP,
map: map
)
# Update
socket.on 'update', (data)->
console.log('update', data)
console.log data.lat, data.lon
marker = new google.maps.Marker(
position: new google.maps.LatLng(coordinates.latitude, coordinates.longitude)
animation: google.maps.Animation.DROP,
map: map
)
i = 0
socket.on 'init', (data)->
users = data
while i < users.length
users[i]
users[i].location[0].lat
users[i].location[0].lon
console.log users[i].location[0].lat, users[i].location[0].lon
latlng = new google.maps.LatLng(users[i].location[0].lat, users[i].location[0].lon)
users[i].userId = new google.maps.Marker(
position: latlng
animation: google.maps.Animation.DROP
)
users[i].userId.setMap(map)
i++
## Push Menu
$menuButton = $('.navbar-toggle')
$menuLeft = $('.menu-left')
$menuRight = $('.menu-right')
$body = $('body')
$el = $(this)
$menuButton.click ->
$el.toggleClass "active"
$body.toggleClass " menu-push-toleft"
$('#overlay').toggleClass "overlay"
$menuRight.toggleClass "menu-open"
$('#overlay').click ->
$menuButton.removeClass "active"
$body.removeClass "menu-push-toleft"
$body.removeClass "menu-push-toright"
$menuRight.removeClass "menu-open"
$menuLeft.removeClass "menu-open"
$('#overlay').removeClass "overlay"
$('.navbar-toggle').removeClass('disabled')
|
[
{
"context": " id: 1234567890,\n# person: {\n# first_name: 'Grant',\n# last_name : 'Klinsing',\n# meta : {\n# ",
"end": 206,
"score": 0.9998624920845032,
"start": 201,
"tag": "NAME",
"value": "Grant"
},
{
"context": ": {\n# first_name: 'Grant',\n# last_name : 'K... | app/assets/javascripts/utility_box/forms.js.coffee | digitalopera/utility_box | 1 | #= require utility_box/utility_box_namespace
# @method parameterizeObject
# data [Object]
# Generate correctly formatted parameters for xhr2
#
# {
# id: 1234567890,
# person: {
# first_name: 'Grant',
# last_name : 'Klinsing',
# meta : {
# foo: 'bar',
# test: [100, 200]
# }
# }
# }
#
# Will become:
#
# id = 1234567890
# person[first_name] = 'Grant'
# person[last_name] = 'Klinsing'
# person[meta][foo] = 'bar'
# person[meta][test] = [100, 200]
window.utilityBox.parameterizeObject = (data) ->
obj = {}
accLoop = (key, val) ->
if $.isPlainObject val
for k, v of val
k = "#{key}[#{k}]"
accLoop(k, v)
else
obj[key] = val
return
for key, val of data
accLoop(key, val)
obj
# @method serializeForm
# form [element|jQuery Element]
window.utilityBox.serializeForm = (form) ->
obj = {}
# if jQuery, break it down
form = form[0] if form.jquery
$.makeArray(form.querySelectorAll('input, select, textarea')).forEach (input) ->
if input.type == 'file'
obj[input.name] = input.files[0]
else
obj[input.name] = input.value
# remove properites that are undefined
for key, val of obj
if val == undefined
delete obj[key]
obj
$(document).ready ->
$('[data-is="datepicker"]').datepicker() if $.fn.datepicker? | 176480 | #= require utility_box/utility_box_namespace
# @method parameterizeObject
# data [Object]
# Generate correctly formatted parameters for xhr2
#
# {
# id: 1234567890,
# person: {
# first_name: '<NAME>',
# last_name : '<NAME>',
# meta : {
# foo: 'bar',
# test: [100, 200]
# }
# }
# }
#
# Will become:
#
# id = 1234567890
# person[first_name] = '<NAME>'
# person[last_name] = '<NAME>'
# person[meta][foo] = 'bar'
# person[meta][test] = [100, 200]
window.utilityBox.parameterizeObject = (data) ->
obj = {}
accLoop = (key, val) ->
if $.isPlainObject val
for k, v of val
k = "#{key}[#{k}]"
accLoop(k, v)
else
obj[key] = val
return
for key, val of data
accLoop(key, val)
obj
# @method serializeForm
# form [element|jQuery Element]
window.utilityBox.serializeForm = (form) ->
obj = {}
# if jQuery, break it down
form = form[0] if form.jquery
$.makeArray(form.querySelectorAll('input, select, textarea')).forEach (input) ->
if input.type == 'file'
obj[input.name] = input.files[0]
else
obj[input.name] = input.value
# remove properites that are undefined
for key, val of obj
if val == undefined
delete obj[key]
obj
$(document).ready ->
$('[data-is="datepicker"]').datepicker() if $.fn.datepicker? | true | #= require utility_box/utility_box_namespace
# @method parameterizeObject
# data [Object]
# Generate correctly formatted parameters for xhr2
#
# {
# id: 1234567890,
# person: {
# first_name: 'PI:NAME:<NAME>END_PI',
# last_name : 'PI:NAME:<NAME>END_PI',
# meta : {
# foo: 'bar',
# test: [100, 200]
# }
# }
# }
#
# Will become:
#
# id = 1234567890
# person[first_name] = 'PI:NAME:<NAME>END_PI'
# person[last_name] = 'PI:NAME:<NAME>END_PI'
# person[meta][foo] = 'bar'
# person[meta][test] = [100, 200]
window.utilityBox.parameterizeObject = (data) ->
obj = {}
accLoop = (key, val) ->
if $.isPlainObject val
for k, v of val
k = "#{key}[#{k}]"
accLoop(k, v)
else
obj[key] = val
return
for key, val of data
accLoop(key, val)
obj
# @method serializeForm
# form [element|jQuery Element]
window.utilityBox.serializeForm = (form) ->
obj = {}
# if jQuery, break it down
form = form[0] if form.jquery
$.makeArray(form.querySelectorAll('input, select, textarea')).forEach (input) ->
if input.type == 'file'
obj[input.name] = input.files[0]
else
obj[input.name] = input.value
# remove properites that are undefined
for key, val of obj
if val == undefined
delete obj[key]
obj
$(document).ready ->
$('[data-is="datepicker"]').datepicker() if $.fn.datepicker? |
[
{
"context": "fileoverview Tests for no-debugger rule.\n# @author Nicholas C. Zakas\n###\n\n'use strict'\n\n#-----------------------------",
"end": 76,
"score": 0.9998018741607666,
"start": 59,
"tag": "NAME",
"value": "Nicholas C. Zakas"
}
] | src/tests/rules/no-debugger.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-debugger rule.
# @author Nicholas C. Zakas
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-debugger'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-debugger', rule,
valid: [
'''
test = { debugger: 1 }
test.debugger
'''
]
invalid: [
code: 'if foo then debugger'
output: null
errors: [messageId: 'unexpected', type: 'DebuggerStatement']
]
| 139327 | ###*
# @fileoverview Tests for no-debugger rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-debugger'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-debugger', rule,
valid: [
'''
test = { debugger: 1 }
test.debugger
'''
]
invalid: [
code: 'if foo then debugger'
output: null
errors: [messageId: 'unexpected', type: 'DebuggerStatement']
]
| true | ###*
# @fileoverview Tests for no-debugger rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-debugger'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-debugger', rule,
valid: [
'''
test = { debugger: 1 }
test.debugger
'''
]
invalid: [
code: 'if foo then debugger'
output: null
errors: [messageId: 'unexpected', type: 'DebuggerStatement']
]
|
[
{
"context": "r useless escapes in strings and regexes\n# @author Onur Temizkan\n###\n\n'use strict'\n\nastUtils = require '../eslint-",
"end": 92,
"score": 0.999883234500885,
"start": 79,
"tag": "NAME",
"value": "Onur Temizkan"
},
{
"context": " are not supported by JSX yet: https:/... | src/rules/no-useless-escape.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Look for useless escapes in strings and regexes
# @author Onur Temizkan
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
###*
# Returns the union of two sets.
# @param {Set} setA The first set
# @param {Set} setB The second set
# @returns {Set} The union of the two sets
###
union = (setA, setB) ->
new Set do ->
yield from setA
yield from setB
VALID_STRING_ESCAPES = union new Set('\\nrvtbfux'), astUtils.LINEBREAKS
REGEX_GENERAL_ESCAPES = new Set '\\bcdDfnpPrsStvwWxu0123456789]/'
REGEX_NON_CHARCLASS_ESCAPES = union(
REGEX_GENERAL_ESCAPES
new Set '^/.$*+?[{}|()Bk'
)
###*
# Parses a regular expression into a list of characters with character class info.
# @param {string} regExpText The raw text used to create the regular expression
# @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class.
# @example
#
# parseRegExp('a\\b[cd-]')
#
# returns:
# [
# {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false},
# {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false},
# {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false},
# {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false},
# {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}
# ]
###
parseRegExp = (regExpText) ->
charList = []
regExpText
.split ''
.reduce(
(state, char, index) ->
unless state.escapeNextChar
return Object.assign state, escapeNextChar: yes if char is '\\'
if char is '[' and not state.inCharClass
return Object.assign state, inCharClass: yes, startingCharClass: yes
if char is ']' and state.inCharClass
if charList.length and charList[charList.length - 1].inCharClass
charList[charList.length - 1].endsCharClass = yes
return Object.assign state, inCharClass: no, startingCharClass: no
charList.push {
text: char
index
escaped: state.escapeNextChar
inCharClass: state.inCharClass
startsCharClass: state.startingCharClass
endsCharClass: no
nextChar: regExpText[index + 1]
}
Object.assign state, escapeNextChar: no, startingCharClass: no
,
escapeNextChar: no, inCharClass: no, startingCharClass: no
)
charList
module.exports =
meta:
docs:
description: 'disallow unnecessary escape characters'
category: 'Best Practices'
recommended: yes
url: 'https://eslint.org/docs/rules/no-useless-escape'
schema: []
create: (context) ->
sourceCode = context.getSourceCode()
###*
# Reports a node
# @param {ASTNode} node The node to report
# @param {number} startOffset The backslash's offset from the start of the node
# @param {string} character The uselessly escaped character (not including the backslash)
# @returns {void}
###
report = (node, startOffset, character) ->
context.report {
node
loc: sourceCode.getLocFromIndex(
sourceCode.getIndexFromLoc(node.loc.start) + startOffset
)
message: 'Unnecessary escape character: \\{{character}}.'
data: {character}
}
###*
# Checks if the escape character in given string slice is unnecessary.
#
# @private
# @param {ASTNode} node - node to validate.
# @param {string} match - string slice to validate.
# @returns {void}
###
validateString = (node, match, value) ->
isTemplateElement = node.type is 'TemplateElement'
escapedChar = match[0][1]
isUnnecessaryEscape = not VALID_STRING_ESCAPES.has escapedChar
if isTemplateElement
{quote} = node.parent
isQuoteEscape = quote? and escapedChar is quote[0]
if isQuoteEscape and quote.length is 3
isQuoteEscape = no
followingQuotes = /// ^ (?: \\?#{quote[0]} )+ ///.exec(
value[(match.index + match[0].length)..]
)
precedingQuotes = /// (?: \\?#{quote[0]} )+ $ ///.exec(
value[...match.index]
)
isClosingQuote = match.index + match[0].length is value.length
# eslint-disable-next-line coffee/no-inner-declarations
getNumFoundQuotes = (quotesMatch) ->
return 0 unless quotesMatch
quotesMatch[0].match(///#{quote[0]}///g).length
isQuoteEscape = yes if (
isClosingQuote or
getNumFoundQuotes(followingQuotes) +
getNumFoundQuotes(precedingQuotes) >=
2
)
else
isQuoteEscape = escapedChar is node.raw[0]
if isTemplateElement or node.extra?.raw?[0] is '"'
if escapedChar is '#'
# Warn if `\#` is not followed by `{`
isUnnecessaryEscape = match.input[match.index + 2] isnt '{'
else if escapedChar is '{'
###
# Warn if `\{` is not preceded by `#`. If preceded by `#`, escaping
# is necessary and the rule should not warn. If preceded by `/#`, the rule
# will warn for the `/#` instead, as it is the first unnecessarily escaped character.
###
isUnnecessaryEscape = match.input[match.index - 1] isnt '#'
if isUnnecessaryEscape and not isQuoteEscape
report node, match.index + 1, match[0].slice 1
###*
# Checks if a node has an escape.
#
# @param {ASTNode} node - node to check.
# @returns {void}
###
check = (node) ->
isTemplateElement = node.type is 'TemplateElement'
# Don't report tagged template literals, because the backslash character is accessible to the tag function.
return if (
isTemplateElement and
node.parent?.parent?.type is 'TaggedTemplateExpression' and
node.parent is node.parent.parent.quasi
)
isInterpolatedRegex =
isTemplateElement and
node.parent?.parent?.type is 'InterpolatedRegExpLiteral'
if (
typeof node.value is 'string' or
(isTemplateElement and not isInterpolatedRegex)
)
###
# JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
# In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
###
return if node.parent.type in [
'JSXAttribute'
'JSXElement'
'JSXFragment'
]
value =
if isTemplateElement
node.value.raw
else
node.raw.slice 1, -1
pattern = /\\[^\d]/g
while match = pattern.exec value
validateString node, match, value
else if node.regex or isInterpolatedRegex
parseRegExp node.regex?.pattern ? node.value.raw
###
# The '-' character is a special case, because it's only valid to escape it if it's in a character
# class, and is not at either edge of the character class. To account for this, don't consider '-'
# characters to be valid in general, and filter out '-' characters that appear in the middle of a
# character class.
###
.filter (charInfo) ->
not (
charInfo.text is '-' and
charInfo.inCharClass and
not charInfo.startsCharClass and
not charInfo.endsCharClass
)
###
# The '^' character is also a special case; it must always be escaped outside of character classes, but
# it only needs to be escaped in character classes if it's at the beginning of the character class. To
# account for this, consider it to be a valid escape character outside of character classes, and filter
# out '^' characters that appear at the start of a character class.
###
.filter (charInfo) ->
not (charInfo.text is '^' and charInfo.startsCharClass)
# Filter out characters that aren't escaped.
.filter (charInfo) -> charInfo.escaped
# Filter out escaped heregex interpolations
.filter (charInfo) ->
not (
charInfo.text is '#' and
charInfo.nextChar is '{' and
(isInterpolatedRegex or node.delimiter is '///')
)
# Filter out characters that are valid to escape, based on their position in the regular expression.
.filter (charInfo) ->
not (
if charInfo.inCharClass
REGEX_GENERAL_ESCAPES
else
REGEX_NON_CHARCLASS_ESCAPES
).has charInfo.text
# Report all the remaining characters.
.forEach (charInfo) -> report node, charInfo.index, charInfo.text
Literal: check
TemplateElement: check
| 171364 | ###*
# @fileoverview Look for useless escapes in strings and regexes
# @author <NAME>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
###*
# Returns the union of two sets.
# @param {Set} setA The first set
# @param {Set} setB The second set
# @returns {Set} The union of the two sets
###
union = (setA, setB) ->
new Set do ->
yield from setA
yield from setB
VALID_STRING_ESCAPES = union new Set('\\nrvtbfux'), astUtils.LINEBREAKS
REGEX_GENERAL_ESCAPES = new Set '\\bcdDfnpPrsStvwWxu0123456789]/'
REGEX_NON_CHARCLASS_ESCAPES = union(
REGEX_GENERAL_ESCAPES
new Set '^/.$*+?[{}|()Bk'
)
###*
# Parses a regular expression into a list of characters with character class info.
# @param {string} regExpText The raw text used to create the regular expression
# @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class.
# @example
#
# parseRegExp('a\\b[cd-]')
#
# returns:
# [
# {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false},
# {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false},
# {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false},
# {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false},
# {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}
# ]
###
parseRegExp = (regExpText) ->
charList = []
regExpText
.split ''
.reduce(
(state, char, index) ->
unless state.escapeNextChar
return Object.assign state, escapeNextChar: yes if char is '\\'
if char is '[' and not state.inCharClass
return Object.assign state, inCharClass: yes, startingCharClass: yes
if char is ']' and state.inCharClass
if charList.length and charList[charList.length - 1].inCharClass
charList[charList.length - 1].endsCharClass = yes
return Object.assign state, inCharClass: no, startingCharClass: no
charList.push {
text: char
index
escaped: state.escapeNextChar
inCharClass: state.inCharClass
startsCharClass: state.startingCharClass
endsCharClass: no
nextChar: regExpText[index + 1]
}
Object.assign state, escapeNextChar: no, startingCharClass: no
,
escapeNextChar: no, inCharClass: no, startingCharClass: no
)
charList
module.exports =
meta:
docs:
description: 'disallow unnecessary escape characters'
category: 'Best Practices'
recommended: yes
url: 'https://eslint.org/docs/rules/no-useless-escape'
schema: []
create: (context) ->
sourceCode = context.getSourceCode()
###*
# Reports a node
# @param {ASTNode} node The node to report
# @param {number} startOffset The backslash's offset from the start of the node
# @param {string} character The uselessly escaped character (not including the backslash)
# @returns {void}
###
report = (node, startOffset, character) ->
context.report {
node
loc: sourceCode.getLocFromIndex(
sourceCode.getIndexFromLoc(node.loc.start) + startOffset
)
message: 'Unnecessary escape character: \\{{character}}.'
data: {character}
}
###*
# Checks if the escape character in given string slice is unnecessary.
#
# @private
# @param {ASTNode} node - node to validate.
# @param {string} match - string slice to validate.
# @returns {void}
###
validateString = (node, match, value) ->
isTemplateElement = node.type is 'TemplateElement'
escapedChar = match[0][1]
isUnnecessaryEscape = not VALID_STRING_ESCAPES.has escapedChar
if isTemplateElement
{quote} = node.parent
isQuoteEscape = quote? and escapedChar is quote[0]
if isQuoteEscape and quote.length is 3
isQuoteEscape = no
followingQuotes = /// ^ (?: \\?#{quote[0]} )+ ///.exec(
value[(match.index + match[0].length)..]
)
precedingQuotes = /// (?: \\?#{quote[0]} )+ $ ///.exec(
value[...match.index]
)
isClosingQuote = match.index + match[0].length is value.length
# eslint-disable-next-line coffee/no-inner-declarations
getNumFoundQuotes = (quotesMatch) ->
return 0 unless quotesMatch
quotesMatch[0].match(///#{quote[0]}///g).length
isQuoteEscape = yes if (
isClosingQuote or
getNumFoundQuotes(followingQuotes) +
getNumFoundQuotes(precedingQuotes) >=
2
)
else
isQuoteEscape = escapedChar is node.raw[0]
if isTemplateElement or node.extra?.raw?[0] is '"'
if escapedChar is '#'
# Warn if `\#` is not followed by `{`
isUnnecessaryEscape = match.input[match.index + 2] isnt '{'
else if escapedChar is '{'
###
# Warn if `\{` is not preceded by `#`. If preceded by `#`, escaping
# is necessary and the rule should not warn. If preceded by `/#`, the rule
# will warn for the `/#` instead, as it is the first unnecessarily escaped character.
###
isUnnecessaryEscape = match.input[match.index - 1] isnt '#'
if isUnnecessaryEscape and not isQuoteEscape
report node, match.index + 1, match[0].slice 1
###*
# Checks if a node has an escape.
#
# @param {ASTNode} node - node to check.
# @returns {void}
###
check = (node) ->
isTemplateElement = node.type is 'TemplateElement'
# Don't report tagged template literals, because the backslash character is accessible to the tag function.
return if (
isTemplateElement and
node.parent?.parent?.type is 'TaggedTemplateExpression' and
node.parent is node.parent.parent.quasi
)
isInterpolatedRegex =
isTemplateElement and
node.parent?.parent?.type is 'InterpolatedRegExpLiteral'
if (
typeof node.value is 'string' or
(isTemplateElement and not isInterpolatedRegex)
)
###
# JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
# In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
###
return if node.parent.type in [
'JSXAttribute'
'JSXElement'
'JSXFragment'
]
value =
if isTemplateElement
node.value.raw
else
node.raw.slice 1, -1
pattern = /\\[^\d]/g
while match = pattern.exec value
validateString node, match, value
else if node.regex or isInterpolatedRegex
parseRegExp node.regex?.pattern ? node.value.raw
###
# The '-' character is a special case, because it's only valid to escape it if it's in a character
# class, and is not at either edge of the character class. To account for this, don't consider '-'
# characters to be valid in general, and filter out '-' characters that appear in the middle of a
# character class.
###
.filter (charInfo) ->
not (
charInfo.text is '-' and
charInfo.inCharClass and
not charInfo.startsCharClass and
not charInfo.endsCharClass
)
###
# The '^' character is also a special case; it must always be escaped outside of character classes, but
# it only needs to be escaped in character classes if it's at the beginning of the character class. To
# account for this, consider it to be a valid escape character outside of character classes, and filter
# out '^' characters that appear at the start of a character class.
###
.filter (charInfo) ->
not (charInfo.text is '^' and charInfo.startsCharClass)
# Filter out characters that aren't escaped.
.filter (charInfo) -> charInfo.escaped
# Filter out escaped heregex interpolations
.filter (charInfo) ->
not (
charInfo.text is '#' and
charInfo.nextChar is '{' and
(isInterpolatedRegex or node.delimiter is '///')
)
# Filter out characters that are valid to escape, based on their position in the regular expression.
.filter (charInfo) ->
not (
if charInfo.inCharClass
REGEX_GENERAL_ESCAPES
else
REGEX_NON_CHARCLASS_ESCAPES
).has charInfo.text
# Report all the remaining characters.
.forEach (charInfo) -> report node, charInfo.index, charInfo.text
Literal: check
TemplateElement: check
| true | ###*
# @fileoverview Look for useless escapes in strings and regexes
# @author PI:NAME:<NAME>END_PI
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
###*
# Returns the union of two sets.
# @param {Set} setA The first set
# @param {Set} setB The second set
# @returns {Set} The union of the two sets
###
union = (setA, setB) ->
new Set do ->
yield from setA
yield from setB
VALID_STRING_ESCAPES = union new Set('\\nrvtbfux'), astUtils.LINEBREAKS
REGEX_GENERAL_ESCAPES = new Set '\\bcdDfnpPrsStvwWxu0123456789]/'
REGEX_NON_CHARCLASS_ESCAPES = union(
REGEX_GENERAL_ESCAPES
new Set '^/.$*+?[{}|()Bk'
)
###*
# Parses a regular expression into a list of characters with character class info.
# @param {string} regExpText The raw text used to create the regular expression
# @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class.
# @example
#
# parseRegExp('a\\b[cd-]')
#
# returns:
# [
# {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false},
# {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false},
# {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false},
# {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false},
# {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}
# ]
###
parseRegExp = (regExpText) ->
charList = []
regExpText
.split ''
.reduce(
(state, char, index) ->
unless state.escapeNextChar
return Object.assign state, escapeNextChar: yes if char is '\\'
if char is '[' and not state.inCharClass
return Object.assign state, inCharClass: yes, startingCharClass: yes
if char is ']' and state.inCharClass
if charList.length and charList[charList.length - 1].inCharClass
charList[charList.length - 1].endsCharClass = yes
return Object.assign state, inCharClass: no, startingCharClass: no
charList.push {
text: char
index
escaped: state.escapeNextChar
inCharClass: state.inCharClass
startsCharClass: state.startingCharClass
endsCharClass: no
nextChar: regExpText[index + 1]
}
Object.assign state, escapeNextChar: no, startingCharClass: no
,
escapeNextChar: no, inCharClass: no, startingCharClass: no
)
charList
module.exports =
meta:
docs:
description: 'disallow unnecessary escape characters'
category: 'Best Practices'
recommended: yes
url: 'https://eslint.org/docs/rules/no-useless-escape'
schema: []
create: (context) ->
sourceCode = context.getSourceCode()
###*
# Reports a node
# @param {ASTNode} node The node to report
# @param {number} startOffset The backslash's offset from the start of the node
# @param {string} character The uselessly escaped character (not including the backslash)
# @returns {void}
###
report = (node, startOffset, character) ->
context.report {
node
loc: sourceCode.getLocFromIndex(
sourceCode.getIndexFromLoc(node.loc.start) + startOffset
)
message: 'Unnecessary escape character: \\{{character}}.'
data: {character}
}
###*
# Checks if the escape character in given string slice is unnecessary.
#
# @private
# @param {ASTNode} node - node to validate.
# @param {string} match - string slice to validate.
# @returns {void}
###
validateString = (node, match, value) ->
isTemplateElement = node.type is 'TemplateElement'
escapedChar = match[0][1]
isUnnecessaryEscape = not VALID_STRING_ESCAPES.has escapedChar
if isTemplateElement
{quote} = node.parent
isQuoteEscape = quote? and escapedChar is quote[0]
if isQuoteEscape and quote.length is 3
isQuoteEscape = no
followingQuotes = /// ^ (?: \\?#{quote[0]} )+ ///.exec(
value[(match.index + match[0].length)..]
)
precedingQuotes = /// (?: \\?#{quote[0]} )+ $ ///.exec(
value[...match.index]
)
isClosingQuote = match.index + match[0].length is value.length
# eslint-disable-next-line coffee/no-inner-declarations
getNumFoundQuotes = (quotesMatch) ->
return 0 unless quotesMatch
quotesMatch[0].match(///#{quote[0]}///g).length
isQuoteEscape = yes if (
isClosingQuote or
getNumFoundQuotes(followingQuotes) +
getNumFoundQuotes(precedingQuotes) >=
2
)
else
isQuoteEscape = escapedChar is node.raw[0]
if isTemplateElement or node.extra?.raw?[0] is '"'
if escapedChar is '#'
# Warn if `\#` is not followed by `{`
isUnnecessaryEscape = match.input[match.index + 2] isnt '{'
else if escapedChar is '{'
###
# Warn if `\{` is not preceded by `#`. If preceded by `#`, escaping
# is necessary and the rule should not warn. If preceded by `/#`, the rule
# will warn for the `/#` instead, as it is the first unnecessarily escaped character.
###
isUnnecessaryEscape = match.input[match.index - 1] isnt '#'
if isUnnecessaryEscape and not isQuoteEscape
report node, match.index + 1, match[0].slice 1
###*
# Checks if a node has an escape.
#
# @param {ASTNode} node - node to check.
# @returns {void}
###
check = (node) ->
isTemplateElement = node.type is 'TemplateElement'
# Don't report tagged template literals, because the backslash character is accessible to the tag function.
return if (
isTemplateElement and
node.parent?.parent?.type is 'TaggedTemplateExpression' and
node.parent is node.parent.parent.quasi
)
isInterpolatedRegex =
isTemplateElement and
node.parent?.parent?.type is 'InterpolatedRegExpLiteral'
if (
typeof node.value is 'string' or
(isTemplateElement and not isInterpolatedRegex)
)
###
# JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
# In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
###
return if node.parent.type in [
'JSXAttribute'
'JSXElement'
'JSXFragment'
]
value =
if isTemplateElement
node.value.raw
else
node.raw.slice 1, -1
pattern = /\\[^\d]/g
while match = pattern.exec value
validateString node, match, value
else if node.regex or isInterpolatedRegex
parseRegExp node.regex?.pattern ? node.value.raw
###
# The '-' character is a special case, because it's only valid to escape it if it's in a character
# class, and is not at either edge of the character class. To account for this, don't consider '-'
# characters to be valid in general, and filter out '-' characters that appear in the middle of a
# character class.
###
.filter (charInfo) ->
not (
charInfo.text is '-' and
charInfo.inCharClass and
not charInfo.startsCharClass and
not charInfo.endsCharClass
)
###
# The '^' character is also a special case; it must always be escaped outside of character classes, but
# it only needs to be escaped in character classes if it's at the beginning of the character class. To
# account for this, consider it to be a valid escape character outside of character classes, and filter
# out '^' characters that appear at the start of a character class.
###
.filter (charInfo) ->
not (charInfo.text is '^' and charInfo.startsCharClass)
# Filter out characters that aren't escaped.
.filter (charInfo) -> charInfo.escaped
# Filter out escaped heregex interpolations
.filter (charInfo) ->
not (
charInfo.text is '#' and
charInfo.nextChar is '{' and
(isInterpolatedRegex or node.delimiter is '///')
)
# Filter out characters that are valid to escape, based on their position in the regular expression.
.filter (charInfo) ->
not (
if charInfo.inCharClass
REGEX_GENERAL_ESCAPES
else
REGEX_NON_CHARCLASS_ESCAPES
).has charInfo.text
# Report all the remaining characters.
.forEach (charInfo) -> report node, charInfo.index, charInfo.text
Literal: check
TemplateElement: check
|
[
{
"context": "# Copyright (c) 2013 Rod Vagg, MIT License\n# Copyright (c) 2014 Riceball LEE, M",
"end": 29,
"score": 0.9998559951782227,
"start": 21,
"tag": "NAME",
"value": "Rod Vagg"
},
{
"context": "c) 2013 Rod Vagg, MIT License\n# Copyright (c) 2014 Riceball LEE, MIT License\nxte... | src/abstract-nosql.coffee | snowyu/abstract-nosql | 0 | # Copyright (c) 2013 Rod Vagg, MIT License
# Copyright (c) 2014 Riceball LEE, MIT License
xtend = require("xtend")
AbstractObject = require("abstract-object")
Codec = require("buffer-codec")
utf8ByteLength = Codec.getByteLen
Errors = require("./abstract-error")
try AbstractIterator = require("abstract-iterator")
AbstractChainedBatch = require("./abstract-chained-batch")
setImmediate = global.setImmediate or process.nextTick
AbstractError = Errors.AbstractError
NotImplementedError = Errors.NotImplementedError
InvalidArgumentError = Errors.InvalidArgumentError
OpenError = Errors.OpenError
CloseError = Errors.CloseError
inherits = require("inherits-ex/lib/inherits")
isString = require("util-ex/lib/is/type/string")
isFunction = require("util-ex/lib/is/type/function")
isArray = require("util-ex/lib/is/type/array")
module.exports = class AbstractNoSQL
inherits AbstractNoSQL, AbstractObject
constructor: ->
super
initialize:(location) ->
#not all database have the location argument.
if location and typeof location isnt "string"
throw new InvalidArgumentError("constructor requires a location string argument")
@location = location
finalize: ->
if @_opened
if @_closeSync then @closeSync()
else @closeAsync()
@_options = null
@::__defineGetter__ "opened", ->
!!@_opened
setOpened: (aValue, options)->
if aValue
@_opened = true
@_options = options if options
else
@_opened = false
#the optimal low-level sync functions:
isExistsSync: (key, options) ->
options = {} unless options?
key = String(key) unless @_isBuffer(key)
if @_isExistsSync
result = @_isExistsSync(key, options)
return result
else if @_getSync
try
@_getSync key, options
return true
catch err
if AbstractError.isNotFound(err)
return false
else
throw err
throw new NotImplementedError()
isExistSync: @::isExistsSync
getSync: (key, options) ->
if @_getSync
options = {} unless options?
throw err if err = @_checkKey(key, "key")
key = String(key) unless @_isBuffer(key) #TODO should move to low-level db.
result = @_getSync(key, options)
return result
throw new NotImplementedError()
getBufferSync: (key, destBuffer, options) ->
if @_getBufferSync
options = {} unless options?
options.offset = 0 unless options.offset?
result = @_getBufferSync(key, destBuffer, options)
return result
throw new NotImplementedError()
mGetSync: (keys, options) ->
if @_mGetSync
options = {} unless options?
options.raiseError = options.raiseError isnt false
needKeyName = options.keys
arr = @_mGetSync(keys, options)
i = 0
result = []
while i < arr.length
if needKeyName isnt false
result.push
key: arr[i]
value: arr[++i]
else
result.push arr[i]
i++
return result
throw new NotImplementedError()
putSync: (key, value, options) ->
if @_putSync
options = {} unless options?
result = @_putSync(key, value, options)
return result
throw new NotImplementedError()
delSync: (key, options) ->
if @_delSync
options = {} unless options?
result = @_delSync(key, options)
return result
throw new NotImplementedError()
batchSync: (operations, options) ->
if @_batchSync
options = {} unless options?
unless isArray(operations)
throw new InvalidArgumentError("batch(operations) requires an array argument")
for e in operations
continue unless typeof e is "object"
throw err if err = @_checkKey(e.type, "type")
throw err if err = @_checkKey(e.key, "key")
result = @_batchSync(operations, options)
return result
throw new NotImplementedError()
approximateSizeSync: (start, end) ->
if @_approximateSizeSync
if not start? or not end?
throw new InvalidArgumentError "
approximateSize() requires valid `start`, `end` arguments"
start = String(start) unless @_isBuffer(start)
end = String(end) unless @_isBuffer(end)
result = @_approximateSizeSync(start, end)
return result
throw new NotImplementedError()
openSync: (options) ->
if @_openSync
options = @_options || {} unless options?
options.createIfMissing = options.createIfMissing isnt false
options.errorIfExists = !!options.errorIfExists
result = @_openSync(options)
@setOpened true, options if result
result = @ if result
return result
throw new NotImplementedError()
#if successful should return true.
closeSync: ->
if @_closeSync
result = @_closeSync()
@setOpened false if result
return result
throw new NotImplementedError()
#the async methods simulated by sync methods:
#the derived class can override these methods to implement
#the real async methods for better performance.
_open: (options, callback) ->
that = this
if @_openSync
setImmediate ->
result = undefined
try
result = that._openSync(options)
catch err
callback err
return
if result
callback null, result
else
callback new OpenError("can not open database.")
else
setImmediate callback
_close: (callback) ->
that = this
if @_closeSync
setImmediate ->
result = undefined
try
result = that._closeSync()
catch err
callback err
return
if result
callback null, result
else
callback new CloseError("can not close database.")
else
setImmediate callback
_isExists: (key, options, callback) ->
that = this
if @_isExistsSync
setImmediate ->
result = undefined
try
result = that._isExistsSync(key, options)
catch err
callback err
return
callback null, result
else
@_get key, options, (err, value) ->
if err
if AbstractError.isNotFound(err)
callback null, false
else
callback err
else
callback null, true
_getBuffer: (key, destBuffer, options, callback) ->
that = this
if @_getSync or @_getBufferSync isnt AbstractNoSQL::_getBufferSync
setImmediate ->
result = undefined
try
result = that._getBufferSync(key, destBuffer, options)
catch err
callback err
return
callback null, result
else if @_get
@_get key, options, (err, value)->
return callback(err) if err
result = utf8ByteLength(value)
if destBuffer
result = Math.min(result, destBuffer.length)
result = destBuffer.write(value, options.offset, result) if result
callback null, result
else
setImmediate callback
_getBufferSync: (key, destBuffer, options) ->
if @_getSync
value = @_getSync(key, options)
result = utf8ByteLength(value)
if destBuffer
result = Math.min(result, destBuffer.length)
result = destBuffer.write(value, options.offset, result) if result
return result
else
throw new NotImplementedError('_mGetSync: _getSync is not implemented.')
_mGetSync: (keys, options) ->
if @_getSync
result = []
needKeyName = options.keys
raiseError = options.raiseError
options.asBuffer = options.asBuffer is true
for key in keys
try
value = @_getSync(key, options)
catch err
throw err if raiseError
value = undefined
if needKeyName isnt false
result.push key, value
else
result.push value
return result
else
throw new NotImplementedError('_mGetSync: _getSync is not implemented.')
_mGet: (keys, options, callback) ->
that = this
if @_getSync or @_mGetSync isnt AbstractNoSQL::_mGetSync
setImmediate ->
result = undefined
try
result = that._mGetSync keys, options
catch err
callback err
return
callback null, result
else if keys.length > 0 and @_get
result = []
i = 0
needKeyName = options.keys
raiseError = options.raiseError
readNext = (err, value)->
return callback(err) if err and raiseError
if needKeyName isnt false
result.push keys[i], value
else
result.push value
i++
return callback(null, result) if i >= keys.length
that._get keys[i], options, readNext
@_get keys[i], options, readNext
else
setImmediate callback
_get: (key, options, callback) ->
that = this
if @_getSync
setImmediate ->
result = undefined
try
result = that._getSync(key, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_put: (key, value, options, callback) ->
that = this
if @_putSync
setImmediate ->
result = undefined
try
result = that._putSync(key, value, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_del: (key, options, callback) ->
that = this
if @_delSync
setImmediate ->
result = undefined
try
result = that._delSync(key, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_batch: (array, options, callback) ->
that = this
if @_batchSync
setImmediate ->
result = undefined
try
result = that._batchSync(array, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
#TODO: remove from here, not a necessary primitive
_approximateSize: (start, end, callback) ->
that = this
if @_approximateSizeSync
setImmediate ->
result = undefined
try
result = that._approximateSizeSync(start, end)
catch err
callback err
return
callback null, result
else
setImmediate callback
#slower impl:
#
#_exec: (fn, args, callback) ->
# that = this
# if fn then setImmediate ->
# result
# try
# result = fn.apply(that, args)
# catch (err)
# callback(err)
# return
#
# callback(null, result)
# else
# setImmediate(callback)
#
#_open: (options, callback) ->
# this._exec(this._openSync, [options], callback)
#
#
openAsync: (options, callback) ->
options = {} unless options?
options.createIfMissing = options.createIfMissing isnt false
options.errorIfExists = !!options.errorIfExists
that = this
@_open options, (err, result) ->
that.setOpened true, options if not err?
callback err, result
open: (options, callback) ->
if isFunction options
callback = options
options = undefined
if callback
@openAsync options, callback
else
@openSync options
closeAsync: (callback) ->
that = this
callback = undefined unless isFunction callback
@_close (err, result) ->
return callback err if err
that.setOpened false
callback null, result if callback
close: (callback) ->
if callback
@closeAsync callback
else
@closeSync()
isExistsAsync: (key, options, callback) ->
options = {} unless options?
key = String(key) unless @_isBuffer(key)
@_isExists key, options, callback
isExists: (key, options, callback) ->
if isFunction options
callback = options
options = {}
else
if callback
@isExistsAsync key, options, callback
else
@isExistsSync key, options
isExist: @::isExists
getBufferAsync: (key, destBuffer, options, callback) ->
options = {} unless options?
options.offset = 0 unless options.offset?
@_getBuffer key, destBuffer, options, callback
getBuffer: (key, destBuffer, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@getBufferAsync key, destBuffer, options, callback
else
@getBufferSync key, destBuffer, options
mGetAsync: (keys, options, callback) ->
options = {} unless options?
options.asBuffer = options.asBuffer is true
options.raiseError = options.raiseError isnt false
needKeyName = options.keys isnt false
@_mGet keys, options, (err, arr)->
return callback(err) if err
if needKeyName
i = 0
result = []
while i < arr.length
result.push
key: arr[i]
value: arr[++i]
i++
else
result = arr
callback null, result
mGet: (keys, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
else
if callback
@mGetAsync keys, options, callback
else
@mGetSync keys, options
getAsync: (key, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key")
key = String(key) unless @_isBuffer(key)
options.asBuffer = options.asBuffer is true
@_get key, options, callback
get: (key, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@getAsync key, options, callback
else
@getSync key, options
putAsync: (key, value, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key", @_isBuffer)
key = String(key) unless @_isBuffer(key)
# coerce value to string in node, don't touch it in browser
# (indexeddb can store any JS type)
value = String(value) if value? and not @_isBuffer(value) and not process.browser
@_put key, value, options, callback
put: (key, value, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@putAsync key, value, options, callback
else
@putSync key, value, options
delAsync: (key, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key", @_isBuffer)
key = String(key) unless @_isBuffer(key)
@_del key, options, callback
del: (key, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@delAsync key, options, callback
else
@delSync key, options
batchAsync: (array, options, callback) ->
options = {} unless options?
unless isArray(array)
vError = new InvalidArgumentError("batch(array) requires an array argument")
return callback(vError)
for e in array
continue unless typeof e is "object"
return callback(err) if err = @_checkKey(e.type, "type")
return callback(err) if err = @_checkKey(e.key, "key")
@_batch array, options, callback
batch: (array, options, callback) ->
return @_chainedBatch() unless arguments.length
if isFunction options
callback = options
options = {}
callback = array if isFunction array
if callback
@batchAsync array, options, callback
else
@batchSync array, options
#TODO: remove from here, not a necessary primitive
approximateSizeAsync: (start, end, callback) ->
start = String(start) unless @_isBuffer(start)
end = String(end) unless @_isBuffer(end)
@_approximateSize start, end, callback
approximateSize: (start, end, callback) ->
if not start? or not end? or isFunction(start) or isFunction(end)
throw new InvalidArgumentError "
approximateSize() requires valid `start`, `end` and `callback`(for async) arguments"
if callback
@approximateSizeAsync start, end, callback
else
@approximateSizeSync start, end
#should override this to test sync or if you do not wanna
#implement the _iterator function.
IteratorClass: AbstractIterator
iterator: (options) ->
options = {} unless typeof options is "object"
if @IteratorClass
return new @IteratorClass(this, options)
else if isFunction @_iterator
console.error "_iterator is deprecated. please use the IteratorClass instead."
return @_iterator(options)
throw new NotImplementedError()
_chainedBatch: ->
new AbstractChainedBatch(this)
_isBuffer: (obj) ->
Buffer.isBuffer obj
_checkKey: (obj, type) ->
if not obj?
return new InvalidArgumentError(type + " cannot be `null` or `undefined`")
if @_isBuffer(obj)
if obj.length is 0
return new InvalidArgumentError(type + " cannot be an empty Buffer")
else if String(obj) is ""
return new InvalidArgumentError(type + " cannot be an empty String")
isOpen: ->
!!@_opened
module.exports.AbstractNoSQL = AbstractNoSQL
module.exports.__defineGetter__ "AbstractLevelDOWN", ->
console.error "AbstractLevelDOWN is deprecated. use AbstractNoSQL instead."
AbstractNoSQL
module.exports.__defineGetter__ "AbstractIterator", ->
console.error "AbstractIterator is deprecated. it's moved to abstract-iterator."
console.error "first `npm install abstract-iterator`" unless AbstractIterator
AbstractIterator
#module.exports.AbstractIterator = AbstractIterator
module.exports.AbstractChainedBatch = AbstractChainedBatch
| 111652 | # Copyright (c) 2013 <NAME>, MIT License
# Copyright (c) 2014 <NAME>, MIT License
xtend = require("xtend")
AbstractObject = require("abstract-object")
Codec = require("buffer-codec")
utf8ByteLength = Codec.getByteLen
Errors = require("./abstract-error")
try AbstractIterator = require("abstract-iterator")
AbstractChainedBatch = require("./abstract-chained-batch")
setImmediate = global.setImmediate or process.nextTick
AbstractError = Errors.AbstractError
NotImplementedError = Errors.NotImplementedError
InvalidArgumentError = Errors.InvalidArgumentError
OpenError = Errors.OpenError
CloseError = Errors.CloseError
inherits = require("inherits-ex/lib/inherits")
isString = require("util-ex/lib/is/type/string")
isFunction = require("util-ex/lib/is/type/function")
isArray = require("util-ex/lib/is/type/array")
module.exports = class AbstractNoSQL
inherits AbstractNoSQL, AbstractObject
constructor: ->
super
initialize:(location) ->
#not all database have the location argument.
if location and typeof location isnt "string"
throw new InvalidArgumentError("constructor requires a location string argument")
@location = location
finalize: ->
if @_opened
if @_closeSync then @closeSync()
else @closeAsync()
@_options = null
@::__defineGetter__ "opened", ->
!!@_opened
setOpened: (aValue, options)->
if aValue
@_opened = true
@_options = options if options
else
@_opened = false
#the optimal low-level sync functions:
isExistsSync: (key, options) ->
options = {} unless options?
key = String(key) unless @_isBuffer(key)
if @_isExistsSync
result = @_isExistsSync(key, options)
return result
else if @_getSync
try
@_getSync key, options
return true
catch err
if AbstractError.isNotFound(err)
return false
else
throw err
throw new NotImplementedError()
isExistSync: @::isExistsSync
getSync: (key, options) ->
if @_getSync
options = {} unless options?
throw err if err = @_checkKey(key, "key")
key = String(key) unless @_isBuffer(key) #TODO should move to low-level db.
result = @_getSync(key, options)
return result
throw new NotImplementedError()
getBufferSync: (key, destBuffer, options) ->
if @_getBufferSync
options = {} unless options?
options.offset = 0 unless options.offset?
result = @_getBufferSync(key, destBuffer, options)
return result
throw new NotImplementedError()
mGetSync: (keys, options) ->
if @_mGetSync
options = {} unless options?
options.raiseError = options.raiseError isnt false
needKeyName = options.keys
arr = @_mGetSync(keys, options)
i = 0
result = []
while i < arr.length
if needKeyName isnt false
result.push
key: arr[i]
value: arr[++i]
else
result.push arr[i]
i++
return result
throw new NotImplementedError()
putSync: (key, value, options) ->
if @_putSync
options = {} unless options?
result = @_putSync(key, value, options)
return result
throw new NotImplementedError()
delSync: (key, options) ->
if @_delSync
options = {} unless options?
result = @_delSync(key, options)
return result
throw new NotImplementedError()
batchSync: (operations, options) ->
if @_batchSync
options = {} unless options?
unless isArray(operations)
throw new InvalidArgumentError("batch(operations) requires an array argument")
for e in operations
continue unless typeof e is "object"
throw err if err = @_checkKey(e.type, "type")
throw err if err = @_checkKey(e.key, "key")
result = @_batchSync(operations, options)
return result
throw new NotImplementedError()
approximateSizeSync: (start, end) ->
if @_approximateSizeSync
if not start? or not end?
throw new InvalidArgumentError "
approximateSize() requires valid `start`, `end` arguments"
start = String(start) unless @_isBuffer(start)
end = String(end) unless @_isBuffer(end)
result = @_approximateSizeSync(start, end)
return result
throw new NotImplementedError()
openSync: (options) ->
if @_openSync
options = @_options || {} unless options?
options.createIfMissing = options.createIfMissing isnt false
options.errorIfExists = !!options.errorIfExists
result = @_openSync(options)
@setOpened true, options if result
result = @ if result
return result
throw new NotImplementedError()
#if successful should return true.
closeSync: ->
if @_closeSync
result = @_closeSync()
@setOpened false if result
return result
throw new NotImplementedError()
#the async methods simulated by sync methods:
#the derived class can override these methods to implement
#the real async methods for better performance.
_open: (options, callback) ->
that = this
if @_openSync
setImmediate ->
result = undefined
try
result = that._openSync(options)
catch err
callback err
return
if result
callback null, result
else
callback new OpenError("can not open database.")
else
setImmediate callback
_close: (callback) ->
that = this
if @_closeSync
setImmediate ->
result = undefined
try
result = that._closeSync()
catch err
callback err
return
if result
callback null, result
else
callback new CloseError("can not close database.")
else
setImmediate callback
_isExists: (key, options, callback) ->
that = this
if @_isExistsSync
setImmediate ->
result = undefined
try
result = that._isExistsSync(key, options)
catch err
callback err
return
callback null, result
else
@_get key, options, (err, value) ->
if err
if AbstractError.isNotFound(err)
callback null, false
else
callback err
else
callback null, true
_getBuffer: (key, destBuffer, options, callback) ->
that = this
if @_getSync or @_getBufferSync isnt AbstractNoSQL::_getBufferSync
setImmediate ->
result = undefined
try
result = that._getBufferSync(key, destBuffer, options)
catch err
callback err
return
callback null, result
else if @_get
@_get key, options, (err, value)->
return callback(err) if err
result = utf8ByteLength(value)
if destBuffer
result = Math.min(result, destBuffer.length)
result = destBuffer.write(value, options.offset, result) if result
callback null, result
else
setImmediate callback
_getBufferSync: (key, destBuffer, options) ->
if @_getSync
value = @_getSync(key, options)
result = utf8ByteLength(value)
if destBuffer
result = Math.min(result, destBuffer.length)
result = destBuffer.write(value, options.offset, result) if result
return result
else
throw new NotImplementedError('_mGetSync: _getSync is not implemented.')
_mGetSync: (keys, options) ->
if @_getSync
result = []
needKeyName = options.keys
raiseError = options.raiseError
options.asBuffer = options.asBuffer is true
for key in keys
try
value = @_getSync(key, options)
catch err
throw err if raiseError
value = undefined
if needKeyName isnt false
result.push key, value
else
result.push value
return result
else
throw new NotImplementedError('_mGetSync: _getSync is not implemented.')
_mGet: (keys, options, callback) ->
that = this
if @_getSync or @_mGetSync isnt AbstractNoSQL::_mGetSync
setImmediate ->
result = undefined
try
result = that._mGetSync keys, options
catch err
callback err
return
callback null, result
else if keys.length > 0 and @_get
result = []
i = 0
needKeyName = options.keys
raiseError = options.raiseError
readNext = (err, value)->
return callback(err) if err and raiseError
if needKeyName isnt false
result.push keys[i], value
else
result.push value
i++
return callback(null, result) if i >= keys.length
that._get keys[i], options, readNext
@_get keys[i], options, readNext
else
setImmediate callback
_get: (key, options, callback) ->
that = this
if @_getSync
setImmediate ->
result = undefined
try
result = that._getSync(key, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_put: (key, value, options, callback) ->
that = this
if @_putSync
setImmediate ->
result = undefined
try
result = that._putSync(key, value, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_del: (key, options, callback) ->
that = this
if @_delSync
setImmediate ->
result = undefined
try
result = that._delSync(key, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_batch: (array, options, callback) ->
that = this
if @_batchSync
setImmediate ->
result = undefined
try
result = that._batchSync(array, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
#TODO: remove from here, not a necessary primitive
_approximateSize: (start, end, callback) ->
that = this
if @_approximateSizeSync
setImmediate ->
result = undefined
try
result = that._approximateSizeSync(start, end)
catch err
callback err
return
callback null, result
else
setImmediate callback
#slower impl:
#
#_exec: (fn, args, callback) ->
# that = this
# if fn then setImmediate ->
# result
# try
# result = fn.apply(that, args)
# catch (err)
# callback(err)
# return
#
# callback(null, result)
# else
# setImmediate(callback)
#
#_open: (options, callback) ->
# this._exec(this._openSync, [options], callback)
#
#
openAsync: (options, callback) ->
options = {} unless options?
options.createIfMissing = options.createIfMissing isnt false
options.errorIfExists = !!options.errorIfExists
that = this
@_open options, (err, result) ->
that.setOpened true, options if not err?
callback err, result
open: (options, callback) ->
if isFunction options
callback = options
options = undefined
if callback
@openAsync options, callback
else
@openSync options
closeAsync: (callback) ->
that = this
callback = undefined unless isFunction callback
@_close (err, result) ->
return callback err if err
that.setOpened false
callback null, result if callback
close: (callback) ->
if callback
@closeAsync callback
else
@closeSync()
isExistsAsync: (key, options, callback) ->
options = {} unless options?
key = String(key) unless @_isBuffer(key)
@_isExists key, options, callback
isExists: (key, options, callback) ->
if isFunction options
callback = options
options = {}
else
if callback
@isExistsAsync key, options, callback
else
@isExistsSync key, options
isExist: @::isExists
getBufferAsync: (key, destBuffer, options, callback) ->
options = {} unless options?
options.offset = 0 unless options.offset?
@_getBuffer key, destBuffer, options, callback
getBuffer: (key, destBuffer, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@getBufferAsync key, destBuffer, options, callback
else
@getBufferSync key, destBuffer, options
mGetAsync: (keys, options, callback) ->
options = {} unless options?
options.asBuffer = options.asBuffer is true
options.raiseError = options.raiseError isnt false
needKeyName = options.keys isnt false
@_mGet keys, options, (err, arr)->
return callback(err) if err
if needKeyName
i = 0
result = []
while i < arr.length
result.push
key: arr[i]
value: arr[++i]
i++
else
result = arr
callback null, result
mGet: (keys, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
else
if callback
@mGetAsync keys, options, callback
else
@mGetSync keys, options
getAsync: (key, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key")
key = String(key) unless @_isBuffer(key)
options.asBuffer = options.asBuffer is true
@_get key, options, callback
get: (key, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@getAsync key, options, callback
else
@getSync key, options
putAsync: (key, value, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key", @_isBuffer)
key = String(key) unless @_isBuffer(key)
# coerce value to string in node, don't touch it in browser
# (indexeddb can store any JS type)
value = String(value) if value? and not @_isBuffer(value) and not process.browser
@_put key, value, options, callback
put: (key, value, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@putAsync key, value, options, callback
else
@putSync key, value, options
delAsync: (key, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key", @_isBuffer)
key = String(key) unless @_isBuffer(key)
@_del key, options, callback
del: (key, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@delAsync key, options, callback
else
@delSync key, options
batchAsync: (array, options, callback) ->
options = {} unless options?
unless isArray(array)
vError = new InvalidArgumentError("batch(array) requires an array argument")
return callback(vError)
for e in array
continue unless typeof e is "object"
return callback(err) if err = @_checkKey(e.type, "type")
return callback(err) if err = @_checkKey(e.key, "key")
@_batch array, options, callback
batch: (array, options, callback) ->
return @_chainedBatch() unless arguments.length
if isFunction options
callback = options
options = {}
callback = array if isFunction array
if callback
@batchAsync array, options, callback
else
@batchSync array, options
#TODO: remove from here, not a necessary primitive
approximateSizeAsync: (start, end, callback) ->
start = String(start) unless @_isBuffer(start)
end = String(end) unless @_isBuffer(end)
@_approximateSize start, end, callback
approximateSize: (start, end, callback) ->
if not start? or not end? or isFunction(start) or isFunction(end)
throw new InvalidArgumentError "
approximateSize() requires valid `start`, `end` and `callback`(for async) arguments"
if callback
@approximateSizeAsync start, end, callback
else
@approximateSizeSync start, end
#should override this to test sync or if you do not wanna
#implement the _iterator function.
IteratorClass: AbstractIterator
iterator: (options) ->
options = {} unless typeof options is "object"
if @IteratorClass
return new @IteratorClass(this, options)
else if isFunction @_iterator
console.error "_iterator is deprecated. please use the IteratorClass instead."
return @_iterator(options)
throw new NotImplementedError()
_chainedBatch: ->
new AbstractChainedBatch(this)
_isBuffer: (obj) ->
Buffer.isBuffer obj
_checkKey: (obj, type) ->
if not obj?
return new InvalidArgumentError(type + " cannot be `null` or `undefined`")
if @_isBuffer(obj)
if obj.length is 0
return new InvalidArgumentError(type + " cannot be an empty Buffer")
else if String(obj) is ""
return new InvalidArgumentError(type + " cannot be an empty String")
isOpen: ->
!!@_opened
module.exports.AbstractNoSQL = AbstractNoSQL
module.exports.__defineGetter__ "AbstractLevelDOWN", ->
console.error "AbstractLevelDOWN is deprecated. use AbstractNoSQL instead."
AbstractNoSQL
module.exports.__defineGetter__ "AbstractIterator", ->
console.error "AbstractIterator is deprecated. it's moved to abstract-iterator."
console.error "first `npm install abstract-iterator`" unless AbstractIterator
AbstractIterator
#module.exports.AbstractIterator = AbstractIterator
module.exports.AbstractChainedBatch = AbstractChainedBatch
| true | # Copyright (c) 2013 PI:NAME:<NAME>END_PI, MIT License
# Copyright (c) 2014 PI:NAME:<NAME>END_PI, MIT License
xtend = require("xtend")
AbstractObject = require("abstract-object")
Codec = require("buffer-codec")
utf8ByteLength = Codec.getByteLen
Errors = require("./abstract-error")
try AbstractIterator = require("abstract-iterator")
AbstractChainedBatch = require("./abstract-chained-batch")
setImmediate = global.setImmediate or process.nextTick
AbstractError = Errors.AbstractError
NotImplementedError = Errors.NotImplementedError
InvalidArgumentError = Errors.InvalidArgumentError
OpenError = Errors.OpenError
CloseError = Errors.CloseError
inherits = require("inherits-ex/lib/inherits")
isString = require("util-ex/lib/is/type/string")
isFunction = require("util-ex/lib/is/type/function")
isArray = require("util-ex/lib/is/type/array")
module.exports = class AbstractNoSQL
inherits AbstractNoSQL, AbstractObject
constructor: ->
super
initialize:(location) ->
#not all database have the location argument.
if location and typeof location isnt "string"
throw new InvalidArgumentError("constructor requires a location string argument")
@location = location
finalize: ->
if @_opened
if @_closeSync then @closeSync()
else @closeAsync()
@_options = null
@::__defineGetter__ "opened", ->
!!@_opened
setOpened: (aValue, options)->
if aValue
@_opened = true
@_options = options if options
else
@_opened = false
#the optimal low-level sync functions:
isExistsSync: (key, options) ->
options = {} unless options?
key = String(key) unless @_isBuffer(key)
if @_isExistsSync
result = @_isExistsSync(key, options)
return result
else if @_getSync
try
@_getSync key, options
return true
catch err
if AbstractError.isNotFound(err)
return false
else
throw err
throw new NotImplementedError()
isExistSync: @::isExistsSync
getSync: (key, options) ->
if @_getSync
options = {} unless options?
throw err if err = @_checkKey(key, "key")
key = String(key) unless @_isBuffer(key) #TODO should move to low-level db.
result = @_getSync(key, options)
return result
throw new NotImplementedError()
getBufferSync: (key, destBuffer, options) ->
if @_getBufferSync
options = {} unless options?
options.offset = 0 unless options.offset?
result = @_getBufferSync(key, destBuffer, options)
return result
throw new NotImplementedError()
mGetSync: (keys, options) ->
if @_mGetSync
options = {} unless options?
options.raiseError = options.raiseError isnt false
needKeyName = options.keys
arr = @_mGetSync(keys, options)
i = 0
result = []
while i < arr.length
if needKeyName isnt false
result.push
key: arr[i]
value: arr[++i]
else
result.push arr[i]
i++
return result
throw new NotImplementedError()
putSync: (key, value, options) ->
if @_putSync
options = {} unless options?
result = @_putSync(key, value, options)
return result
throw new NotImplementedError()
delSync: (key, options) ->
if @_delSync
options = {} unless options?
result = @_delSync(key, options)
return result
throw new NotImplementedError()
batchSync: (operations, options) ->
if @_batchSync
options = {} unless options?
unless isArray(operations)
throw new InvalidArgumentError("batch(operations) requires an array argument")
for e in operations
continue unless typeof e is "object"
throw err if err = @_checkKey(e.type, "type")
throw err if err = @_checkKey(e.key, "key")
result = @_batchSync(operations, options)
return result
throw new NotImplementedError()
approximateSizeSync: (start, end) ->
if @_approximateSizeSync
if not start? or not end?
throw new InvalidArgumentError "
approximateSize() requires valid `start`, `end` arguments"
start = String(start) unless @_isBuffer(start)
end = String(end) unless @_isBuffer(end)
result = @_approximateSizeSync(start, end)
return result
throw new NotImplementedError()
openSync: (options) ->
if @_openSync
options = @_options || {} unless options?
options.createIfMissing = options.createIfMissing isnt false
options.errorIfExists = !!options.errorIfExists
result = @_openSync(options)
@setOpened true, options if result
result = @ if result
return result
throw new NotImplementedError()
#if successful should return true.
closeSync: ->
if @_closeSync
result = @_closeSync()
@setOpened false if result
return result
throw new NotImplementedError()
#the async methods simulated by sync methods:
#the derived class can override these methods to implement
#the real async methods for better performance.
_open: (options, callback) ->
that = this
if @_openSync
setImmediate ->
result = undefined
try
result = that._openSync(options)
catch err
callback err
return
if result
callback null, result
else
callback new OpenError("can not open database.")
else
setImmediate callback
_close: (callback) ->
that = this
if @_closeSync
setImmediate ->
result = undefined
try
result = that._closeSync()
catch err
callback err
return
if result
callback null, result
else
callback new CloseError("can not close database.")
else
setImmediate callback
_isExists: (key, options, callback) ->
that = this
if @_isExistsSync
setImmediate ->
result = undefined
try
result = that._isExistsSync(key, options)
catch err
callback err
return
callback null, result
else
@_get key, options, (err, value) ->
if err
if AbstractError.isNotFound(err)
callback null, false
else
callback err
else
callback null, true
_getBuffer: (key, destBuffer, options, callback) ->
that = this
if @_getSync or @_getBufferSync isnt AbstractNoSQL::_getBufferSync
setImmediate ->
result = undefined
try
result = that._getBufferSync(key, destBuffer, options)
catch err
callback err
return
callback null, result
else if @_get
@_get key, options, (err, value)->
return callback(err) if err
result = utf8ByteLength(value)
if destBuffer
result = Math.min(result, destBuffer.length)
result = destBuffer.write(value, options.offset, result) if result
callback null, result
else
setImmediate callback
_getBufferSync: (key, destBuffer, options) ->
if @_getSync
value = @_getSync(key, options)
result = utf8ByteLength(value)
if destBuffer
result = Math.min(result, destBuffer.length)
result = destBuffer.write(value, options.offset, result) if result
return result
else
throw new NotImplementedError('_mGetSync: _getSync is not implemented.')
_mGetSync: (keys, options) ->
if @_getSync
result = []
needKeyName = options.keys
raiseError = options.raiseError
options.asBuffer = options.asBuffer is true
for key in keys
try
value = @_getSync(key, options)
catch err
throw err if raiseError
value = undefined
if needKeyName isnt false
result.push key, value
else
result.push value
return result
else
throw new NotImplementedError('_mGetSync: _getSync is not implemented.')
_mGet: (keys, options, callback) ->
that = this
if @_getSync or @_mGetSync isnt AbstractNoSQL::_mGetSync
setImmediate ->
result = undefined
try
result = that._mGetSync keys, options
catch err
callback err
return
callback null, result
else if keys.length > 0 and @_get
result = []
i = 0
needKeyName = options.keys
raiseError = options.raiseError
readNext = (err, value)->
return callback(err) if err and raiseError
if needKeyName isnt false
result.push keys[i], value
else
result.push value
i++
return callback(null, result) if i >= keys.length
that._get keys[i], options, readNext
@_get keys[i], options, readNext
else
setImmediate callback
_get: (key, options, callback) ->
that = this
if @_getSync
setImmediate ->
result = undefined
try
result = that._getSync(key, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_put: (key, value, options, callback) ->
that = this
if @_putSync
setImmediate ->
result = undefined
try
result = that._putSync(key, value, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_del: (key, options, callback) ->
that = this
if @_delSync
setImmediate ->
result = undefined
try
result = that._delSync(key, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
_batch: (array, options, callback) ->
that = this
if @_batchSync
setImmediate ->
result = undefined
try
result = that._batchSync(array, options)
catch err
callback err
return
callback null, result
else
setImmediate callback
#TODO: remove from here, not a necessary primitive
_approximateSize: (start, end, callback) ->
that = this
if @_approximateSizeSync
setImmediate ->
result = undefined
try
result = that._approximateSizeSync(start, end)
catch err
callback err
return
callback null, result
else
setImmediate callback
#slower impl:
#
#_exec: (fn, args, callback) ->
# that = this
# if fn then setImmediate ->
# result
# try
# result = fn.apply(that, args)
# catch (err)
# callback(err)
# return
#
# callback(null, result)
# else
# setImmediate(callback)
#
#_open: (options, callback) ->
# this._exec(this._openSync, [options], callback)
#
#
openAsync: (options, callback) ->
options = {} unless options?
options.createIfMissing = options.createIfMissing isnt false
options.errorIfExists = !!options.errorIfExists
that = this
@_open options, (err, result) ->
that.setOpened true, options if not err?
callback err, result
open: (options, callback) ->
if isFunction options
callback = options
options = undefined
if callback
@openAsync options, callback
else
@openSync options
closeAsync: (callback) ->
that = this
callback = undefined unless isFunction callback
@_close (err, result) ->
return callback err if err
that.setOpened false
callback null, result if callback
close: (callback) ->
if callback
@closeAsync callback
else
@closeSync()
isExistsAsync: (key, options, callback) ->
options = {} unless options?
key = String(key) unless @_isBuffer(key)
@_isExists key, options, callback
isExists: (key, options, callback) ->
if isFunction options
callback = options
options = {}
else
if callback
@isExistsAsync key, options, callback
else
@isExistsSync key, options
isExist: @::isExists
getBufferAsync: (key, destBuffer, options, callback) ->
options = {} unless options?
options.offset = 0 unless options.offset?
@_getBuffer key, destBuffer, options, callback
getBuffer: (key, destBuffer, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@getBufferAsync key, destBuffer, options, callback
else
@getBufferSync key, destBuffer, options
mGetAsync: (keys, options, callback) ->
options = {} unless options?
options.asBuffer = options.asBuffer is true
options.raiseError = options.raiseError isnt false
needKeyName = options.keys isnt false
@_mGet keys, options, (err, arr)->
return callback(err) if err
if needKeyName
i = 0
result = []
while i < arr.length
result.push
key: arr[i]
value: arr[++i]
i++
else
result = arr
callback null, result
mGet: (keys, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
else
if callback
@mGetAsync keys, options, callback
else
@mGetSync keys, options
getAsync: (key, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key")
key = String(key) unless @_isBuffer(key)
options.asBuffer = options.asBuffer is true
@_get key, options, callback
get: (key, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@getAsync key, options, callback
else
@getSync key, options
putAsync: (key, value, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key", @_isBuffer)
key = String(key) unless @_isBuffer(key)
# coerce value to string in node, don't touch it in browser
# (indexeddb can store any JS type)
value = String(value) if value? and not @_isBuffer(value) and not process.browser
@_put key, value, options, callback
put: (key, value, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@putAsync key, value, options, callback
else
@putSync key, value, options
delAsync: (key, options, callback) ->
options = {} unless options?
return callback(err) if err = @_checkKey(key, "key", @_isBuffer)
key = String(key) unless @_isBuffer(key)
@_del key, options, callback
del: (key, options, callback) ->
err = undefined
if isFunction options
callback = options
options = {}
if callback
@delAsync key, options, callback
else
@delSync key, options
batchAsync: (array, options, callback) ->
options = {} unless options?
unless isArray(array)
vError = new InvalidArgumentError("batch(array) requires an array argument")
return callback(vError)
for e in array
continue unless typeof e is "object"
return callback(err) if err = @_checkKey(e.type, "type")
return callback(err) if err = @_checkKey(e.key, "key")
@_batch array, options, callback
batch: (array, options, callback) ->
return @_chainedBatch() unless arguments.length
if isFunction options
callback = options
options = {}
callback = array if isFunction array
if callback
@batchAsync array, options, callback
else
@batchSync array, options
#TODO: remove from here, not a necessary primitive
approximateSizeAsync: (start, end, callback) ->
start = String(start) unless @_isBuffer(start)
end = String(end) unless @_isBuffer(end)
@_approximateSize start, end, callback
approximateSize: (start, end, callback) ->
if not start? or not end? or isFunction(start) or isFunction(end)
throw new InvalidArgumentError "
approximateSize() requires valid `start`, `end` and `callback`(for async) arguments"
if callback
@approximateSizeAsync start, end, callback
else
@approximateSizeSync start, end
#should override this to test sync or if you do not wanna
#implement the _iterator function.
IteratorClass: AbstractIterator
iterator: (options) ->
options = {} unless typeof options is "object"
if @IteratorClass
return new @IteratorClass(this, options)
else if isFunction @_iterator
console.error "_iterator is deprecated. please use the IteratorClass instead."
return @_iterator(options)
throw new NotImplementedError()
_chainedBatch: ->
new AbstractChainedBatch(this)
_isBuffer: (obj) ->
Buffer.isBuffer obj
_checkKey: (obj, type) ->
if not obj?
return new InvalidArgumentError(type + " cannot be `null` or `undefined`")
if @_isBuffer(obj)
if obj.length is 0
return new InvalidArgumentError(type + " cannot be an empty Buffer")
else if String(obj) is ""
return new InvalidArgumentError(type + " cannot be an empty String")
isOpen: ->
!!@_opened
module.exports.AbstractNoSQL = AbstractNoSQL
module.exports.__defineGetter__ "AbstractLevelDOWN", ->
console.error "AbstractLevelDOWN is deprecated. use AbstractNoSQL instead."
AbstractNoSQL
module.exports.__defineGetter__ "AbstractIterator", ->
console.error "AbstractIterator is deprecated. it's moved to abstract-iterator."
console.error "first `npm install abstract-iterator`" unless AbstractIterator
AbstractIterator
#module.exports.AbstractIterator = AbstractIterator
module.exports.AbstractChainedBatch = AbstractChainedBatch
|
[
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 968,
"score": 0.9920727014541626,
"start": 961,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n ... | Src/coffeescript/cql-execution/test/elm/logical/data.coffee | esteban-aliverti/clinical_quality_language | 0 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### And
library TestSnippet version '1'
using QUICK
context Patient
define TT = true and true
define TF = true and false
define TN = true and null
define FF = false and false
define FT = false and true
define FN = false and null
define NN = null and null
define NT = null and true
define NF = null and false
###
module.exports['And'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "TT",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "TF",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "TN",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "FF",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "FT",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "FN",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "NN",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "NT",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "NF",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### Or
library TestSnippet version '1'
using QUICK
context Patient
define TT = true or true
define TF = true or false
define TN = true or null
define FF = false or false
define FT = false or true
define FN = false or null
define NN = null or null
define NT = null or true
define NF = null or false
###
module.exports['Or'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "TT",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "TF",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "TN",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "FF",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "FT",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "FN",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "NN",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "NT",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "NF",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### XOr
library TestSnippet version '1'
using QUICK
context Patient
define TT = true xor true
define TF = true xor false
define TN = true xor null
define FF = false xor false
define FT = false xor true
define FN = false xor null
define NN = null xor null
define NT = null xor true
define NF = null xor false
###
module.exports['XOr'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "TT",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "TF",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "TN",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "FF",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "FT",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "FN",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "NN",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "NT",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "NF",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### Not
library TestSnippet version '1'
using QUICK
context Patient
define NotTrue = not true
define NotFalse = not false
define NotNull = not null
###
module.exports['Not'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "NotTrue",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}
}
}, {
"name" : "NotFalse",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}
}
}, {
"name" : "NotNull",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"type" : "Null"
}
}
} ]
}
}
}
| 32086 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### And
library TestSnippet version '1'
using QUICK
context Patient
define TT = true and true
define TF = true and false
define TN = true and null
define FF = false and false
define FT = false and true
define FN = false and null
define NN = null and null
define NT = null and true
define NF = null and false
###
module.exports['And'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### Or
library TestSnippet version '1'
using QUICK
context Patient
define TT = true or true
define TF = true or false
define TN = true or null
define FF = false or false
define FT = false or true
define FN = false or null
define NN = null or null
define NT = null or true
define NF = null or false
###
module.exports['Or'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### XOr
library TestSnippet version '1'
using QUICK
context Patient
define TT = true xor true
define TF = true xor false
define TN = true xor null
define FF = false xor false
define FT = false xor true
define FN = false xor null
define NN = null xor null
define NT = null xor true
define NF = null xor false
###
module.exports['XOr'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### Not
library TestSnippet version '1'
using QUICK
context Patient
define NotTrue = not true
define NotFalse = not false
define NotNull = not null
###
module.exports['Not'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"type" : "Null"
}
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### And
library TestSnippet version '1'
using QUICK
context Patient
define TT = true and true
define TF = true and false
define TN = true and null
define FF = false and false
define FT = false and true
define FN = false and null
define NN = null and null
define NT = null and true
define NF = null and false
###
module.exports['And'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### Or
library TestSnippet version '1'
using QUICK
context Patient
define TT = true or true
define TF = true or false
define TN = true or null
define FF = false or false
define FT = false or true
define FN = false or null
define NN = null or null
define NT = null or true
define NF = null or false
###
module.exports['Or'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Or",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### XOr
library TestSnippet version '1'
using QUICK
context Patient
define TT = true xor true
define TF = true xor false
define TN = true xor null
define FF = false xor false
define FT = false xor true
define FN = false xor null
define NN = null xor null
define NT = null xor true
define NF = null xor false
###
module.exports['XOr'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"type" : "Null"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Xor",
"operand" : [ {
"type" : "Null"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
} ]
}
} ]
}
}
}
### Not
library TestSnippet version '1'
using QUICK
context Patient
define NotTrue = not true
define NotFalse = not false
define NotNull = not null
###
module.exports['Not'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "true",
"type" : "Literal"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"valueType" : "{http://www.w3.org/2001/XMLSchema}bool",
"value" : "false",
"type" : "Literal"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Not",
"operand" : {
"type" : "Null"
}
}
} ]
}
}
}
|
[
{
"context": "n unknown error occured. Please contact support at precisionfda-support@dnanexus.com\"\n })\n\nclass ObjectListModel\n constructor: (",
"end": 3153,
"score": 0.9999217987060547,
"start": 3120,
"tag": "EMAIL",
"value": "precisionfda-support@dnanexus.com"
}
] | app/assets/javascripts/_precision/precision.selector.coffee | pamelladnanexus/pfda-release-repo | 0 | # @opts
# listModelConfigs (required): array of listModel configurations
#
class SelectorModel
constructor: (@opts) ->
@id = _.uniqueId('object-selector-modal-')
@modal = null
@title = ko.observable(@opts.title ? "Select data")
@help = ko.observable(@opts.help)
@selectionType = @opts.selectionType ? "checkbox"
@selectableClasses = @opts.selectableClasses ? true
@listRelatedParams = @opts.listRelatedParams
@busy = ko.observable(false)
@saving = ko.observable(false)
@error = ko.observable()
@filterByEditable = ko.observable(false)
@calls = []
@callsDeferred = $.Deferred()
@selectedList = new ObjectListModel(this, {
className: "selected"
name: "Selected"
})
@selected = @selectedList.objects
@numSelected = ko.computed(=>
if _.isArray(@selected())
_.size(@selected())
else if _.isObject(@selected())
return 1
)
@objectLists = ko.observableArray([@selectedList].concat(_.map(@opts.listModelConfigs, (listModelConfig) =>
new ObjectListModel(this, listModelConfig)
)))
@objectsHash = {}
@canSave = ko.computed(=>
!@busy() && !@saving() && !_.isEmpty(@selected())
)
@hasError = ko.computed(=>
@error()?
)
getParentTypeFromContext: (context, type) ->
return _.find(context.$parents, (parent) ->
parent instanceof type
)
getObjectLists: () ->
@busy(true)
_.each(@objectLists.peek(), (listModel) =>
@calls.push(listModel.getObjects()) if listModel.className != "selected"
)
$.when(this, @calls).always(() =>
@callsDeferred.resolve()
@busy(false)
)
reset: () =>
@busy(false)
@saving(false)
@error(null)
_.each(@calls, (call) -> call.abort())
@calls = []
@objectsHash = {}
@callsDeferred = $.Deferred()
open: () =>
@modal = $("##{@id}")
@modal.on('hidden.bs.modal', =>
@modal.off()
if @selectionType == "radio"
@selected(null)
else
@selected.removeAll()
@error(null)
)
@modal.on("click", ".object-related-link, .list-group-item.not-selectable label", () ->
objectModel = ko.dataFor(this)
context = ko.contextFor(this)
objectModel.getRelatedObjects(context)
)
if _.size(@objectsHash) == 0
@reset()
@getObjectLists()
.done(() =>
@modal.modal('handleUpdate')
@modal.find(".nav-pills li:first-child a").click()
)
.fail(@onError)
@modal.modal('show')
save: () =>
@saving(true)
@error(null)
@opts.onSave(@selected())
.done(() =>
@modal.modal('hide')
@opts.onAfterSave?()
)
.fail(@onError)
.always(=>
@saving(false)
)
onError: (e) =>
console.error(e.status, e.statusText, e.responseText)
if e.responseText? && _.isObject(e.responseText)
errorObject = JSON.parse e.responseText
@error(errorObject.error)
else
@error({
type: "#{e.status}: #{e.statusText}"
message: "An unknown error occured. Please contact support at precisionfda-support@dnanexus.com"
})
class ObjectListModel
constructor: (@selectorModel, config) ->
@className = config.className
@name = config.name
@apiEndpoint = config.apiEndpoint
@apiParams = config.apiParams ? {}
@selectable = config.selectable ? false
@busy = ko.observable(false)
@patternQuery = ko.observable(config.patterns)
@filterQuery = ko.observable()
if @className == "selected" && @selectorModel.selectionType == "radio"
@objects = ko.observable()
else
@objects = ko.observableArray()
@objects.filtered = ko.computed(=>
return [] if !@objects()?
if @className == "selected" && @selectorModel.selectionType == "radio"
objects = [@objects()]
else
objects = @objects()
if @className != "selected"
objects = @filterByProperty(objects, 'editable') if @selectorModel.filterByEditable()
if @className == 'file' && @totalCount && @totalCount != @objects().length && !_.isEmpty(@filterQuery())
@objects.removeAll()
@getObjects(0, @totalCount)
objects = @filterSetOfObjects(objects, @patternQuery()) if @patternQuery()?
objects = @filterSetOfObjects(objects, @filterQuery())
objects = _.sortBy(objects, 'name')
return objects
)
@numFilteredObjects = ko.computed(=>
@objects.filtered().length
)
@activeRelatedObjects = ko.observableArray().extend({notify: 'always'})
@isRelatedVisible = ko.computed(=>
_.size(@activeRelatedObjects()) > 0
)
clearActiveRelated: () ->
@activeRelatedObjects([])
getObjects: (offset = 0, limit = 100) ->
return $.Deferred().resolve() if !@apiEndpoint?
rootContext = ko.contextFor(@selectorModel.modal.get(0)).$root
if @className == 'file'
@apiParams['offset'] = offset
@apiParams['limit'] = limit
@apiParams['scopes'] = rootContext.accessibleScope if rootContext.accessibleScope
params = _.defaults(@apiParams, {
describe:
include:
all_tags_list: false
user: true
org: true
})
@objects.removeAll() unless @className == 'file'
@busy(true)
Precision.api("/api/#{@apiEndpoint}", params, (result) =>
@totalCount = result['count'] if result['count']
objects = if result['objects'] then result['objects'] else result
objectModels = _.map(objects, (object) =>
objectModel = new ObjectItemModel(@selectorModel, this, object)
@selectorModel.objectsHash[objectModel.uid] = objectModel
objectModel
)
@objects(@objects().concat(objectModels))
).always(=>
@busy(false)
)
filterByProperty: (objects, property) ->
return _.filter(objects, (object) ->
object[property].peek()
)
filterSetOfObjects: (objects, query) ->
return objects if _.isEmpty(query)
if _.isArray(query)
return _.filter(objects, (object) ->
_.some(query, (queryToTest) ->
regexp = Precision.utils.globToRegex(queryToTest, "i")
object.title.peek().match(regexp) || _.some(object.all_tags_list.peek(), (tag) -> tag.match(regexp))
)
)
else
regexp = new RegExp(query, "i")
return _.filter(objects, (object) ->
object.title.peek().match(regexp) || _.some(object.all_tags_list.peek(), (tag) -> tag.match(regexp))
)
class ObjectItemModel
constructor: (@selectorModel, @listModel, object, opts = {}) ->
@loaded = ko.observable(false)
@selected = @selectorModel.selected
@selectionType = @selectorModel.selectionType
@selectableClasses = @selectorModel.selectableClasses
@id = object.id
@uid = object.uid
@title = ko.observable(object.title)
@className = ko.observable(object.className || object.klass)
@classIcon = ko.observable("fa fa-fw #{object.fa_class}")
@scope = ko.observable(object.scope)
@path = ko.observable(object.path)
@userName = ko.observable(object.user?.full_name)
@orgName = ko.observable(object.org?.name)
@all_tags_list = ko.observable(object.all_tags_list)
@editable = ko.observable(object.editable)
@accessible = ko.observable(object.accessible)
@public = ko.observable(object.public)
@private = ko.observable(object.private)
@in_space = ko.observable(object.in_space)
@review_space_private = object.space_private
@review_space_public = object.space_public
@scopeFormatted = ko.computed(=>
if @public()
"Public"
else if @private()
"Private"
else if @review_space_private
"Shared in Space(Confidential)"
else if @review_space_public
"Shared in Space(Cooperative)"
else if @in_space()
"Shared in Space"
)
@scopeIcon = ko.computed(=>
if @public()
"fa fa-fw fa-globe"
else if @private()
"fa fa-fw fa-lock"
else if @in_space()
"fa fa-fw fa-object-group"
)
@activeRelatedObjects = @listModel.activeRelatedObjects
@relatedObjects = ko.observable().extend({notify: 'always'})
@numRelatedObjects = ko.computed(=> _.size(@relatedObjects()))
@loadingRelated = ko.observable(false)
@loadedRelated = ko.observable(false)
@license = ko.observable(object.license)
@user_license = ko.observable(object.user_license)
@user_license.accepted = ko.computed(=> @user_license()?.accepted)
@user_license.pending = ko.computed(=> @user_license()?.pending)
@user_license.unset = ko.computed(=> @user_license()?.unset)
@isSelectable = ko.computed(=>
@selectableClasses == true || (_.isArray(@selectableClasses) && _.includes(@selectableClasses, @className()))
)
if opts.update
@describe().done((item) =>
@update(item)
)
else
@loaded(true)
update: (object) ->
@title(object.title)
@className(object.className || object.klass)
@classIcon("fa fa-fw #{object.fa_class}")
@scope(object.scope)
@path(object.path)
@userName(object.user?.full_name)
@orgName(object.org?.name)
@editable(object.editable)
@accessible(object.accessible)
@public(object.public)
@private(object.private)
@in_space(object.in_space)
@license(object.license)
@user_license(object.user_license)
@all_tags_list(object.all_tags_list)
@loaded(true)
describe: () ->
params = _.defaults(@listModel.apiParams, {
uid: @uid
describe:
include:
all_tags_list: true
user: true
org: true
})
Precision.api("/api/describe", params)
getRelatedObjects: (context) ->
listModel = @selectorModel.getParentTypeFromContext(context, ObjectListModel)
return if !listModel?
if !@loadedRelated()
@loadingRelated(true)
@selectorModel.callsDeferred.done(=>
params =
uid: @uid
opts: _.extend({
describe:
include:
all_tags_list: true
user: true
org: true
}, @selectorModel.listRelatedParams)
Precision.api("/api/list_related", params)
.done((objects) =>
relatedObjects = []
_.each(objects, (object) =>
if @selectorModel.objectsHash[object.uid]?
relatedObjects.push(@selectorModel.objectsHash[object.uid])
else
newObjectModel = new ObjectItemModel(@selectorModel, this, object)
@selectorModel.objectsHash[newObjectModel.uid] = newObjectModel
relatedObjects.push(newObjectModel)
)
@relatedObjects(relatedObjects)
listModel.activeRelatedObjects(@relatedObjects()) if _.size(@relatedObjects()) > 0
)
.fail(@selectorModel.onError)
.always(() =>
@loadingRelated(false)
@loadedRelated(true)
)
)
else if @numRelatedObjects() > 0
listModel.activeRelatedObjects(@relatedObjects())
window.Precision ||= {}
window.Precision.models ||= {}
window.Precision.models.SelectorModel = SelectorModel
$ ->
$('.object-selector-modal .modal-body').on 'scroll', (event) ->
element = $(@).find('.tab-pane.active').find('.list-group').get(1)
return unless element
context = ko.contextFor(element)
currentNumberOfObjects = context.$data.objects().length
if element && context.$data.className == 'file' && (@scrollTop == (@scrollHeight - @offsetHeight)) && currentNumberOfObjects != context.$data.totalCount
context.$data.getObjects(currentNumberOfObjects) | 56651 | # @opts
# listModelConfigs (required): array of listModel configurations
#
class SelectorModel
constructor: (@opts) ->
@id = _.uniqueId('object-selector-modal-')
@modal = null
@title = ko.observable(@opts.title ? "Select data")
@help = ko.observable(@opts.help)
@selectionType = @opts.selectionType ? "checkbox"
@selectableClasses = @opts.selectableClasses ? true
@listRelatedParams = @opts.listRelatedParams
@busy = ko.observable(false)
@saving = ko.observable(false)
@error = ko.observable()
@filterByEditable = ko.observable(false)
@calls = []
@callsDeferred = $.Deferred()
@selectedList = new ObjectListModel(this, {
className: "selected"
name: "Selected"
})
@selected = @selectedList.objects
@numSelected = ko.computed(=>
if _.isArray(@selected())
_.size(@selected())
else if _.isObject(@selected())
return 1
)
@objectLists = ko.observableArray([@selectedList].concat(_.map(@opts.listModelConfigs, (listModelConfig) =>
new ObjectListModel(this, listModelConfig)
)))
@objectsHash = {}
@canSave = ko.computed(=>
!@busy() && !@saving() && !_.isEmpty(@selected())
)
@hasError = ko.computed(=>
@error()?
)
getParentTypeFromContext: (context, type) ->
return _.find(context.$parents, (parent) ->
parent instanceof type
)
getObjectLists: () ->
@busy(true)
_.each(@objectLists.peek(), (listModel) =>
@calls.push(listModel.getObjects()) if listModel.className != "selected"
)
$.when(this, @calls).always(() =>
@callsDeferred.resolve()
@busy(false)
)
reset: () =>
@busy(false)
@saving(false)
@error(null)
_.each(@calls, (call) -> call.abort())
@calls = []
@objectsHash = {}
@callsDeferred = $.Deferred()
open: () =>
@modal = $("##{@id}")
@modal.on('hidden.bs.modal', =>
@modal.off()
if @selectionType == "radio"
@selected(null)
else
@selected.removeAll()
@error(null)
)
@modal.on("click", ".object-related-link, .list-group-item.not-selectable label", () ->
objectModel = ko.dataFor(this)
context = ko.contextFor(this)
objectModel.getRelatedObjects(context)
)
if _.size(@objectsHash) == 0
@reset()
@getObjectLists()
.done(() =>
@modal.modal('handleUpdate')
@modal.find(".nav-pills li:first-child a").click()
)
.fail(@onError)
@modal.modal('show')
save: () =>
@saving(true)
@error(null)
@opts.onSave(@selected())
.done(() =>
@modal.modal('hide')
@opts.onAfterSave?()
)
.fail(@onError)
.always(=>
@saving(false)
)
onError: (e) =>
console.error(e.status, e.statusText, e.responseText)
if e.responseText? && _.isObject(e.responseText)
errorObject = JSON.parse e.responseText
@error(errorObject.error)
else
@error({
type: "#{e.status}: #{e.statusText}"
message: "An unknown error occured. Please contact support at <EMAIL>"
})
class ObjectListModel
constructor: (@selectorModel, config) ->
@className = config.className
@name = config.name
@apiEndpoint = config.apiEndpoint
@apiParams = config.apiParams ? {}
@selectable = config.selectable ? false
@busy = ko.observable(false)
@patternQuery = ko.observable(config.patterns)
@filterQuery = ko.observable()
if @className == "selected" && @selectorModel.selectionType == "radio"
@objects = ko.observable()
else
@objects = ko.observableArray()
@objects.filtered = ko.computed(=>
return [] if !@objects()?
if @className == "selected" && @selectorModel.selectionType == "radio"
objects = [@objects()]
else
objects = @objects()
if @className != "selected"
objects = @filterByProperty(objects, 'editable') if @selectorModel.filterByEditable()
if @className == 'file' && @totalCount && @totalCount != @objects().length && !_.isEmpty(@filterQuery())
@objects.removeAll()
@getObjects(0, @totalCount)
objects = @filterSetOfObjects(objects, @patternQuery()) if @patternQuery()?
objects = @filterSetOfObjects(objects, @filterQuery())
objects = _.sortBy(objects, 'name')
return objects
)
@numFilteredObjects = ko.computed(=>
@objects.filtered().length
)
@activeRelatedObjects = ko.observableArray().extend({notify: 'always'})
@isRelatedVisible = ko.computed(=>
_.size(@activeRelatedObjects()) > 0
)
clearActiveRelated: () ->
@activeRelatedObjects([])
getObjects: (offset = 0, limit = 100) ->
return $.Deferred().resolve() if !@apiEndpoint?
rootContext = ko.contextFor(@selectorModel.modal.get(0)).$root
if @className == 'file'
@apiParams['offset'] = offset
@apiParams['limit'] = limit
@apiParams['scopes'] = rootContext.accessibleScope if rootContext.accessibleScope
params = _.defaults(@apiParams, {
describe:
include:
all_tags_list: false
user: true
org: true
})
@objects.removeAll() unless @className == 'file'
@busy(true)
Precision.api("/api/#{@apiEndpoint}", params, (result) =>
@totalCount = result['count'] if result['count']
objects = if result['objects'] then result['objects'] else result
objectModels = _.map(objects, (object) =>
objectModel = new ObjectItemModel(@selectorModel, this, object)
@selectorModel.objectsHash[objectModel.uid] = objectModel
objectModel
)
@objects(@objects().concat(objectModels))
).always(=>
@busy(false)
)
filterByProperty: (objects, property) ->
return _.filter(objects, (object) ->
object[property].peek()
)
filterSetOfObjects: (objects, query) ->
return objects if _.isEmpty(query)
if _.isArray(query)
return _.filter(objects, (object) ->
_.some(query, (queryToTest) ->
regexp = Precision.utils.globToRegex(queryToTest, "i")
object.title.peek().match(regexp) || _.some(object.all_tags_list.peek(), (tag) -> tag.match(regexp))
)
)
else
regexp = new RegExp(query, "i")
return _.filter(objects, (object) ->
object.title.peek().match(regexp) || _.some(object.all_tags_list.peek(), (tag) -> tag.match(regexp))
)
class ObjectItemModel
constructor: (@selectorModel, @listModel, object, opts = {}) ->
@loaded = ko.observable(false)
@selected = @selectorModel.selected
@selectionType = @selectorModel.selectionType
@selectableClasses = @selectorModel.selectableClasses
@id = object.id
@uid = object.uid
@title = ko.observable(object.title)
@className = ko.observable(object.className || object.klass)
@classIcon = ko.observable("fa fa-fw #{object.fa_class}")
@scope = ko.observable(object.scope)
@path = ko.observable(object.path)
@userName = ko.observable(object.user?.full_name)
@orgName = ko.observable(object.org?.name)
@all_tags_list = ko.observable(object.all_tags_list)
@editable = ko.observable(object.editable)
@accessible = ko.observable(object.accessible)
@public = ko.observable(object.public)
@private = ko.observable(object.private)
@in_space = ko.observable(object.in_space)
@review_space_private = object.space_private
@review_space_public = object.space_public
@scopeFormatted = ko.computed(=>
if @public()
"Public"
else if @private()
"Private"
else if @review_space_private
"Shared in Space(Confidential)"
else if @review_space_public
"Shared in Space(Cooperative)"
else if @in_space()
"Shared in Space"
)
@scopeIcon = ko.computed(=>
if @public()
"fa fa-fw fa-globe"
else if @private()
"fa fa-fw fa-lock"
else if @in_space()
"fa fa-fw fa-object-group"
)
@activeRelatedObjects = @listModel.activeRelatedObjects
@relatedObjects = ko.observable().extend({notify: 'always'})
@numRelatedObjects = ko.computed(=> _.size(@relatedObjects()))
@loadingRelated = ko.observable(false)
@loadedRelated = ko.observable(false)
@license = ko.observable(object.license)
@user_license = ko.observable(object.user_license)
@user_license.accepted = ko.computed(=> @user_license()?.accepted)
@user_license.pending = ko.computed(=> @user_license()?.pending)
@user_license.unset = ko.computed(=> @user_license()?.unset)
@isSelectable = ko.computed(=>
@selectableClasses == true || (_.isArray(@selectableClasses) && _.includes(@selectableClasses, @className()))
)
if opts.update
@describe().done((item) =>
@update(item)
)
else
@loaded(true)
update: (object) ->
@title(object.title)
@className(object.className || object.klass)
@classIcon("fa fa-fw #{object.fa_class}")
@scope(object.scope)
@path(object.path)
@userName(object.user?.full_name)
@orgName(object.org?.name)
@editable(object.editable)
@accessible(object.accessible)
@public(object.public)
@private(object.private)
@in_space(object.in_space)
@license(object.license)
@user_license(object.user_license)
@all_tags_list(object.all_tags_list)
@loaded(true)
describe: () ->
params = _.defaults(@listModel.apiParams, {
uid: @uid
describe:
include:
all_tags_list: true
user: true
org: true
})
Precision.api("/api/describe", params)
getRelatedObjects: (context) ->
listModel = @selectorModel.getParentTypeFromContext(context, ObjectListModel)
return if !listModel?
if !@loadedRelated()
@loadingRelated(true)
@selectorModel.callsDeferred.done(=>
params =
uid: @uid
opts: _.extend({
describe:
include:
all_tags_list: true
user: true
org: true
}, @selectorModel.listRelatedParams)
Precision.api("/api/list_related", params)
.done((objects) =>
relatedObjects = []
_.each(objects, (object) =>
if @selectorModel.objectsHash[object.uid]?
relatedObjects.push(@selectorModel.objectsHash[object.uid])
else
newObjectModel = new ObjectItemModel(@selectorModel, this, object)
@selectorModel.objectsHash[newObjectModel.uid] = newObjectModel
relatedObjects.push(newObjectModel)
)
@relatedObjects(relatedObjects)
listModel.activeRelatedObjects(@relatedObjects()) if _.size(@relatedObjects()) > 0
)
.fail(@selectorModel.onError)
.always(() =>
@loadingRelated(false)
@loadedRelated(true)
)
)
else if @numRelatedObjects() > 0
listModel.activeRelatedObjects(@relatedObjects())
window.Precision ||= {}
window.Precision.models ||= {}
window.Precision.models.SelectorModel = SelectorModel
$ ->
$('.object-selector-modal .modal-body').on 'scroll', (event) ->
element = $(@).find('.tab-pane.active').find('.list-group').get(1)
return unless element
context = ko.contextFor(element)
currentNumberOfObjects = context.$data.objects().length
if element && context.$data.className == 'file' && (@scrollTop == (@scrollHeight - @offsetHeight)) && currentNumberOfObjects != context.$data.totalCount
context.$data.getObjects(currentNumberOfObjects) | true | # @opts
# listModelConfigs (required): array of listModel configurations
#
class SelectorModel
constructor: (@opts) ->
@id = _.uniqueId('object-selector-modal-')
@modal = null
@title = ko.observable(@opts.title ? "Select data")
@help = ko.observable(@opts.help)
@selectionType = @opts.selectionType ? "checkbox"
@selectableClasses = @opts.selectableClasses ? true
@listRelatedParams = @opts.listRelatedParams
@busy = ko.observable(false)
@saving = ko.observable(false)
@error = ko.observable()
@filterByEditable = ko.observable(false)
@calls = []
@callsDeferred = $.Deferred()
@selectedList = new ObjectListModel(this, {
className: "selected"
name: "Selected"
})
@selected = @selectedList.objects
@numSelected = ko.computed(=>
if _.isArray(@selected())
_.size(@selected())
else if _.isObject(@selected())
return 1
)
@objectLists = ko.observableArray([@selectedList].concat(_.map(@opts.listModelConfigs, (listModelConfig) =>
new ObjectListModel(this, listModelConfig)
)))
@objectsHash = {}
@canSave = ko.computed(=>
!@busy() && !@saving() && !_.isEmpty(@selected())
)
@hasError = ko.computed(=>
@error()?
)
getParentTypeFromContext: (context, type) ->
return _.find(context.$parents, (parent) ->
parent instanceof type
)
getObjectLists: () ->
@busy(true)
_.each(@objectLists.peek(), (listModel) =>
@calls.push(listModel.getObjects()) if listModel.className != "selected"
)
$.when(this, @calls).always(() =>
@callsDeferred.resolve()
@busy(false)
)
reset: () =>
@busy(false)
@saving(false)
@error(null)
_.each(@calls, (call) -> call.abort())
@calls = []
@objectsHash = {}
@callsDeferred = $.Deferred()
open: () =>
@modal = $("##{@id}")
@modal.on('hidden.bs.modal', =>
@modal.off()
if @selectionType == "radio"
@selected(null)
else
@selected.removeAll()
@error(null)
)
@modal.on("click", ".object-related-link, .list-group-item.not-selectable label", () ->
objectModel = ko.dataFor(this)
context = ko.contextFor(this)
objectModel.getRelatedObjects(context)
)
if _.size(@objectsHash) == 0
@reset()
@getObjectLists()
.done(() =>
@modal.modal('handleUpdate')
@modal.find(".nav-pills li:first-child a").click()
)
.fail(@onError)
@modal.modal('show')
save: () =>
@saving(true)
@error(null)
@opts.onSave(@selected())
.done(() =>
@modal.modal('hide')
@opts.onAfterSave?()
)
.fail(@onError)
.always(=>
@saving(false)
)
onError: (e) =>
console.error(e.status, e.statusText, e.responseText)
if e.responseText? && _.isObject(e.responseText)
errorObject = JSON.parse e.responseText
@error(errorObject.error)
else
@error({
type: "#{e.status}: #{e.statusText}"
message: "An unknown error occured. Please contact support at PI:EMAIL:<EMAIL>END_PI"
})
class ObjectListModel
constructor: (@selectorModel, config) ->
@className = config.className
@name = config.name
@apiEndpoint = config.apiEndpoint
@apiParams = config.apiParams ? {}
@selectable = config.selectable ? false
@busy = ko.observable(false)
@patternQuery = ko.observable(config.patterns)
@filterQuery = ko.observable()
if @className == "selected" && @selectorModel.selectionType == "radio"
@objects = ko.observable()
else
@objects = ko.observableArray()
@objects.filtered = ko.computed(=>
return [] if !@objects()?
if @className == "selected" && @selectorModel.selectionType == "radio"
objects = [@objects()]
else
objects = @objects()
if @className != "selected"
objects = @filterByProperty(objects, 'editable') if @selectorModel.filterByEditable()
if @className == 'file' && @totalCount && @totalCount != @objects().length && !_.isEmpty(@filterQuery())
@objects.removeAll()
@getObjects(0, @totalCount)
objects = @filterSetOfObjects(objects, @patternQuery()) if @patternQuery()?
objects = @filterSetOfObjects(objects, @filterQuery())
objects = _.sortBy(objects, 'name')
return objects
)
@numFilteredObjects = ko.computed(=>
@objects.filtered().length
)
@activeRelatedObjects = ko.observableArray().extend({notify: 'always'})
@isRelatedVisible = ko.computed(=>
_.size(@activeRelatedObjects()) > 0
)
clearActiveRelated: () ->
@activeRelatedObjects([])
getObjects: (offset = 0, limit = 100) ->
return $.Deferred().resolve() if !@apiEndpoint?
rootContext = ko.contextFor(@selectorModel.modal.get(0)).$root
if @className == 'file'
@apiParams['offset'] = offset
@apiParams['limit'] = limit
@apiParams['scopes'] = rootContext.accessibleScope if rootContext.accessibleScope
params = _.defaults(@apiParams, {
describe:
include:
all_tags_list: false
user: true
org: true
})
@objects.removeAll() unless @className == 'file'
@busy(true)
Precision.api("/api/#{@apiEndpoint}", params, (result) =>
@totalCount = result['count'] if result['count']
objects = if result['objects'] then result['objects'] else result
objectModels = _.map(objects, (object) =>
objectModel = new ObjectItemModel(@selectorModel, this, object)
@selectorModel.objectsHash[objectModel.uid] = objectModel
objectModel
)
@objects(@objects().concat(objectModels))
).always(=>
@busy(false)
)
filterByProperty: (objects, property) ->
return _.filter(objects, (object) ->
object[property].peek()
)
filterSetOfObjects: (objects, query) ->
return objects if _.isEmpty(query)
if _.isArray(query)
return _.filter(objects, (object) ->
_.some(query, (queryToTest) ->
regexp = Precision.utils.globToRegex(queryToTest, "i")
object.title.peek().match(regexp) || _.some(object.all_tags_list.peek(), (tag) -> tag.match(regexp))
)
)
else
regexp = new RegExp(query, "i")
return _.filter(objects, (object) ->
object.title.peek().match(regexp) || _.some(object.all_tags_list.peek(), (tag) -> tag.match(regexp))
)
class ObjectItemModel
constructor: (@selectorModel, @listModel, object, opts = {}) ->
@loaded = ko.observable(false)
@selected = @selectorModel.selected
@selectionType = @selectorModel.selectionType
@selectableClasses = @selectorModel.selectableClasses
@id = object.id
@uid = object.uid
@title = ko.observable(object.title)
@className = ko.observable(object.className || object.klass)
@classIcon = ko.observable("fa fa-fw #{object.fa_class}")
@scope = ko.observable(object.scope)
@path = ko.observable(object.path)
@userName = ko.observable(object.user?.full_name)
@orgName = ko.observable(object.org?.name)
@all_tags_list = ko.observable(object.all_tags_list)
@editable = ko.observable(object.editable)
@accessible = ko.observable(object.accessible)
@public = ko.observable(object.public)
@private = ko.observable(object.private)
@in_space = ko.observable(object.in_space)
@review_space_private = object.space_private
@review_space_public = object.space_public
@scopeFormatted = ko.computed(=>
if @public()
"Public"
else if @private()
"Private"
else if @review_space_private
"Shared in Space(Confidential)"
else if @review_space_public
"Shared in Space(Cooperative)"
else if @in_space()
"Shared in Space"
)
@scopeIcon = ko.computed(=>
if @public()
"fa fa-fw fa-globe"
else if @private()
"fa fa-fw fa-lock"
else if @in_space()
"fa fa-fw fa-object-group"
)
@activeRelatedObjects = @listModel.activeRelatedObjects
@relatedObjects = ko.observable().extend({notify: 'always'})
@numRelatedObjects = ko.computed(=> _.size(@relatedObjects()))
@loadingRelated = ko.observable(false)
@loadedRelated = ko.observable(false)
@license = ko.observable(object.license)
@user_license = ko.observable(object.user_license)
@user_license.accepted = ko.computed(=> @user_license()?.accepted)
@user_license.pending = ko.computed(=> @user_license()?.pending)
@user_license.unset = ko.computed(=> @user_license()?.unset)
@isSelectable = ko.computed(=>
@selectableClasses == true || (_.isArray(@selectableClasses) && _.includes(@selectableClasses, @className()))
)
if opts.update
@describe().done((item) =>
@update(item)
)
else
@loaded(true)
update: (object) ->
@title(object.title)
@className(object.className || object.klass)
@classIcon("fa fa-fw #{object.fa_class}")
@scope(object.scope)
@path(object.path)
@userName(object.user?.full_name)
@orgName(object.org?.name)
@editable(object.editable)
@accessible(object.accessible)
@public(object.public)
@private(object.private)
@in_space(object.in_space)
@license(object.license)
@user_license(object.user_license)
@all_tags_list(object.all_tags_list)
@loaded(true)
describe: () ->
params = _.defaults(@listModel.apiParams, {
uid: @uid
describe:
include:
all_tags_list: true
user: true
org: true
})
Precision.api("/api/describe", params)
getRelatedObjects: (context) ->
listModel = @selectorModel.getParentTypeFromContext(context, ObjectListModel)
return if !listModel?
if !@loadedRelated()
@loadingRelated(true)
@selectorModel.callsDeferred.done(=>
params =
uid: @uid
opts: _.extend({
describe:
include:
all_tags_list: true
user: true
org: true
}, @selectorModel.listRelatedParams)
Precision.api("/api/list_related", params)
.done((objects) =>
relatedObjects = []
_.each(objects, (object) =>
if @selectorModel.objectsHash[object.uid]?
relatedObjects.push(@selectorModel.objectsHash[object.uid])
else
newObjectModel = new ObjectItemModel(@selectorModel, this, object)
@selectorModel.objectsHash[newObjectModel.uid] = newObjectModel
relatedObjects.push(newObjectModel)
)
@relatedObjects(relatedObjects)
listModel.activeRelatedObjects(@relatedObjects()) if _.size(@relatedObjects()) > 0
)
.fail(@selectorModel.onError)
.always(() =>
@loadingRelated(false)
@loadedRelated(true)
)
)
else if @numRelatedObjects() > 0
listModel.activeRelatedObjects(@relatedObjects())
window.Precision ||= {}
window.Precision.models ||= {}
window.Precision.models.SelectorModel = SelectorModel
$ ->
$('.object-selector-modal .modal-body').on 'scroll', (event) ->
element = $(@).find('.tab-pane.active').find('.list-group').get(1)
return unless element
context = ko.contextFor(element)
currentNumberOfObjects = context.$data.objects().length
if element && context.$data.className == 'file' && (@scrollTop == (@scrollHeight - @offsetHeight)) && currentNumberOfObjects != context.$data.totalCount
context.$data.getObjects(currentNumberOfObjects) |
[
{
"context": "ary'\n custom:\n apiaryApiKey: '123123123'\n apiaryApiName: 'asdadqweqweq'\n\n\n ",
"end": 2222,
"score": 0.9995953440666199,
"start": 2213,
"tag": "KEY",
"value": "123123123"
},
{
"context": "ryApiKey: '123123123'\n apiaryAp... | test/unit/interactive-config-test.coffee | jasonrayles-nbcuni/dredd-public | 0 | {assert} = require 'chai'
sinon = require 'sinon'
proxyquire = require 'proxyquire'
inquirerStub = require 'inquirer'
fsStub = require 'fs'
interactiveConfig = proxyquire '../../src/interactive-config', {
'inquirer': inquirerStub
'fs': fsStub
}
describe 'interactiveConfig', () ->
it 'exports a object', () ->
assert.isObject interactiveConfig
describe '.prompt(config, callback)', () ->
it 'is a defined function', () ->
assert.isFunction interactiveConfig.prompt
describe 'when I call it ', () ->
it 'should run inquirer', (done) ->
sinon.stub inquirerStub, 'prompt', (quesetions, cb) -> cb()
interactiveConfig.prompt {}, () ->
assert.isTrue inquirerStub.prompt.called
done()
describe '.processAnswers(config, answers, callback)', () ->
answers = {}
config = {}
describe 'when no apiary config passed', () ->
before () ->
answers =
blueprint: 'apiary.apib'
server: 'rails server'
endpoint: 'http://localhost:3000'
apiary: true
apiaryApiKey: 'key'
apiaryApiName: 'name'
ciAdd: true
config =
'_': []
custom: {}
describe 'config object passed to callback', () ->
object = {}
before (done) ->
interactiveConfig.processAnswers config, answers, (config) ->
object = config
done()
it 'should have properties set from the config on proper places', () ->
assert.equal object['_'][0], 'apiary.apib'
assert.equal object['_'][1], 'http://localhost:3000'
assert.equal object['server'], 'rails server'
assert.equal object['reporter'], 'apiary'
assert.equal object['custom']['apiaryApiKey'], 'key'
assert.equal object['custom']['apiaryApiName'], 'name'
describe 'when apiary config passed from cli', () ->
before () ->
answers =
blueprint: 'apiary.apib',
server: 'rails server',
endpoint: 'http://localhost:3000',
ciAdd: true
config =
'_': []
reporter: 'apiary'
custom:
apiaryApiKey: '123123123'
apiaryApiName: 'asdadqweqweq'
describe 'config object passed to callback', () ->
object = {}
before (done) ->
interactiveConfig.processAnswers config, answers, (config) ->
object = config
done()
it 'should have properties set from the config on proper places', () ->
assert.equal object['_'][0], 'apiary.apib'
assert.equal object['_'][1], 'http://localhost:3000'
assert.equal object['reporter'], 'apiary'
assert.equal object['custom']['apiaryApiKey'], '123123123'
assert.equal object['custom']['apiaryApiName'], 'asdadqweqweq'
describe '.run(config, callback)', () ->
it 'is a defined function', () ->
assert.isFunction interactiveConfig.run
describe '.updateCircle()', () ->
beforeEach () ->
sinon.stub fsStub, 'writeFileSync'
afterEach () ->
fsStub.writeFileSync.restore()
it 'should save the file', () ->
interactiveConfig.updateCircle()
assert.isTrue fsStub.writeFileSync.called
it 'should save proper config', () ->
describe '.updateTravis()', () ->
beforeEach () ->
sinon.stub fsStub, 'writeFileSync'
afterEach () ->
fsStub.writeFileSync.restore()
it 'should save the file', () ->
interactiveConfig.updateTravis()
assert.isTrue fsStub.writeFileSync.called
| 9675 | {assert} = require 'chai'
sinon = require 'sinon'
proxyquire = require 'proxyquire'
inquirerStub = require 'inquirer'
fsStub = require 'fs'
interactiveConfig = proxyquire '../../src/interactive-config', {
'inquirer': inquirerStub
'fs': fsStub
}
describe 'interactiveConfig', () ->
it 'exports a object', () ->
assert.isObject interactiveConfig
describe '.prompt(config, callback)', () ->
it 'is a defined function', () ->
assert.isFunction interactiveConfig.prompt
describe 'when I call it ', () ->
it 'should run inquirer', (done) ->
sinon.stub inquirerStub, 'prompt', (quesetions, cb) -> cb()
interactiveConfig.prompt {}, () ->
assert.isTrue inquirerStub.prompt.called
done()
describe '.processAnswers(config, answers, callback)', () ->
answers = {}
config = {}
describe 'when no apiary config passed', () ->
before () ->
answers =
blueprint: 'apiary.apib'
server: 'rails server'
endpoint: 'http://localhost:3000'
apiary: true
apiaryApiKey: 'key'
apiaryApiName: 'name'
ciAdd: true
config =
'_': []
custom: {}
describe 'config object passed to callback', () ->
object = {}
before (done) ->
interactiveConfig.processAnswers config, answers, (config) ->
object = config
done()
it 'should have properties set from the config on proper places', () ->
assert.equal object['_'][0], 'apiary.apib'
assert.equal object['_'][1], 'http://localhost:3000'
assert.equal object['server'], 'rails server'
assert.equal object['reporter'], 'apiary'
assert.equal object['custom']['apiaryApiKey'], 'key'
assert.equal object['custom']['apiaryApiName'], 'name'
describe 'when apiary config passed from cli', () ->
before () ->
answers =
blueprint: 'apiary.apib',
server: 'rails server',
endpoint: 'http://localhost:3000',
ciAdd: true
config =
'_': []
reporter: 'apiary'
custom:
apiaryApiKey: '<KEY>'
apiaryApiName: '<KEY>'
describe 'config object passed to callback', () ->
object = {}
before (done) ->
interactiveConfig.processAnswers config, answers, (config) ->
object = config
done()
it 'should have properties set from the config on proper places', () ->
assert.equal object['_'][0], 'apiary.apib'
assert.equal object['_'][1], 'http://localhost:3000'
assert.equal object['reporter'], 'apiary'
assert.equal object['custom']['apiaryApiKey'], '<KEY>'
assert.equal object['custom']['apiaryApiName'], 'as<KEY>weq'
describe '.run(config, callback)', () ->
it 'is a defined function', () ->
assert.isFunction interactiveConfig.run
describe '.updateCircle()', () ->
beforeEach () ->
sinon.stub fsStub, 'writeFileSync'
afterEach () ->
fsStub.writeFileSync.restore()
it 'should save the file', () ->
interactiveConfig.updateCircle()
assert.isTrue fsStub.writeFileSync.called
it 'should save proper config', () ->
describe '.updateTravis()', () ->
beforeEach () ->
sinon.stub fsStub, 'writeFileSync'
afterEach () ->
fsStub.writeFileSync.restore()
it 'should save the file', () ->
interactiveConfig.updateTravis()
assert.isTrue fsStub.writeFileSync.called
| true | {assert} = require 'chai'
sinon = require 'sinon'
proxyquire = require 'proxyquire'
inquirerStub = require 'inquirer'
fsStub = require 'fs'
interactiveConfig = proxyquire '../../src/interactive-config', {
'inquirer': inquirerStub
'fs': fsStub
}
describe 'interactiveConfig', () ->
it 'exports a object', () ->
assert.isObject interactiveConfig
describe '.prompt(config, callback)', () ->
it 'is a defined function', () ->
assert.isFunction interactiveConfig.prompt
describe 'when I call it ', () ->
it 'should run inquirer', (done) ->
sinon.stub inquirerStub, 'prompt', (quesetions, cb) -> cb()
interactiveConfig.prompt {}, () ->
assert.isTrue inquirerStub.prompt.called
done()
describe '.processAnswers(config, answers, callback)', () ->
answers = {}
config = {}
describe 'when no apiary config passed', () ->
before () ->
answers =
blueprint: 'apiary.apib'
server: 'rails server'
endpoint: 'http://localhost:3000'
apiary: true
apiaryApiKey: 'key'
apiaryApiName: 'name'
ciAdd: true
config =
'_': []
custom: {}
describe 'config object passed to callback', () ->
object = {}
before (done) ->
interactiveConfig.processAnswers config, answers, (config) ->
object = config
done()
it 'should have properties set from the config on proper places', () ->
assert.equal object['_'][0], 'apiary.apib'
assert.equal object['_'][1], 'http://localhost:3000'
assert.equal object['server'], 'rails server'
assert.equal object['reporter'], 'apiary'
assert.equal object['custom']['apiaryApiKey'], 'key'
assert.equal object['custom']['apiaryApiName'], 'name'
describe 'when apiary config passed from cli', () ->
before () ->
answers =
blueprint: 'apiary.apib',
server: 'rails server',
endpoint: 'http://localhost:3000',
ciAdd: true
config =
'_': []
reporter: 'apiary'
custom:
apiaryApiKey: 'PI:KEY:<KEY>END_PI'
apiaryApiName: 'PI:KEY:<KEY>END_PI'
describe 'config object passed to callback', () ->
object = {}
before (done) ->
interactiveConfig.processAnswers config, answers, (config) ->
object = config
done()
it 'should have properties set from the config on proper places', () ->
assert.equal object['_'][0], 'apiary.apib'
assert.equal object['_'][1], 'http://localhost:3000'
assert.equal object['reporter'], 'apiary'
assert.equal object['custom']['apiaryApiKey'], 'PI:KEY:<KEY>END_PI'
assert.equal object['custom']['apiaryApiName'], 'asPI:KEY:<KEY>END_PIweq'
describe '.run(config, callback)', () ->
it 'is a defined function', () ->
assert.isFunction interactiveConfig.run
describe '.updateCircle()', () ->
beforeEach () ->
sinon.stub fsStub, 'writeFileSync'
afterEach () ->
fsStub.writeFileSync.restore()
it 'should save the file', () ->
interactiveConfig.updateCircle()
assert.isTrue fsStub.writeFileSync.called
it 'should save proper config', () ->
describe '.updateTravis()', () ->
beforeEach () ->
sinon.stub fsStub, 'writeFileSync'
afterEach () ->
fsStub.writeFileSync.restore()
it 'should save the file', () ->
interactiveConfig.updateTravis()
assert.isTrue fsStub.writeFileSync.called
|
[
{
"context": "th: 800\nproxy:\n use: \"none\"\n socks5:\n host: \"127.0.0.1\"\n port: 1080\n http:\n host: \"127.0.0.1\"\n ",
"end": 187,
"score": 0.9997704029083252,
"start": 178,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "st: \"127.0.0.1\"\n port: 1... | default-config.cson | wafer-li/poi | 0 | poi:
theme: "paperdark"
layout: "horizonal"
window:
x: 60
y: 60
width: 1274
height: 616
webview:
width: 800
proxy:
use: "none"
socks5:
host: "127.0.0.1"
port: 1080
http:
host: "127.0.0.1"
port: 8099
shadowsocks:
server:
host: "106.185.25.115"
port: 27017
local:
port: 12451
password: "@_PoiPublic_@"
method: "aes-256-cfb"
timeout: 600000
| 190514 | poi:
theme: "paperdark"
layout: "horizonal"
window:
x: 60
y: 60
width: 1274
height: 616
webview:
width: 800
proxy:
use: "none"
socks5:
host: "127.0.0.1"
port: 1080
http:
host: "127.0.0.1"
port: 8099
shadowsocks:
server:
host: "172.16.17.32"
port: 27017
local:
port: 12451
password: <PASSWORD>@"
method: "aes-256-cfb"
timeout: 600000
| true | poi:
theme: "paperdark"
layout: "horizonal"
window:
x: 60
y: 60
width: 1274
height: 616
webview:
width: 800
proxy:
use: "none"
socks5:
host: "127.0.0.1"
port: 1080
http:
host: "127.0.0.1"
port: 8099
shadowsocks:
server:
host: "PI:IP_ADDRESS:172.16.17.32END_PI"
port: 27017
local:
port: 12451
password: PI:PASSWORD:<PASSWORD>END_PI@"
method: "aes-256-cfb"
timeout: 600000
|
[
{
"context": " Rule to check for max length on a line.\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n{i",
"end": 82,
"score": 0.9997696876525879,
"start": 71,
"tag": "NAME",
"value": "Matt DuVall"
}
] | src/rules/max-len.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to check for max length on a line.
# @author Matt DuVall <http://www.mattduvall.com>
###
'use strict'
{isString} = require 'lodash'
#------------------------------------------------------------------------------
# Constants
#------------------------------------------------------------------------------
OPTIONS_SCHEMA =
type: 'object'
properties:
code:
type: 'integer'
minimum: 0
comments:
type: 'integer'
minimum: 0
tabWidth:
type: 'integer'
minimum: 0
ignorePattern:
type: 'string'
ignoreComments:
type: 'boolean'
ignoreStrings:
type: 'boolean'
ignoreUrls:
type: 'boolean'
ignoreTemplateLiterals:
type: 'boolean'
ignoreRegExpLiterals:
type: 'boolean'
ignoreTrailingComments:
type: 'boolean'
additionalProperties: no
OPTIONS_OR_INTEGER_SCHEMA =
anyOf: [
OPTIONS_SCHEMA
,
type: 'integer'
minimum: 0
]
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce a maximum line length'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/max-len'
schema: [
OPTIONS_OR_INTEGER_SCHEMA
OPTIONS_OR_INTEGER_SCHEMA
OPTIONS_SCHEMA
]
create: (context) ->
###
# Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
# - They're matching an entire string that we know is a URI
# - We're matching part of a string where we think there *might* be a URL
# - We're only concerned about URLs, as picking out any URI would cause
# too many false positives
# - We don't care about matching the entire URL, any small segment is fine
###
URL_REGEXP = /[^:/?#]:\/\/[^?#]/
sourceCode = context.getSourceCode()
###*
# Computes the length of a line that may contain tabs. The width of each
# tab will be the number of spaces to the next tab stop.
# @param {string} line The line.
# @param {int} tabWidth The width of each tab stop in spaces.
# @returns {int} The computed line length.
# @private
###
computeLineLength = (line, tabWidth) ->
extraCharacterCount = 0
line.replace /\t/g, (match, offset) ->
totalOffset = offset + extraCharacterCount
previousTabStopOffset = if tabWidth then totalOffset % tabWidth else 0
spaceCount = tabWidth - previousTabStopOffset
extraCharacterCount += spaceCount - 1 # -1 for the replaced tab
Array.from(line).length + extraCharacterCount
# The options object must be the last option specified…
lastOption = context.options[context.options.length - 1]
options =
if typeof lastOption is 'object'
Object.create lastOption
else
{}
# …but max code length…
if typeof context.options[0] is 'number'
options.code = context.options[0]
# …and tabWidth can be optionally specified directly as integers.
if typeof context.options[1] is 'number'
options.tabWidth = context.options[1]
maxLength = options.code or 80
tabWidth = options.tabWidth or 4
ignoreComments = options.ignoreComments or no
ignoreStrings = options.ignoreStrings or no
ignoreTemplateLiterals = options.ignoreTemplateLiterals or no
ignoreRegExpLiterals = options.ignoreRegExpLiterals or no
ignoreTrailingComments =
options.ignoreTrailingComments or options.ignoreComments or no
ignoreUrls = options.ignoreUrls or no
maxCommentLength = options.comments
ignorePattern = options.ignorePattern or null
if ignorePattern then ignorePattern = new RegExp ignorePattern
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# Tells if a given comment is trailing: it starts on the current line and
# extends to or past the end of the current line.
# @param {string} line The source line we want to check for a trailing comment on
# @param {number} lineNumber The one-indexed line number for line
# @param {ASTNode} comment The comment to inspect
# @returns {boolean} If the comment is trailing on the given line
###
isTrailingComment = (line, lineNumber, comment) ->
comment and
(comment.loc.start.line is lineNumber and
lineNumber <= comment.loc.end.line) and
(comment.loc.end.line > lineNumber or
comment.loc.end.column is line.length)
###*
# Tells if a comment encompasses the entire line.
# @param {string} line The source line with a trailing comment
# @param {number} lineNumber The one-indexed line number this is on
# @param {ASTNode} comment The comment to remove
# @returns {boolean} If the comment covers the entire line
###
isFullLineComment = (line, lineNumber, comment) ->
{start, end} = comment.loc
isFirstTokenOnLine = not line.slice(0, comment.loc.start.column).trim()
(start.line < lineNumber or
(start.line is lineNumber and isFirstTokenOnLine)) and
(end.line > lineNumber or
(end.line is lineNumber and end.column is line.length))
###*
# Gets the line after the comment and any remaining trailing whitespace is
# stripped.
# @param {string} line The source line with a trailing comment
# @param {ASTNode} comment The comment to remove
# @returns {string} Line without comment and trailing whitepace
###
stripTrailingComment = (line, comment) ->
# loc.column is zero-indexed
line.slice(0, comment.loc.start.column).replace /\s+$/, ''
###*
# Ensure that an array exists at [key] on `object`, and add `value` to it.
#
# @param {Object} object the object to mutate
# @param {string} key the object's key
# @param {*} value the value to add
# @returns {void}
# @private
###
ensureArrayAndPush = (object, key, value) ->
unless Array.isArray object[key] then object[key] = []
object[key].push value
allStringLiterals = []
###*
# Retrieves an array containing all strings (" or ') in the source code.
#
# @returns {ASTNode[]} An array of string nodes.
###
getAllStrings = ->
# sourceCode.ast.tokens.filter (token) ->
# token.type is 'String' or
# (token.type is 'JSXText' and
# sourceCode.getNodeByRangeIndex(token.range[0] - 1).type is
# 'JSXAttribute')
allStringLiterals
allTemplateLiterals = []
###*
# Retrieves an array containing all template literals in the source code.
#
# @returns {ASTNode[]} An array of template literal nodes.
###
getAllTemplateLiterals = ->
# sourceCode.ast.tokens.filter (token) -> token.type is 'Template'
allTemplateLiterals
###*
# Retrieves an array containing all RegExp literals in the source code.
#
# @returns {ASTNode[]} An array of RegExp literal nodes.
###
getAllRegExpLiterals = ->
sourceCode.ast.tokens.filter (token) -> token.type is 'RegularExpression'
###*
# A reducer to group an AST node by line number, both start and end.
#
# @param {Object} acc the accumulator
# @param {ASTNode} node the AST node in question
# @returns {Object} the modified accumulator
# @private
###
groupByLineNumber = (acc, node) ->
i = node.loc.start.line
while i <= node.loc.end.line
ensureArrayAndPush acc, i, node
++i
acc
###*
# Check the program for max length
# @param {ASTNode} node Node to examine
# @returns {void}
# @private
###
checkProgramForMaxLength = (node) ->
# split (honors line-ending)
{lines} = sourceCode
# list of comments to ignore
comments =
if ignoreComments or maxCommentLength or ignoreTrailingComments
sourceCode.getAllComments()
else
[]
# we iterate over comments in parallel with the lines
commentsIndex = 0
strings = getAllStrings()
stringsByLine = strings.reduce groupByLineNumber, {}
templateLiterals = getAllTemplateLiterals()
templateLiteralsByLine = templateLiterals.reduce groupByLineNumber, {}
regExpLiterals = getAllRegExpLiterals()
regExpLiteralsByLine = regExpLiterals.reduce groupByLineNumber, {}
lines.forEach (line, i) ->
# i is zero-indexed, line numbers are one-indexed
lineNumber = i + 1
###
# if we're checking comment length; we need to know whether this
# line is a comment
###
lineIsComment = no
###
# We can short-circuit the comment checks if we're already out of
# comments to check.
###
if commentsIndex < comments.length
# iterate over comments until we find one past the current line
while (
(comment = comments[++commentsIndex]) and
comment.loc.start.line <= lineNumber
)
# eslint-disable-line no-empty
;
# and step back by one
comment = comments[--commentsIndex]
if isFullLineComment line, lineNumber, comment
lineIsComment = yes
textToMeasure = line
else if (
ignoreTrailingComments and
isTrailingComment line, lineNumber, comment
)
textToMeasure = stripTrailingComment line, comment
else
textToMeasure = line
else
textToMeasure = line
# ignore this line
return if (
ignorePattern?.test(textToMeasure) or
(ignoreUrls and URL_REGEXP.test(textToMeasure)) or
(ignoreStrings and stringsByLine[lineNumber]) or
(ignoreTemplateLiterals and templateLiteralsByLine[lineNumber]) or
(ignoreRegExpLiterals and regExpLiteralsByLine[lineNumber])
)
lineLength = computeLineLength textToMeasure, tabWidth
commentLengthApplies = lineIsComment and maxCommentLength
return if lineIsComment and ignoreComments
if commentLengthApplies
if lineLength > maxCommentLength
context.report {
node
loc: line: lineNumber, column: 0
message:
'Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}.'
data: {
lineNumber: i + 1
maxCommentLength
}
}
else if lineLength > maxLength
context.report {
node
loc: line: lineNumber, column: 0
message:
'Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.'
data: {
lineNumber: i + 1
maxLength
}
}
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
TemplateLiteral: (node) ->
allTemplateLiterals.push node
Literal: (node) ->
allStringLiterals.push node if (
isString(node.value) and node.parent.type isnt 'JSXElement'
)
'Program:exit': checkProgramForMaxLength
| 5262 | ###*
# @fileoverview Rule to check for max length on a line.
# @author <NAME> <http://www.mattduvall.com>
###
'use strict'
{isString} = require 'lodash'
#------------------------------------------------------------------------------
# Constants
#------------------------------------------------------------------------------
OPTIONS_SCHEMA =
type: 'object'
properties:
code:
type: 'integer'
minimum: 0
comments:
type: 'integer'
minimum: 0
tabWidth:
type: 'integer'
minimum: 0
ignorePattern:
type: 'string'
ignoreComments:
type: 'boolean'
ignoreStrings:
type: 'boolean'
ignoreUrls:
type: 'boolean'
ignoreTemplateLiterals:
type: 'boolean'
ignoreRegExpLiterals:
type: 'boolean'
ignoreTrailingComments:
type: 'boolean'
additionalProperties: no
OPTIONS_OR_INTEGER_SCHEMA =
anyOf: [
OPTIONS_SCHEMA
,
type: 'integer'
minimum: 0
]
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce a maximum line length'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/max-len'
schema: [
OPTIONS_OR_INTEGER_SCHEMA
OPTIONS_OR_INTEGER_SCHEMA
OPTIONS_SCHEMA
]
create: (context) ->
###
# Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
# - They're matching an entire string that we know is a URI
# - We're matching part of a string where we think there *might* be a URL
# - We're only concerned about URLs, as picking out any URI would cause
# too many false positives
# - We don't care about matching the entire URL, any small segment is fine
###
URL_REGEXP = /[^:/?#]:\/\/[^?#]/
sourceCode = context.getSourceCode()
###*
# Computes the length of a line that may contain tabs. The width of each
# tab will be the number of spaces to the next tab stop.
# @param {string} line The line.
# @param {int} tabWidth The width of each tab stop in spaces.
# @returns {int} The computed line length.
# @private
###
computeLineLength = (line, tabWidth) ->
extraCharacterCount = 0
line.replace /\t/g, (match, offset) ->
totalOffset = offset + extraCharacterCount
previousTabStopOffset = if tabWidth then totalOffset % tabWidth else 0
spaceCount = tabWidth - previousTabStopOffset
extraCharacterCount += spaceCount - 1 # -1 for the replaced tab
Array.from(line).length + extraCharacterCount
# The options object must be the last option specified…
lastOption = context.options[context.options.length - 1]
options =
if typeof lastOption is 'object'
Object.create lastOption
else
{}
# …but max code length…
if typeof context.options[0] is 'number'
options.code = context.options[0]
# …and tabWidth can be optionally specified directly as integers.
if typeof context.options[1] is 'number'
options.tabWidth = context.options[1]
maxLength = options.code or 80
tabWidth = options.tabWidth or 4
ignoreComments = options.ignoreComments or no
ignoreStrings = options.ignoreStrings or no
ignoreTemplateLiterals = options.ignoreTemplateLiterals or no
ignoreRegExpLiterals = options.ignoreRegExpLiterals or no
ignoreTrailingComments =
options.ignoreTrailingComments or options.ignoreComments or no
ignoreUrls = options.ignoreUrls or no
maxCommentLength = options.comments
ignorePattern = options.ignorePattern or null
if ignorePattern then ignorePattern = new RegExp ignorePattern
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# Tells if a given comment is trailing: it starts on the current line and
# extends to or past the end of the current line.
# @param {string} line The source line we want to check for a trailing comment on
# @param {number} lineNumber The one-indexed line number for line
# @param {ASTNode} comment The comment to inspect
# @returns {boolean} If the comment is trailing on the given line
###
isTrailingComment = (line, lineNumber, comment) ->
comment and
(comment.loc.start.line is lineNumber and
lineNumber <= comment.loc.end.line) and
(comment.loc.end.line > lineNumber or
comment.loc.end.column is line.length)
###*
# Tells if a comment encompasses the entire line.
# @param {string} line The source line with a trailing comment
# @param {number} lineNumber The one-indexed line number this is on
# @param {ASTNode} comment The comment to remove
# @returns {boolean} If the comment covers the entire line
###
isFullLineComment = (line, lineNumber, comment) ->
{start, end} = comment.loc
isFirstTokenOnLine = not line.slice(0, comment.loc.start.column).trim()
(start.line < lineNumber or
(start.line is lineNumber and isFirstTokenOnLine)) and
(end.line > lineNumber or
(end.line is lineNumber and end.column is line.length))
###*
# Gets the line after the comment and any remaining trailing whitespace is
# stripped.
# @param {string} line The source line with a trailing comment
# @param {ASTNode} comment The comment to remove
# @returns {string} Line without comment and trailing whitepace
###
stripTrailingComment = (line, comment) ->
# loc.column is zero-indexed
line.slice(0, comment.loc.start.column).replace /\s+$/, ''
###*
# Ensure that an array exists at [key] on `object`, and add `value` to it.
#
# @param {Object} object the object to mutate
# @param {string} key the object's key
# @param {*} value the value to add
# @returns {void}
# @private
###
ensureArrayAndPush = (object, key, value) ->
unless Array.isArray object[key] then object[key] = []
object[key].push value
allStringLiterals = []
###*
# Retrieves an array containing all strings (" or ') in the source code.
#
# @returns {ASTNode[]} An array of string nodes.
###
getAllStrings = ->
# sourceCode.ast.tokens.filter (token) ->
# token.type is 'String' or
# (token.type is 'JSXText' and
# sourceCode.getNodeByRangeIndex(token.range[0] - 1).type is
# 'JSXAttribute')
allStringLiterals
allTemplateLiterals = []
###*
# Retrieves an array containing all template literals in the source code.
#
# @returns {ASTNode[]} An array of template literal nodes.
###
getAllTemplateLiterals = ->
# sourceCode.ast.tokens.filter (token) -> token.type is 'Template'
allTemplateLiterals
###*
# Retrieves an array containing all RegExp literals in the source code.
#
# @returns {ASTNode[]} An array of RegExp literal nodes.
###
getAllRegExpLiterals = ->
sourceCode.ast.tokens.filter (token) -> token.type is 'RegularExpression'
###*
# A reducer to group an AST node by line number, both start and end.
#
# @param {Object} acc the accumulator
# @param {ASTNode} node the AST node in question
# @returns {Object} the modified accumulator
# @private
###
groupByLineNumber = (acc, node) ->
i = node.loc.start.line
while i <= node.loc.end.line
ensureArrayAndPush acc, i, node
++i
acc
###*
# Check the program for max length
# @param {ASTNode} node Node to examine
# @returns {void}
# @private
###
checkProgramForMaxLength = (node) ->
# split (honors line-ending)
{lines} = sourceCode
# list of comments to ignore
comments =
if ignoreComments or maxCommentLength or ignoreTrailingComments
sourceCode.getAllComments()
else
[]
# we iterate over comments in parallel with the lines
commentsIndex = 0
strings = getAllStrings()
stringsByLine = strings.reduce groupByLineNumber, {}
templateLiterals = getAllTemplateLiterals()
templateLiteralsByLine = templateLiterals.reduce groupByLineNumber, {}
regExpLiterals = getAllRegExpLiterals()
regExpLiteralsByLine = regExpLiterals.reduce groupByLineNumber, {}
lines.forEach (line, i) ->
# i is zero-indexed, line numbers are one-indexed
lineNumber = i + 1
###
# if we're checking comment length; we need to know whether this
# line is a comment
###
lineIsComment = no
###
# We can short-circuit the comment checks if we're already out of
# comments to check.
###
if commentsIndex < comments.length
# iterate over comments until we find one past the current line
while (
(comment = comments[++commentsIndex]) and
comment.loc.start.line <= lineNumber
)
# eslint-disable-line no-empty
;
# and step back by one
comment = comments[--commentsIndex]
if isFullLineComment line, lineNumber, comment
lineIsComment = yes
textToMeasure = line
else if (
ignoreTrailingComments and
isTrailingComment line, lineNumber, comment
)
textToMeasure = stripTrailingComment line, comment
else
textToMeasure = line
else
textToMeasure = line
# ignore this line
return if (
ignorePattern?.test(textToMeasure) or
(ignoreUrls and URL_REGEXP.test(textToMeasure)) or
(ignoreStrings and stringsByLine[lineNumber]) or
(ignoreTemplateLiterals and templateLiteralsByLine[lineNumber]) or
(ignoreRegExpLiterals and regExpLiteralsByLine[lineNumber])
)
lineLength = computeLineLength textToMeasure, tabWidth
commentLengthApplies = lineIsComment and maxCommentLength
return if lineIsComment and ignoreComments
if commentLengthApplies
if lineLength > maxCommentLength
context.report {
node
loc: line: lineNumber, column: 0
message:
'Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}.'
data: {
lineNumber: i + 1
maxCommentLength
}
}
else if lineLength > maxLength
context.report {
node
loc: line: lineNumber, column: 0
message:
'Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.'
data: {
lineNumber: i + 1
maxLength
}
}
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
TemplateLiteral: (node) ->
allTemplateLiterals.push node
Literal: (node) ->
allStringLiterals.push node if (
isString(node.value) and node.parent.type isnt 'JSXElement'
)
'Program:exit': checkProgramForMaxLength
| true | ###*
# @fileoverview Rule to check for max length on a line.
# @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com>
###
'use strict'
{isString} = require 'lodash'
#------------------------------------------------------------------------------
# Constants
#------------------------------------------------------------------------------
OPTIONS_SCHEMA =
type: 'object'
properties:
code:
type: 'integer'
minimum: 0
comments:
type: 'integer'
minimum: 0
tabWidth:
type: 'integer'
minimum: 0
ignorePattern:
type: 'string'
ignoreComments:
type: 'boolean'
ignoreStrings:
type: 'boolean'
ignoreUrls:
type: 'boolean'
ignoreTemplateLiterals:
type: 'boolean'
ignoreRegExpLiterals:
type: 'boolean'
ignoreTrailingComments:
type: 'boolean'
additionalProperties: no
OPTIONS_OR_INTEGER_SCHEMA =
anyOf: [
OPTIONS_SCHEMA
,
type: 'integer'
minimum: 0
]
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce a maximum line length'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/max-len'
schema: [
OPTIONS_OR_INTEGER_SCHEMA
OPTIONS_OR_INTEGER_SCHEMA
OPTIONS_SCHEMA
]
create: (context) ->
###
# Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
# - They're matching an entire string that we know is a URI
# - We're matching part of a string where we think there *might* be a URL
# - We're only concerned about URLs, as picking out any URI would cause
# too many false positives
# - We don't care about matching the entire URL, any small segment is fine
###
URL_REGEXP = /[^:/?#]:\/\/[^?#]/
sourceCode = context.getSourceCode()
###*
# Computes the length of a line that may contain tabs. The width of each
# tab will be the number of spaces to the next tab stop.
# @param {string} line The line.
# @param {int} tabWidth The width of each tab stop in spaces.
# @returns {int} The computed line length.
# @private
###
computeLineLength = (line, tabWidth) ->
extraCharacterCount = 0
line.replace /\t/g, (match, offset) ->
totalOffset = offset + extraCharacterCount
previousTabStopOffset = if tabWidth then totalOffset % tabWidth else 0
spaceCount = tabWidth - previousTabStopOffset
extraCharacterCount += spaceCount - 1 # -1 for the replaced tab
Array.from(line).length + extraCharacterCount
# The options object must be the last option specified…
lastOption = context.options[context.options.length - 1]
options =
if typeof lastOption is 'object'
Object.create lastOption
else
{}
# …but max code length…
if typeof context.options[0] is 'number'
options.code = context.options[0]
# …and tabWidth can be optionally specified directly as integers.
if typeof context.options[1] is 'number'
options.tabWidth = context.options[1]
maxLength = options.code or 80
tabWidth = options.tabWidth or 4
ignoreComments = options.ignoreComments or no
ignoreStrings = options.ignoreStrings or no
ignoreTemplateLiterals = options.ignoreTemplateLiterals or no
ignoreRegExpLiterals = options.ignoreRegExpLiterals or no
ignoreTrailingComments =
options.ignoreTrailingComments or options.ignoreComments or no
ignoreUrls = options.ignoreUrls or no
maxCommentLength = options.comments
ignorePattern = options.ignorePattern or null
if ignorePattern then ignorePattern = new RegExp ignorePattern
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
###*
# Tells if a given comment is trailing: it starts on the current line and
# extends to or past the end of the current line.
# @param {string} line The source line we want to check for a trailing comment on
# @param {number} lineNumber The one-indexed line number for line
# @param {ASTNode} comment The comment to inspect
# @returns {boolean} If the comment is trailing on the given line
###
isTrailingComment = (line, lineNumber, comment) ->
comment and
(comment.loc.start.line is lineNumber and
lineNumber <= comment.loc.end.line) and
(comment.loc.end.line > lineNumber or
comment.loc.end.column is line.length)
###*
# Tells if a comment encompasses the entire line.
# @param {string} line The source line with a trailing comment
# @param {number} lineNumber The one-indexed line number this is on
# @param {ASTNode} comment The comment to remove
# @returns {boolean} If the comment covers the entire line
###
isFullLineComment = (line, lineNumber, comment) ->
{start, end} = comment.loc
isFirstTokenOnLine = not line.slice(0, comment.loc.start.column).trim()
(start.line < lineNumber or
(start.line is lineNumber and isFirstTokenOnLine)) and
(end.line > lineNumber or
(end.line is lineNumber and end.column is line.length))
###*
# Gets the line after the comment and any remaining trailing whitespace is
# stripped.
# @param {string} line The source line with a trailing comment
# @param {ASTNode} comment The comment to remove
# @returns {string} Line without comment and trailing whitepace
###
stripTrailingComment = (line, comment) ->
# loc.column is zero-indexed
line.slice(0, comment.loc.start.column).replace /\s+$/, ''
###*
# Ensure that an array exists at [key] on `object`, and add `value` to it.
#
# @param {Object} object the object to mutate
# @param {string} key the object's key
# @param {*} value the value to add
# @returns {void}
# @private
###
ensureArrayAndPush = (object, key, value) ->
unless Array.isArray object[key] then object[key] = []
object[key].push value
allStringLiterals = []
###*
# Retrieves an array containing all strings (" or ') in the source code.
#
# @returns {ASTNode[]} An array of string nodes.
###
getAllStrings = ->
# sourceCode.ast.tokens.filter (token) ->
# token.type is 'String' or
# (token.type is 'JSXText' and
# sourceCode.getNodeByRangeIndex(token.range[0] - 1).type is
# 'JSXAttribute')
allStringLiterals
allTemplateLiterals = []
###*
# Retrieves an array containing all template literals in the source code.
#
# @returns {ASTNode[]} An array of template literal nodes.
###
getAllTemplateLiterals = ->
# sourceCode.ast.tokens.filter (token) -> token.type is 'Template'
allTemplateLiterals
###*
# Retrieves an array containing all RegExp literals in the source code.
#
# @returns {ASTNode[]} An array of RegExp literal nodes.
###
getAllRegExpLiterals = ->
sourceCode.ast.tokens.filter (token) -> token.type is 'RegularExpression'
###*
# A reducer to group an AST node by line number, both start and end.
#
# @param {Object} acc the accumulator
# @param {ASTNode} node the AST node in question
# @returns {Object} the modified accumulator
# @private
###
groupByLineNumber = (acc, node) ->
i = node.loc.start.line
while i <= node.loc.end.line
ensureArrayAndPush acc, i, node
++i
acc
###*
# Check the program for max length
# @param {ASTNode} node Node to examine
# @returns {void}
# @private
###
checkProgramForMaxLength = (node) ->
# split (honors line-ending)
{lines} = sourceCode
# list of comments to ignore
comments =
if ignoreComments or maxCommentLength or ignoreTrailingComments
sourceCode.getAllComments()
else
[]
# we iterate over comments in parallel with the lines
commentsIndex = 0
strings = getAllStrings()
stringsByLine = strings.reduce groupByLineNumber, {}
templateLiterals = getAllTemplateLiterals()
templateLiteralsByLine = templateLiterals.reduce groupByLineNumber, {}
regExpLiterals = getAllRegExpLiterals()
regExpLiteralsByLine = regExpLiterals.reduce groupByLineNumber, {}
lines.forEach (line, i) ->
# i is zero-indexed, line numbers are one-indexed
lineNumber = i + 1
###
# if we're checking comment length; we need to know whether this
# line is a comment
###
lineIsComment = no
###
# We can short-circuit the comment checks if we're already out of
# comments to check.
###
if commentsIndex < comments.length
# iterate over comments until we find one past the current line
while (
(comment = comments[++commentsIndex]) and
comment.loc.start.line <= lineNumber
)
# eslint-disable-line no-empty
;
# and step back by one
comment = comments[--commentsIndex]
if isFullLineComment line, lineNumber, comment
lineIsComment = yes
textToMeasure = line
else if (
ignoreTrailingComments and
isTrailingComment line, lineNumber, comment
)
textToMeasure = stripTrailingComment line, comment
else
textToMeasure = line
else
textToMeasure = line
# ignore this line
return if (
ignorePattern?.test(textToMeasure) or
(ignoreUrls and URL_REGEXP.test(textToMeasure)) or
(ignoreStrings and stringsByLine[lineNumber]) or
(ignoreTemplateLiterals and templateLiteralsByLine[lineNumber]) or
(ignoreRegExpLiterals and regExpLiteralsByLine[lineNumber])
)
lineLength = computeLineLength textToMeasure, tabWidth
commentLengthApplies = lineIsComment and maxCommentLength
return if lineIsComment and ignoreComments
if commentLengthApplies
if lineLength > maxCommentLength
context.report {
node
loc: line: lineNumber, column: 0
message:
'Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}.'
data: {
lineNumber: i + 1
maxCommentLength
}
}
else if lineLength > maxLength
context.report {
node
loc: line: lineNumber, column: 0
message:
'Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.'
data: {
lineNumber: i + 1
maxLength
}
}
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
TemplateLiteral: (node) ->
allTemplateLiterals.push node
Literal: (node) ->
allStringLiterals.push node if (
isString(node.value) and node.parent.type isnt 'JSXElement'
)
'Program:exit': checkProgramForMaxLength
|
[
{
"context": "'scopeName': 'source.ruby.hanami'\n'name': 'Hanami'\n'fileTypes': [\n 'rb'\n 'Gemfile'\n]\n'patterns",
"end": 46,
"score": 0.7288309335708618,
"start": 43,
"tag": "NAME",
"value": "Han"
}
] | grammars/hanami.cson | shiroginne/language-hanami | 1 | 'scopeName': 'source.ruby.hanami'
'name': 'Hanami'
'fileTypes': [
'rb'
'Gemfile'
]
'patterns': [
{
'begin': '(^\\s*)(?=class\\s+(([.a-zA-Z0-9_:]+Web::Controllers\\b(\\s*<\\s*[.a-zA-Z0-9_:]+)?)|(<<\\s*[.a-zA-Z0-9_:]+)))(?!.+\\bend\\b)'
'comment': 'Uses lookahead to match classes with the Web::Controllers suffix; includes \'source.ruby\' to avoid infinite recursion'
'end': '^\\1(?=end)\\b'
'name': 'meta.hanami.controller'
'patterns': [
{
'include': 'source.ruby'
}
{
'include': '$self'
}
]
}
{
'include': 'source.ruby'
}
]
| 225838 | 'scopeName': 'source.ruby.hanami'
'name': '<NAME>ami'
'fileTypes': [
'rb'
'Gemfile'
]
'patterns': [
{
'begin': '(^\\s*)(?=class\\s+(([.a-zA-Z0-9_:]+Web::Controllers\\b(\\s*<\\s*[.a-zA-Z0-9_:]+)?)|(<<\\s*[.a-zA-Z0-9_:]+)))(?!.+\\bend\\b)'
'comment': 'Uses lookahead to match classes with the Web::Controllers suffix; includes \'source.ruby\' to avoid infinite recursion'
'end': '^\\1(?=end)\\b'
'name': 'meta.hanami.controller'
'patterns': [
{
'include': 'source.ruby'
}
{
'include': '$self'
}
]
}
{
'include': 'source.ruby'
}
]
| true | 'scopeName': 'source.ruby.hanami'
'name': 'PI:NAME:<NAME>END_PIami'
'fileTypes': [
'rb'
'Gemfile'
]
'patterns': [
{
'begin': '(^\\s*)(?=class\\s+(([.a-zA-Z0-9_:]+Web::Controllers\\b(\\s*<\\s*[.a-zA-Z0-9_:]+)?)|(<<\\s*[.a-zA-Z0-9_:]+)))(?!.+\\bend\\b)'
'comment': 'Uses lookahead to match classes with the Web::Controllers suffix; includes \'source.ruby\' to avoid infinite recursion'
'end': '^\\1(?=end)\\b'
'name': 'meta.hanami.controller'
'patterns': [
{
'include': 'source.ruby'
}
{
'include': '$self'
}
]
}
{
'include': 'source.ruby'
}
]
|
[
{
"context": "ed()\n\n @brain.quack {},\n message: \"Hi, ducky\"",
"end": 415,
"score": 0.793078601360321,
"start": 410,
"tag": "NAME",
"value": "ducky"
}
] | test/coffeescript/tests/brain_test.coffee | stefano81/rubber_duck | 52 | describe "The Brain", ->
it "can be instantiated", ->
expect ->
new duck.Brain(->)
.not.toThrow()
describe "when processing text", ->
beforeEach ->
@duck = ->
@brain = new duck.Brain(@duck)
it "can give an answer", ->
$(@duck).on 'response', (event, response)->
expect(response['next_question']).toBeDefined()
@brain.quack {},
message: "Hi, ducky" | 70333 | describe "The Brain", ->
it "can be instantiated", ->
expect ->
new duck.Brain(->)
.not.toThrow()
describe "when processing text", ->
beforeEach ->
@duck = ->
@brain = new duck.Brain(@duck)
it "can give an answer", ->
$(@duck).on 'response', (event, response)->
expect(response['next_question']).toBeDefined()
@brain.quack {},
message: "Hi, <NAME>" | true | describe "The Brain", ->
it "can be instantiated", ->
expect ->
new duck.Brain(->)
.not.toThrow()
describe "when processing text", ->
beforeEach ->
@duck = ->
@brain = new duck.Brain(@duck)
it "can give an answer", ->
$(@duck).on 'response', (event, response)->
expect(response['next_question']).toBeDefined()
@brain.quack {},
message: "Hi, PI:NAME:<NAME>END_PI" |
[
{
"context": "\n vendor: vendor\n code: code\n name: name\n price: displayPrice(price, rounded)\n )\n",
"end": 687,
"score": 0.9570372700691223,
"start": 683,
"tag": "NAME",
"value": "name"
}
] | kirppu/static_src/js/checkout/printreceipttable.coffee | kcsry/kirppu | 0 | class @PrintReceiptTable
@strCode: gettext("code")
@strItem: gettext("item")
@strPrice: gettext("price")
@strVendor: gettext("vendor")
constructor: (caption=null)->
@table = $ Templates.render("receipt_table",
caption: caption
vendor: @constructor.strVendor
code: @constructor.strCode
item: @constructor.strItem
price: @constructor.strPrice
)
@body = $("tbody", @table)
@joinedLine: (text="") ->
Templates.render("receipt_table_row",
joined: true
text: text
)
@createRow: (vendor, code, name, price, rounded) ->
Templates.render("receipt_table_row",
vendor: vendor
code: code
name: name
price: displayPrice(price, rounded)
)
| 23681 | class @PrintReceiptTable
@strCode: gettext("code")
@strItem: gettext("item")
@strPrice: gettext("price")
@strVendor: gettext("vendor")
constructor: (caption=null)->
@table = $ Templates.render("receipt_table",
caption: caption
vendor: @constructor.strVendor
code: @constructor.strCode
item: @constructor.strItem
price: @constructor.strPrice
)
@body = $("tbody", @table)
@joinedLine: (text="") ->
Templates.render("receipt_table_row",
joined: true
text: text
)
@createRow: (vendor, code, name, price, rounded) ->
Templates.render("receipt_table_row",
vendor: vendor
code: code
name: <NAME>
price: displayPrice(price, rounded)
)
| true | class @PrintReceiptTable
@strCode: gettext("code")
@strItem: gettext("item")
@strPrice: gettext("price")
@strVendor: gettext("vendor")
constructor: (caption=null)->
@table = $ Templates.render("receipt_table",
caption: caption
vendor: @constructor.strVendor
code: @constructor.strCode
item: @constructor.strItem
price: @constructor.strPrice
)
@body = $("tbody", @table)
@joinedLine: (text="") ->
Templates.render("receipt_table_row",
joined: true
text: text
)
@createRow: (vendor, code, name, price, rounded) ->
Templates.render("receipt_table_row",
vendor: vendor
code: code
name: PI:NAME:<NAME>END_PI
price: displayPrice(price, rounded)
)
|
[
{
"context": "ing\n\ndescribe 'Wongo Find', ->\n\n docs = [{name: 'Meow'}, {name: 'Boo', selectField: 'Cow'}, {name: 'Fra",
"end": 186,
"score": 0.9759775400161743,
"start": 182,
"tag": "NAME",
"value": "Meow"
},
{
"context": "ongo Find', ->\n\n docs = [{name: 'Meow'}, {name: 'Boo'... | test/find.test.coffee | wookets/wongo | 0 | assert = require 'assert'
wongo = require '../lib/wongo'
wongo.schema 'MockFind',
fields:
name: String
selectField: String
describe 'Wongo Find', ->
docs = [{name: 'Meow'}, {name: 'Boo', selectField: 'Cow'}, {name: 'Fran'}, {name: 'Kitty'}, {name: 'Woof'}]
it 'should be able to save all documents', (done) ->
wongo.save 'MockFind', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to find all documents', (done) ->
query = {}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result?.length, 5)
done()
it 'should be able to find one document from many', (done) ->
query = {}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.ok(result)
done()
it 'should be able to find one document by name', (done) ->
query = {name: 'Boo'}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.name, 'Boo')
done()
it 'should be able to find documents by name', (done) ->
query = {name: 'Fran'}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 1)
assert.equal(result[0].name, 'Fran')
done()
it 'should be able to find select fields on document', (done) ->
query = {select: 'name', where: {name: 'Boo'}}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.name, 'Boo')
assert.ok(not result.selectField)
done()
it 'should be able to find documents by name with where', (done) ->
query = {where: {name: 'Fran'}}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 1)
assert.equal(result[0].name, 'Fran')
done()
it 'should be able to limit documents to 3', (done) ->
query = {where: {}, limit: 3}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 3)
done() | 79786 | assert = require 'assert'
wongo = require '../lib/wongo'
wongo.schema 'MockFind',
fields:
name: String
selectField: String
describe 'Wongo Find', ->
docs = [{name: '<NAME>'}, {name: '<NAME>', selectField: '<NAME>'}, {name: '<NAME>'}, {name: '<NAME>'}, {name: '<NAME>'}]
it 'should be able to save all documents', (done) ->
wongo.save 'MockFind', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to find all documents', (done) ->
query = {}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result?.length, 5)
done()
it 'should be able to find one document from many', (done) ->
query = {}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.ok(result)
done()
it 'should be able to find one document by name', (done) ->
query = {name: '<NAME>'}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.name, 'Boo')
done()
it 'should be able to find documents by name', (done) ->
query = {name: '<NAME>'}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 1)
assert.equal(result[0].name, '<NAME>')
done()
it 'should be able to find select fields on document', (done) ->
query = {select: 'name', where: {name: 'Boo'}}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.name, 'Boo')
assert.ok(not result.selectField)
done()
it 'should be able to find documents by name with where', (done) ->
query = {where: {name: '<NAME>'}}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 1)
assert.equal(result[0].name, '<NAME>')
done()
it 'should be able to limit documents to 3', (done) ->
query = {where: {}, limit: 3}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 3)
done() | true | assert = require 'assert'
wongo = require '../lib/wongo'
wongo.schema 'MockFind',
fields:
name: String
selectField: String
describe 'Wongo Find', ->
docs = [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI', selectField: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}]
it 'should be able to save all documents', (done) ->
wongo.save 'MockFind', docs, (err, result) ->
assert.ifError(err)
assert.ok(item._id) for item in result
done()
it 'should be able to find all documents', (done) ->
query = {}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result?.length, 5)
done()
it 'should be able to find one document from many', (done) ->
query = {}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.ok(result)
done()
it 'should be able to find one document by name', (done) ->
query = {name: 'PI:NAME:<NAME>END_PI'}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.name, 'Boo')
done()
it 'should be able to find documents by name', (done) ->
query = {name: 'PI:NAME:<NAME>END_PI'}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 1)
assert.equal(result[0].name, 'PI:NAME:<NAME>END_PI')
done()
it 'should be able to find select fields on document', (done) ->
query = {select: 'name', where: {name: 'Boo'}}
wongo.findOne 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.name, 'Boo')
assert.ok(not result.selectField)
done()
it 'should be able to find documents by name with where', (done) ->
query = {where: {name: 'PI:NAME:<NAME>END_PI'}}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 1)
assert.equal(result[0].name, 'PI:NAME:<NAME>END_PI')
done()
it 'should be able to limit documents to 3', (done) ->
query = {where: {}, limit: 3}
wongo.find 'MockFind', query, (err, result) ->
assert.ifError(err)
assert.equal(result.length, 3)
done() |
[
{
"context": "ions.\nclass BasicAI\n name: 'Basic AI'\n author: 'rspeer'\n \n # Referring to `state.current` to find in",
"end": 1466,
"score": 0.9996985197067261,
"start": 1460,
"tag": "USERNAME",
"value": "rspeer"
},
{
"context": " there is probably a better spot for it\n ... | basicAI.coffee | rspeer/dominiate | 65 | {c} = require './cards' if exports?
# The Basic AI
# ------------
# This class defines a rule-based AI of the kind that is popular
# for evaluating Dominion strategies. It can be subclassed -- or simply
# have its methods overwritten on an instance -- to play new strategies.
#
# Every time the player needs to make a meaningful decision, a method called
# `chooseX` (for some X) will be called on the AI, which can examine the game
# state and make a decision accordingly.
#
# In any case that is not a simple yes/no decision, the method will be
# given a list of choices. It will first check a method called `xPriority`,
# which takes in the state and returns an ordered list of choices.
# The player will make the first valid choice in that list. Choices are
# skipped when they have an "if" clause that fails.
#
# If the priority list doesn't choose anything, or if there is no priority
# function, it will consult the `xValue` method instead, which takes in
# a specific choice and assigns it a numerical value.
#
# Priority functions are usually easier to define than value functions, but
# value functions can easily cover every possible case.
#
# The BasicAI has a default decision function for every decision, so
# every AI that derives from it will have *some* way to decide what to do in
# any situation. However, when defining an AI, you will often want to override
# some of these decision functions.
class BasicAI
name: 'Basic AI'
author: 'rspeer'
# Referring to `state.current` to find information about one's own state is
# not always safe! Some of these decisions may be made during other players'
# turns. In those cases, what we want is `this.myPlayer(state)`.
#
# This is passed in as an argument `my` to the decision functions, because
# it's convenient and it creates nice idioms such as `my.hand`.
myPlayer: (state) ->
for player in state.players
if player.ai is this
return player
throw new Error("#{this} is being asked to make a decision, but isn't playing the game...?")
# Decision-making machinery
# -------------------------
# Make the AI's preferred choice, first by checking its explicit priority
# list. If no valid choices are on the list, ask the value function instead.
#
# The priority function returns an ordered list of choices it will want to
# make when they are available. If 'null' is on the priority list, that
# represents an explicit preference to choose "none of the above" when it's
# an option.
#
# The value list assigns a numerical value to every possible choice. 'null'
# automatically has a value of 0. Here you can represent actions you will
# only take when forced to, by giving them negative values.
#
# If a choice should be made entirely using the value function, make the
# priority function return an empty list.
choose: (type, state, choices) ->
my = this.myPlayer(state)
# Are there no choices? We follow the rule that makes the null choice
# available in that situation, and choose it.
if choices.length == 0
return null
# First, try the priority function. If the priority function reaches
# the end of its list, it is treated as "none of the above".
priorityfunc = this[type+'Priority']
if priorityfunc?
# Construct an object with the choices as keys, so we can look them
# up quickly.
choiceSet = {}
for choice in choices
choiceSet[choice] = choice
nullable = null in choices
# Get the priority list.
priority = priorityfunc.call(this, state, my)
# Now look up all the preferences in that list. The moment we encounter
# a valid choice, we can return it.
for preference in priority
if preference is null and nullable
return null
if choiceSet[preference]?
return choiceSet[preference]
# The priority list doesn't want any of these choices (perhaps because
# it doesn't exist). Now try the value function.
bestChoice = null
bestValue = -Infinity
for choice in choices
value = this.getChoiceValue(type, state, choice, my)
if value > bestValue
bestValue = value
bestChoice = choice
# If we got a valid choice, return it.
if bestChoice in choices
return bestChoice
# If we get here, the AI probably wants to choose none of the above.
if null in choices
return null
throw new Error("#{this} somehow failed to make a choice")
getChoiceValue: (type, state, choice, my) ->
if choice is null or choice is no
return 0
specificValueFunc = this[type+'Value']
if specificValueFunc?
result = specificValueFunc.call(this, state, choice, my)
if result is undefined
throw new Error("#{this} has an undefined #{type} value for #{choice}")
if result isnt null
return result
defaultValueFunc = choice['ai_'+type+'Value']
if defaultValueFunc?
result = defaultValueFunc.call(choice, state, my)
if result is undefined
throw new Error("#{this} has an undefined #{type} value for #{choice}")
if result isnt null
return result
state.warn("#{this} doesn't know how to make a #{type} decision for #{choice}")
return -1000
# Sometimes we need to compare choices in a strictly numeric way. This takes
# a particular choice for a particular choice type, and gets its numeric value.
# If the value comes from a priority list, it will be 100 * (distance from end
# of list).
#
# So, for example, the default choiceToValue of discarding a Colony is 999, while
# the choiceToValue of discarding an extra terminal is 1.
choiceToValue: (type, state, choice) ->
return 0 if choice is null or choice is no
my = this.myPlayer(state)
priorityfunc = this[type+'Priority']
if priorityfunc?
priority = priorityfunc.bind(this)(state, my)
else
priority = []
index = priority.indexOf(stringify(choice))
if index != -1
return (priority.length - index) * 100
else
return this.getChoiceValue(type, state, choice, my)
# Originally implemented in the `Rebuild.coffee` strategy, this method gets
# the difference in score if the game were to end now.
getScoreDifference: (state, my) ->
for status in state.getFinalStatus()
[name, score, turns] = status
if name == my.ai.toString()
myScore = score
else
opponentScore = score
return myScore - opponentScore
# More utilities from the Rebuild strategy.
countNotInHand: (my, card) ->
return my.countInDeck(card) - my.countInHand(card)
countInDraw: (my, card) ->
return my.countInDeck(card) - my.countInHand(card) - my.countInDiscard(card)
#### Backwards-compatible choices
#
# To avoid having to rewrite all the code at once, we support these functions
# that pass `chooseAction` onto `choose('action')`, and so on.
chooseAction: (state, choices) -> this.choose('play', state, choices)
chooseTreasure: (state, choices) -> this.choose('play', state, choices)
chooseGain: (state, choices) -> this.choose('gain', state, choices)
chooseDiscard: (state, choices) -> this.choose('discard', state, choices)
chooseTrash: (state, choices) -> this.choose('trash', state, choices)
# Default strategies
# ------------------
# The default buying strategy is a form of Big Money that has, by now,
# been beaten by the newer one in BigMoney.coffee.
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6
"Duchy" if 0 < state.gainsToEndGame() <= 5
"Estate" if 0 < state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Silver"
"Copper" if state.gainsToEndGame() <= 3
]
# gainValue covers cases where a strategy has to gain a card that isn't in
# its priority list. The default is to favor more expensive cards,
# particularly action and treasure cards.
#
# It is important for all these values to be negative, to avoid giving defined
# strategies cards they don't actually want.
gainValue: (state, card, my) ->
card.cost + 2*card.costPotion + card.isTreasure + card.isAction - 20
# This used to be the default action-playing priority. Now the value of playing
# a card is defined on the "ai_playValue" function of each card.
old_actionPriority: (state, my, skipMultipliers = false) ->
wantsToTrash = this.wantsToTrash(state)
countInHandCopper = my.countInHand("Copper")
currentAction = my.getCurrentAction()
multiplier = 1
if currentAction?.isMultiplier
multiplier = currentAction.multiplier
wantsToPlayMultiplier = false
okayToPlayMultiplier = false
unless skipMultipliers
mults = (card for card in my.hand when card.isMultiplier)
if mults.length > 0
# We've got a multiplier in hand. Figure out if we want to play it.
mult = mults[0]
choices = my.hand.slice(0)
choices.remove(mult)
choices.push(null)
# Determine if it's better than nothing.
choice1 = this.choose('multipliedAction', state, choices)
if choice1 isnt null
okayToPlayMultiplier = true
# Now add the "wait" option and see if we want to multiply an action
# *right now*.
if choices.length > 1
choices.push("wait")
choice = this.choose('multipliedAction', state, choices)
if choice != "wait"
wantsToPlayMultiplier = true
# Priority 1: cards that succeed if we play them now, and might
# not if we play them later. (950-999)
["Menagerie" if my.menagerieDraws() == 3
"Shanty Town" if my.shantyTownDraws(true) == 2
"Tournament" if my.countInHand("Province") > 0
"Library" if my.hand.length <= 3 and my.actions > 1
# 2: Multipliers that do something sufficiently cool. (900-949)
"Throne Room" if wantsToPlayMultiplier
"King's Court" if wantsToPlayMultiplier
# 3: cards that stack the deck. (850-899)
"Lookout" if state.gainsToEndGame() >= 5 or state.cardInfo.Curse in my.draw
"Cartographer"
"Bag of Gold"
"Apothecary"
"Scout"
"Scrying Pool"
"Spy"
# 4: cards that give +2 actions. (800-849)
"Trusty Steed"
"Festival"
"University"
"Farming Village"
"Bazaar"
"Worker's Village"
"City"
"Walled Village"
"Fishing Village"
"Village"
"Border Village"
"Mining Village"
# 5: cards that give +1 action and are almost always good. (700-800)
"Grand Market"
"Hunting Party"
"Alchemist"
"Laboratory"
"Caravan"
"Market"
"Peddler"
"Treasury"
"Conspirator" if my.inPlay.length >= 2 or multiplier > 1
"Familiar"
"Highway"
"Scheme"
"Wishing Well"
"Golem" # seems to be reasonable to expect +1 action from Golem
"Great Hall" if state.cardInfo.Crossroads not in my.hand
"Spice Merchant" if state.cardInfo.Copper in my.hand
"Stables" if this.choose('stablesDiscard', state, my.hand.concat([null]))
"Apprentice"
"Pearl Diver"
"Hamlet"
"Lighthouse"
"Haven"
"Minion"
# 6: terminal card-drawers, if we have actions to spare. (600-699)
"Library" if my.actions > 1 and my.hand.length <= 4 # 695
"Torturer" if my.actions > 1
"Margrave" if my.actions > 1
"Rabble" if my.actions > 1
"Witch" if my.actions > 1
"Ghost Ship" if my.actions > 1
"Smithy" if my.actions > 1
"Embassy" if my.actions > 1
"Watchtower" if my.actions > 1 and my.hand.length <= 4
"Library" if my.actions > 1 and my.hand.length <= 5 # 620
"Council Room" if my.actions > 1
"Courtyard" if my.actions > 1 and (my.discard.length + my.draw.length) <= 3
"Oracle" if my.actions > 1
# 7: Let's insert here an overly simplistic idea of how to play Crossroads.
# Or if we don't have a Crossroads, play a Great Hall that we might otherwise
# have played in priority level 5. (500-599)
"Crossroads" unless my.countInPlay(state.cardInfo.Crossroads) > 0
"Great Hall"
# 8: card-cycling that might improve the hand. (400-499)
"Upgrade" if wantsToTrash >= multiplier
"Oasis"
"Pawn"
"Warehouse"
"Cellar"
"Library" if my.actions > 1 and my.hand.length <= 6
"Spice Merchant" if this.choose('spiceMerchantTrash', state, my.hand.concat([null]))
# 9: non-terminal cards that don't succeed but at least give us something. (300-399)
"King's Court"
"Throne Room" if okayToPlayMultiplier
"Tournament"
"Menagerie"
"Shanty Town" if my.actions < 2
# 10: terminals. Of course, Nobles might be a non-terminal
# if we decide we need the actions more than the cards. (100-299)
"Crossroads"
"Nobles"
"Treasure Map" if my.countInHand("Treasure Map") >= 2
"Followers"
"Mountebank" # 290
"Witch"
"Sea Hag"
"Torturer"
"Young Witch"
"Tribute" # after Cursers but before other terminals, there is probably a better spot for it
"Margrave" # 280
"Goons"
"Wharf"
# Tactician needs a play condition, but I don't know what it would be.
"Tactician"
"Masquerade" # 270
"Vault"
"Ghost Ship"
"Princess"
"Explorer" if my.countInHand("Province") >= 1
"Library" if my.hand.length <= 3 # 260
"Jester"
"Militia"
"Cutpurse" # 250
"Bridge"
"Bishop"
"Horse Traders" # 240
"Jack of All Trades"
"Steward"
"Moneylender" if countInHandCopper >= 1 # 230
"Expand"
"Remodel"
"Salvager" # 220
"Mine"
"Coppersmith" if countInHandCopper >= 3
"Library" if my.hand.length <= 4 # 210
"Rabble"
"Envoy"
"Smithy" # 200
"Embassy"
"Watchtower" if my.hand.length <= 3
"Council Room"
"Library" if my.hand.length <= 5
"Watchtower" if my.hand.length <= 4 # 190
"Courtyard" if (my.discard.length + my.draw.length) > 0
"Merchant Ship"
"Baron" if my.countInHand("Estate") >= 1
"Monument"
"Oracle" # 180
"Remake" if wantsToTrash >= multiplier * 2 # has a low priority so it'll mostly be played early in the game
"Adventurer"
"Harvest"
"Haggler" # probably needs to make sure the gained card will be wanted; 170
"Mandarin"
"Explorer"
"Woodcutter"
"Nomad Camp"
"Chancellor" # 160
"Counting House"
"Coppersmith" if countInHandCopper >= 2
"Outpost" if state.extraturn == false
"Ambassador" if wantsToTrash # 150
"Trading Post" if wantsToTrash + my.countInHand("Silver") >= 2 * multiplier
"Chapel" if wantsToTrash
"Trader" if wantsToTrash >= multiplier
"Trade Route" if wantsToTrash >= multiplier
"Mint" if my.ai.choose('mint', state, my.hand) # 140
"Secret Chamber"
"Pirate Ship"
"Noble Brigand"
"Thief"
"Island" # could be moved
"Fortune Teller" # 130
"Bureaucrat"
"Navigator"
"Conspirator" if my.actions < 2
"Herbalist"
"Moat" # 120
"Library" if my.hand.length <= 6
"Ironworks" # should have higher priority if condition can see it will gain an Action card
"Workshop"
"Smugglers" if state.smugglerChoices().length > 1 # 110
"Feast"
"Transmute" if wantsToTrash >= multiplier
"Coppersmith"
"Saboteur"
"Poor House"
"Duchess"
"Library" if my.hand.length <= 7
"Thief" # 100
# 11: cards that have become useless. Maybe they'll decrease
# the cost of Peddler, trigger Conspirator, or something. (20-99)
"Treasure Map" if my.countInDeck("Gold") >= 4 and state.current.countInDeck("Treasure Map") == 1
"Spice Merchant"
"Shanty Town"
"Stables" # 50
"Chapel"
"Library"
# 12: Conspirator when +actions remain. (10)
"Conspirator"
# "Baron"
# At this point, we take no action if that choice is available.
null
# Nope, something is forcing us to take an action.
#
# Last priority: cards that are actively harmful to play at this point,
# in order of increasing badness.
"Baron"
"Mint"
"Watchtower"
"Outpost"
"Ambassador" # -20
"Trader"
"Transmute"
"Trade Route"
"Upgrade" # -30
"Remake"
"Trading Post"
"Treasure Map" # -40
"Throne Room"
]
# `multipliedActionPriority` is similar to `actionPriority`, but is used when
# we have played a Throne Room or King's Court.
#
# This list emphasizes cards that are really good when multiplied, especially
# terminals when there are +actions left. At the end, it falls back on the
# usual actionPriority list.
old_multipliedActionPriority: (state, my) ->
[
"King's Court" # 2000
"Throne Room" # 1900
"Followers" if my.actions > 0
"Grand Market"
"Mountebank" if my.actions > 0
"Witch" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Sea Hag" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Torturer" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Young Witch" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Crossroads" if my.actions > 0 or my.countInPlay(state.cardInfo.Crossroads) == 0 # 1800
"Scheme" if my.countInDeck("King's Court") >= 2
# Scrying Pool was here once, but I think you'd rather use it to *draw*
# actions for your KC
"Wharf" if my.actions > 0
"Bridge" if my.actions > 0
"Minion" # 1700
"Ghost Ship" if my.actions > 0
"Jester" if my.actions > 0
"Horse Traders" if my.actions > 0
"Mandarin" if my.actions > 0
"Rabble" if my.actions > 0 # 1600
"Council Room" if my.actions > 0
"Margrave" if my.actions > 0
"Smithy" if my.actions > 0
"Embassy" if my.actions > 0
"Merchant Ship" if my.actions > 0 # 1500
"Pirate Ship" if my.actions > 0
"Saboteur" if my.actions > 0
"Noble Brigand" if my.actions > 0
"Thief" if my.actions > 0
"Monument" if my.actions > 0 # 1400
"Feast" if my.actions > 0
"Conspirator"
"Nobles"
"Tribute"
"Steward" if my.actions > 0 # 1300
"Goons" if my.actions > 0
"Mine" if my.actions > 0
"Masquerade" if my.actions > 0
"Vault" if my.actions > 0
"Oracle" if my.actions > 0 # 1200
"Cutpurse" if my.actions > 0
"Coppersmith" if my.actions > 0 and my.countInHand("Copper") >= 2
"Ambassador" if my.actions > 0 and this.wantsToTrash(state) # 1100
"wait"
# We could add here some more cards that would be nice to play with a
# multiplier. Nicer than Lookout, let's say, which appears pretty high
# on the regular action priority list.
#
# But at this point, just fall back on that priority list.
].concat(this.old_actionPriority(state, my, skipMultipliers=true))
# `treasurePriority` determines what order to play treasures in.
# Most of the order has no effect on gameplay. The
# important part is that Bank and Horn of Plenty are last.
treasurePriority: (state, my) -> [
"Platinum"
"Diadem"
"Philosopher's Stone"
"Gold"
"Cache"
"Hoard"
"Royal Seal"
"Harem"
"Silver"
"Fool's Gold"
"Quarry"
"Talisman"
"Copper"
"Masterpiece"
"Potion" # 100 from here up
"Loan" # 90
"Venture" # 80
"Ill-Gotten Gains"
"Bank"
"Horn of Plenty" if my.numUniqueCardsInPlay() >= 2
"Spoils" if this.wantsToPlaySpoils(state)
null
]
# The default `discardPriority` is tuned for Big Money where the decisions
# are obvious. But many strategies would probably prefer a different
# priority list, especially one that knows about action cards.
#
# It doesn't understand
# discarding cards to make Shanty Town or Menagerie work, for example.
discardPriority: (state, my) -> [
"Tunnel"
"Vineyard"
"Colony"
"Duke"
"Duchy"
"Fairgrounds"
"Gardens"
"Province" # Provinces are occasionally useful in hand
"Curse"
"Estate"
]
discardValue: (state, card, my) ->
# If we can discard excess actions, do so. Otherwise, discard the cheapest
# cards. Victory cards would already have been discarded by discardPriority,
# but if Tunnel fell through somehow we discard it here.
#
# First, check to see if it's our turn. That changes whether we want to discard
# actions.
myTurn = (state.current == my)
if card.name == 'Tunnel'
25
else if card.isAction and myTurn and \
((card.actions == 0 and my.actionBalance() <= 0) or (my.actions == 0))
20 - card.cost
else
0 - card.cost
trashPriority: (state, my) -> [
"Curse"
"Estate" if state.gainsToEndGame() > 4
"Copper" if my.getTotalMoney() > 4
"Potion" if my.turnsTaken >= 10
"Estate" if state.gainsToEndGame() > 2
]
# If we have to trash a card we don't want to, assign a value to each card.
# By default, we want to trash the card with the lowest (cost + VP).
trashValue: (state, card, my) ->
0 - card.vp - card.cost
#developPriority: (state, my) =>
# trashPriority(state, my)
#developValue: (state, card, my) =>
# this.trashValue(state, card, my)
# Some cards give you a choice to discard an opponent's deck. These are
# evaluated with `discardFromOpponentDeckValue`.
discardFromOpponentDeckValue: (state, card, my) ->
if card.name == 'Tunnel'
return -2000
else if not (card.isAction) and not (card.isTreasure)
return -10
else
return card.coins + card.cost + 2*card.isAttack
# `discardHandValue` decides whether to discard an entire hand of cards.
discardHandValue: (state, hand, my, nCards = 5) ->
return 0 if hand is null
deck = my.discard.concat(my.draw)
total = 0
for i in [0...5]
shuffle(deck)
randomHand = deck[0...nCards]
# If a random hand from this deck is better, discard this hand.
total += my.ai.compareByDiscarding(state, randomHand, hand)
return total
# Prefer to gain action and treasure cards on the deck, assuming we want
# them at all. Give other cards a value of -1 so that `null` is a better
# choice.
gainOnDeckValue: (state, card, my) ->
if (card.isAction or card.isTreasure)
this.getChoiceValue('gain', state, card, my)
else
-1
# Changed Priorities for putting cards back on deck. Only works well for putting back 1 card, and for 1 buy.
#
putOnDeckPriority: (state, my) ->
# Make a priority order of:
#
# 1. Actions we can't or don't intend to play, from best to worst
# 2. Treasures we can afford to put back
# 3. Junk cards
# 1) Actions
actions = (card for card in my.hand when card.isAction)
getChoiceValue = this.getChoiceValue
byPlayValue = (x, y) ->
getChoiceValue('play', state, y, my) - getChoiceValue('play', state, x, my)
actions.sort(byPlayValue)
putBack = actions[my.countPlayableTerminals(state) ...]
# 2) Put back as much money as you can
if putBack.length == 0
# Get a list of all distinct treasures in hand, in order.
treasures = []
for card in my.hand
if (card.isTreasure) and (not (card in treasures))
treasures.push card
treasures.sort( (x, y) -> y.coins - x.coins )
# Get the margin of how much money we're willing to discard.
margin = my.ai.coinLossMargin(state)
# Find the treasure cards worth less than that.
for card in treasures
if my.ai.coinsDueToCard(state, card) <= margin
putBack.push(card)
# Don't put back last Potion if Alchemists are in play
if my.countInPlay(state.cardInfo["Alchemist"])>0
if "Potion" in putBack
putBack.remove(state.cardInfo["Potion"])
# 3) Put back the worst card (take priority for discard)
if putBack.length == 0
putBack = [my.ai.choose('discard', state, my.hand)]
putBack
putOnDeckValue: (state, card, my) =>
this.discardValue(state, card, my)
# How much does the AI want to discard its deck right now (for Chancellor)?
# Here, we decide to reshuffle (returning a reshuffleValue over 0) when most
# of the non-Action, non-Treasure cards are in the draw pile, or when there
# are no such cards in the deck.
reshuffleValue: (state, choice, my) ->
junkToDraw = 0
totalJunk = 0
for card in my.draw
if not (card.isAction or card.isTreasure)
junkToDraw++
for card in my.getDeck()
if not (card.isAction or card.isTreasure)
totalJunk++
return 1 if (totalJunk == 0)
proportion = junkToDraw/totalJunk
return (proportion - 0.5)
# Choose opponent treasure to trash; go by the card's base cost.
# Diadems are comparable to the cost-5 treasures.
trashOppTreasureValue: (state, card, my) =>
if card is 'Diadem'
return 5
return card.cost
#### Decisions for particular cards
# `ambassadorPriority` chooses a card to Ambassador and how many of it to
# return.
#
# These choices may look odd: remember that choices are evaluated as strings.
# So if we return lists, they won't match any of the choices. We need to
# return their joined string versions.
#
# This is a moderately acceptable way to deal with the fact that, in
# JavaScript, lists are never "equal" to other lists anyway.
ambassadorPriority: (state, my) ->
[
"[Curse, 2]"
"[Curse, 1]"
"[Curse, 0]"
# Handle a silly case:
"[Ambassador, 2]"
"[Estate, 2]"
"[Estate, 1]"
# Make sure we have at least $5 in the deck, including if we buy a Silver.
"[Copper, 2]" if my.getTreasureInHand() < 3 and my.getTotalMoney() >= 5
"[Copper, 2]" if my.getTreasureInHand() >= 5
"[Copper, 2]" if my.getTreasureInHand() == 3 and my.getTotalMoney() >= 7
"[Copper, 1]" if my.getTreasureInHand() < 3 and my.getTotalMoney() >= 4
"[Copper, 1]" if my.getTreasureInHand() >= 4
"[Estate, 0]"
"[Copper, 0]"
"[Potion, 2]"
"[Potion, 1]"
null
].concat ("[#{card}, 1]" for card in my.ai.trashPriority(state, my) when card?)\
.concat ("[#{card}, 0]" for card in my.hand)
apprenticeTrashPriority: (state, my) ->
"Border Village"
"Mandarin"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Feodum"
"Estate"
"Curse"
"Apprentice"
apprenticeTrashValue: (state, card, my) ->
vp = card.getVP(my)
[coins, potions] = card.getCost(state)
drawn = Math.min(my.draw.length + my.discard.length, coins+2*potions)
return this.choiceToValue('trash', state, card) + 2*drawn - vp
# The question here is: do you want to discard an Estate using a Baron?
# And the answer is yes.
baronDiscardPriority: (state, my) -> [yes]
# `bishopTrashPriority` lists cards that are especially good to trash.
bishopTrashPriority: (state, my) -> [
"Farmland"
"Duchy" if this.goingGreen(state) < 3
"Border Village"
"Mandarin"
"Feodum"
"Bishop"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Curse"
]
bishopTrashValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
value = Math.floor(coins/2) - card.getVP(my)
# if we're going for victory points, that's all we care about.
if this.goingGreen(state) >= 3
return value
# otherwise, focus on what we want to trash
else
if card in this.trashPriority(state, my)
value += 1
if card.isAction and ((card.actions == 0 and my.actionBalance() <= 0) or (my.actions == 0))
value += 1
if card.isTreasure and card.coins > (this.coinLossMargin(state) + 1)
value -= 10
return value
envoyValue: (state, card, my) ->
# Choose a card to discard from your opponent's hand when it's their turn.
opp = state.current
if card.name == 'Tunnel'
return -25
else if not (card.isAction) and not (card.isTreasure)
return -10
else if opp.actions == 0 and card.isAction
return -5
else if opp.actions >= 2
return card.cards + card.coins + card.cost + 2*card.isAttack
else
return card.coins + card.cost + 2*card.isAttack
# `foolsGoldTrashPriority` will trash a Fool's Gold for a real Gold if
# it's nearing the endgame (5 gains or less), there is one FG in hand,
# and losing it will not change its buy.
foolsGoldTrashPriority: (state, my) ->
if my.countInHand(state.cardInfo["Fool's Gold"]) == 1 and my.ai.coinLossMargin(state) >= 1
[yes]
else
[no]
# Do you want to gain a copper from Ill-Gotten Gains? Yes, we want if that improves our buy
gainCopperPriority: (state, my) ->
if my.ai.coinGainMargin(state) <= my.countInHand("Ill-Gotten Gains")+1
[yes]
else
[no]
# The `herbalist` decision puts a treasure card back on the deck. It sounds
# the same as `putOnDeck`, but it's for a different
# situation -- the card is coming from in play, not from your hand. So
# actually we use the `mintValue` by default.
herbalistValue: (state, card, my) =>
this.mintValue(state, card, my)
huntingGroundsGainPriority: (state, my) -> [
"Duchy"
"Estates"
]
# islandPriority chooses which card to set aside with Island. At present this
# list is incomplete, but covers just about everything that we would want to set aside
# with an Island.
islandPriority: (state, my) ->
[
"Colony"
"Province"
"Fairgrounds"
"Duchy"
"Duke"
"Gardens"
"Vineyard"
"Estate"
"Copper"
"Curse"
"Island"
"Tunnel"
]
islandValue: (state, card, my) -> this.discardValue(state, card, my)
librarySetAsideValue: (state, card, my) -> [
if my.actions == 0 and card.isAction
1
else
-1
]
miningVillageTrashValue: (state, choice, my) ->
if this.goingGreen(state) and this.coinGainMargin(state) <= 2
1
else
-1
minionDiscardValue: (state, choice, my) ->
if choice == yes
# Find out how valuable it would be to discard these cards and draw 4.
value = this.discardHandValue(state, my.hand, my, 4)
opponent = state.players[state.players.length - 1]
# If the attack would decrease an opponent's hand size, it's more valuable.
if opponent.hand.length > 4
value += 2
return value
else
return 0
# Mint anything but Copper and Diadem. Otherwise, go mostly by the card's base cost.
# There is only 1 Diadem, never any available to gain, so never Mint it.
mintValue: (state, card, my) ->
return card.cost - 1
# Choose whether we want these cards or two random cards.
oracleDiscardValue: (state, cards, my) ->
deck = my.discard.concat(my.draw)
shuffle(deck)
randomCards = deck[0...cards.length]
return my.ai.compareByDiscarding(state, my.hand.concat(randomCards), my.hand.concat(cards))
# Choose to attack or use available coins when playing Pirate Ship.
# Current strategy is basically Geronimoo's attackUntil5Coins play strategy,
# but only with Provinces--or technically, cards costing 8 or more.
pirateShipPriority: (state, my) -> [
'coins' if state.current.mats.pirateShip >= 5 and state.current.getAvailableMoney()+state.current.mats.pirateShip >= 8
'attack'
]
# might want to think about something more clever, but for first, just discard Coppers
plazaDiscardPriority: (state, my) -> [
"Copper"
null
]
rogueGainValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
return coins
rogueTrashValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
return coins
salvagerTrashPriority: (state, card, my) -> [
"Border Village"
"Mandarin"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Feodum"
"Salvager"
]
# To calculate the salvagerTrashValue, we simulate trashing each card, determine
# the best card we would buy as a result, and evaluate it as if we were
# upgrading the trashed card into the bought one.
salvagerTrashValue: (state, card, my) ->
[hypothesis, hypothetically_my] = state.hypothetical(this)
hypothetically_my.hand.remove(card)
[coins, potions] = card.getCost(hypothesis)
hypothetically_my.coins += coins
hypothetically_my.buys += 1
buyState = this.fastForwardToBuy(hypothesis, hypothetically_my)
gained = buyState.getSingleBuyDecision()
return this.upgradeValue(state, [card, gained], my)
# Scheme uses the same priority function as multiplied actions. Good actions
# to multiply this turn are typically good actions to have around next turn.
schemeValue: (state, card, my) ->
# Project a little of what the state will look like at the beginning of the
# next turn. This keeps multipliedActionPriority from evaluating a card
# as though it will be used in the current (finished) turn.
myNext = {}
myNext[key] = value for key, value of my
myNext.actions = 1
myNext.buys = 1
myNext.coins = 0
return this.getChoiceValue('multiplied', state, card, myNext)
# `scryingPoolDiscardValue` is like `discardValue`, except it strongly
# prefers to discard non-actions.
scryingPoolDiscardValue: (state, card, my) ->
if not card.isAction
2000
else
this.choiceToValue('discard', state, card)
spiceMerchantTrashPriority: (state, my) -> [
"Copper",
"Potion",
"Loan",
"Ill-Gotten Gains",
"Fool's Gold" if my.countInDeck("Fool's Gold") == 1,
"Silver" if my.getTotalMoney() >= 8,
null,
"Silver",
"Venture",
"Cache",
"Gold",
"Harem",
"Platinum"
]
# Which treasure, if any, should be discarded to feed Stables? Defaults
# to a list of generally crappy treasures. Doesn't include $1 Fool's Gold
# because you presumably have another one you're trying to draw.
stablesDiscardPriority: (state, my) -> [
"Copper"
"Potion" if my.countInPlay(state.cardInfo["Alchemist"]) == 0
"Ill-Gotten Gains"
"Silver"
"Horn of Plenty"
null
"Potion"
"Venture"
"Cache"
"Gold"
"Platinum"
]
# Do you want to discard a Province to win a Tournament? The answer is
# *very* yes.
tournamentDiscardPriority: (state, my) -> [yes]
transmuteValue: (state, card, my) ->
if card.isAction and this.goingGreen(state)
return 10
else if card.isAction and card.isVictory and card.cost <= 4
return 1000
else
return this.choiceToValue('trash', state, card)
# `wishValue` prefers to wish for the card its draw pile contains
# the most of.
#
# The fact that this doesn't make a hypothetical copy is a shortcut. We are
# technically "peeking" at the deck, but we don't use any information except
# the count of each card, which would be the same in any hypothetical version.
wishValue: (state, card, my) ->
pile = my.draw
if pile.length == 0
pile = my.discard
return countInList(pile, card)
# Choose to discard or to gain a curse when attacked by Torturer.
torturerPriority: (state, my) -> [
'curse' if state.countInSupply("Curse") == 0
'discard' if my.ai.wantsToDiscard(state) >= 2
'discard' if my.hand.length <= 1
'curse' if my.trashingInHand() > 0
'curse' if my.hand.length <= 3
'discard'
'curse'
]
#### Trash-for-benefit decisions
# Taking into account gain priorities, gain values, trash priorities, and
# trash values, how much do we like having this card in our deck overall?
cardInDeckValue: (state, card, my) ->
endgamePower = 1
# Are we in the late game? If so, we care much more about getting cards
# at the top of our priority order.
if state.gainsToEndGame() <= 5
endgamePower = 3
return -(this.choiceToValue('trash', state, card)) + \
Math.pow(this.choiceToValue('gain', state, card), endgamePower)
# upgradeValue measures the benefit of choices on Remodel, Upgrade,
# and so on, where you exchange one card for a better one.
#
# So here's a really basic thing that might work.
upgradeValue: (state, choice, my) ->
[oldCard, newCard] = choice
return my.ai.cardInDeckValue(state, newCard, my) - \
my.ai.cardInDeckValue(state, oldCard, my)
# developValue measures the benefit of choices Develop,
# where you exchange one card for two.
#
# So here's a really basic thing that might work.
developValue: (state, choice, my) ->
[oldCard, [newCard1, newCard2]] = choice
return my.ai.cardInDeckValue(state, newCard1, my) + \
my.ai.cardInDeckValue(state, newCard2, my) - \
my.ai.cardInDeckValue(state, oldCard, my)
# `chooseOrderOnDeck` handles situations where multiple cards are returned
# to the deck, such as Scout and Apothecary.
#
# This decision doesn't fit into the xPriority / xValue framework, as there
# are a number of mostly indistinguishable choices. Instead of listing all
# the permutations of cards as choices, we just list the cards to arrange.
#
# The default decision is to put the cards with the lowest discard value on
# top.
chooseOrderOnDeck: (state, cards, my) ->
sorter = (card1, card2) ->
my.ai.choiceToValue('discard', state, card1)\
- my.ai.choiceToValue('discard', state, card2)
choice = cards.slice(0)
return choice.sort(sorter)
# How much do we want to overpay for Masterpiece?
# If we care to buy it probably as much as possible
#
chooseOverpayMasterpiece: (state, maxAmount) ->
return maxAmount
# How many Coin Tokens do we want to spend?
# Try to buy the 'best' card you can afford, and spend as less as possible for this
#
spendCoinTokens: (state, my) ->
cardsBoughtOld = []
ct = my.coinTokens
loop
[hypState, hypMy] = state.hypothetical(this)
hypMy.coins += ct
hypMy.coinTokensSpendThisTurn = ct
cardsBought = []
while hypMy.buys > 0
cardBought = hypState.getSingleBuyDecision()
if cardBought?
[coinCost, potionCost] = cardBought.getCost(hypState)
hypMy.coins -= coinCost
hypMy.potions -= potionCost
cardsBought.push cardBought
hypMy.buys -= 1
if ((ct < my.coinTokens) and not (arrayEqual(cardsBought, cardsBoughtOld)))
ct += 1
break
if ct == 0
break
ct -= 1
cardsBoughtOld = cardsBought
return ct
#### Informational methods
# When presented with a card with simple but variable benefits, such as
# Nobles, this is the default way for an AI to decide which benefit it wants.
# This function should actually handle a number of common situations.
benefitValue: (state, choice, my) ->
buyValue = 1
cardValue = 2
coinValue = 3
trashValue = 4 # if there are cards we want to trash
actionValue = 10 # if we need more actions
actionBalance = my.actionBalance()
usableActions = Math.max(0, -actionBalance)
if actionBalance >= 1
cardValue += actionBalance
if my.ai.wantsToTrash(state) < (choice.trash ? 0)
trashValue = -4
value = cardValue * (choice.cards ? 0)
value += coinValue * (choice.coins ? 0)
value += buyValue * (choice.buys ? 0)
value += trashValue * (choice.trash ? 0)
value += actionValue * Math.min((choice.actions ? 0), usableActions)
value
# `wantsToTrash` returns the number of cards in hand that we would trash
# for no benefit.
wantsToTrash: (state) ->
my = this.myPlayer(state)
trashableCards = 0
for card in my.hand
if this.chooseTrash(state, [card, null]) is card
trashableCards += 1
return trashableCards
# `wantsToPlayRats` is like `wantsToTrash` except that the answer is no.
#
# Come on, it's a first-order approximation of good strategy. If you've got
# a better idea, put it in a strategy file.
wantsToPlayRats: (state) -> no
# `wantsToDiscard` returns the number of cards in hand that we would
# freely discard.
wantsToDiscard: (state) ->
my = this.myPlayer(state)
discardableCards = 0
for card in my.hand
if this.chooseDiscard(state, [card, null]) is card
discardableCards += 1
return discardableCards
multiplierChoices: (state) ->
my = this.myPlayer(state)
mults = (card for card in my.hand when card.isMultiplier)
if mults.length > 0
mult = mults[0]
choices = (card for card in my.hand when card.isAction)
choices.remove(mult)
choices.push(null)
return choices
else
return []
okayToPlayMultiplier: (state) ->
choices = this.multiplierChoices(state)
if this.choose('multiplied', state, choices)?
return true
else
return false
wantsToPlayMultiplier: (state) ->
my = this.myPlayer(state)
choices = this.multiplierChoices(state)
if choices.length > 1
choice = this.choose('multiplied', state, choices)
multipliedValue = this.getChoiceValue('multiplied', state, choice, my)
if choice? and choice.isMultiplier
# prevent infinite loops
unmultipliedValue = 0
else
unmultipliedValue = this.getChoiceValue('play', state, choice, my)
return (multipliedValue > unmultipliedValue)
return false
# play Spoils if it changes your buys this turn. Or if in hypothetical state to solve recursion
wantsToPlaySpoils: (state) ->
if state.depth > 0
return true
else
cardsGainedWithout = this.pessimisticCardsGained(state)
[hypState, hypMy] = state.hypothetical(this)
hypState.current.hand.remove(c["Spoils"])
cardsGainedWith = this.pessimisticCardsGained(hypState)
if arrayEqual(cardsGainedWithout, cardsGainedWith)
return false
else
return true
# wantsToRebuild and rebuildPriority: taken from the Rebuild strategy
wantsToRebuild: (state, my) ->
if my.countInHand("Rebuild") >= state.countInSupply("Province") \
and my.ai.getScoreDifference(state, my) > 0
answer = 1
else if state.countInSupply("Province") == 1 \
and my.ai.getScoreDifference(state, my) < -4
answer = 0
else if state.countInSupply("Duchy") == 0 \
and my.ai.countNotInHand(my, "Duchy") == 0\
and my.ai.getScoreDifference(state, my) < 0
answer = 0
else if my.getTreasureInHand() > 7 and state.countInSupply("Province") == 1
answer = 0
else
answer = state.countInSupply("Province") > 0
return answer
rebuildPriority: (state, my) -> [
"Province"
"Duchy"
"Estate"
]
nameVPPriority: (state, my) -> [
"Colony" if my.countInDeck("Colony") > 0
"Province"
]
# Assume we always want to play Journeyman
wantsToJM: (state, my) ->
true
wantsToDiscardBeggar: (state) ->
return true
# `goingGreen`: determine when we're playing for victory points. By default,
# it's if there are any Colonies, Provinces, or Duchies in the deck.
#
# The bigger the number, the greener the deck, but a true (greater than 0)
# value is a good indication in itself that we want victory cards.
goingGreen: (state) ->
my = this.myPlayer(state)
bigGreen = my.countInDeck("Colony") + my.countInDeck("Province") + my.countInDeck("Duchy")
return bigGreen
# `pessimisticMoneyInHand` establishes a minimum on how much money the
# player will be able to spend in this game state. It assumes the player
# will draw no money from the deck.
pessimisticMoneyInHand: (state) ->
# Don't recurse more than once. If we're already in a hypothetical
# situation, use the stupid version instead.
if state.depth > 0
return this.myPlayer(state).getAvailableMoney()
buyPhase = this.pessimisticBuyPhase(state)
return buyPhase.current.coins
# Look ahead to the buy phase, assuming we draw no money from the deck.
#
# TODO: when we can handle known cards on top of the deck, take them
# into account.
pessimisticBuyPhase: (state) ->
if state.depth > 0
# A last-ditch effort to avoid recursion, by simply fast-forwarding
# to the next phase.
if state.phase == 'action'
state.phase = 'treasure'
else if state.phase == 'treasure'
state.phase = 'buy'
[hypothesis, hypothetically_my] = state.hypothetical(this)
return this.fastForwardToBuy(hypothesis, hypothetically_my)
fastForwardToBuy: (state, my) ->
if state.depth == 0
throw new Error("Can only fast-forward in a hypothetical state")
#We need to save draw and discard before emptying and restore them before buyPhase, to be able to choose the right buys in actionPriority(state)
oldDraws = my.draw.slice(0)
oldDiscard = my.discard.slice(0)
my.draw = []
my.discard = []
while state.phase != 'buy'
state.doPlay()
my.draw = oldDraws
my.discard = oldDiscard
return state
pessimisticCardsGained: (state) ->
newState = this.pessimisticBuyPhase(state)
newState.doPlay()
return newState.current.gainedThisTurn
# coinLossMargin determines how much treasure the player can lose
# "for free" (because it won't change their buy decision). Intended to be
# more efficient than calling pessimisticCardsGained on a number
# of different states.
#
# TODO: do we need an equivalent for potions?
coinLossMargin: (state) ->
newState = this.pessimisticBuyPhase(state)
coins = newState.current.coins
cardToBuy = newState.getSingleBuyDecision()
return 0 if cardToBuy is null
[coinsCost, potionsCost] = cardToBuy.getCost(newState)
return coins - coinsCost
# coinGainMargin determines how much treasure the player wants to gain,
# in order to get a better card. Tries up to +$8, then returns Infinity
# if nothing changes.
coinGainMargin: (state) ->
newState = this.pessimisticBuyPhase(state)
coins = newState.current.coins
baseCard = newState.getSingleBuyDecision()
for increment in [1, 2, 3, 4, 5, 6, 7, 8]
newState.current.coins = coins+increment
cardToBuy = newState.getSingleBuyDecision()
if cardToBuy != baseCard
return increment
return Infinity
# Estimate the number of coins we'd lose by discarding/trashing/putting back
# a card.
coinsDueToCard: (state, card) ->
c = state.cardInfo
value = card.getCoins(state)
if card.isTreasure
banks = state.current.countInHand(state.cardInfo.Bank)
value += banks
if card is state.cardInfo.Bank
nonbanks = (aCard for aCard in state.current.hand when aCard.isTreasure).length
value += nonbanks
value
# Figure out whether hand1 or hand2 is better by discarding their cards
# in priority order, until one of them gets to 2 or fewer cards.
#
# Returns a -1 or 1 that can be used in sorting; it's
# positive if the first hand is better.
compareByDiscarding: (state, hand1, hand2) ->
# Guard against accidental mutation; we're going to be messing with
# these lists.
hand1 = hand1.slice(0)
hand2 = hand2.slice(0)
# Preserve our number of actions.
savedActions = state.current.actions
state.current.actions = 1
#state.log("hand1 = #{hand1}")
#state.log("hand2 = #{hand2}")
counter = 0
loop
counter++
if counter >= 100
throw new Error("got stuck in a loop")
# Figure out whether we'd rather discard from hand1 or hand2.
discard1 = this.choose('discard', state, hand1)
value1 = this.choiceToValue('discard', state, discard1)
discard2 = this.choose('discard', state, hand2)
value2 = this.choiceToValue('discard', state, discard2)
if value1 > value2
hand1.remove(discard1)
else if value2 > value1
hand2.remove(discard2)
else
hand1.remove(discard1)
hand2.remove(discard2)
if hand1.length <= 2 and hand2.length <= 2
state.current.actions = savedActions
return 0
if hand1.length <= 2
state.current.actions = savedActions
return -1
if hand2.length <= 2
state.current.actions = savedActions
return 1
#### Utility methods
#
# `copy` makes a copy of the AI. It will have the same behavior but a
# different name, and will not be equal to this AI.
copy: () =>
ai = new BasicAI()
for key, value of this
ai[key] = value
ai.name = this.name+'*'
ai
# Some functions need to check the actionPriority a lot. This pair of
# methods will save a cached value so you don't need to run such an expensive
# function over and over.
cachedActionPriority: (state, my) ->
my.ai.cachedAP
cacheActionPriority: (state, my) ->
@cachedAP = my.ai.actionPriority(state, my)
toString: () -> this.name
this.BasicAI = BasicAI
# Utility functions
# -----------------
# `count` counts the number of times `elt` appears in `list`.
countInList = (list, elt) ->
count = 0
for member in list
if member == elt
count++
count
# `stringify` turns an object into a string, while handling `null` safely.
stringify = (obj) ->
if obj is null
return null
else
return obj.toString()
# General function to randomly shuffle a list.
shuffle = (v) ->
i = v.length
while i
j = parseInt(Math.random() * i)
i -= 1
temp = v[i]
v[i] = v[j]
v[j] = temp
v
# compare Arrays
arrayEqual = (a, b) ->
a.length is b.length and a.every (elem, i) -> elem is b[i]
| 214775 | {c} = require './cards' if exports?
# The Basic AI
# ------------
# This class defines a rule-based AI of the kind that is popular
# for evaluating Dominion strategies. It can be subclassed -- or simply
# have its methods overwritten on an instance -- to play new strategies.
#
# Every time the player needs to make a meaningful decision, a method called
# `chooseX` (for some X) will be called on the AI, which can examine the game
# state and make a decision accordingly.
#
# In any case that is not a simple yes/no decision, the method will be
# given a list of choices. It will first check a method called `xPriority`,
# which takes in the state and returns an ordered list of choices.
# The player will make the first valid choice in that list. Choices are
# skipped when they have an "if" clause that fails.
#
# If the priority list doesn't choose anything, or if there is no priority
# function, it will consult the `xValue` method instead, which takes in
# a specific choice and assigns it a numerical value.
#
# Priority functions are usually easier to define than value functions, but
# value functions can easily cover every possible case.
#
# The BasicAI has a default decision function for every decision, so
# every AI that derives from it will have *some* way to decide what to do in
# any situation. However, when defining an AI, you will often want to override
# some of these decision functions.
class BasicAI
name: 'Basic AI'
author: 'rspeer'
# Referring to `state.current` to find information about one's own state is
# not always safe! Some of these decisions may be made during other players'
# turns. In those cases, what we want is `this.myPlayer(state)`.
#
# This is passed in as an argument `my` to the decision functions, because
# it's convenient and it creates nice idioms such as `my.hand`.
myPlayer: (state) ->
for player in state.players
if player.ai is this
return player
throw new Error("#{this} is being asked to make a decision, but isn't playing the game...?")
# Decision-making machinery
# -------------------------
# Make the AI's preferred choice, first by checking its explicit priority
# list. If no valid choices are on the list, ask the value function instead.
#
# The priority function returns an ordered list of choices it will want to
# make when they are available. If 'null' is on the priority list, that
# represents an explicit preference to choose "none of the above" when it's
# an option.
#
# The value list assigns a numerical value to every possible choice. 'null'
# automatically has a value of 0. Here you can represent actions you will
# only take when forced to, by giving them negative values.
#
# If a choice should be made entirely using the value function, make the
# priority function return an empty list.
choose: (type, state, choices) ->
my = this.myPlayer(state)
# Are there no choices? We follow the rule that makes the null choice
# available in that situation, and choose it.
if choices.length == 0
return null
# First, try the priority function. If the priority function reaches
# the end of its list, it is treated as "none of the above".
priorityfunc = this[type+'Priority']
if priorityfunc?
# Construct an object with the choices as keys, so we can look them
# up quickly.
choiceSet = {}
for choice in choices
choiceSet[choice] = choice
nullable = null in choices
# Get the priority list.
priority = priorityfunc.call(this, state, my)
# Now look up all the preferences in that list. The moment we encounter
# a valid choice, we can return it.
for preference in priority
if preference is null and nullable
return null
if choiceSet[preference]?
return choiceSet[preference]
# The priority list doesn't want any of these choices (perhaps because
# it doesn't exist). Now try the value function.
bestChoice = null
bestValue = -Infinity
for choice in choices
value = this.getChoiceValue(type, state, choice, my)
if value > bestValue
bestValue = value
bestChoice = choice
# If we got a valid choice, return it.
if bestChoice in choices
return bestChoice
# If we get here, the AI probably wants to choose none of the above.
if null in choices
return null
throw new Error("#{this} somehow failed to make a choice")
getChoiceValue: (type, state, choice, my) ->
if choice is null or choice is no
return 0
specificValueFunc = this[type+'Value']
if specificValueFunc?
result = specificValueFunc.call(this, state, choice, my)
if result is undefined
throw new Error("#{this} has an undefined #{type} value for #{choice}")
if result isnt null
return result
defaultValueFunc = choice['ai_'+type+'Value']
if defaultValueFunc?
result = defaultValueFunc.call(choice, state, my)
if result is undefined
throw new Error("#{this} has an undefined #{type} value for #{choice}")
if result isnt null
return result
state.warn("#{this} doesn't know how to make a #{type} decision for #{choice}")
return -1000
# Sometimes we need to compare choices in a strictly numeric way. This takes
# a particular choice for a particular choice type, and gets its numeric value.
# If the value comes from a priority list, it will be 100 * (distance from end
# of list).
#
# So, for example, the default choiceToValue of discarding a Colony is 999, while
# the choiceToValue of discarding an extra terminal is 1.
choiceToValue: (type, state, choice) ->
return 0 if choice is null or choice is no
my = this.myPlayer(state)
priorityfunc = this[type+'Priority']
if priorityfunc?
priority = priorityfunc.bind(this)(state, my)
else
priority = []
index = priority.indexOf(stringify(choice))
if index != -1
return (priority.length - index) * 100
else
return this.getChoiceValue(type, state, choice, my)
# Originally implemented in the `Rebuild.coffee` strategy, this method gets
# the difference in score if the game were to end now.
getScoreDifference: (state, my) ->
for status in state.getFinalStatus()
[name, score, turns] = status
if name == my.ai.toString()
myScore = score
else
opponentScore = score
return myScore - opponentScore
# More utilities from the Rebuild strategy.
countNotInHand: (my, card) ->
return my.countInDeck(card) - my.countInHand(card)
countInDraw: (my, card) ->
return my.countInDeck(card) - my.countInHand(card) - my.countInDiscard(card)
#### Backwards-compatible choices
#
# To avoid having to rewrite all the code at once, we support these functions
# that pass `chooseAction` onto `choose('action')`, and so on.
chooseAction: (state, choices) -> this.choose('play', state, choices)
chooseTreasure: (state, choices) -> this.choose('play', state, choices)
chooseGain: (state, choices) -> this.choose('gain', state, choices)
chooseDiscard: (state, choices) -> this.choose('discard', state, choices)
chooseTrash: (state, choices) -> this.choose('trash', state, choices)
# Default strategies
# ------------------
# The default buying strategy is a form of Big Money that has, by now,
# been beaten by the newer one in BigMoney.coffee.
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6
"Duchy" if 0 < state.gainsToEndGame() <= 5
"Estate" if 0 < state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Silver"
"Copper" if state.gainsToEndGame() <= 3
]
# gainValue covers cases where a strategy has to gain a card that isn't in
# its priority list. The default is to favor more expensive cards,
# particularly action and treasure cards.
#
# It is important for all these values to be negative, to avoid giving defined
# strategies cards they don't actually want.
gainValue: (state, card, my) ->
card.cost + 2*card.costPotion + card.isTreasure + card.isAction - 20
# This used to be the default action-playing priority. Now the value of playing
# a card is defined on the "ai_playValue" function of each card.
old_actionPriority: (state, my, skipMultipliers = false) ->
wantsToTrash = this.wantsToTrash(state)
countInHandCopper = my.countInHand("Copper")
currentAction = my.getCurrentAction()
multiplier = 1
if currentAction?.isMultiplier
multiplier = currentAction.multiplier
wantsToPlayMultiplier = false
okayToPlayMultiplier = false
unless skipMultipliers
mults = (card for card in my.hand when card.isMultiplier)
if mults.length > 0
# We've got a multiplier in hand. Figure out if we want to play it.
mult = mults[0]
choices = my.hand.slice(0)
choices.remove(mult)
choices.push(null)
# Determine if it's better than nothing.
choice1 = this.choose('multipliedAction', state, choices)
if choice1 isnt null
okayToPlayMultiplier = true
# Now add the "wait" option and see if we want to multiply an action
# *right now*.
if choices.length > 1
choices.push("wait")
choice = this.choose('multipliedAction', state, choices)
if choice != "wait"
wantsToPlayMultiplier = true
# Priority 1: cards that succeed if we play them now, and might
# not if we play them later. (950-999)
["Menagerie" if my.menagerieDraws() == 3
"Shanty Town" if my.shantyTownDraws(true) == 2
"Tournament" if my.countInHand("Province") > 0
"Library" if my.hand.length <= 3 and my.actions > 1
# 2: Multipliers that do something sufficiently cool. (900-949)
"Throne Room" if wantsToPlayMultiplier
"King's Court" if wantsToPlayMultiplier
# 3: cards that stack the deck. (850-899)
"Lookout" if state.gainsToEndGame() >= 5 or state.cardInfo.Curse in my.draw
"Cartographer"
"Bag of Gold"
"Apothecary"
"Scout"
"Scrying Pool"
"Spy"
# 4: cards that give +2 actions. (800-849)
"Trusty Steed"
"Festival"
"University"
"Farming Village"
"Bazaar"
"Worker's Village"
"City"
"Walled Village"
"Fishing Village"
"Village"
"Border Village"
"Mining Village"
# 5: cards that give +1 action and are almost always good. (700-800)
"Grand Market"
"Hunting Party"
"Alchemist"
"Laboratory"
"Caravan"
"Market"
"Peddler"
"Treasury"
"Conspirator" if my.inPlay.length >= 2 or multiplier > 1
"Familiar"
"Highway"
"Scheme"
"Wishing Well"
"Golem" # seems to be reasonable to expect +1 action from Golem
"Great Hall" if state.cardInfo.Crossroads not in my.hand
"Spice Merchant" if state.cardInfo.Copper in my.hand
"Stables" if this.choose('stablesDiscard', state, my.hand.concat([null]))
"Apprentice"
"Pearl Diver"
"Hamlet"
"Lighthouse"
"Haven"
"Minion"
# 6: terminal card-drawers, if we have actions to spare. (600-699)
"Library" if my.actions > 1 and my.hand.length <= 4 # 695
"Torturer" if my.actions > 1
"Margrave" if my.actions > 1
"Rabble" if my.actions > 1
"Witch" if my.actions > 1
"Ghost Ship" if my.actions > 1
"Smithy" if my.actions > 1
"Embassy" if my.actions > 1
"Watchtower" if my.actions > 1 and my.hand.length <= 4
"Library" if my.actions > 1 and my.hand.length <= 5 # 620
"Council Room" if my.actions > 1
"Courtyard" if my.actions > 1 and (my.discard.length + my.draw.length) <= 3
"Oracle" if my.actions > 1
# 7: Let's insert here an overly simplistic idea of how to play Crossroads.
# Or if we don't have a Crossroads, play a Great Hall that we might otherwise
# have played in priority level 5. (500-599)
"Crossroads" unless my.countInPlay(state.cardInfo.Crossroads) > 0
"Great Hall"
# 8: card-cycling that might improve the hand. (400-499)
"Upgrade" if wantsToTrash >= multiplier
"Oasis"
"Pawn"
"Warehouse"
"Cellar"
"Library" if my.actions > 1 and my.hand.length <= 6
"Spice Merchant" if this.choose('spiceMerchantTrash', state, my.hand.concat([null]))
# 9: non-terminal cards that don't succeed but at least give us something. (300-399)
"King's Court"
"Throne Room" if okayToPlayMultiplier
"Tournament"
"Menagerie"
"Shanty Town" if my.actions < 2
# 10: terminals. Of course, Nobles might be a non-terminal
# if we decide we need the actions more than the cards. (100-299)
"Crossroads"
"Nobles"
"Treasure Map" if my.countInHand("Treasure Map") >= 2
"Followers"
"Mountebank" # 290
"Witch"
"Sea Hag"
"Torturer"
"Young Witch"
"Tribute" # after Cursers but before other terminals, there is probably a better spot for it
"Margr<NAME>" # 280
"Goons"
"Wharf"
# Tactician needs a play condition, but I don't know what it would be.
"Tactician"
"Masquerade" # 270
"Vault"
"Ghost Ship"
"<NAME>"
"Explorer" if my.countInHand("Province") >= 1
"Library" if my.hand.length <= 3 # 260
"<NAME>"
"<NAME>"
"Cutpurse" # 250
"Bridge"
"Bishop"
"Horse Traders" # 240
"Jack of All Trades"
"<NAME>ard"
"Money<NAME>" if countInHandCopper >= 1 # 230
"Expand"
"Remodel"
"Sal<NAME>ager" # 220
"Mine"
"<NAME>" if countInHandCopper >= 3
"Library" if my.hand.length <= 4 # 210
"Rabble"
"Envoy"
"Smithy" # 200
"Embassy"
"Watchtower" if my.hand.length <= 3
"Council Room"
"Library" if my.hand.length <= 5
"Watchtower" if my.hand.length <= 4 # 190
"Courtyard" if (my.discard.length + my.draw.length) > 0
"Merchant Ship"
"Baron" if my.countInHand("Estate") >= 1
"Monument"
"Oracle" # 180
"Remake" if wantsToTrash >= multiplier * 2 # has a low priority so it'll mostly be played early in the game
"Adventurer"
"Harvest"
"Haggler" # probably needs to make sure the gained card will be wanted; 170
"<NAME>"
"Explorer"
"Woodcutter"
"Nomad Camp"
"Chancellor" # 160
"Counting House"
"<NAME>" if countInHandCopper >= 2
"Outpost" if state.extraturn == false
"Ambassador" if wantsToTrash # 150
"Trading Post" if wantsToTrash + my.countInHand("Silver") >= 2 * multiplier
"Chapel" if wantsToTrash
"Trader" if wantsToTrash >= multiplier
"Trade Route" if wantsToTrash >= multiplier
"Mint" if my.ai.choose('mint', state, my.hand) # 140
"Secret Chamber"
"Pirate Ship"
"Noble Brigand"
"Thief"
"Island" # could be moved
"Fortune Teller" # 130
"Bureaucrat"
"Navigator"
"Conspirator" if my.actions < 2
"Herbalist"
"Moat" # 120
"Library" if my.hand.length <= 6
"Ironworks" # should have higher priority if condition can see it will gain an Action card
"Workshop"
"Smugglers" if state.smugglerChoices().length > 1 # 110
"Feast"
"Transmute" if wantsToTrash >= multiplier
"<NAME>"
"Saboteur"
"Poor House"
"Duchess"
"Library" if my.hand.length <= 7
"Thief" # 100
# 11: cards that have become useless. Maybe they'll decrease
# the cost of Peddler, trigger Conspirator, or something. (20-99)
"Treasure Map" if my.countInDeck("Gold") >= 4 and state.current.countInDeck("Treasure Map") == 1
"Spice Merchant"
"Shanty Town"
"Stables" # 50
"Chapel"
"Library"
# 12: Conspirator when +actions remain. (10)
"Conspirator"
# "Baron"
# At this point, we take no action if that choice is available.
null
# Nope, something is forcing us to take an action.
#
# Last priority: cards that are actively harmful to play at this point,
# in order of increasing badness.
"Baron"
"Mint"
"Watchtower"
"Outpost"
"Ambassador" # -20
"Trader"
"Transmute"
"Trade Route"
"Upgrade" # -30
"Remake"
"Trading Post"
"Treasure Map" # -40
"Throne Room"
]
# `multipliedActionPriority` is similar to `actionPriority`, but is used when
# we have played a Throne Room or King's Court.
#
# This list emphasizes cards that are really good when multiplied, especially
# terminals when there are +actions left. At the end, it falls back on the
# usual actionPriority list.
old_multipliedActionPriority: (state, my) ->
[
"King's Court" # 2000
"Throne Room" # 1900
"Followers" if my.actions > 0
"Grand Market"
"Mountebank" if my.actions > 0
"Witch" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Sea Hag" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Torturer" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Young Witch" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Crossroads" if my.actions > 0 or my.countInPlay(state.cardInfo.Crossroads) == 0 # 1800
"Scheme" if my.countInDeck("King's Court") >= 2
# Scrying Pool was here once, but I think you'd rather use it to *draw*
# actions for your KC
"Wharf" if my.actions > 0
"Bridge" if my.actions > 0
"Minion" # 1700
"Ghost Ship" if my.actions > 0
"Jester" if my.actions > 0
"Horse Traders" if my.actions > 0
"Mandarin" if my.actions > 0
"Rabble" if my.actions > 0 # 1600
"Council Room" if my.actions > 0
"Margrave" if my.actions > 0
"Smithy" if my.actions > 0
"Embassy" if my.actions > 0
"Merchant Ship" if my.actions > 0 # 1500
"Pirate Ship" if my.actions > 0
"Saboteur" if my.actions > 0
"Noble Brigand" if my.actions > 0
"Thief" if my.actions > 0
"Monument" if my.actions > 0 # 1400
"Feast" if my.actions > 0
"Conspirator"
"Nobles"
"Tribute"
"Steward" if my.actions > 0 # 1300
"Goons" if my.actions > 0
"Mine" if my.actions > 0
"Masquerade" if my.actions > 0
"Vault" if my.actions > 0
"Oracle" if my.actions > 0 # 1200
"Cutpurse" if my.actions > 0
"Coppersmith" if my.actions > 0 and my.countInHand("Copper") >= 2
"Ambassador" if my.actions > 0 and this.wantsToTrash(state) # 1100
"wait"
# We could add here some more cards that would be nice to play with a
# multiplier. Nicer than Lookout, let's say, which appears pretty high
# on the regular action priority list.
#
# But at this point, just fall back on that priority list.
].concat(this.old_actionPriority(state, my, skipMultipliers=true))
# `treasurePriority` determines what order to play treasures in.
# Most of the order has no effect on gameplay. The
# important part is that Bank and Horn of Plenty are last.
treasurePriority: (state, my) -> [
"Platinum"
"<NAME>"
"Philosopher's Stone"
"Gold"
"Cache"
"Hoard"
"Royal Seal"
"<NAME>"
"Silver"
"Fool's Gold"
"<NAME>"
"<NAME>"
"<NAME>"
"Masterpiece"
"Potion" # 100 from here up
"Loan" # 90
"Venture" # 80
"Ill-Gotten Gains"
"Bank"
"Horn of Plenty" if my.numUniqueCardsInPlay() >= 2
"Spoils" if this.wantsToPlaySpoils(state)
null
]
# The default `discardPriority` is tuned for Big Money where the decisions
# are obvious. But many strategies would probably prefer a different
# priority list, especially one that knows about action cards.
#
# It doesn't understand
# discarding cards to make Shanty Town or Menagerie work, for example.
discardPriority: (state, my) -> [
"Tunnel"
"Vineyard"
"Colony"
"Duke"
"Duchy"
"Fairgrounds"
"Gardens"
"Province" # Provinces are occasionally useful in hand
"Curse"
"Estate"
]
discardValue: (state, card, my) ->
# If we can discard excess actions, do so. Otherwise, discard the cheapest
# cards. Victory cards would already have been discarded by discardPriority,
# but if Tunnel fell through somehow we discard it here.
#
# First, check to see if it's our turn. That changes whether we want to discard
# actions.
myTurn = (state.current == my)
if card.name == 'Tunnel'
25
else if card.isAction and myTurn and \
((card.actions == 0 and my.actionBalance() <= 0) or (my.actions == 0))
20 - card.cost
else
0 - card.cost
trashPriority: (state, my) -> [
"Curse"
"Estate" if state.gainsToEndGame() > 4
"Copper" if my.getTotalMoney() > 4
"Potion" if my.turnsTaken >= 10
"Estate" if state.gainsToEndGame() > 2
]
# If we have to trash a card we don't want to, assign a value to each card.
# By default, we want to trash the card with the lowest (cost + VP).
trashValue: (state, card, my) ->
0 - card.vp - card.cost
#developPriority: (state, my) =>
# trashPriority(state, my)
#developValue: (state, card, my) =>
# this.trashValue(state, card, my)
# Some cards give you a choice to discard an opponent's deck. These are
# evaluated with `discardFromOpponentDeckValue`.
discardFromOpponentDeckValue: (state, card, my) ->
if card.name == 'Tunnel'
return -2000
else if not (card.isAction) and not (card.isTreasure)
return -10
else
return card.coins + card.cost + 2*card.isAttack
# `discardHandValue` decides whether to discard an entire hand of cards.
discardHandValue: (state, hand, my, nCards = 5) ->
return 0 if hand is null
deck = my.discard.concat(my.draw)
total = 0
for i in [0...5]
shuffle(deck)
randomHand = deck[0...nCards]
# If a random hand from this deck is better, discard this hand.
total += my.ai.compareByDiscarding(state, randomHand, hand)
return total
# Prefer to gain action and treasure cards on the deck, assuming we want
# them at all. Give other cards a value of -1 so that `null` is a better
# choice.
gainOnDeckValue: (state, card, my) ->
if (card.isAction or card.isTreasure)
this.getChoiceValue('gain', state, card, my)
else
-1
# Changed Priorities for putting cards back on deck. Only works well for putting back 1 card, and for 1 buy.
#
putOnDeckPriority: (state, my) ->
# Make a priority order of:
#
# 1. Actions we can't or don't intend to play, from best to worst
# 2. Treasures we can afford to put back
# 3. Junk cards
# 1) Actions
actions = (card for card in my.hand when card.isAction)
getChoiceValue = this.getChoiceValue
byPlayValue = (x, y) ->
getChoiceValue('play', state, y, my) - getChoiceValue('play', state, x, my)
actions.sort(byPlayValue)
putBack = actions[my.countPlayableTerminals(state) ...]
# 2) Put back as much money as you can
if putBack.length == 0
# Get a list of all distinct treasures in hand, in order.
treasures = []
for card in my.hand
if (card.isTreasure) and (not (card in treasures))
treasures.push card
treasures.sort( (x, y) -> y.coins - x.coins )
# Get the margin of how much money we're willing to discard.
margin = my.ai.coinLossMargin(state)
# Find the treasure cards worth less than that.
for card in treasures
if my.ai.coinsDueToCard(state, card) <= margin
putBack.push(card)
# Don't put back last Potion if Alchemists are in play
if my.countInPlay(state.cardInfo["Alchemist"])>0
if "Potion" in putBack
putBack.remove(state.cardInfo["Potion"])
# 3) Put back the worst card (take priority for discard)
if putBack.length == 0
putBack = [my.ai.choose('discard', state, my.hand)]
putBack
putOnDeckValue: (state, card, my) =>
this.discardValue(state, card, my)
# How much does the AI want to discard its deck right now (for Chancellor)?
# Here, we decide to reshuffle (returning a reshuffleValue over 0) when most
# of the non-Action, non-Treasure cards are in the draw pile, or when there
# are no such cards in the deck.
reshuffleValue: (state, choice, my) ->
junkToDraw = 0
totalJunk = 0
for card in my.draw
if not (card.isAction or card.isTreasure)
junkToDraw++
for card in my.getDeck()
if not (card.isAction or card.isTreasure)
totalJunk++
return 1 if (totalJunk == 0)
proportion = junkToDraw/totalJunk
return (proportion - 0.5)
# Choose opponent treasure to trash; go by the card's base cost.
# Diadems are comparable to the cost-5 treasures.
trashOppTreasureValue: (state, card, my) =>
if card is 'Diadem'
return 5
return card.cost
#### Decisions for particular cards
# `ambassadorPriority` chooses a card to Ambassador and how many of it to
# return.
#
# These choices may look odd: remember that choices are evaluated as strings.
# So if we return lists, they won't match any of the choices. We need to
# return their joined string versions.
#
# This is a moderately acceptable way to deal with the fact that, in
# JavaScript, lists are never "equal" to other lists anyway.
ambassadorPriority: (state, my) ->
[
"[Curse, 2]"
"[Curse, 1]"
"[Curse, 0]"
# Handle a silly case:
"[Ambassador, 2]"
"[Estate, 2]"
"[Estate, 1]"
# Make sure we have at least $5 in the deck, including if we buy a Silver.
"[Copper, 2]" if my.getTreasureInHand() < 3 and my.getTotalMoney() >= 5
"[Copper, 2]" if my.getTreasureInHand() >= 5
"[Copper, 2]" if my.getTreasureInHand() == 3 and my.getTotalMoney() >= 7
"[Copper, 1]" if my.getTreasureInHand() < 3 and my.getTotalMoney() >= 4
"[Copper, 1]" if my.getTreasureInHand() >= 4
"[Estate, 0]"
"[Copper, 0]"
"[Potion, 2]"
"[Potion, 1]"
null
].concat ("[#{card}, 1]" for card in my.ai.trashPriority(state, my) when card?)\
.concat ("[#{card}, 0]" for card in my.hand)
apprenticeTrashPriority: (state, my) ->
"Border Village"
"Mandarin"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Feodum"
"Estate"
"Curse"
"Apprentice"
apprenticeTrashValue: (state, card, my) ->
vp = card.getVP(my)
[coins, potions] = card.getCost(state)
drawn = Math.min(my.draw.length + my.discard.length, coins+2*potions)
return this.choiceToValue('trash', state, card) + 2*drawn - vp
# The question here is: do you want to discard an Estate using a Baron?
# And the answer is yes.
baronDiscardPriority: (state, my) -> [yes]
# `bishopTrashPriority` lists cards that are especially good to trash.
bishopTrashPriority: (state, my) -> [
"Farmland"
"Duchy" if this.goingGreen(state) < 3
"Border Village"
"Mandarin"
"Feodum"
"Bishop"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Curse"
]
bishopTrashValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
value = Math.floor(coins/2) - card.getVP(my)
# if we're going for victory points, that's all we care about.
if this.goingGreen(state) >= 3
return value
# otherwise, focus on what we want to trash
else
if card in this.trashPriority(state, my)
value += 1
if card.isAction and ((card.actions == 0 and my.actionBalance() <= 0) or (my.actions == 0))
value += 1
if card.isTreasure and card.coins > (this.coinLossMargin(state) + 1)
value -= 10
return value
envoyValue: (state, card, my) ->
# Choose a card to discard from your opponent's hand when it's their turn.
opp = state.current
if card.name == 'Tunnel'
return -25
else if not (card.isAction) and not (card.isTreasure)
return -10
else if opp.actions == 0 and card.isAction
return -5
else if opp.actions >= 2
return card.cards + card.coins + card.cost + 2*card.isAttack
else
return card.coins + card.cost + 2*card.isAttack
# `foolsGoldTrashPriority` will trash a Fool's Gold for a real Gold if
# it's nearing the endgame (5 gains or less), there is one FG in hand,
# and losing it will not change its buy.
foolsGoldTrashPriority: (state, my) ->
if my.countInHand(state.cardInfo["Fool's Gold"]) == 1 and my.ai.coinLossMargin(state) >= 1
[yes]
else
[no]
# Do you want to gain a copper from Ill-Gotten Gains? Yes, we want if that improves our buy
gainCopperPriority: (state, my) ->
if my.ai.coinGainMargin(state) <= my.countInHand("Ill-Gotten Gains")+1
[yes]
else
[no]
# The `herbalist` decision puts a treasure card back on the deck. It sounds
# the same as `putOnDeck`, but it's for a different
# situation -- the card is coming from in play, not from your hand. So
# actually we use the `mintValue` by default.
herbalistValue: (state, card, my) =>
this.mintValue(state, card, my)
huntingGroundsGainPriority: (state, my) -> [
"Duchy"
"Estates"
]
# islandPriority chooses which card to set aside with Island. At present this
# list is incomplete, but covers just about everything that we would want to set aside
# with an Island.
islandPriority: (state, my) ->
[
"Colony"
"Province"
"Fairgrounds"
"Duchy"
"Duke"
"Gardens"
"Vineyard"
"Estate"
"Copper"
"Curse"
"Island"
"Tunnel"
]
islandValue: (state, card, my) -> this.discardValue(state, card, my)
librarySetAsideValue: (state, card, my) -> [
if my.actions == 0 and card.isAction
1
else
-1
]
miningVillageTrashValue: (state, choice, my) ->
if this.goingGreen(state) and this.coinGainMargin(state) <= 2
1
else
-1
minionDiscardValue: (state, choice, my) ->
if choice == yes
# Find out how valuable it would be to discard these cards and draw 4.
value = this.discardHandValue(state, my.hand, my, 4)
opponent = state.players[state.players.length - 1]
# If the attack would decrease an opponent's hand size, it's more valuable.
if opponent.hand.length > 4
value += 2
return value
else
return 0
# Mint anything but Copper and Diadem. Otherwise, go mostly by the card's base cost.
# There is only 1 Diadem, never any available to gain, so never Mint it.
mintValue: (state, card, my) ->
return card.cost - 1
# Choose whether we want these cards or two random cards.
oracleDiscardValue: (state, cards, my) ->
deck = my.discard.concat(my.draw)
shuffle(deck)
randomCards = deck[0...cards.length]
return my.ai.compareByDiscarding(state, my.hand.concat(randomCards), my.hand.concat(cards))
# Choose to attack or use available coins when playing Pirate Ship.
# Current strategy is basically Geronimoo's attackUntil5Coins play strategy,
# but only with Provinces--or technically, cards costing 8 or more.
pirateShipPriority: (state, my) -> [
'coins' if state.current.mats.pirateShip >= 5 and state.current.getAvailableMoney()+state.current.mats.pirateShip >= 8
'attack'
]
# might want to think about something more clever, but for first, just discard Coppers
plazaDiscardPriority: (state, my) -> [
"Copper"
null
]
rogueGainValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
return coins
rogueTrashValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
return coins
salvagerTrashPriority: (state, card, my) -> [
"Border Village"
"Mandarin"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Feodum"
"Salvager"
]
# To calculate the salvagerTrashValue, we simulate trashing each card, determine
# the best card we would buy as a result, and evaluate it as if we were
# upgrading the trashed card into the bought one.
salvagerTrashValue: (state, card, my) ->
[hypothesis, hypothetically_my] = state.hypothetical(this)
hypothetically_my.hand.remove(card)
[coins, potions] = card.getCost(hypothesis)
hypothetically_my.coins += coins
hypothetically_my.buys += 1
buyState = this.fastForwardToBuy(hypothesis, hypothetically_my)
gained = buyState.getSingleBuyDecision()
return this.upgradeValue(state, [card, gained], my)
# Scheme uses the same priority function as multiplied actions. Good actions
# to multiply this turn are typically good actions to have around next turn.
schemeValue: (state, card, my) ->
# Project a little of what the state will look like at the beginning of the
# next turn. This keeps multipliedActionPriority from evaluating a card
# as though it will be used in the current (finished) turn.
myNext = {}
myNext[key] = value for key, value of my
myNext.actions = 1
myNext.buys = 1
myNext.coins = 0
return this.getChoiceValue('multiplied', state, card, myNext)
# `scryingPoolDiscardValue` is like `discardValue`, except it strongly
# prefers to discard non-actions.
scryingPoolDiscardValue: (state, card, my) ->
if not card.isAction
2000
else
this.choiceToValue('discard', state, card)
spiceMerchantTrashPriority: (state, my) -> [
"Copper",
"Potion",
"Loan",
"Ill-Gotten Gains",
"Fool's Gold" if my.countInDeck("Fool's Gold") == 1,
"Silver" if my.getTotalMoney() >= 8,
null,
"Silver",
"Venture",
"Cache",
"Gold",
"Harem",
"Platinum"
]
# Which treasure, if any, should be discarded to feed Stables? Defaults
# to a list of generally crappy treasures. Doesn't include $1 Fool's Gold
# because you presumably have another one you're trying to draw.
stablesDiscardPriority: (state, my) -> [
"Copper"
"Potion" if my.countInPlay(state.cardInfo["Alchemist"]) == 0
"Ill-Gotten Gains"
"Silver"
"Horn of Plenty"
null
"Potion"
"Venture"
"Cache"
"Gold"
"Platinum"
]
# Do you want to discard a Province to win a Tournament? The answer is
# *very* yes.
tournamentDiscardPriority: (state, my) -> [yes]
transmuteValue: (state, card, my) ->
if card.isAction and this.goingGreen(state)
return 10
else if card.isAction and card.isVictory and card.cost <= 4
return 1000
else
return this.choiceToValue('trash', state, card)
# `wishValue` prefers to wish for the card its draw pile contains
# the most of.
#
# The fact that this doesn't make a hypothetical copy is a shortcut. We are
# technically "peeking" at the deck, but we don't use any information except
# the count of each card, which would be the same in any hypothetical version.
wishValue: (state, card, my) ->
pile = my.draw
if pile.length == 0
pile = my.discard
return countInList(pile, card)
# Choose to discard or to gain a curse when attacked by Torturer.
torturerPriority: (state, my) -> [
'curse' if state.countInSupply("Curse") == 0
'discard' if my.ai.wantsToDiscard(state) >= 2
'discard' if my.hand.length <= 1
'curse' if my.trashingInHand() > 0
'curse' if my.hand.length <= 3
'discard'
'curse'
]
#### Trash-for-benefit decisions
# Taking into account gain priorities, gain values, trash priorities, and
# trash values, how much do we like having this card in our deck overall?
cardInDeckValue: (state, card, my) ->
endgamePower = 1
# Are we in the late game? If so, we care much more about getting cards
# at the top of our priority order.
if state.gainsToEndGame() <= 5
endgamePower = 3
return -(this.choiceToValue('trash', state, card)) + \
Math.pow(this.choiceToValue('gain', state, card), endgamePower)
# upgradeValue measures the benefit of choices on Remodel, Upgrade,
# and so on, where you exchange one card for a better one.
#
# So here's a really basic thing that might work.
upgradeValue: (state, choice, my) ->
[oldCard, newCard] = choice
return my.ai.cardInDeckValue(state, newCard, my) - \
my.ai.cardInDeckValue(state, oldCard, my)
# developValue measures the benefit of choices Develop,
# where you exchange one card for two.
#
# So here's a really basic thing that might work.
developValue: (state, choice, my) ->
[oldCard, [newCard1, newCard2]] = choice
return my.ai.cardInDeckValue(state, newCard1, my) + \
my.ai.cardInDeckValue(state, newCard2, my) - \
my.ai.cardInDeckValue(state, oldCard, my)
# `chooseOrderOnDeck` handles situations where multiple cards are returned
# to the deck, such as Scout and Apothecary.
#
# This decision doesn't fit into the xPriority / xValue framework, as there
# are a number of mostly indistinguishable choices. Instead of listing all
# the permutations of cards as choices, we just list the cards to arrange.
#
# The default decision is to put the cards with the lowest discard value on
# top.
chooseOrderOnDeck: (state, cards, my) ->
sorter = (card1, card2) ->
my.ai.choiceToValue('discard', state, card1)\
- my.ai.choiceToValue('discard', state, card2)
choice = cards.slice(0)
return choice.sort(sorter)
# How much do we want to overpay for Masterpiece?
# If we care to buy it probably as much as possible
#
chooseOverpayMasterpiece: (state, maxAmount) ->
return maxAmount
# How many Coin Tokens do we want to spend?
# Try to buy the 'best' card you can afford, and spend as less as possible for this
#
spendCoinTokens: (state, my) ->
cardsBoughtOld = []
ct = my.coinTokens
loop
[hypState, hypMy] = state.hypothetical(this)
hypMy.coins += ct
hypMy.coinTokensSpendThisTurn = ct
cardsBought = []
while hypMy.buys > 0
cardBought = hypState.getSingleBuyDecision()
if cardBought?
[coinCost, potionCost] = cardBought.getCost(hypState)
hypMy.coins -= coinCost
hypMy.potions -= potionCost
cardsBought.push cardBought
hypMy.buys -= 1
if ((ct < my.coinTokens) and not (arrayEqual(cardsBought, cardsBoughtOld)))
ct += 1
break
if ct == 0
break
ct -= 1
cardsBoughtOld = cardsBought
return ct
#### Informational methods
# When presented with a card with simple but variable benefits, such as
# Nobles, this is the default way for an AI to decide which benefit it wants.
# This function should actually handle a number of common situations.
benefitValue: (state, choice, my) ->
buyValue = 1
cardValue = 2
coinValue = 3
trashValue = 4 # if there are cards we want to trash
actionValue = 10 # if we need more actions
actionBalance = my.actionBalance()
usableActions = Math.max(0, -actionBalance)
if actionBalance >= 1
cardValue += actionBalance
if my.ai.wantsToTrash(state) < (choice.trash ? 0)
trashValue = -4
value = cardValue * (choice.cards ? 0)
value += coinValue * (choice.coins ? 0)
value += buyValue * (choice.buys ? 0)
value += trashValue * (choice.trash ? 0)
value += actionValue * Math.min((choice.actions ? 0), usableActions)
value
# `wantsToTrash` returns the number of cards in hand that we would trash
# for no benefit.
wantsToTrash: (state) ->
my = this.myPlayer(state)
trashableCards = 0
for card in my.hand
if this.chooseTrash(state, [card, null]) is card
trashableCards += 1
return trashableCards
# `wantsToPlayRats` is like `wantsToTrash` except that the answer is no.
#
# Come on, it's a first-order approximation of good strategy. If you've got
# a better idea, put it in a strategy file.
wantsToPlayRats: (state) -> no
# `wantsToDiscard` returns the number of cards in hand that we would
# freely discard.
wantsToDiscard: (state) ->
my = this.myPlayer(state)
discardableCards = 0
for card in my.hand
if this.chooseDiscard(state, [card, null]) is card
discardableCards += 1
return discardableCards
multiplierChoices: (state) ->
my = this.myPlayer(state)
mults = (card for card in my.hand when card.isMultiplier)
if mults.length > 0
mult = mults[0]
choices = (card for card in my.hand when card.isAction)
choices.remove(mult)
choices.push(null)
return choices
else
return []
okayToPlayMultiplier: (state) ->
choices = this.multiplierChoices(state)
if this.choose('multiplied', state, choices)?
return true
else
return false
wantsToPlayMultiplier: (state) ->
my = this.myPlayer(state)
choices = this.multiplierChoices(state)
if choices.length > 1
choice = this.choose('multiplied', state, choices)
multipliedValue = this.getChoiceValue('multiplied', state, choice, my)
if choice? and choice.isMultiplier
# prevent infinite loops
unmultipliedValue = 0
else
unmultipliedValue = this.getChoiceValue('play', state, choice, my)
return (multipliedValue > unmultipliedValue)
return false
# play Spoils if it changes your buys this turn. Or if in hypothetical state to solve recursion
wantsToPlaySpoils: (state) ->
if state.depth > 0
return true
else
cardsGainedWithout = this.pessimisticCardsGained(state)
[hypState, hypMy] = state.hypothetical(this)
hypState.current.hand.remove(c["Spoils"])
cardsGainedWith = this.pessimisticCardsGained(hypState)
if arrayEqual(cardsGainedWithout, cardsGainedWith)
return false
else
return true
# wantsToRebuild and rebuildPriority: taken from the Rebuild strategy
wantsToRebuild: (state, my) ->
if my.countInHand("Rebuild") >= state.countInSupply("Province") \
and my.ai.getScoreDifference(state, my) > 0
answer = 1
else if state.countInSupply("Province") == 1 \
and my.ai.getScoreDifference(state, my) < -4
answer = 0
else if state.countInSupply("Duchy") == 0 \
and my.ai.countNotInHand(my, "Duchy") == 0\
and my.ai.getScoreDifference(state, my) < 0
answer = 0
else if my.getTreasureInHand() > 7 and state.countInSupply("Province") == 1
answer = 0
else
answer = state.countInSupply("Province") > 0
return answer
rebuildPriority: (state, my) -> [
"Province"
"Duchy"
"Estate"
]
nameVPPriority: (state, my) -> [
"Colony" if my.countInDeck("Colony") > 0
"Province"
]
# Assume we always want to play Journeyman
wantsToJM: (state, my) ->
true
wantsToDiscardBeggar: (state) ->
return true
# `goingGreen`: determine when we're playing for victory points. By default,
# it's if there are any Colonies, Provinces, or Duchies in the deck.
#
# The bigger the number, the greener the deck, but a true (greater than 0)
# value is a good indication in itself that we want victory cards.
goingGreen: (state) ->
my = this.myPlayer(state)
bigGreen = my.countInDeck("Colony") + my.countInDeck("Province") + my.countInDeck("Duchy")
return bigGreen
# `pessimisticMoneyInHand` establishes a minimum on how much money the
# player will be able to spend in this game state. It assumes the player
# will draw no money from the deck.
pessimisticMoneyInHand: (state) ->
# Don't recurse more than once. If we're already in a hypothetical
# situation, use the stupid version instead.
if state.depth > 0
return this.myPlayer(state).getAvailableMoney()
buyPhase = this.pessimisticBuyPhase(state)
return buyPhase.current.coins
# Look ahead to the buy phase, assuming we draw no money from the deck.
#
# TODO: when we can handle known cards on top of the deck, take them
# into account.
pessimisticBuyPhase: (state) ->
if state.depth > 0
# A last-ditch effort to avoid recursion, by simply fast-forwarding
# to the next phase.
if state.phase == 'action'
state.phase = 'treasure'
else if state.phase == 'treasure'
state.phase = 'buy'
[hypothesis, hypothetically_my] = state.hypothetical(this)
return this.fastForwardToBuy(hypothesis, hypothetically_my)
fastForwardToBuy: (state, my) ->
if state.depth == 0
throw new Error("Can only fast-forward in a hypothetical state")
#We need to save draw and discard before emptying and restore them before buyPhase, to be able to choose the right buys in actionPriority(state)
oldDraws = my.draw.slice(0)
oldDiscard = my.discard.slice(0)
my.draw = []
my.discard = []
while state.phase != 'buy'
state.doPlay()
my.draw = oldDraws
my.discard = oldDiscard
return state
pessimisticCardsGained: (state) ->
newState = this.pessimisticBuyPhase(state)
newState.doPlay()
return newState.current.gainedThisTurn
# coinLossMargin determines how much treasure the player can lose
# "for free" (because it won't change their buy decision). Intended to be
# more efficient than calling pessimisticCardsGained on a number
# of different states.
#
# TODO: do we need an equivalent for potions?
coinLossMargin: (state) ->
newState = this.pessimisticBuyPhase(state)
coins = newState.current.coins
cardToBuy = newState.getSingleBuyDecision()
return 0 if cardToBuy is null
[coinsCost, potionsCost] = cardToBuy.getCost(newState)
return coins - coinsCost
# coinGainMargin determines how much treasure the player wants to gain,
# in order to get a better card. Tries up to +$8, then returns Infinity
# if nothing changes.
coinGainMargin: (state) ->
newState = this.pessimisticBuyPhase(state)
coins = newState.current.coins
baseCard = newState.getSingleBuyDecision()
for increment in [1, 2, 3, 4, 5, 6, 7, 8]
newState.current.coins = coins+increment
cardToBuy = newState.getSingleBuyDecision()
if cardToBuy != baseCard
return increment
return Infinity
# Estimate the number of coins we'd lose by discarding/trashing/putting back
# a card.
coinsDueToCard: (state, card) ->
c = state.cardInfo
value = card.getCoins(state)
if card.isTreasure
banks = state.current.countInHand(state.cardInfo.Bank)
value += banks
if card is state.cardInfo.Bank
nonbanks = (aCard for aCard in state.current.hand when aCard.isTreasure).length
value += nonbanks
value
# Figure out whether hand1 or hand2 is better by discarding their cards
# in priority order, until one of them gets to 2 or fewer cards.
#
# Returns a -1 or 1 that can be used in sorting; it's
# positive if the first hand is better.
compareByDiscarding: (state, hand1, hand2) ->
# Guard against accidental mutation; we're going to be messing with
# these lists.
hand1 = hand1.slice(0)
hand2 = hand2.slice(0)
# Preserve our number of actions.
savedActions = state.current.actions
state.current.actions = 1
#state.log("hand1 = #{hand1}")
#state.log("hand2 = #{hand2}")
counter = 0
loop
counter++
if counter >= 100
throw new Error("got stuck in a loop")
# Figure out whether we'd rather discard from hand1 or hand2.
discard1 = this.choose('discard', state, hand1)
value1 = this.choiceToValue('discard', state, discard1)
discard2 = this.choose('discard', state, hand2)
value2 = this.choiceToValue('discard', state, discard2)
if value1 > value2
hand1.remove(discard1)
else if value2 > value1
hand2.remove(discard2)
else
hand1.remove(discard1)
hand2.remove(discard2)
if hand1.length <= 2 and hand2.length <= 2
state.current.actions = savedActions
return 0
if hand1.length <= 2
state.current.actions = savedActions
return -1
if hand2.length <= 2
state.current.actions = savedActions
return 1
#### Utility methods
#
# `copy` makes a copy of the AI. It will have the same behavior but a
# different name, and will not be equal to this AI.
copy: () =>
ai = new BasicAI()
for key, value of this
ai[key] = value
ai.name = this.name+'*'
ai
# Some functions need to check the actionPriority a lot. This pair of
# methods will save a cached value so you don't need to run such an expensive
# function over and over.
cachedActionPriority: (state, my) ->
my.ai.cachedAP
cacheActionPriority: (state, my) ->
@cachedAP = my.ai.actionPriority(state, my)
toString: () -> this.name
this.BasicAI = BasicAI
# Utility functions
# -----------------
# `count` counts the number of times `elt` appears in `list`.
countInList = (list, elt) ->
count = 0
for member in list
if member == elt
count++
count
# `stringify` turns an object into a string, while handling `null` safely.
stringify = (obj) ->
if obj is null
return null
else
return obj.toString()
# General function to randomly shuffle a list.
shuffle = (v) ->
i = v.length
while i
j = parseInt(Math.random() * i)
i -= 1
temp = v[i]
v[i] = v[j]
v[j] = temp
v
# compare Arrays
arrayEqual = (a, b) ->
a.length is b.length and a.every (elem, i) -> elem is b[i]
| true | {c} = require './cards' if exports?
# The Basic AI
# ------------
# This class defines a rule-based AI of the kind that is popular
# for evaluating Dominion strategies. It can be subclassed -- or simply
# have its methods overwritten on an instance -- to play new strategies.
#
# Every time the player needs to make a meaningful decision, a method called
# `chooseX` (for some X) will be called on the AI, which can examine the game
# state and make a decision accordingly.
#
# In any case that is not a simple yes/no decision, the method will be
# given a list of choices. It will first check a method called `xPriority`,
# which takes in the state and returns an ordered list of choices.
# The player will make the first valid choice in that list. Choices are
# skipped when they have an "if" clause that fails.
#
# If the priority list doesn't choose anything, or if there is no priority
# function, it will consult the `xValue` method instead, which takes in
# a specific choice and assigns it a numerical value.
#
# Priority functions are usually easier to define than value functions, but
# value functions can easily cover every possible case.
#
# The BasicAI has a default decision function for every decision, so
# every AI that derives from it will have *some* way to decide what to do in
# any situation. However, when defining an AI, you will often want to override
# some of these decision functions.
class BasicAI
name: 'Basic AI'
author: 'rspeer'
# Referring to `state.current` to find information about one's own state is
# not always safe! Some of these decisions may be made during other players'
# turns. In those cases, what we want is `this.myPlayer(state)`.
#
# This is passed in as an argument `my` to the decision functions, because
# it's convenient and it creates nice idioms such as `my.hand`.
myPlayer: (state) ->
for player in state.players
if player.ai is this
return player
throw new Error("#{this} is being asked to make a decision, but isn't playing the game...?")
# Decision-making machinery
# -------------------------
# Make the AI's preferred choice, first by checking its explicit priority
# list. If no valid choices are on the list, ask the value function instead.
#
# The priority function returns an ordered list of choices it will want to
# make when they are available. If 'null' is on the priority list, that
# represents an explicit preference to choose "none of the above" when it's
# an option.
#
# The value list assigns a numerical value to every possible choice. 'null'
# automatically has a value of 0. Here you can represent actions you will
# only take when forced to, by giving them negative values.
#
# If a choice should be made entirely using the value function, make the
# priority function return an empty list.
choose: (type, state, choices) ->
my = this.myPlayer(state)
# Are there no choices? We follow the rule that makes the null choice
# available in that situation, and choose it.
if choices.length == 0
return null
# First, try the priority function. If the priority function reaches
# the end of its list, it is treated as "none of the above".
priorityfunc = this[type+'Priority']
if priorityfunc?
# Construct an object with the choices as keys, so we can look them
# up quickly.
choiceSet = {}
for choice in choices
choiceSet[choice] = choice
nullable = null in choices
# Get the priority list.
priority = priorityfunc.call(this, state, my)
# Now look up all the preferences in that list. The moment we encounter
# a valid choice, we can return it.
for preference in priority
if preference is null and nullable
return null
if choiceSet[preference]?
return choiceSet[preference]
# The priority list doesn't want any of these choices (perhaps because
# it doesn't exist). Now try the value function.
bestChoice = null
bestValue = -Infinity
for choice in choices
value = this.getChoiceValue(type, state, choice, my)
if value > bestValue
bestValue = value
bestChoice = choice
# If we got a valid choice, return it.
if bestChoice in choices
return bestChoice
# If we get here, the AI probably wants to choose none of the above.
if null in choices
return null
throw new Error("#{this} somehow failed to make a choice")
getChoiceValue: (type, state, choice, my) ->
if choice is null or choice is no
return 0
specificValueFunc = this[type+'Value']
if specificValueFunc?
result = specificValueFunc.call(this, state, choice, my)
if result is undefined
throw new Error("#{this} has an undefined #{type} value for #{choice}")
if result isnt null
return result
defaultValueFunc = choice['ai_'+type+'Value']
if defaultValueFunc?
result = defaultValueFunc.call(choice, state, my)
if result is undefined
throw new Error("#{this} has an undefined #{type} value for #{choice}")
if result isnt null
return result
state.warn("#{this} doesn't know how to make a #{type} decision for #{choice}")
return -1000
# Sometimes we need to compare choices in a strictly numeric way. This takes
# a particular choice for a particular choice type, and gets its numeric value.
# If the value comes from a priority list, it will be 100 * (distance from end
# of list).
#
# So, for example, the default choiceToValue of discarding a Colony is 999, while
# the choiceToValue of discarding an extra terminal is 1.
choiceToValue: (type, state, choice) ->
return 0 if choice is null or choice is no
my = this.myPlayer(state)
priorityfunc = this[type+'Priority']
if priorityfunc?
priority = priorityfunc.bind(this)(state, my)
else
priority = []
index = priority.indexOf(stringify(choice))
if index != -1
return (priority.length - index) * 100
else
return this.getChoiceValue(type, state, choice, my)
# Originally implemented in the `Rebuild.coffee` strategy, this method gets
# the difference in score if the game were to end now.
getScoreDifference: (state, my) ->
for status in state.getFinalStatus()
[name, score, turns] = status
if name == my.ai.toString()
myScore = score
else
opponentScore = score
return myScore - opponentScore
# More utilities from the Rebuild strategy.
countNotInHand: (my, card) ->
return my.countInDeck(card) - my.countInHand(card)
countInDraw: (my, card) ->
return my.countInDeck(card) - my.countInHand(card) - my.countInDiscard(card)
#### Backwards-compatible choices
#
# To avoid having to rewrite all the code at once, we support these functions
# that pass `chooseAction` onto `choose('action')`, and so on.
chooseAction: (state, choices) -> this.choose('play', state, choices)
chooseTreasure: (state, choices) -> this.choose('play', state, choices)
chooseGain: (state, choices) -> this.choose('gain', state, choices)
chooseDiscard: (state, choices) -> this.choose('discard', state, choices)
chooseTrash: (state, choices) -> this.choose('trash', state, choices)
# Default strategies
# ------------------
# The default buying strategy is a form of Big Money that has, by now,
# been beaten by the newer one in BigMoney.coffee.
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6
"Duchy" if 0 < state.gainsToEndGame() <= 5
"Estate" if 0 < state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Silver"
"Copper" if state.gainsToEndGame() <= 3
]
# gainValue covers cases where a strategy has to gain a card that isn't in
# its priority list. The default is to favor more expensive cards,
# particularly action and treasure cards.
#
# It is important for all these values to be negative, to avoid giving defined
# strategies cards they don't actually want.
gainValue: (state, card, my) ->
card.cost + 2*card.costPotion + card.isTreasure + card.isAction - 20
# This used to be the default action-playing priority. Now the value of playing
# a card is defined on the "ai_playValue" function of each card.
old_actionPriority: (state, my, skipMultipliers = false) ->
wantsToTrash = this.wantsToTrash(state)
countInHandCopper = my.countInHand("Copper")
currentAction = my.getCurrentAction()
multiplier = 1
if currentAction?.isMultiplier
multiplier = currentAction.multiplier
wantsToPlayMultiplier = false
okayToPlayMultiplier = false
unless skipMultipliers
mults = (card for card in my.hand when card.isMultiplier)
if mults.length > 0
# We've got a multiplier in hand. Figure out if we want to play it.
mult = mults[0]
choices = my.hand.slice(0)
choices.remove(mult)
choices.push(null)
# Determine if it's better than nothing.
choice1 = this.choose('multipliedAction', state, choices)
if choice1 isnt null
okayToPlayMultiplier = true
# Now add the "wait" option and see if we want to multiply an action
# *right now*.
if choices.length > 1
choices.push("wait")
choice = this.choose('multipliedAction', state, choices)
if choice != "wait"
wantsToPlayMultiplier = true
# Priority 1: cards that succeed if we play them now, and might
# not if we play them later. (950-999)
["Menagerie" if my.menagerieDraws() == 3
"Shanty Town" if my.shantyTownDraws(true) == 2
"Tournament" if my.countInHand("Province") > 0
"Library" if my.hand.length <= 3 and my.actions > 1
# 2: Multipliers that do something sufficiently cool. (900-949)
"Throne Room" if wantsToPlayMultiplier
"King's Court" if wantsToPlayMultiplier
# 3: cards that stack the deck. (850-899)
"Lookout" if state.gainsToEndGame() >= 5 or state.cardInfo.Curse in my.draw
"Cartographer"
"Bag of Gold"
"Apothecary"
"Scout"
"Scrying Pool"
"Spy"
# 4: cards that give +2 actions. (800-849)
"Trusty Steed"
"Festival"
"University"
"Farming Village"
"Bazaar"
"Worker's Village"
"City"
"Walled Village"
"Fishing Village"
"Village"
"Border Village"
"Mining Village"
# 5: cards that give +1 action and are almost always good. (700-800)
"Grand Market"
"Hunting Party"
"Alchemist"
"Laboratory"
"Caravan"
"Market"
"Peddler"
"Treasury"
"Conspirator" if my.inPlay.length >= 2 or multiplier > 1
"Familiar"
"Highway"
"Scheme"
"Wishing Well"
"Golem" # seems to be reasonable to expect +1 action from Golem
"Great Hall" if state.cardInfo.Crossroads not in my.hand
"Spice Merchant" if state.cardInfo.Copper in my.hand
"Stables" if this.choose('stablesDiscard', state, my.hand.concat([null]))
"Apprentice"
"Pearl Diver"
"Hamlet"
"Lighthouse"
"Haven"
"Minion"
# 6: terminal card-drawers, if we have actions to spare. (600-699)
"Library" if my.actions > 1 and my.hand.length <= 4 # 695
"Torturer" if my.actions > 1
"Margrave" if my.actions > 1
"Rabble" if my.actions > 1
"Witch" if my.actions > 1
"Ghost Ship" if my.actions > 1
"Smithy" if my.actions > 1
"Embassy" if my.actions > 1
"Watchtower" if my.actions > 1 and my.hand.length <= 4
"Library" if my.actions > 1 and my.hand.length <= 5 # 620
"Council Room" if my.actions > 1
"Courtyard" if my.actions > 1 and (my.discard.length + my.draw.length) <= 3
"Oracle" if my.actions > 1
# 7: Let's insert here an overly simplistic idea of how to play Crossroads.
# Or if we don't have a Crossroads, play a Great Hall that we might otherwise
# have played in priority level 5. (500-599)
"Crossroads" unless my.countInPlay(state.cardInfo.Crossroads) > 0
"Great Hall"
# 8: card-cycling that might improve the hand. (400-499)
"Upgrade" if wantsToTrash >= multiplier
"Oasis"
"Pawn"
"Warehouse"
"Cellar"
"Library" if my.actions > 1 and my.hand.length <= 6
"Spice Merchant" if this.choose('spiceMerchantTrash', state, my.hand.concat([null]))
# 9: non-terminal cards that don't succeed but at least give us something. (300-399)
"King's Court"
"Throne Room" if okayToPlayMultiplier
"Tournament"
"Menagerie"
"Shanty Town" if my.actions < 2
# 10: terminals. Of course, Nobles might be a non-terminal
# if we decide we need the actions more than the cards. (100-299)
"Crossroads"
"Nobles"
"Treasure Map" if my.countInHand("Treasure Map") >= 2
"Followers"
"Mountebank" # 290
"Witch"
"Sea Hag"
"Torturer"
"Young Witch"
"Tribute" # after Cursers but before other terminals, there is probably a better spot for it
"MargrPI:NAME:<NAME>END_PI" # 280
"Goons"
"Wharf"
# Tactician needs a play condition, but I don't know what it would be.
"Tactician"
"Masquerade" # 270
"Vault"
"Ghost Ship"
"PI:NAME:<NAME>END_PI"
"Explorer" if my.countInHand("Province") >= 1
"Library" if my.hand.length <= 3 # 260
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"Cutpurse" # 250
"Bridge"
"Bishop"
"Horse Traders" # 240
"Jack of All Trades"
"PI:NAME:<NAME>END_PIard"
"MoneyPI:NAME:<NAME>END_PI" if countInHandCopper >= 1 # 230
"Expand"
"Remodel"
"SalPI:NAME:<NAME>END_PIager" # 220
"Mine"
"PI:NAME:<NAME>END_PI" if countInHandCopper >= 3
"Library" if my.hand.length <= 4 # 210
"Rabble"
"Envoy"
"Smithy" # 200
"Embassy"
"Watchtower" if my.hand.length <= 3
"Council Room"
"Library" if my.hand.length <= 5
"Watchtower" if my.hand.length <= 4 # 190
"Courtyard" if (my.discard.length + my.draw.length) > 0
"Merchant Ship"
"Baron" if my.countInHand("Estate") >= 1
"Monument"
"Oracle" # 180
"Remake" if wantsToTrash >= multiplier * 2 # has a low priority so it'll mostly be played early in the game
"Adventurer"
"Harvest"
"Haggler" # probably needs to make sure the gained card will be wanted; 170
"PI:NAME:<NAME>END_PI"
"Explorer"
"Woodcutter"
"Nomad Camp"
"Chancellor" # 160
"Counting House"
"PI:NAME:<NAME>END_PI" if countInHandCopper >= 2
"Outpost" if state.extraturn == false
"Ambassador" if wantsToTrash # 150
"Trading Post" if wantsToTrash + my.countInHand("Silver") >= 2 * multiplier
"Chapel" if wantsToTrash
"Trader" if wantsToTrash >= multiplier
"Trade Route" if wantsToTrash >= multiplier
"Mint" if my.ai.choose('mint', state, my.hand) # 140
"Secret Chamber"
"Pirate Ship"
"Noble Brigand"
"Thief"
"Island" # could be moved
"Fortune Teller" # 130
"Bureaucrat"
"Navigator"
"Conspirator" if my.actions < 2
"Herbalist"
"Moat" # 120
"Library" if my.hand.length <= 6
"Ironworks" # should have higher priority if condition can see it will gain an Action card
"Workshop"
"Smugglers" if state.smugglerChoices().length > 1 # 110
"Feast"
"Transmute" if wantsToTrash >= multiplier
"PI:NAME:<NAME>END_PI"
"Saboteur"
"Poor House"
"Duchess"
"Library" if my.hand.length <= 7
"Thief" # 100
# 11: cards that have become useless. Maybe they'll decrease
# the cost of Peddler, trigger Conspirator, or something. (20-99)
"Treasure Map" if my.countInDeck("Gold") >= 4 and state.current.countInDeck("Treasure Map") == 1
"Spice Merchant"
"Shanty Town"
"Stables" # 50
"Chapel"
"Library"
# 12: Conspirator when +actions remain. (10)
"Conspirator"
# "Baron"
# At this point, we take no action if that choice is available.
null
# Nope, something is forcing us to take an action.
#
# Last priority: cards that are actively harmful to play at this point,
# in order of increasing badness.
"Baron"
"Mint"
"Watchtower"
"Outpost"
"Ambassador" # -20
"Trader"
"Transmute"
"Trade Route"
"Upgrade" # -30
"Remake"
"Trading Post"
"Treasure Map" # -40
"Throne Room"
]
# `multipliedActionPriority` is similar to `actionPriority`, but is used when
# we have played a Throne Room or King's Court.
#
# This list emphasizes cards that are really good when multiplied, especially
# terminals when there are +actions left. At the end, it falls back on the
# usual actionPriority list.
old_multipliedActionPriority: (state, my) ->
[
"King's Court" # 2000
"Throne Room" # 1900
"Followers" if my.actions > 0
"Grand Market"
"Mountebank" if my.actions > 0
"Witch" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Sea Hag" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Torturer" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Young Witch" if my.actions > 0 and state.countInSupply("Curse") >= 2
"Crossroads" if my.actions > 0 or my.countInPlay(state.cardInfo.Crossroads) == 0 # 1800
"Scheme" if my.countInDeck("King's Court") >= 2
# Scrying Pool was here once, but I think you'd rather use it to *draw*
# actions for your KC
"Wharf" if my.actions > 0
"Bridge" if my.actions > 0
"Minion" # 1700
"Ghost Ship" if my.actions > 0
"Jester" if my.actions > 0
"Horse Traders" if my.actions > 0
"Mandarin" if my.actions > 0
"Rabble" if my.actions > 0 # 1600
"Council Room" if my.actions > 0
"Margrave" if my.actions > 0
"Smithy" if my.actions > 0
"Embassy" if my.actions > 0
"Merchant Ship" if my.actions > 0 # 1500
"Pirate Ship" if my.actions > 0
"Saboteur" if my.actions > 0
"Noble Brigand" if my.actions > 0
"Thief" if my.actions > 0
"Monument" if my.actions > 0 # 1400
"Feast" if my.actions > 0
"Conspirator"
"Nobles"
"Tribute"
"Steward" if my.actions > 0 # 1300
"Goons" if my.actions > 0
"Mine" if my.actions > 0
"Masquerade" if my.actions > 0
"Vault" if my.actions > 0
"Oracle" if my.actions > 0 # 1200
"Cutpurse" if my.actions > 0
"Coppersmith" if my.actions > 0 and my.countInHand("Copper") >= 2
"Ambassador" if my.actions > 0 and this.wantsToTrash(state) # 1100
"wait"
# We could add here some more cards that would be nice to play with a
# multiplier. Nicer than Lookout, let's say, which appears pretty high
# on the regular action priority list.
#
# But at this point, just fall back on that priority list.
].concat(this.old_actionPriority(state, my, skipMultipliers=true))
# `treasurePriority` determines what order to play treasures in.
# Most of the order has no effect on gameplay. The
# important part is that Bank and Horn of Plenty are last.
treasurePriority: (state, my) -> [
"Platinum"
"PI:NAME:<NAME>END_PI"
"Philosopher's Stone"
"Gold"
"Cache"
"Hoard"
"Royal Seal"
"PI:NAME:<NAME>END_PI"
"Silver"
"Fool's Gold"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"Masterpiece"
"Potion" # 100 from here up
"Loan" # 90
"Venture" # 80
"Ill-Gotten Gains"
"Bank"
"Horn of Plenty" if my.numUniqueCardsInPlay() >= 2
"Spoils" if this.wantsToPlaySpoils(state)
null
]
# The default `discardPriority` is tuned for Big Money where the decisions
# are obvious. But many strategies would probably prefer a different
# priority list, especially one that knows about action cards.
#
# It doesn't understand
# discarding cards to make Shanty Town or Menagerie work, for example.
discardPriority: (state, my) -> [
"Tunnel"
"Vineyard"
"Colony"
"Duke"
"Duchy"
"Fairgrounds"
"Gardens"
"Province" # Provinces are occasionally useful in hand
"Curse"
"Estate"
]
discardValue: (state, card, my) ->
# If we can discard excess actions, do so. Otherwise, discard the cheapest
# cards. Victory cards would already have been discarded by discardPriority,
# but if Tunnel fell through somehow we discard it here.
#
# First, check to see if it's our turn. That changes whether we want to discard
# actions.
myTurn = (state.current == my)
if card.name == 'Tunnel'
25
else if card.isAction and myTurn and \
((card.actions == 0 and my.actionBalance() <= 0) or (my.actions == 0))
20 - card.cost
else
0 - card.cost
trashPriority: (state, my) -> [
"Curse"
"Estate" if state.gainsToEndGame() > 4
"Copper" if my.getTotalMoney() > 4
"Potion" if my.turnsTaken >= 10
"Estate" if state.gainsToEndGame() > 2
]
# If we have to trash a card we don't want to, assign a value to each card.
# By default, we want to trash the card with the lowest (cost + VP).
trashValue: (state, card, my) ->
0 - card.vp - card.cost
#developPriority: (state, my) =>
# trashPriority(state, my)
#developValue: (state, card, my) =>
# this.trashValue(state, card, my)
# Some cards give you a choice to discard an opponent's deck. These are
# evaluated with `discardFromOpponentDeckValue`.
discardFromOpponentDeckValue: (state, card, my) ->
if card.name == 'Tunnel'
return -2000
else if not (card.isAction) and not (card.isTreasure)
return -10
else
return card.coins + card.cost + 2*card.isAttack
# `discardHandValue` decides whether to discard an entire hand of cards.
discardHandValue: (state, hand, my, nCards = 5) ->
return 0 if hand is null
deck = my.discard.concat(my.draw)
total = 0
for i in [0...5]
shuffle(deck)
randomHand = deck[0...nCards]
# If a random hand from this deck is better, discard this hand.
total += my.ai.compareByDiscarding(state, randomHand, hand)
return total
# Prefer to gain action and treasure cards on the deck, assuming we want
# them at all. Give other cards a value of -1 so that `null` is a better
# choice.
gainOnDeckValue: (state, card, my) ->
if (card.isAction or card.isTreasure)
this.getChoiceValue('gain', state, card, my)
else
-1
# Changed Priorities for putting cards back on deck. Only works well for putting back 1 card, and for 1 buy.
#
putOnDeckPriority: (state, my) ->
# Make a priority order of:
#
# 1. Actions we can't or don't intend to play, from best to worst
# 2. Treasures we can afford to put back
# 3. Junk cards
# 1) Actions
actions = (card for card in my.hand when card.isAction)
getChoiceValue = this.getChoiceValue
byPlayValue = (x, y) ->
getChoiceValue('play', state, y, my) - getChoiceValue('play', state, x, my)
actions.sort(byPlayValue)
putBack = actions[my.countPlayableTerminals(state) ...]
# 2) Put back as much money as you can
if putBack.length == 0
# Get a list of all distinct treasures in hand, in order.
treasures = []
for card in my.hand
if (card.isTreasure) and (not (card in treasures))
treasures.push card
treasures.sort( (x, y) -> y.coins - x.coins )
# Get the margin of how much money we're willing to discard.
margin = my.ai.coinLossMargin(state)
# Find the treasure cards worth less than that.
for card in treasures
if my.ai.coinsDueToCard(state, card) <= margin
putBack.push(card)
# Don't put back last Potion if Alchemists are in play
if my.countInPlay(state.cardInfo["Alchemist"])>0
if "Potion" in putBack
putBack.remove(state.cardInfo["Potion"])
# 3) Put back the worst card (take priority for discard)
if putBack.length == 0
putBack = [my.ai.choose('discard', state, my.hand)]
putBack
putOnDeckValue: (state, card, my) =>
this.discardValue(state, card, my)
# How much does the AI want to discard its deck right now (for Chancellor)?
# Here, we decide to reshuffle (returning a reshuffleValue over 0) when most
# of the non-Action, non-Treasure cards are in the draw pile, or when there
# are no such cards in the deck.
reshuffleValue: (state, choice, my) ->
junkToDraw = 0
totalJunk = 0
for card in my.draw
if not (card.isAction or card.isTreasure)
junkToDraw++
for card in my.getDeck()
if not (card.isAction or card.isTreasure)
totalJunk++
return 1 if (totalJunk == 0)
proportion = junkToDraw/totalJunk
return (proportion - 0.5)
# Choose opponent treasure to trash; go by the card's base cost.
# Diadems are comparable to the cost-5 treasures.
trashOppTreasureValue: (state, card, my) =>
if card is 'Diadem'
return 5
return card.cost
#### Decisions for particular cards
# `ambassadorPriority` chooses a card to Ambassador and how many of it to
# return.
#
# These choices may look odd: remember that choices are evaluated as strings.
# So if we return lists, they won't match any of the choices. We need to
# return their joined string versions.
#
# This is a moderately acceptable way to deal with the fact that, in
# JavaScript, lists are never "equal" to other lists anyway.
ambassadorPriority: (state, my) ->
[
"[Curse, 2]"
"[Curse, 1]"
"[Curse, 0]"
# Handle a silly case:
"[Ambassador, 2]"
"[Estate, 2]"
"[Estate, 1]"
# Make sure we have at least $5 in the deck, including if we buy a Silver.
"[Copper, 2]" if my.getTreasureInHand() < 3 and my.getTotalMoney() >= 5
"[Copper, 2]" if my.getTreasureInHand() >= 5
"[Copper, 2]" if my.getTreasureInHand() == 3 and my.getTotalMoney() >= 7
"[Copper, 1]" if my.getTreasureInHand() < 3 and my.getTotalMoney() >= 4
"[Copper, 1]" if my.getTreasureInHand() >= 4
"[Estate, 0]"
"[Copper, 0]"
"[Potion, 2]"
"[Potion, 1]"
null
].concat ("[#{card}, 1]" for card in my.ai.trashPriority(state, my) when card?)\
.concat ("[#{card}, 0]" for card in my.hand)
apprenticeTrashPriority: (state, my) ->
"Border Village"
"Mandarin"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Feodum"
"Estate"
"Curse"
"Apprentice"
apprenticeTrashValue: (state, card, my) ->
vp = card.getVP(my)
[coins, potions] = card.getCost(state)
drawn = Math.min(my.draw.length + my.discard.length, coins+2*potions)
return this.choiceToValue('trash', state, card) + 2*drawn - vp
# The question here is: do you want to discard an Estate using a Baron?
# And the answer is yes.
baronDiscardPriority: (state, my) -> [yes]
# `bishopTrashPriority` lists cards that are especially good to trash.
bishopTrashPriority: (state, my) -> [
"Farmland"
"Duchy" if this.goingGreen(state) < 3
"Border Village"
"Mandarin"
"Feodum"
"Bishop"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Curse"
]
bishopTrashValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
value = Math.floor(coins/2) - card.getVP(my)
# if we're going for victory points, that's all we care about.
if this.goingGreen(state) >= 3
return value
# otherwise, focus on what we want to trash
else
if card in this.trashPriority(state, my)
value += 1
if card.isAction and ((card.actions == 0 and my.actionBalance() <= 0) or (my.actions == 0))
value += 1
if card.isTreasure and card.coins > (this.coinLossMargin(state) + 1)
value -= 10
return value
envoyValue: (state, card, my) ->
# Choose a card to discard from your opponent's hand when it's their turn.
opp = state.current
if card.name == 'Tunnel'
return -25
else if not (card.isAction) and not (card.isTreasure)
return -10
else if opp.actions == 0 and card.isAction
return -5
else if opp.actions >= 2
return card.cards + card.coins + card.cost + 2*card.isAttack
else
return card.coins + card.cost + 2*card.isAttack
# `foolsGoldTrashPriority` will trash a Fool's Gold for a real Gold if
# it's nearing the endgame (5 gains or less), there is one FG in hand,
# and losing it will not change its buy.
foolsGoldTrashPriority: (state, my) ->
if my.countInHand(state.cardInfo["Fool's Gold"]) == 1 and my.ai.coinLossMargin(state) >= 1
[yes]
else
[no]
# Do you want to gain a copper from Ill-Gotten Gains? Yes, we want if that improves our buy
gainCopperPriority: (state, my) ->
if my.ai.coinGainMargin(state) <= my.countInHand("Ill-Gotten Gains")+1
[yes]
else
[no]
# The `herbalist` decision puts a treasure card back on the deck. It sounds
# the same as `putOnDeck`, but it's for a different
# situation -- the card is coming from in play, not from your hand. So
# actually we use the `mintValue` by default.
herbalistValue: (state, card, my) =>
this.mintValue(state, card, my)
huntingGroundsGainPriority: (state, my) -> [
"Duchy"
"Estates"
]
# islandPriority chooses which card to set aside with Island. At present this
# list is incomplete, but covers just about everything that we would want to set aside
# with an Island.
islandPriority: (state, my) ->
[
"Colony"
"Province"
"Fairgrounds"
"Duchy"
"Duke"
"Gardens"
"Vineyard"
"Estate"
"Copper"
"Curse"
"Island"
"Tunnel"
]
islandValue: (state, card, my) -> this.discardValue(state, card, my)
librarySetAsideValue: (state, card, my) -> [
if my.actions == 0 and card.isAction
1
else
-1
]
miningVillageTrashValue: (state, choice, my) ->
if this.goingGreen(state) and this.coinGainMargin(state) <= 2
1
else
-1
minionDiscardValue: (state, choice, my) ->
if choice == yes
# Find out how valuable it would be to discard these cards and draw 4.
value = this.discardHandValue(state, my.hand, my, 4)
opponent = state.players[state.players.length - 1]
# If the attack would decrease an opponent's hand size, it's more valuable.
if opponent.hand.length > 4
value += 2
return value
else
return 0
# Mint anything but Copper and Diadem. Otherwise, go mostly by the card's base cost.
# There is only 1 Diadem, never any available to gain, so never Mint it.
mintValue: (state, card, my) ->
return card.cost - 1
# Choose whether we want these cards or two random cards.
oracleDiscardValue: (state, cards, my) ->
deck = my.discard.concat(my.draw)
shuffle(deck)
randomCards = deck[0...cards.length]
return my.ai.compareByDiscarding(state, my.hand.concat(randomCards), my.hand.concat(cards))
# Choose to attack or use available coins when playing Pirate Ship.
# Current strategy is basically Geronimoo's attackUntil5Coins play strategy,
# but only with Provinces--or technically, cards costing 8 or more.
pirateShipPriority: (state, my) -> [
'coins' if state.current.mats.pirateShip >= 5 and state.current.getAvailableMoney()+state.current.mats.pirateShip >= 8
'attack'
]
# might want to think about something more clever, but for first, just discard Coppers
plazaDiscardPriority: (state, my) -> [
"Copper"
null
]
rogueGainValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
return coins
rogueTrashValue: (state, card, my) ->
[coins, potions] = card.getCost(state)
return coins
salvagerTrashPriority: (state, card, my) -> [
"Border Village"
"Mandarin"
"Ill-Gotten Gains" if this.coinLossMargin(state) > 0
"Feodum"
"Salvager"
]
# To calculate the salvagerTrashValue, we simulate trashing each card, determine
# the best card we would buy as a result, and evaluate it as if we were
# upgrading the trashed card into the bought one.
salvagerTrashValue: (state, card, my) ->
[hypothesis, hypothetically_my] = state.hypothetical(this)
hypothetically_my.hand.remove(card)
[coins, potions] = card.getCost(hypothesis)
hypothetically_my.coins += coins
hypothetically_my.buys += 1
buyState = this.fastForwardToBuy(hypothesis, hypothetically_my)
gained = buyState.getSingleBuyDecision()
return this.upgradeValue(state, [card, gained], my)
# Scheme uses the same priority function as multiplied actions. Good actions
# to multiply this turn are typically good actions to have around next turn.
schemeValue: (state, card, my) ->
# Project a little of what the state will look like at the beginning of the
# next turn. This keeps multipliedActionPriority from evaluating a card
# as though it will be used in the current (finished) turn.
myNext = {}
myNext[key] = value for key, value of my
myNext.actions = 1
myNext.buys = 1
myNext.coins = 0
return this.getChoiceValue('multiplied', state, card, myNext)
# `scryingPoolDiscardValue` is like `discardValue`, except it strongly
# prefers to discard non-actions.
scryingPoolDiscardValue: (state, card, my) ->
if not card.isAction
2000
else
this.choiceToValue('discard', state, card)
spiceMerchantTrashPriority: (state, my) -> [
"Copper",
"Potion",
"Loan",
"Ill-Gotten Gains",
"Fool's Gold" if my.countInDeck("Fool's Gold") == 1,
"Silver" if my.getTotalMoney() >= 8,
null,
"Silver",
"Venture",
"Cache",
"Gold",
"Harem",
"Platinum"
]
# Which treasure, if any, should be discarded to feed Stables? Defaults
# to a list of generally crappy treasures. Doesn't include $1 Fool's Gold
# because you presumably have another one you're trying to draw.
stablesDiscardPriority: (state, my) -> [
"Copper"
"Potion" if my.countInPlay(state.cardInfo["Alchemist"]) == 0
"Ill-Gotten Gains"
"Silver"
"Horn of Plenty"
null
"Potion"
"Venture"
"Cache"
"Gold"
"Platinum"
]
# Do you want to discard a Province to win a Tournament? The answer is
# *very* yes.
tournamentDiscardPriority: (state, my) -> [yes]
transmuteValue: (state, card, my) ->
if card.isAction and this.goingGreen(state)
return 10
else if card.isAction and card.isVictory and card.cost <= 4
return 1000
else
return this.choiceToValue('trash', state, card)
# `wishValue` prefers to wish for the card its draw pile contains
# the most of.
#
# The fact that this doesn't make a hypothetical copy is a shortcut. We are
# technically "peeking" at the deck, but we don't use any information except
# the count of each card, which would be the same in any hypothetical version.
wishValue: (state, card, my) ->
pile = my.draw
if pile.length == 0
pile = my.discard
return countInList(pile, card)
# Choose to discard or to gain a curse when attacked by Torturer.
torturerPriority: (state, my) -> [
'curse' if state.countInSupply("Curse") == 0
'discard' if my.ai.wantsToDiscard(state) >= 2
'discard' if my.hand.length <= 1
'curse' if my.trashingInHand() > 0
'curse' if my.hand.length <= 3
'discard'
'curse'
]
#### Trash-for-benefit decisions
# Taking into account gain priorities, gain values, trash priorities, and
# trash values, how much do we like having this card in our deck overall?
cardInDeckValue: (state, card, my) ->
endgamePower = 1
# Are we in the late game? If so, we care much more about getting cards
# at the top of our priority order.
if state.gainsToEndGame() <= 5
endgamePower = 3
return -(this.choiceToValue('trash', state, card)) + \
Math.pow(this.choiceToValue('gain', state, card), endgamePower)
# upgradeValue measures the benefit of choices on Remodel, Upgrade,
# and so on, where you exchange one card for a better one.
#
# So here's a really basic thing that might work.
upgradeValue: (state, choice, my) ->
[oldCard, newCard] = choice
return my.ai.cardInDeckValue(state, newCard, my) - \
my.ai.cardInDeckValue(state, oldCard, my)
# developValue measures the benefit of choices Develop,
# where you exchange one card for two.
#
# So here's a really basic thing that might work.
developValue: (state, choice, my) ->
[oldCard, [newCard1, newCard2]] = choice
return my.ai.cardInDeckValue(state, newCard1, my) + \
my.ai.cardInDeckValue(state, newCard2, my) - \
my.ai.cardInDeckValue(state, oldCard, my)
# `chooseOrderOnDeck` handles situations where multiple cards are returned
# to the deck, such as Scout and Apothecary.
#
# This decision doesn't fit into the xPriority / xValue framework, as there
# are a number of mostly indistinguishable choices. Instead of listing all
# the permutations of cards as choices, we just list the cards to arrange.
#
# The default decision is to put the cards with the lowest discard value on
# top.
chooseOrderOnDeck: (state, cards, my) ->
sorter = (card1, card2) ->
my.ai.choiceToValue('discard', state, card1)\
- my.ai.choiceToValue('discard', state, card2)
choice = cards.slice(0)
return choice.sort(sorter)
# How much do we want to overpay for Masterpiece?
# If we care to buy it probably as much as possible
#
chooseOverpayMasterpiece: (state, maxAmount) ->
return maxAmount
# How many Coin Tokens do we want to spend?
# Try to buy the 'best' card you can afford, and spend as less as possible for this
#
spendCoinTokens: (state, my) ->
cardsBoughtOld = []
ct = my.coinTokens
loop
[hypState, hypMy] = state.hypothetical(this)
hypMy.coins += ct
hypMy.coinTokensSpendThisTurn = ct
cardsBought = []
while hypMy.buys > 0
cardBought = hypState.getSingleBuyDecision()
if cardBought?
[coinCost, potionCost] = cardBought.getCost(hypState)
hypMy.coins -= coinCost
hypMy.potions -= potionCost
cardsBought.push cardBought
hypMy.buys -= 1
if ((ct < my.coinTokens) and not (arrayEqual(cardsBought, cardsBoughtOld)))
ct += 1
break
if ct == 0
break
ct -= 1
cardsBoughtOld = cardsBought
return ct
#### Informational methods
# When presented with a card with simple but variable benefits, such as
# Nobles, this is the default way for an AI to decide which benefit it wants.
# This function should actually handle a number of common situations.
benefitValue: (state, choice, my) ->
buyValue = 1
cardValue = 2
coinValue = 3
trashValue = 4 # if there are cards we want to trash
actionValue = 10 # if we need more actions
actionBalance = my.actionBalance()
usableActions = Math.max(0, -actionBalance)
if actionBalance >= 1
cardValue += actionBalance
if my.ai.wantsToTrash(state) < (choice.trash ? 0)
trashValue = -4
value = cardValue * (choice.cards ? 0)
value += coinValue * (choice.coins ? 0)
value += buyValue * (choice.buys ? 0)
value += trashValue * (choice.trash ? 0)
value += actionValue * Math.min((choice.actions ? 0), usableActions)
value
# `wantsToTrash` returns the number of cards in hand that we would trash
# for no benefit.
wantsToTrash: (state) ->
my = this.myPlayer(state)
trashableCards = 0
for card in my.hand
if this.chooseTrash(state, [card, null]) is card
trashableCards += 1
return trashableCards
# `wantsToPlayRats` is like `wantsToTrash` except that the answer is no.
#
# Come on, it's a first-order approximation of good strategy. If you've got
# a better idea, put it in a strategy file.
wantsToPlayRats: (state) -> no
# `wantsToDiscard` returns the number of cards in hand that we would
# freely discard.
wantsToDiscard: (state) ->
my = this.myPlayer(state)
discardableCards = 0
for card in my.hand
if this.chooseDiscard(state, [card, null]) is card
discardableCards += 1
return discardableCards
multiplierChoices: (state) ->
my = this.myPlayer(state)
mults = (card for card in my.hand when card.isMultiplier)
if mults.length > 0
mult = mults[0]
choices = (card for card in my.hand when card.isAction)
choices.remove(mult)
choices.push(null)
return choices
else
return []
okayToPlayMultiplier: (state) ->
choices = this.multiplierChoices(state)
if this.choose('multiplied', state, choices)?
return true
else
return false
wantsToPlayMultiplier: (state) ->
my = this.myPlayer(state)
choices = this.multiplierChoices(state)
if choices.length > 1
choice = this.choose('multiplied', state, choices)
multipliedValue = this.getChoiceValue('multiplied', state, choice, my)
if choice? and choice.isMultiplier
# prevent infinite loops
unmultipliedValue = 0
else
unmultipliedValue = this.getChoiceValue('play', state, choice, my)
return (multipliedValue > unmultipliedValue)
return false
# play Spoils if it changes your buys this turn. Or if in hypothetical state to solve recursion
wantsToPlaySpoils: (state) ->
if state.depth > 0
return true
else
cardsGainedWithout = this.pessimisticCardsGained(state)
[hypState, hypMy] = state.hypothetical(this)
hypState.current.hand.remove(c["Spoils"])
cardsGainedWith = this.pessimisticCardsGained(hypState)
if arrayEqual(cardsGainedWithout, cardsGainedWith)
return false
else
return true
# wantsToRebuild and rebuildPriority: taken from the Rebuild strategy
wantsToRebuild: (state, my) ->
if my.countInHand("Rebuild") >= state.countInSupply("Province") \
and my.ai.getScoreDifference(state, my) > 0
answer = 1
else if state.countInSupply("Province") == 1 \
and my.ai.getScoreDifference(state, my) < -4
answer = 0
else if state.countInSupply("Duchy") == 0 \
and my.ai.countNotInHand(my, "Duchy") == 0\
and my.ai.getScoreDifference(state, my) < 0
answer = 0
else if my.getTreasureInHand() > 7 and state.countInSupply("Province") == 1
answer = 0
else
answer = state.countInSupply("Province") > 0
return answer
rebuildPriority: (state, my) -> [
"Province"
"Duchy"
"Estate"
]
nameVPPriority: (state, my) -> [
"Colony" if my.countInDeck("Colony") > 0
"Province"
]
# Assume we always want to play Journeyman
wantsToJM: (state, my) ->
true
wantsToDiscardBeggar: (state) ->
return true
# `goingGreen`: determine when we're playing for victory points. By default,
# it's if there are any Colonies, Provinces, or Duchies in the deck.
#
# The bigger the number, the greener the deck, but a true (greater than 0)
# value is a good indication in itself that we want victory cards.
goingGreen: (state) ->
my = this.myPlayer(state)
bigGreen = my.countInDeck("Colony") + my.countInDeck("Province") + my.countInDeck("Duchy")
return bigGreen
# `pessimisticMoneyInHand` establishes a minimum on how much money the
# player will be able to spend in this game state. It assumes the player
# will draw no money from the deck.
pessimisticMoneyInHand: (state) ->
# Don't recurse more than once. If we're already in a hypothetical
# situation, use the stupid version instead.
if state.depth > 0
return this.myPlayer(state).getAvailableMoney()
buyPhase = this.pessimisticBuyPhase(state)
return buyPhase.current.coins
# Look ahead to the buy phase, assuming we draw no money from the deck.
#
# TODO: when we can handle known cards on top of the deck, take them
# into account.
pessimisticBuyPhase: (state) ->
if state.depth > 0
# A last-ditch effort to avoid recursion, by simply fast-forwarding
# to the next phase.
if state.phase == 'action'
state.phase = 'treasure'
else if state.phase == 'treasure'
state.phase = 'buy'
[hypothesis, hypothetically_my] = state.hypothetical(this)
return this.fastForwardToBuy(hypothesis, hypothetically_my)
fastForwardToBuy: (state, my) ->
if state.depth == 0
throw new Error("Can only fast-forward in a hypothetical state")
#We need to save draw and discard before emptying and restore them before buyPhase, to be able to choose the right buys in actionPriority(state)
oldDraws = my.draw.slice(0)
oldDiscard = my.discard.slice(0)
my.draw = []
my.discard = []
while state.phase != 'buy'
state.doPlay()
my.draw = oldDraws
my.discard = oldDiscard
return state
pessimisticCardsGained: (state) ->
newState = this.pessimisticBuyPhase(state)
newState.doPlay()
return newState.current.gainedThisTurn
# coinLossMargin determines how much treasure the player can lose
# "for free" (because it won't change their buy decision). Intended to be
# more efficient than calling pessimisticCardsGained on a number
# of different states.
#
# TODO: do we need an equivalent for potions?
coinLossMargin: (state) ->
newState = this.pessimisticBuyPhase(state)
coins = newState.current.coins
cardToBuy = newState.getSingleBuyDecision()
return 0 if cardToBuy is null
[coinsCost, potionsCost] = cardToBuy.getCost(newState)
return coins - coinsCost
# coinGainMargin determines how much treasure the player wants to gain,
# in order to get a better card. Tries up to +$8, then returns Infinity
# if nothing changes.
coinGainMargin: (state) ->
newState = this.pessimisticBuyPhase(state)
coins = newState.current.coins
baseCard = newState.getSingleBuyDecision()
for increment in [1, 2, 3, 4, 5, 6, 7, 8]
newState.current.coins = coins+increment
cardToBuy = newState.getSingleBuyDecision()
if cardToBuy != baseCard
return increment
return Infinity
# Estimate the number of coins we'd lose by discarding/trashing/putting back
# a card.
coinsDueToCard: (state, card) ->
c = state.cardInfo
value = card.getCoins(state)
if card.isTreasure
banks = state.current.countInHand(state.cardInfo.Bank)
value += banks
if card is state.cardInfo.Bank
nonbanks = (aCard for aCard in state.current.hand when aCard.isTreasure).length
value += nonbanks
value
# Figure out whether hand1 or hand2 is better by discarding their cards
# in priority order, until one of them gets to 2 or fewer cards.
#
# Returns a -1 or 1 that can be used in sorting; it's
# positive if the first hand is better.
compareByDiscarding: (state, hand1, hand2) ->
# Guard against accidental mutation; we're going to be messing with
# these lists.
hand1 = hand1.slice(0)
hand2 = hand2.slice(0)
# Preserve our number of actions.
savedActions = state.current.actions
state.current.actions = 1
#state.log("hand1 = #{hand1}")
#state.log("hand2 = #{hand2}")
counter = 0
loop
counter++
if counter >= 100
throw new Error("got stuck in a loop")
# Figure out whether we'd rather discard from hand1 or hand2.
discard1 = this.choose('discard', state, hand1)
value1 = this.choiceToValue('discard', state, discard1)
discard2 = this.choose('discard', state, hand2)
value2 = this.choiceToValue('discard', state, discard2)
if value1 > value2
hand1.remove(discard1)
else if value2 > value1
hand2.remove(discard2)
else
hand1.remove(discard1)
hand2.remove(discard2)
if hand1.length <= 2 and hand2.length <= 2
state.current.actions = savedActions
return 0
if hand1.length <= 2
state.current.actions = savedActions
return -1
if hand2.length <= 2
state.current.actions = savedActions
return 1
#### Utility methods
#
# `copy` makes a copy of the AI. It will have the same behavior but a
# different name, and will not be equal to this AI.
copy: () =>
ai = new BasicAI()
for key, value of this
ai[key] = value
ai.name = this.name+'*'
ai
# Some functions need to check the actionPriority a lot. This pair of
# methods will save a cached value so you don't need to run such an expensive
# function over and over.
cachedActionPriority: (state, my) ->
my.ai.cachedAP
cacheActionPriority: (state, my) ->
@cachedAP = my.ai.actionPriority(state, my)
toString: () -> this.name
this.BasicAI = BasicAI
# Utility functions
# -----------------
# `count` counts the number of times `elt` appears in `list`.
countInList = (list, elt) ->
count = 0
for member in list
if member == elt
count++
count
# `stringify` turns an object into a string, while handling `null` safely.
stringify = (obj) ->
if obj is null
return null
else
return obj.toString()
# General function to randomly shuffle a list.
shuffle = (v) ->
i = v.length
while i
j = parseInt(Math.random() * i)
i -= 1
temp = v[i]
v[i] = v[j]
v[j] = temp
v
# compare Arrays
arrayEqual = (a, b) ->
a.length is b.length and a.every (elem, i) -> elem is b[i]
|
[
{
"context": "\n\t\tif req.query.password and req.query.password is password\n\t\t\tnext()\n\t\telse\n\t\t\tres.send(401)\nmongoose.connec",
"end": 931,
"score": 0.5975074768066406,
"start": 923,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\t@endpoint.addMiddleware('post'... | coffee/test/post.coffee | lbacas/mongoose-rest-endpoints | 1 | express = require 'express'
request = require 'supertest'
should = require 'should'
Q = require 'q'
mongoose = require 'mongoose'
require('../lib/log').verbose(true)
mre = require '../lib/endpoint'
# Custom "Post" and "Comment" documents
tracker = require '../lib/tracker'
moment = require 'moment'
commentSchema = new mongoose.Schema
comment:String
_post:
type:mongoose.Schema.Types.ObjectId
ref:'Post'
_author:
type:mongoose.Schema.Types.ObjectId
ref:'Author'
postSchema = new mongoose.Schema
date:Date
number:Number
string:
type:String
required:true
_comments:[
type:mongoose.Schema.Types.ObjectId
ref:'Comment'
$through:'_post'
]
_author:
type:mongoose.Schema.Types.ObjectId
ref:'Author'
authorSchema = new mongoose.Schema
name:'String'
# Custom middleware for testing
requirePassword = (password) ->
return (req, res, next) ->
if req.query.password and req.query.password is password
next()
else
res.send(401)
mongoose.connect('mongodb://localhost/mre_test')
cascade = require 'cascading-relations'
postSchema.plugin(cascade)
commentSchema.plugin(cascade)
authorSchema.plugin(cascade)
mongoose.model('Post', postSchema)
mongoose.model('Comment', commentSchema)
mongoose.model('Author', authorSchema)
mongoose.set 'debug', true
describe 'Post', ->
@timeout(5000)
describe 'Basic object', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', mongoose.model('Post'))
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
# clear out
mongoose.connection.collections.posts.drop()
done()
it 'should let you post with no hooks', (done) ->
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').send(data).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
done()
it 'should run middleware', (done) ->
@endpoint.addMiddleware('post', requirePassword('asdf')).register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').query
password:'asdf'
.send(data).end (err, res) =>
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
request(@app).post('/api/posts/').query
password:'ffff'
.send(data).end (err, res) =>
res.status.should.equal(401)
done()
it 'should run pre save', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_save', 'post', (req, model, next) ->
model.set('number', 8)
next(model)
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(8)
res.body.string.should.equal('Test')
done()
it 'should handle a thrown error on pre save', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_save', 'post', (req, model, next) ->
setTimeout ->
err = new Error('test')
err.code = 405
next(err)
, 2000
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(405)
done()
it 'should run pre response', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_response', 'post', (req, data, next) ->
setTimeout ->
data.number = 7
next(data)
, 2000
return null
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(7)
res.body.string.should.equal('Test')
# Make sure it didn't actually update the post
mongoose.model('Post').findById res.body._id, (err, mod) ->
mod.number.should.equal(5)
done()
describe 'Cascading relations', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', 'Post')
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
# clear out
mongoose.connection.collections.posts.drop()
done()
it 'should let you post with relations', (done) ->
@endpoint.cascade ['_comments'], (data, path) ->
data.comment += 'FFF'
return data
.register(@app)
data =
date:Date.now()
number:5
string:'Test'
_related:
_comments:[
comment:'asdf1234'
]
request(@app).post('/api/posts/').send(data).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
res.body._comments.length.should.equal(1)
res.body._related._comments.length.should.equal(1)
res.body._related._comments[0].comment.should.equal('asdf1234FFF')
done()
it 'should let you post with a ref and respond with populated relation', (done) ->
@endpoint.populate(['_author', '_comments']).cascade(['_comments']).register(@app)
aClass = mongoose.model('Author')
author = new aClass
name:'Testy McGee'
author.save =>
data =
date:Date.now()
number:5
string:'Test'
_author:author._id
_related:
_comments:[
comment:'test'
]
request(@app).post('/api/posts/').send(data).end (err, res) =>
console.log(res.body)
should.exist(res.body._related._author._id)
done()
it 'should let you post, update, put, update', (done) ->
@endpoint.cascade(['_comments'])
.populate('_comments')
.register(@app)
data =
date:Date.now()
number:5
string:'Test'
_related:
_comments:[
comment:'asdf1234'
]
console.log 'About to post...'
request(@app).post('/api/posts/').send(data).end (err, res) =>
post = res.body
post._related._comments.push
comment:'ffff5555'
request(@app).put('/api/posts/' + post._id).send(post).end (err, res) ->
res.status.should.equal(200)
res.body._comments.length.should.equal(2)
res.body._related._comments.length.should.equal(2)
should.not.exist(res.body._comments[1]._id)
res.body._related._comments[0].comment.should.equal('asdf1234')
res.body._related._comments[1].comment.should.equal('ffff5555')
done()
describe 'Tracking interface', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', 'Post')
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
if @mod
@mod.remove ->
done()
else
done()
it 'should run tracking interface on success', (done) ->
tracker.interface =
track: (params) ->
console.log 'Tracking params', params
params.response.code.should.equal(201)
(params.time < 50).should.equal(true)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').send(data).end (err, res) ->
console.log 'Ended'
it 'should run tracking interface on error', (done) ->
tracker.interface =
track: (params) ->
console.log 'Tracking params:', params
params.response.code.should.equal(400)
(params.time < 50).should.equal(true)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
request(@app).post('/api/posts/').send(data).end (err, res) ->
console.log 'Ended'
it 'should calculate time based on X-Request-Start header', (done) ->
tracker.interface =
track: (params) ->
params.response.code.should.equal(201)
params.time.should.be.greaterThan(100)
params.time.should.be.lessThan(200)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
requestStart = moment().valueOf() - 100
request(@app).post('/api/posts/').set('X-Request-Start', requestStart.toString()).send(data).end (err, res) ->
console.log 'Ended'
| 92604 | express = require 'express'
request = require 'supertest'
should = require 'should'
Q = require 'q'
mongoose = require 'mongoose'
require('../lib/log').verbose(true)
mre = require '../lib/endpoint'
# Custom "Post" and "Comment" documents
tracker = require '../lib/tracker'
moment = require 'moment'
commentSchema = new mongoose.Schema
comment:String
_post:
type:mongoose.Schema.Types.ObjectId
ref:'Post'
_author:
type:mongoose.Schema.Types.ObjectId
ref:'Author'
postSchema = new mongoose.Schema
date:Date
number:Number
string:
type:String
required:true
_comments:[
type:mongoose.Schema.Types.ObjectId
ref:'Comment'
$through:'_post'
]
_author:
type:mongoose.Schema.Types.ObjectId
ref:'Author'
authorSchema = new mongoose.Schema
name:'String'
# Custom middleware for testing
requirePassword = (password) ->
return (req, res, next) ->
if req.query.password and req.query.password is <PASSWORD>
next()
else
res.send(401)
mongoose.connect('mongodb://localhost/mre_test')
cascade = require 'cascading-relations'
postSchema.plugin(cascade)
commentSchema.plugin(cascade)
authorSchema.plugin(cascade)
mongoose.model('Post', postSchema)
mongoose.model('Comment', commentSchema)
mongoose.model('Author', authorSchema)
mongoose.set 'debug', true
describe 'Post', ->
@timeout(5000)
describe 'Basic object', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', mongoose.model('Post'))
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
# clear out
mongoose.connection.collections.posts.drop()
done()
it 'should let you post with no hooks', (done) ->
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').send(data).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
done()
it 'should run middleware', (done) ->
@endpoint.addMiddleware('post', requirePassword('<PASSWORD>')).register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').query
password:'<PASSWORD>'
.send(data).end (err, res) =>
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
request(@app).post('/api/posts/').query
password:'<PASSWORD>'
.send(data).end (err, res) =>
res.status.should.equal(401)
done()
it 'should run pre save', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_save', 'post', (req, model, next) ->
model.set('number', 8)
next(model)
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(8)
res.body.string.should.equal('Test')
done()
it 'should handle a thrown error on pre save', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_save', 'post', (req, model, next) ->
setTimeout ->
err = new Error('test')
err.code = 405
next(err)
, 2000
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(405)
done()
it 'should run pre response', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_response', 'post', (req, data, next) ->
setTimeout ->
data.number = 7
next(data)
, 2000
return null
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(7)
res.body.string.should.equal('Test')
# Make sure it didn't actually update the post
mongoose.model('Post').findById res.body._id, (err, mod) ->
mod.number.should.equal(5)
done()
describe 'Cascading relations', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', 'Post')
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
# clear out
mongoose.connection.collections.posts.drop()
done()
it 'should let you post with relations', (done) ->
@endpoint.cascade ['_comments'], (data, path) ->
data.comment += 'FFF'
return data
.register(@app)
data =
date:Date.now()
number:5
string:'Test'
_related:
_comments:[
comment:'asdf1234'
]
request(@app).post('/api/posts/').send(data).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
res.body._comments.length.should.equal(1)
res.body._related._comments.length.should.equal(1)
res.body._related._comments[0].comment.should.equal('asdf1234FFF')
done()
it 'should let you post with a ref and respond with populated relation', (done) ->
@endpoint.populate(['_author', '_comments']).cascade(['_comments']).register(@app)
aClass = mongoose.model('Author')
author = new aClass
name:'<NAME>'
author.save =>
data =
date:Date.now()
number:5
string:'Test'
_author:author._id
_related:
_comments:[
comment:'test'
]
request(@app).post('/api/posts/').send(data).end (err, res) =>
console.log(res.body)
should.exist(res.body._related._author._id)
done()
it 'should let you post, update, put, update', (done) ->
@endpoint.cascade(['_comments'])
.populate('_comments')
.register(@app)
data =
date:Date.now()
number:5
string:'Test'
_related:
_comments:[
comment:'asdf1234'
]
console.log 'About to post...'
request(@app).post('/api/posts/').send(data).end (err, res) =>
post = res.body
post._related._comments.push
comment:'ffff5555'
request(@app).put('/api/posts/' + post._id).send(post).end (err, res) ->
res.status.should.equal(200)
res.body._comments.length.should.equal(2)
res.body._related._comments.length.should.equal(2)
should.not.exist(res.body._comments[1]._id)
res.body._related._comments[0].comment.should.equal('asdf1234')
res.body._related._comments[1].comment.should.equal('ffff5555')
done()
describe 'Tracking interface', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', 'Post')
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
if @mod
@mod.remove ->
done()
else
done()
it 'should run tracking interface on success', (done) ->
tracker.interface =
track: (params) ->
console.log 'Tracking params', params
params.response.code.should.equal(201)
(params.time < 50).should.equal(true)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').send(data).end (err, res) ->
console.log 'Ended'
it 'should run tracking interface on error', (done) ->
tracker.interface =
track: (params) ->
console.log 'Tracking params:', params
params.response.code.should.equal(400)
(params.time < 50).should.equal(true)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
request(@app).post('/api/posts/').send(data).end (err, res) ->
console.log 'Ended'
it 'should calculate time based on X-Request-Start header', (done) ->
tracker.interface =
track: (params) ->
params.response.code.should.equal(201)
params.time.should.be.greaterThan(100)
params.time.should.be.lessThan(200)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
requestStart = moment().valueOf() - 100
request(@app).post('/api/posts/').set('X-Request-Start', requestStart.toString()).send(data).end (err, res) ->
console.log 'Ended'
| true | express = require 'express'
request = require 'supertest'
should = require 'should'
Q = require 'q'
mongoose = require 'mongoose'
require('../lib/log').verbose(true)
mre = require '../lib/endpoint'
# Custom "Post" and "Comment" documents
tracker = require '../lib/tracker'
moment = require 'moment'
commentSchema = new mongoose.Schema
comment:String
_post:
type:mongoose.Schema.Types.ObjectId
ref:'Post'
_author:
type:mongoose.Schema.Types.ObjectId
ref:'Author'
postSchema = new mongoose.Schema
date:Date
number:Number
string:
type:String
required:true
_comments:[
type:mongoose.Schema.Types.ObjectId
ref:'Comment'
$through:'_post'
]
_author:
type:mongoose.Schema.Types.ObjectId
ref:'Author'
authorSchema = new mongoose.Schema
name:'String'
# Custom middleware for testing
requirePassword = (password) ->
return (req, res, next) ->
if req.query.password and req.query.password is PI:PASSWORD:<PASSWORD>END_PI
next()
else
res.send(401)
mongoose.connect('mongodb://localhost/mre_test')
cascade = require 'cascading-relations'
postSchema.plugin(cascade)
commentSchema.plugin(cascade)
authorSchema.plugin(cascade)
mongoose.model('Post', postSchema)
mongoose.model('Comment', commentSchema)
mongoose.model('Author', authorSchema)
mongoose.set 'debug', true
describe 'Post', ->
@timeout(5000)
describe 'Basic object', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', mongoose.model('Post'))
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
# clear out
mongoose.connection.collections.posts.drop()
done()
it 'should let you post with no hooks', (done) ->
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').send(data).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
done()
it 'should run middleware', (done) ->
@endpoint.addMiddleware('post', requirePassword('PI:PASSWORD:<PASSWORD>END_PI')).register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').query
password:'PI:PASSWORD:<PASSWORD>END_PI'
.send(data).end (err, res) =>
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
request(@app).post('/api/posts/').query
password:'PI:PASSWORD:<PASSWORD>END_PI'
.send(data).end (err, res) =>
res.status.should.equal(401)
done()
it 'should run pre save', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_save', 'post', (req, model, next) ->
model.set('number', 8)
next(model)
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(8)
res.body.string.should.equal('Test')
done()
it 'should handle a thrown error on pre save', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_save', 'post', (req, model, next) ->
setTimeout ->
err = new Error('test')
err.code = 405
next(err)
, 2000
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(405)
done()
it 'should run pre response', (done) ->
postData =
date:Date.now()
number:5
string:'Test'
@endpoint.tap 'pre_response', 'post', (req, data, next) ->
setTimeout ->
data.number = 7
next(data)
, 2000
return null
.register(@app)
request(@app).post('/api/posts/').send(postData).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(7)
res.body.string.should.equal('Test')
# Make sure it didn't actually update the post
mongoose.model('Post').findById res.body._id, (err, mod) ->
mod.number.should.equal(5)
done()
describe 'Cascading relations', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', 'Post')
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
# clear out
mongoose.connection.collections.posts.drop()
done()
it 'should let you post with relations', (done) ->
@endpoint.cascade ['_comments'], (data, path) ->
data.comment += 'FFF'
return data
.register(@app)
data =
date:Date.now()
number:5
string:'Test'
_related:
_comments:[
comment:'asdf1234'
]
request(@app).post('/api/posts/').send(data).end (err, res) ->
res.status.should.equal(201)
res.body.number.should.equal(5)
res.body.string.should.equal('Test')
res.body._comments.length.should.equal(1)
res.body._related._comments.length.should.equal(1)
res.body._related._comments[0].comment.should.equal('asdf1234FFF')
done()
it 'should let you post with a ref and respond with populated relation', (done) ->
@endpoint.populate(['_author', '_comments']).cascade(['_comments']).register(@app)
aClass = mongoose.model('Author')
author = new aClass
name:'PI:NAME:<NAME>END_PI'
author.save =>
data =
date:Date.now()
number:5
string:'Test'
_author:author._id
_related:
_comments:[
comment:'test'
]
request(@app).post('/api/posts/').send(data).end (err, res) =>
console.log(res.body)
should.exist(res.body._related._author._id)
done()
it 'should let you post, update, put, update', (done) ->
@endpoint.cascade(['_comments'])
.populate('_comments')
.register(@app)
data =
date:Date.now()
number:5
string:'Test'
_related:
_comments:[
comment:'asdf1234'
]
console.log 'About to post...'
request(@app).post('/api/posts/').send(data).end (err, res) =>
post = res.body
post._related._comments.push
comment:'ffff5555'
request(@app).put('/api/posts/' + post._id).send(post).end (err, res) ->
res.status.should.equal(200)
res.body._comments.length.should.equal(2)
res.body._related._comments.length.should.equal(2)
should.not.exist(res.body._comments[1]._id)
res.body._related._comments[0].comment.should.equal('asdf1234')
res.body._related._comments[1].comment.should.equal('ffff5555')
done()
describe 'Tracking interface', ->
beforeEach (done) ->
@endpoint = new mre('/api/posts', 'Post')
@app = express()
@app.use(express.bodyParser())
@app.use(express.methodOverride())
done()
afterEach (done) ->
if @mod
@mod.remove ->
done()
else
done()
it 'should run tracking interface on success', (done) ->
tracker.interface =
track: (params) ->
console.log 'Tracking params', params
params.response.code.should.equal(201)
(params.time < 50).should.equal(true)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
request(@app).post('/api/posts/').send(data).end (err, res) ->
console.log 'Ended'
it 'should run tracking interface on error', (done) ->
tracker.interface =
track: (params) ->
console.log 'Tracking params:', params
params.response.code.should.equal(400)
(params.time < 50).should.equal(true)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
request(@app).post('/api/posts/').send(data).end (err, res) ->
console.log 'Ended'
it 'should calculate time based on X-Request-Start header', (done) ->
tracker.interface =
track: (params) ->
params.response.code.should.equal(201)
params.time.should.be.greaterThan(100)
params.time.should.be.lessThan(200)
done()
@endpoint.register(@app)
data =
date:Date.now()
number:5
string:'Test'
requestStart = moment().valueOf() - 100
request(@app).post('/api/posts/').set('X-Request-Start', requestStart.toString()).send(data).end (err, res) ->
console.log 'Ended'
|
[
{
"context": " = req.body.username.trim()\n newUser.password = req.body.password\n User.create newUser, (err, user) ->\n if ",
"end": 1044,
"score": 0.9989855885505676,
"start": 1027,
"tag": "PASSWORD",
"value": "req.body.password"
}
] | application/user/server/boot/routes.coffee | darkoverlordofdata/games | 0 | ensureLoggedIn = require("connect-ensure-login").ensureLoggedIn
module.exports = (app, mod) ->
app.get "/demo", (req, res, next) ->
mod.render res, "pages/index",
user: req.user
url: req.url
return
app.get "/auth/account", ensureLoggedIn("/login"), (req, res, next) ->
mod.render res, "pages/loginProfiles",
user: req.user
url: req.url
return
app.get "/link/account", ensureLoggedIn("/login"), (req, res, next) ->
mod.render res, "pages/linkedAccounts",
user: req.user
url: req.url
return
app.get "/local", (req, res, next) ->
mod.render res, "pages/local",
user: req.user
url: req.url
return
app.get "/signup", (req, res, next) ->
mod.render res, "pages/signup",
user: req.user
url: req.url
return
app.post "/signup", (req, res, next) ->
User = app.models.user
newUser = {}
newUser.email = req.body.email.toLowerCase()
newUser.username = req.body.username.trim()
newUser.password = req.body.password
User.create newUser, (err, user) ->
if err
req.flash "error", err.message
res.redirect "back"
else
# Passport exposes a login() function on req (also aliased as logIn())
# that can be used to establish a login session. This function is
# primarily used when users sign up, during which req.login() can
# be invoked to log in the newly registered user.
req.login user, (err) ->
if err
req.flash "error", err.message
return res.redirect("back")
res.redirect "/auth/account"
return
return
app.get "/login", (req, res, next) ->
mod.render res, "pages/login",
user: req.user
url: req.url
return
app.get "/link", (req, res, next) ->
mod.render res, "pages/link",
user: req.user
url: req.url
return
app.get "/auth/logout", (req, res, next) ->
req.logout()
res.redirect "/"
return
| 93509 | ensureLoggedIn = require("connect-ensure-login").ensureLoggedIn
module.exports = (app, mod) ->
app.get "/demo", (req, res, next) ->
mod.render res, "pages/index",
user: req.user
url: req.url
return
app.get "/auth/account", ensureLoggedIn("/login"), (req, res, next) ->
mod.render res, "pages/loginProfiles",
user: req.user
url: req.url
return
app.get "/link/account", ensureLoggedIn("/login"), (req, res, next) ->
mod.render res, "pages/linkedAccounts",
user: req.user
url: req.url
return
app.get "/local", (req, res, next) ->
mod.render res, "pages/local",
user: req.user
url: req.url
return
app.get "/signup", (req, res, next) ->
mod.render res, "pages/signup",
user: req.user
url: req.url
return
app.post "/signup", (req, res, next) ->
User = app.models.user
newUser = {}
newUser.email = req.body.email.toLowerCase()
newUser.username = req.body.username.trim()
newUser.password = <PASSWORD>
User.create newUser, (err, user) ->
if err
req.flash "error", err.message
res.redirect "back"
else
# Passport exposes a login() function on req (also aliased as logIn())
# that can be used to establish a login session. This function is
# primarily used when users sign up, during which req.login() can
# be invoked to log in the newly registered user.
req.login user, (err) ->
if err
req.flash "error", err.message
return res.redirect("back")
res.redirect "/auth/account"
return
return
app.get "/login", (req, res, next) ->
mod.render res, "pages/login",
user: req.user
url: req.url
return
app.get "/link", (req, res, next) ->
mod.render res, "pages/link",
user: req.user
url: req.url
return
app.get "/auth/logout", (req, res, next) ->
req.logout()
res.redirect "/"
return
| true | ensureLoggedIn = require("connect-ensure-login").ensureLoggedIn
module.exports = (app, mod) ->
app.get "/demo", (req, res, next) ->
mod.render res, "pages/index",
user: req.user
url: req.url
return
app.get "/auth/account", ensureLoggedIn("/login"), (req, res, next) ->
mod.render res, "pages/loginProfiles",
user: req.user
url: req.url
return
app.get "/link/account", ensureLoggedIn("/login"), (req, res, next) ->
mod.render res, "pages/linkedAccounts",
user: req.user
url: req.url
return
app.get "/local", (req, res, next) ->
mod.render res, "pages/local",
user: req.user
url: req.url
return
app.get "/signup", (req, res, next) ->
mod.render res, "pages/signup",
user: req.user
url: req.url
return
app.post "/signup", (req, res, next) ->
User = app.models.user
newUser = {}
newUser.email = req.body.email.toLowerCase()
newUser.username = req.body.username.trim()
newUser.password = PI:PASSWORD:<PASSWORD>END_PI
User.create newUser, (err, user) ->
if err
req.flash "error", err.message
res.redirect "back"
else
# Passport exposes a login() function on req (also aliased as logIn())
# that can be used to establish a login session. This function is
# primarily used when users sign up, during which req.login() can
# be invoked to log in the newly registered user.
req.login user, (err) ->
if err
req.flash "error", err.message
return res.redirect("back")
res.redirect "/auth/account"
return
return
app.get "/login", (req, res, next) ->
mod.render res, "pages/login",
user: req.user
url: req.url
return
app.get "/link", (req, res, next) ->
mod.render res, "pages/link",
user: req.user
url: req.url
return
app.get "/auth/logout", (req, res, next) ->
req.logout()
res.redirect "/"
return
|
[
{
"context": " database: 'fridgemagnets'\n username: 'fridgemagnets'\n password: 'some witty password here'\n",
"end": 343,
"score": 0.9996513724327087,
"start": 330,
"tag": "USERNAME",
"value": "fridgemagnets"
},
{
"context": " username: 'fridgemagnets'\n ... | server/config.coffee | elfsternberg/fridgemagnets | 0 | module.exports =
twitter:
consumer_key: "YOUR TWITTER CONSUMER KEY"
consumer_private_key: "YOUR TWITTER SECRET KEY"
access_token_key: "YOUR TWITTER ONE TIME ACCESS KEY"
access_token_secret: "YOUR TWITTER ONE TIME ACCESS SECRET"
tracker:
database: 'fridgemagnets'
username: 'fridgemagnets'
password: 'some witty password here'
| 33248 | module.exports =
twitter:
consumer_key: "YOUR TWITTER CONSUMER KEY"
consumer_private_key: "YOUR TWITTER SECRET KEY"
access_token_key: "YOUR TWITTER ONE TIME ACCESS KEY"
access_token_secret: "YOUR TWITTER ONE TIME ACCESS SECRET"
tracker:
database: 'fridgemagnets'
username: 'fridgemagnets'
password: '<PASSWORD>'
| true | module.exports =
twitter:
consumer_key: "YOUR TWITTER CONSUMER KEY"
consumer_private_key: "YOUR TWITTER SECRET KEY"
access_token_key: "YOUR TWITTER ONE TIME ACCESS KEY"
access_token_secret: "YOUR TWITTER ONE TIME ACCESS SECRET"
tracker:
database: 'fridgemagnets'
username: 'fridgemagnets'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
|
[
{
"context": "done) ->\n data = {message: 'Hello', author: 'world'}\n $.ajax\n type : 'PATCH'\n url",
"end": 3891,
"score": 0.6497218608856201,
"start": 3886,
"tag": "NAME",
"value": "world"
}
] | source/test/spec/fake_request.coffee | davidfou/plasticine | 1 | module.exports = -> describe 'Fake request', ->
mock_callback = null
done_callback = null
fail_callback = null
ajax_call = null
content = null
before ->
ajax_call = ->
$.ajax
type : 'GET'
url : '/info.json'
.done(done_callback)
.fail(fail_callback)
beforeEach ->
mock_callback = sinon.spy()
done_callback = sinon.spy()
fail_callback = sinon.spy()
content =
message : 'Hello'
receiver : 'world'
describe 'basic functionalities', ->
mock = null
before ->
mock = @plasticine.addMock
route: '/info.json'
get: ->
mock_callback()
status: 200
body:
message : 'Someone here?'
receiver : 'world'
it 'should intercept with a static route on a GET', (done) ->
ajax_call().always =>
@requests.should.have.length 0
fail_callback.should.not.have.been.called
done_callback.should.have.been.calledOnce
response_text = done_callback.firstCall.args[0]
(JSON.parse response_text).should.be.deep.equal
message : 'Someone here?'
receiver : 'world'
mock_callback.should.have.been.calledOnce
done()
it 'should not intercept when the mock is disposed', (done) ->
mock.dispose()
ajax_call().always ->
fail_callback.should.not.have.been.called
done_callback.should.have.been.calledOnce
response_text = done_callback.firstCall.args[0]
(JSON.parse response_text).should.be.deep.equal content
mock_callback.should.not.have.been.called
done()
@requests.should.have.length 1
@requests[0].respondHelper 200, content
describe 'arguments passed to callbacks', ->
mock = null
get_callback_stub = sinon.stub()
delete_callback_stub = sinon.stub()
post_callback_stub = sinon.stub()
put_callback_stub = sinon.stub()
patch_callback_stub = sinon.stub()
before ->
get_callback_stub.returns status: 200, body: {}
delete_callback_stub.returns status: 200, body: {}
post_callback_stub.returns status: 200, body: {}
put_callback_stub.returns status: 200, body: {}
patch_callback_stub.returns status: 200, body: {}
mock = @plasticine.addMock
route : '/info.json'
get : get_callback_stub
delete : delete_callback_stub
post : post_callback_stub
put : put_callback_stub
patch : patch_callback_stub
after ->
mock.dispose()
it 'should not give argument on a GET', (done) ->
$.ajax
type : 'GET'
url : '/info.json'
.always ->
get_callback_stub.getCall(0).args.should.have.length 1
done()
it 'should not give argument on a DELETE', (done) ->
$.ajax
type : 'DELETE'
url : '/info.json'
.always ->
delete_callback_stub.getCall(0).args.should.have.length 1
done()
it 'should give request data as argument on a POST', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'POST'
url : '/info.json'
data : JSON.stringify(data)
.always ->
post_callback_stub.getCall(0).args.should.have.length 2
post_callback_stub.getCall(0).args[1].should.eql data
done()
it 'should give request data as argument on a PUT', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'PUT'
url : '/info.json'
data : JSON.stringify(data)
.always ->
put_callback_stub.getCall(0).args.should.have.length 2
put_callback_stub.getCall(0).args[1].should.be.eql data
done()
it 'should give request data as argument on a PATCH', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'PATCH'
url : '/info.json'
data : JSON.stringify(data)
.always ->
patch_callback_stub.getCall(0).args.should.have.length 2
patch_callback_stub.getCall(0).args[1].should.be.eql data
done()
describe 'with concurrent mocks', ->
mock1 = null
mock2 = null
mock1_spy = sinon.spy()
mock2_spy = sinon.spy()
logger_spy = sinon.spy()
before ->
mock1 = @plasticine.addMock
route : '/info.json'
get : ->
mock1_spy()
status : 200
body : {}
mock2 = @plasticine.addMock
route : '/info.json'
get : ->
mock2_spy()
status : 200
body : {}
after ->
mock1.dispose()
mock2.dispose()
it 'should warn if 2 mocks try to fake the same route', (done) ->
@plasticine.logger.warn.add logger_spy
$.ajax
type : 'GET'
url : '/info.json'
.always (data, event, xhr) ->
mock1_spy.should.have.been.calledOnce
mock2_spy.should.have.not.been.called
logger_spy.should.have.been.calledOnce
logger_spy.firstCall.args[0].should.equal 'ALREADY_FAKED'
logger_spy.firstCall.args[1].should.equal mock2
done()
| 121105 | module.exports = -> describe 'Fake request', ->
mock_callback = null
done_callback = null
fail_callback = null
ajax_call = null
content = null
before ->
ajax_call = ->
$.ajax
type : 'GET'
url : '/info.json'
.done(done_callback)
.fail(fail_callback)
beforeEach ->
mock_callback = sinon.spy()
done_callback = sinon.spy()
fail_callback = sinon.spy()
content =
message : 'Hello'
receiver : 'world'
describe 'basic functionalities', ->
mock = null
before ->
mock = @plasticine.addMock
route: '/info.json'
get: ->
mock_callback()
status: 200
body:
message : 'Someone here?'
receiver : 'world'
it 'should intercept with a static route on a GET', (done) ->
ajax_call().always =>
@requests.should.have.length 0
fail_callback.should.not.have.been.called
done_callback.should.have.been.calledOnce
response_text = done_callback.firstCall.args[0]
(JSON.parse response_text).should.be.deep.equal
message : 'Someone here?'
receiver : 'world'
mock_callback.should.have.been.calledOnce
done()
it 'should not intercept when the mock is disposed', (done) ->
mock.dispose()
ajax_call().always ->
fail_callback.should.not.have.been.called
done_callback.should.have.been.calledOnce
response_text = done_callback.firstCall.args[0]
(JSON.parse response_text).should.be.deep.equal content
mock_callback.should.not.have.been.called
done()
@requests.should.have.length 1
@requests[0].respondHelper 200, content
describe 'arguments passed to callbacks', ->
mock = null
get_callback_stub = sinon.stub()
delete_callback_stub = sinon.stub()
post_callback_stub = sinon.stub()
put_callback_stub = sinon.stub()
patch_callback_stub = sinon.stub()
before ->
get_callback_stub.returns status: 200, body: {}
delete_callback_stub.returns status: 200, body: {}
post_callback_stub.returns status: 200, body: {}
put_callback_stub.returns status: 200, body: {}
patch_callback_stub.returns status: 200, body: {}
mock = @plasticine.addMock
route : '/info.json'
get : get_callback_stub
delete : delete_callback_stub
post : post_callback_stub
put : put_callback_stub
patch : patch_callback_stub
after ->
mock.dispose()
it 'should not give argument on a GET', (done) ->
$.ajax
type : 'GET'
url : '/info.json'
.always ->
get_callback_stub.getCall(0).args.should.have.length 1
done()
it 'should not give argument on a DELETE', (done) ->
$.ajax
type : 'DELETE'
url : '/info.json'
.always ->
delete_callback_stub.getCall(0).args.should.have.length 1
done()
it 'should give request data as argument on a POST', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'POST'
url : '/info.json'
data : JSON.stringify(data)
.always ->
post_callback_stub.getCall(0).args.should.have.length 2
post_callback_stub.getCall(0).args[1].should.eql data
done()
it 'should give request data as argument on a PUT', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'PUT'
url : '/info.json'
data : JSON.stringify(data)
.always ->
put_callback_stub.getCall(0).args.should.have.length 2
put_callback_stub.getCall(0).args[1].should.be.eql data
done()
it 'should give request data as argument on a PATCH', (done) ->
data = {message: 'Hello', author: '<NAME>'}
$.ajax
type : 'PATCH'
url : '/info.json'
data : JSON.stringify(data)
.always ->
patch_callback_stub.getCall(0).args.should.have.length 2
patch_callback_stub.getCall(0).args[1].should.be.eql data
done()
describe 'with concurrent mocks', ->
mock1 = null
mock2 = null
mock1_spy = sinon.spy()
mock2_spy = sinon.spy()
logger_spy = sinon.spy()
before ->
mock1 = @plasticine.addMock
route : '/info.json'
get : ->
mock1_spy()
status : 200
body : {}
mock2 = @plasticine.addMock
route : '/info.json'
get : ->
mock2_spy()
status : 200
body : {}
after ->
mock1.dispose()
mock2.dispose()
it 'should warn if 2 mocks try to fake the same route', (done) ->
@plasticine.logger.warn.add logger_spy
$.ajax
type : 'GET'
url : '/info.json'
.always (data, event, xhr) ->
mock1_spy.should.have.been.calledOnce
mock2_spy.should.have.not.been.called
logger_spy.should.have.been.calledOnce
logger_spy.firstCall.args[0].should.equal 'ALREADY_FAKED'
logger_spy.firstCall.args[1].should.equal mock2
done()
| true | module.exports = -> describe 'Fake request', ->
mock_callback = null
done_callback = null
fail_callback = null
ajax_call = null
content = null
before ->
ajax_call = ->
$.ajax
type : 'GET'
url : '/info.json'
.done(done_callback)
.fail(fail_callback)
beforeEach ->
mock_callback = sinon.spy()
done_callback = sinon.spy()
fail_callback = sinon.spy()
content =
message : 'Hello'
receiver : 'world'
describe 'basic functionalities', ->
mock = null
before ->
mock = @plasticine.addMock
route: '/info.json'
get: ->
mock_callback()
status: 200
body:
message : 'Someone here?'
receiver : 'world'
it 'should intercept with a static route on a GET', (done) ->
ajax_call().always =>
@requests.should.have.length 0
fail_callback.should.not.have.been.called
done_callback.should.have.been.calledOnce
response_text = done_callback.firstCall.args[0]
(JSON.parse response_text).should.be.deep.equal
message : 'Someone here?'
receiver : 'world'
mock_callback.should.have.been.calledOnce
done()
it 'should not intercept when the mock is disposed', (done) ->
mock.dispose()
ajax_call().always ->
fail_callback.should.not.have.been.called
done_callback.should.have.been.calledOnce
response_text = done_callback.firstCall.args[0]
(JSON.parse response_text).should.be.deep.equal content
mock_callback.should.not.have.been.called
done()
@requests.should.have.length 1
@requests[0].respondHelper 200, content
describe 'arguments passed to callbacks', ->
mock = null
get_callback_stub = sinon.stub()
delete_callback_stub = sinon.stub()
post_callback_stub = sinon.stub()
put_callback_stub = sinon.stub()
patch_callback_stub = sinon.stub()
before ->
get_callback_stub.returns status: 200, body: {}
delete_callback_stub.returns status: 200, body: {}
post_callback_stub.returns status: 200, body: {}
put_callback_stub.returns status: 200, body: {}
patch_callback_stub.returns status: 200, body: {}
mock = @plasticine.addMock
route : '/info.json'
get : get_callback_stub
delete : delete_callback_stub
post : post_callback_stub
put : put_callback_stub
patch : patch_callback_stub
after ->
mock.dispose()
it 'should not give argument on a GET', (done) ->
$.ajax
type : 'GET'
url : '/info.json'
.always ->
get_callback_stub.getCall(0).args.should.have.length 1
done()
it 'should not give argument on a DELETE', (done) ->
$.ajax
type : 'DELETE'
url : '/info.json'
.always ->
delete_callback_stub.getCall(0).args.should.have.length 1
done()
it 'should give request data as argument on a POST', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'POST'
url : '/info.json'
data : JSON.stringify(data)
.always ->
post_callback_stub.getCall(0).args.should.have.length 2
post_callback_stub.getCall(0).args[1].should.eql data
done()
it 'should give request data as argument on a PUT', (done) ->
data = {message: 'Hello', author: 'world'}
$.ajax
type : 'PUT'
url : '/info.json'
data : JSON.stringify(data)
.always ->
put_callback_stub.getCall(0).args.should.have.length 2
put_callback_stub.getCall(0).args[1].should.be.eql data
done()
it 'should give request data as argument on a PATCH', (done) ->
data = {message: 'Hello', author: 'PI:NAME:<NAME>END_PI'}
$.ajax
type : 'PATCH'
url : '/info.json'
data : JSON.stringify(data)
.always ->
patch_callback_stub.getCall(0).args.should.have.length 2
patch_callback_stub.getCall(0).args[1].should.be.eql data
done()
describe 'with concurrent mocks', ->
mock1 = null
mock2 = null
mock1_spy = sinon.spy()
mock2_spy = sinon.spy()
logger_spy = sinon.spy()
before ->
mock1 = @plasticine.addMock
route : '/info.json'
get : ->
mock1_spy()
status : 200
body : {}
mock2 = @plasticine.addMock
route : '/info.json'
get : ->
mock2_spy()
status : 200
body : {}
after ->
mock1.dispose()
mock2.dispose()
it 'should warn if 2 mocks try to fake the same route', (done) ->
@plasticine.logger.warn.add logger_spy
$.ajax
type : 'GET'
url : '/info.json'
.always (data, event, xhr) ->
mock1_spy.should.have.been.calledOnce
mock2_spy.should.have.not.been.called
logger_spy.should.have.been.calledOnce
logger_spy.firstCall.args[0].should.equal 'ALREADY_FAKED'
logger_spy.firstCall.args[1].should.equal mock2
done()
|
[
{
"context": "ascript.fastExtend({\n\t\t\tuserId: player1Id\n\t\t\tname: player1Name\n\t\t\tdeck: player1DeckData,\n\t\t\tstartingHandSiz",
"end": 6980,
"score": 0.836635410785675,
"start": 6974,
"tag": "NAME",
"value": "player"
},
{
"context": "fastExtend({\n\t\t\tuserId: player1Id\... | app/sdk/challenges/challenge.coffee | willroberts/duelyst | 5 | EventBus = require 'app/common/eventbus'
EVENTS = require 'app/common/event_types'
UtilsJavascript = require 'app/common/utils/utils_javascript'
GameSession = require 'app/sdk/gameSession'
GameStatus = require 'app/sdk/gameStatus'
GameType = require 'app/sdk/gameType'
GameSetup = require 'app/sdk/gameSetup'
Card = require 'app/sdk/cards/card'
StaticAgent = require 'app/sdk/agents/staticAgent'
DrawStartingHandAction = require 'app/sdk/actions/drawStartingHandAction'
BattleMapTemplate = require 'app/sdk/battleMapTemplate'
i18next = require 'i18next'
class Challenge
@type: "Challenge"
type: "Challenge"
name: "Challenge"
description: "Learn how to play DUELYST."
battleMapTemplateIndex: 0 # when set will attempt to force battlemap to a specific template
_currentInstruction: null
_currentPlayerTurn: null
_eventBus:null
hiddenUIElements:null # array of strings representing unneeded ui elements # TODO: this is just a hacky string checker
iconUrl: null # path to icon resource
_instructions:null
_instructionQueueByTurnIndex:null # Map of instruction queues by player turn index
isChallengeLost: false # (boolean) Tracks whether the current challenge has been lost (resets on rollback)
_musicOverride: undefined # (RSX entry) Manual override of the music to play for this map
_nextInstructionIndex: 0
_playerOwnedBoardTemplate: undefined # array of arrays that can be filled with unit card ids the player owns at start of challenge
prerequisiteChallengeTypes: null # list of challenge types that must be completed before this challenge is enabled
_opponentAgent:null
_opponentOwnedBoardTemplate: undefined # array of arrays that can be filled with unit card ids the player owns at start of challenge
otkChallengeFailureCount: null # Integer representing quantity of times otk challenge has been failed
otkChallengeFailureMessages: null # Array of strings, advances each time challenge has been failed
otkChallengeStartMessage: null # String to display when starting otk challenge
requiredMulliganHandIndices: null
showCardInstructionalTextForTurns: 0 # integer - will show instructional ui on cards for this many turns
customBoard: true # whether challenge uses a custom board, when true will start board completely empty except for generals
skipMulligan: true
snapShotOnPlayerTurn: null
startingHandSize: null # (Integer, optional) number of cards to have in hand at start of challenge (0-6)
startingHandSizePlayer: null # (Integer, optional) number of cards to have in player hand at start of challenge (0-6)
startingHandSizeOpponent: null # (Integer, optional) number of cards to have in opponent hand at start of challenge (0-6)
startingMana: null # (Integer, optional) starting amount of mana, +1 for player 2
startingManaPlayer: null # (Integer, optional) starting amount of mana for player, +1 when player 2
startingManaOpponent: null # (Integer, optional) starting amount of mana for opponent, +1 when player 2
unmulliganableHandIndices: null
userIsPlayer1: true
usesResetTurn: true # (boolean) If true, end turn functionality will be replaced with resetting OTK
###*
# Challenge constructor.
# @public
###
constructor:()->
@_eventBus = EventBus.create()
@_instructions = []
@hiddenUIElements = ["SignatureCard"]
@_instructionsByTurnIndex = []
@_nextInstructionIndex = 0
@unmulliganableHandIndices = []
@requiredMulliganHandIndices = []
@prerequisiteChallengeTypes = []
@otkChallengeFailureCount = 0
###*
* SDK event handler. Do not call this method manually.
###
onEvent: (event) ->
if event.type == EVENTS.validate_game_over
@_onValidateGameOver(event)
else if event.type == EVENTS.start_turn
@_onStartTurn(event)
if @_currentInstruction?
@_currentInstruction.onEvent(event)
###*
# Get the event bus for this challenge.
# @public
###
getEventBus:()->
return @_eventBus
getType: () ->
return @type
getSkipMulligan: () ->
return @skipMulligan
###*
# Get an array of all the instructions for this challenge.
# @public
# @return {Array} Array of Instruction objects.
###
getInstructions:()->
return @_instructions
###*
# Get current instruction for this challenge.
# @public
# @return {Instruction} Current instruction.
###
getCurrentInstruction:()->
return @_currentInstruction
###*
# Get opponent agent for this challenge.
# @public
# @return {BaseAgent} Current instruction.
###
getOpponentAgent:()->
return @_opponentAgent
###*
* Returns deck data for my player.
* @param {GameSession} gameSession
* @returns {Array}
###
getMyPlayerDeckData: (gameSession) ->
# override in subclass
return []
###*
* Returns deck data for opponent player
* @param {GameSession} gameSession
* @returns {Array}
###
getOpponentPlayerDeckData: (gameSession) ->
# override in subclass
return []
###*
# Set up the GameSession for this challenge.
# @public
###
setupSession:(gameSession, player1Data, player2Data)->
# set game session challenge
gameSession.setChallenge(@)
# set modes
@setupSessionModes(gameSession)
# set battlemap template
if @battleMapTemplateIndex?
gameSession.setBattleMapTemplate(new BattleMapTemplate(gameSession, @battleMapTemplateIndex))
# get ids and names
if @userIsPlayer1
player1Name = i18next.t("battle.your_name_default_label")
player2Name = i18next.t("battle.opponent_name_default_label")
player1Id = gameSession.getUserId()
player2Id = "CPU"
player1StartingMana = if @startingManaPlayer? then @startingManaPlayer else if @startingMana? then @startingMana else null
player2StartingMana = if @startingManaOpponent? then @startingManaOpponent else if @startingMana? then (@startingMana + 1) else null
player1StartingHandSize = if @startingHandSizePlayer? then @startingHandSizePlayer else @startingHandSize
player2StartingHandSize = if @startingHandSizeOpponent? then @startingHandSizeOpponent else @startingHandSize
player1DeckData = @getMyPlayerDeckData(gameSession)
player2DeckData = @getOpponentPlayerDeckData(gameSession)
else
player1Name = i18next.t("battle.opponent_name_default_label")
player2Name = i18next.t("battle.your_name_default_label")
player1Id = "CPU"
player2Id = gameSession.getUserId()
player1StartingMana = if @startingManaOpponent? then @startingManaOpponent else if @startingMana? then @startingMana else null
player2StartingMana = if @startingManaPlayer? then @startingManaPlayer else if @startingMana? then (@startingMana + 1) else null
player1StartingHandSize = if @startingHandSizeOpponent? then @startingHandSizeOpponent else @startingHandSize
player2StartingHandSize = if @startingHandSizePlayer? then @startingHandSizePlayer else @startingHandSize
player1DeckData = @getOpponentPlayerDeckData(gameSession)
player2DeckData = @getMyPlayerDeckData(gameSession)
# ensure basic player data
player1Data = UtilsJavascript.fastExtend({
userId: player1Id
name: player1Name
deck: player1DeckData,
startingHandSize: player1StartingHandSize,
startingMana: player1StartingMana
}, player1Data)
player2Data = UtilsJavascript.fastExtend({
userId: player2Id
name: player2Name
deck: player2DeckData,
startingHandSize: player2StartingHandSize,
startingMana: player2StartingMana
}, player2Data)
# setup session
GameSetup.setupNewSession(gameSession, player1Data, player2Data, @customBoard)
# skip mulligan as needed
if @skipMulligan
gameSession.setStatus(GameStatus.active)
for player in gameSession.players
player.setHasStartingHand(true)
# setup board
@setupBoard(gameSession)
# setup agent
@setupOpponentAgent(gameSession)
# force game session to sync state
# in case any challenges set custom board state or stats
gameSession.syncState()
# snapshot complete session
@_snapShotChallengeIfNeeded()
return gameSession
###*
* Sets up the game session modes before creating any game elements.
* @param {GameSession} gameSession
###
setupSessionModes: (gameSession) ->
gameSession.setGameType(GameType.Challenge)
gameSession.setIsRunningAsAuthoritative(true)
###*
* Sets up the board state.
* @param {GameSession} gameSession
###
setupBoard: (gameSession) ->
# override in subclass
###*
* Creates the opponent agent.
* @param {GameSession} gameSession
###
setupOpponentAgent: (gameSession) ->
# get agent player id
if @userIsPlayer1
cpuPlayer = gameSession.getPlayer2()
cpuPlayerId = cpuPlayer.getPlayerId()
cpuGeneral = gameSession.getGeneralForPlayer2()
else
cpuPlayer = gameSession.getPlayer1()
cpuPlayerId = cpuPlayer.getPlayerId()
cpuGeneral = gameSession.getGeneralForPlayer1()
# create agent
@_opponentAgent = new StaticAgent(cpuPlayerId)
# skip agent mulligan
cpuPlayer.setHasStartingHand(true)
# tag general
@_opponentAgent.addUnitWithTag(cpuGeneral, "general")
###*
# Pushes an instruction onto the queue for a turn
# @param {Object} event event data with format {step:...}
# @private
###
addInstructionToQueueForTurnIndex:(turnIndex, instruction) ->
if not @_instructionsByTurnIndex[turnIndex]
@_instructionsByTurnIndex[turnIndex] = []
@_instructionsByTurnIndex[turnIndex].push(instruction)
##*
#Activates the next instruction if it's the players turn
# TODO: Can check here for if the last instruction was completed to allow for instructions that span multiple steps
#@private
##
activateNextInstruction:()->
if @_currentInstruction
@_currentInstruction = null
if !GameSession.current().isMyTurn()
return
# Get the player turn index
currentTurnIndex = GameSession.current().getNumberOfTurns() # current turn count calculation is ugly
playersTurnIndex = Math.floor(currentTurnIndex / 2) # represents the index of turn for this player
# check for a new turn
if !@_currentPlayerTurn? or @_currentPlayerTurn != playersTurnIndex
@_currentPlayerTurn = playersTurnIndex
@_nextInstructionIndex = 0
nextInstruction = @_instructionsByTurnIndex[playersTurnIndex]?[@_nextInstructionIndex]
if nextInstruction
@_currentInstruction = nextInstruction
@_eventBus.trigger(EVENTS.instruction_triggered, {type: EVENTS.instruction_triggered, instruction:nextInstruction})
@_nextInstructionIndex++
hasInstructionForGameTurn: (gameTurnIndex) ->
playersTurnIndex = Math.floor(gameTurnIndex / 2) # represents the index of turn for this player
return @_instructionsByTurnIndex[playersTurnIndex]?
_onStartTurn: (e) ->
@_snapShotChallengeIfNeeded()
_snapShotChallengeIfNeeded: () ->
if @snapShotOnPlayerTurn? and GameSession.current().getCurrentPlayerId() == GameSession.current().getMyPlayerId()
# Get the player turn index
currentTurnIndex = GameSession.current().getNumberOfTurns() # current turn count calculation is ugly
playersTurnIndex = Math.floor(currentTurnIndex / 2) # represents the index of turn for this player
if playersTurnIndex == @snapShotOnPlayerTurn and !@_snapShotData
gameSession = GameSession.current()
@_snapShotData = gameSession.serializeToJSON(gameSession)
@_eventBus.trigger(EVENTS.challenge_start, {type: EVENTS.challenge_start});
_onValidateGameOver:()->
gameSession = GameSession.current()
myGeneral = gameSession.getGeneralForPlayerId(gameSession.getMyPlayerId())
if @snapShotOnPlayerTurn? and myGeneral.getIsRemoved()
# set general as not removed so that game does not end
myGeneral.setIsRemoved(false)
# trigger challenge loss
@onChallengeLost()
onChallengeLost: () ->
# record loss
@otkChallengeFailureCount++
@isChallengeLost = true
# trigger challenge lost event
@_eventBus.trigger(EVENTS.challenge_lost, {type: EVENTS.challenge_lost, needsRollback:true})
challengeReset: () ->
# trigger challenge loss
@onChallengeLost()
# trigger challenge reset event
@_eventBus.trigger(EVENTS.challenge_reset, {type: EVENTS.challenge_reset})
challengeRollback: () ->
gameSession = GameSession.current()
gameSession._rollbackToSnapshot(@_snapShotData)
# Reset opponent agents action sequence
this._opponentAgent.currentTurnIndex = undefined
this._opponentAgent.currentActionIndexInTurn = 0
@isChallengeLost = false
applyCardToBoard: (cardOrCardData, boardX, boardY, ownerId) ->
gameSession = GameSession.getInstance()
# create card as needed
if !(cardOrCardData instanceof Card)
cardOrCardData = gameSession.getExistingCardFromIndexOrCreateCardFromData(cardOrCardData)
# apply card
if cardOrCardData?
if ownerId? then cardOrCardData.setOwnerId(ownerId)
gameSession.applyCardToBoard(cardOrCardData, boardX, boardY)
if cardOrCardData.refreshExhaustion
cardOrCardData.refreshExhaustion()
return cardOrCardData
module.exports = Challenge
| 212661 | EventBus = require 'app/common/eventbus'
EVENTS = require 'app/common/event_types'
UtilsJavascript = require 'app/common/utils/utils_javascript'
GameSession = require 'app/sdk/gameSession'
GameStatus = require 'app/sdk/gameStatus'
GameType = require 'app/sdk/gameType'
GameSetup = require 'app/sdk/gameSetup'
Card = require 'app/sdk/cards/card'
StaticAgent = require 'app/sdk/agents/staticAgent'
DrawStartingHandAction = require 'app/sdk/actions/drawStartingHandAction'
BattleMapTemplate = require 'app/sdk/battleMapTemplate'
i18next = require 'i18next'
class Challenge
@type: "Challenge"
type: "Challenge"
name: "Challenge"
description: "Learn how to play DUELYST."
battleMapTemplateIndex: 0 # when set will attempt to force battlemap to a specific template
_currentInstruction: null
_currentPlayerTurn: null
_eventBus:null
hiddenUIElements:null # array of strings representing unneeded ui elements # TODO: this is just a hacky string checker
iconUrl: null # path to icon resource
_instructions:null
_instructionQueueByTurnIndex:null # Map of instruction queues by player turn index
isChallengeLost: false # (boolean) Tracks whether the current challenge has been lost (resets on rollback)
_musicOverride: undefined # (RSX entry) Manual override of the music to play for this map
_nextInstructionIndex: 0
_playerOwnedBoardTemplate: undefined # array of arrays that can be filled with unit card ids the player owns at start of challenge
prerequisiteChallengeTypes: null # list of challenge types that must be completed before this challenge is enabled
_opponentAgent:null
_opponentOwnedBoardTemplate: undefined # array of arrays that can be filled with unit card ids the player owns at start of challenge
otkChallengeFailureCount: null # Integer representing quantity of times otk challenge has been failed
otkChallengeFailureMessages: null # Array of strings, advances each time challenge has been failed
otkChallengeStartMessage: null # String to display when starting otk challenge
requiredMulliganHandIndices: null
showCardInstructionalTextForTurns: 0 # integer - will show instructional ui on cards for this many turns
customBoard: true # whether challenge uses a custom board, when true will start board completely empty except for generals
skipMulligan: true
snapShotOnPlayerTurn: null
startingHandSize: null # (Integer, optional) number of cards to have in hand at start of challenge (0-6)
startingHandSizePlayer: null # (Integer, optional) number of cards to have in player hand at start of challenge (0-6)
startingHandSizeOpponent: null # (Integer, optional) number of cards to have in opponent hand at start of challenge (0-6)
startingMana: null # (Integer, optional) starting amount of mana, +1 for player 2
startingManaPlayer: null # (Integer, optional) starting amount of mana for player, +1 when player 2
startingManaOpponent: null # (Integer, optional) starting amount of mana for opponent, +1 when player 2
unmulliganableHandIndices: null
userIsPlayer1: true
usesResetTurn: true # (boolean) If true, end turn functionality will be replaced with resetting OTK
###*
# Challenge constructor.
# @public
###
constructor:()->
@_eventBus = EventBus.create()
@_instructions = []
@hiddenUIElements = ["SignatureCard"]
@_instructionsByTurnIndex = []
@_nextInstructionIndex = 0
@unmulliganableHandIndices = []
@requiredMulliganHandIndices = []
@prerequisiteChallengeTypes = []
@otkChallengeFailureCount = 0
###*
* SDK event handler. Do not call this method manually.
###
onEvent: (event) ->
if event.type == EVENTS.validate_game_over
@_onValidateGameOver(event)
else if event.type == EVENTS.start_turn
@_onStartTurn(event)
if @_currentInstruction?
@_currentInstruction.onEvent(event)
###*
# Get the event bus for this challenge.
# @public
###
getEventBus:()->
return @_eventBus
getType: () ->
return @type
getSkipMulligan: () ->
return @skipMulligan
###*
# Get an array of all the instructions for this challenge.
# @public
# @return {Array} Array of Instruction objects.
###
getInstructions:()->
return @_instructions
###*
# Get current instruction for this challenge.
# @public
# @return {Instruction} Current instruction.
###
getCurrentInstruction:()->
return @_currentInstruction
###*
# Get opponent agent for this challenge.
# @public
# @return {BaseAgent} Current instruction.
###
getOpponentAgent:()->
return @_opponentAgent
###*
* Returns deck data for my player.
* @param {GameSession} gameSession
* @returns {Array}
###
getMyPlayerDeckData: (gameSession) ->
# override in subclass
return []
###*
* Returns deck data for opponent player
* @param {GameSession} gameSession
* @returns {Array}
###
getOpponentPlayerDeckData: (gameSession) ->
# override in subclass
return []
###*
# Set up the GameSession for this challenge.
# @public
###
setupSession:(gameSession, player1Data, player2Data)->
# set game session challenge
gameSession.setChallenge(@)
# set modes
@setupSessionModes(gameSession)
# set battlemap template
if @battleMapTemplateIndex?
gameSession.setBattleMapTemplate(new BattleMapTemplate(gameSession, @battleMapTemplateIndex))
# get ids and names
if @userIsPlayer1
player1Name = i18next.t("battle.your_name_default_label")
player2Name = i18next.t("battle.opponent_name_default_label")
player1Id = gameSession.getUserId()
player2Id = "CPU"
player1StartingMana = if @startingManaPlayer? then @startingManaPlayer else if @startingMana? then @startingMana else null
player2StartingMana = if @startingManaOpponent? then @startingManaOpponent else if @startingMana? then (@startingMana + 1) else null
player1StartingHandSize = if @startingHandSizePlayer? then @startingHandSizePlayer else @startingHandSize
player2StartingHandSize = if @startingHandSizeOpponent? then @startingHandSizeOpponent else @startingHandSize
player1DeckData = @getMyPlayerDeckData(gameSession)
player2DeckData = @getOpponentPlayerDeckData(gameSession)
else
player1Name = i18next.t("battle.opponent_name_default_label")
player2Name = i18next.t("battle.your_name_default_label")
player1Id = "CPU"
player2Id = gameSession.getUserId()
player1StartingMana = if @startingManaOpponent? then @startingManaOpponent else if @startingMana? then @startingMana else null
player2StartingMana = if @startingManaPlayer? then @startingManaPlayer else if @startingMana? then (@startingMana + 1) else null
player1StartingHandSize = if @startingHandSizeOpponent? then @startingHandSizeOpponent else @startingHandSize
player2StartingHandSize = if @startingHandSizePlayer? then @startingHandSizePlayer else @startingHandSize
player1DeckData = @getOpponentPlayerDeckData(gameSession)
player2DeckData = @getMyPlayerDeckData(gameSession)
# ensure basic player data
player1Data = UtilsJavascript.fastExtend({
userId: player1Id
name: <NAME>1<NAME>
deck: player1DeckData,
startingHandSize: player1StartingHandSize,
startingMana: player1StartingMana
}, player1Data)
player2Data = UtilsJavascript.fastExtend({
userId: player2Id
name: <NAME>
deck: player2DeckData,
startingHandSize: player2StartingHandSize,
startingMana: player2StartingMana
}, player2Data)
# setup session
GameSetup.setupNewSession(gameSession, player1Data, player2Data, @customBoard)
# skip mulligan as needed
if @skipMulligan
gameSession.setStatus(GameStatus.active)
for player in gameSession.players
player.setHasStartingHand(true)
# setup board
@setupBoard(gameSession)
# setup agent
@setupOpponentAgent(gameSession)
# force game session to sync state
# in case any challenges set custom board state or stats
gameSession.syncState()
# snapshot complete session
@_snapShotChallengeIfNeeded()
return gameSession
###*
* Sets up the game session modes before creating any game elements.
* @param {GameSession} gameSession
###
setupSessionModes: (gameSession) ->
gameSession.setGameType(GameType.Challenge)
gameSession.setIsRunningAsAuthoritative(true)
###*
* Sets up the board state.
* @param {GameSession} gameSession
###
setupBoard: (gameSession) ->
# override in subclass
###*
* Creates the opponent agent.
* @param {GameSession} gameSession
###
setupOpponentAgent: (gameSession) ->
# get agent player id
if @userIsPlayer1
cpuPlayer = gameSession.getPlayer2()
cpuPlayerId = cpuPlayer.getPlayerId()
cpuGeneral = gameSession.getGeneralForPlayer2()
else
cpuPlayer = gameSession.getPlayer1()
cpuPlayerId = cpuPlayer.getPlayerId()
cpuGeneral = gameSession.getGeneralForPlayer1()
# create agent
@_opponentAgent = new StaticAgent(cpuPlayerId)
# skip agent mulligan
cpuPlayer.setHasStartingHand(true)
# tag general
@_opponentAgent.addUnitWithTag(cpuGeneral, "general")
###*
# Pushes an instruction onto the queue for a turn
# @param {Object} event event data with format {step:...}
# @private
###
addInstructionToQueueForTurnIndex:(turnIndex, instruction) ->
if not @_instructionsByTurnIndex[turnIndex]
@_instructionsByTurnIndex[turnIndex] = []
@_instructionsByTurnIndex[turnIndex].push(instruction)
##*
#Activates the next instruction if it's the players turn
# TODO: Can check here for if the last instruction was completed to allow for instructions that span multiple steps
#@private
##
activateNextInstruction:()->
if @_currentInstruction
@_currentInstruction = null
if !GameSession.current().isMyTurn()
return
# Get the player turn index
currentTurnIndex = GameSession.current().getNumberOfTurns() # current turn count calculation is ugly
playersTurnIndex = Math.floor(currentTurnIndex / 2) # represents the index of turn for this player
# check for a new turn
if !@_currentPlayerTurn? or @_currentPlayerTurn != playersTurnIndex
@_currentPlayerTurn = playersTurnIndex
@_nextInstructionIndex = 0
nextInstruction = @_instructionsByTurnIndex[playersTurnIndex]?[@_nextInstructionIndex]
if nextInstruction
@_currentInstruction = nextInstruction
@_eventBus.trigger(EVENTS.instruction_triggered, {type: EVENTS.instruction_triggered, instruction:nextInstruction})
@_nextInstructionIndex++
hasInstructionForGameTurn: (gameTurnIndex) ->
playersTurnIndex = Math.floor(gameTurnIndex / 2) # represents the index of turn for this player
return @_instructionsByTurnIndex[playersTurnIndex]?
_onStartTurn: (e) ->
@_snapShotChallengeIfNeeded()
_snapShotChallengeIfNeeded: () ->
if @snapShotOnPlayerTurn? and GameSession.current().getCurrentPlayerId() == GameSession.current().getMyPlayerId()
# Get the player turn index
currentTurnIndex = GameSession.current().getNumberOfTurns() # current turn count calculation is ugly
playersTurnIndex = Math.floor(currentTurnIndex / 2) # represents the index of turn for this player
if playersTurnIndex == @snapShotOnPlayerTurn and !@_snapShotData
gameSession = GameSession.current()
@_snapShotData = gameSession.serializeToJSON(gameSession)
@_eventBus.trigger(EVENTS.challenge_start, {type: EVENTS.challenge_start});
_onValidateGameOver:()->
gameSession = GameSession.current()
myGeneral = gameSession.getGeneralForPlayerId(gameSession.getMyPlayerId())
if @snapShotOnPlayerTurn? and myGeneral.getIsRemoved()
# set general as not removed so that game does not end
myGeneral.setIsRemoved(false)
# trigger challenge loss
@onChallengeLost()
onChallengeLost: () ->
# record loss
@otkChallengeFailureCount++
@isChallengeLost = true
# trigger challenge lost event
@_eventBus.trigger(EVENTS.challenge_lost, {type: EVENTS.challenge_lost, needsRollback:true})
challengeReset: () ->
# trigger challenge loss
@onChallengeLost()
# trigger challenge reset event
@_eventBus.trigger(EVENTS.challenge_reset, {type: EVENTS.challenge_reset})
challengeRollback: () ->
gameSession = GameSession.current()
gameSession._rollbackToSnapshot(@_snapShotData)
# Reset opponent agents action sequence
this._opponentAgent.currentTurnIndex = undefined
this._opponentAgent.currentActionIndexInTurn = 0
@isChallengeLost = false
applyCardToBoard: (cardOrCardData, boardX, boardY, ownerId) ->
gameSession = GameSession.getInstance()
# create card as needed
if !(cardOrCardData instanceof Card)
cardOrCardData = gameSession.getExistingCardFromIndexOrCreateCardFromData(cardOrCardData)
# apply card
if cardOrCardData?
if ownerId? then cardOrCardData.setOwnerId(ownerId)
gameSession.applyCardToBoard(cardOrCardData, boardX, boardY)
if cardOrCardData.refreshExhaustion
cardOrCardData.refreshExhaustion()
return cardOrCardData
module.exports = Challenge
| true | EventBus = require 'app/common/eventbus'
EVENTS = require 'app/common/event_types'
UtilsJavascript = require 'app/common/utils/utils_javascript'
GameSession = require 'app/sdk/gameSession'
GameStatus = require 'app/sdk/gameStatus'
GameType = require 'app/sdk/gameType'
GameSetup = require 'app/sdk/gameSetup'
Card = require 'app/sdk/cards/card'
StaticAgent = require 'app/sdk/agents/staticAgent'
DrawStartingHandAction = require 'app/sdk/actions/drawStartingHandAction'
BattleMapTemplate = require 'app/sdk/battleMapTemplate'
i18next = require 'i18next'
class Challenge
@type: "Challenge"
type: "Challenge"
name: "Challenge"
description: "Learn how to play DUELYST."
battleMapTemplateIndex: 0 # when set will attempt to force battlemap to a specific template
_currentInstruction: null
_currentPlayerTurn: null
_eventBus:null
hiddenUIElements:null # array of strings representing unneeded ui elements # TODO: this is just a hacky string checker
iconUrl: null # path to icon resource
_instructions:null
_instructionQueueByTurnIndex:null # Map of instruction queues by player turn index
isChallengeLost: false # (boolean) Tracks whether the current challenge has been lost (resets on rollback)
_musicOverride: undefined # (RSX entry) Manual override of the music to play for this map
_nextInstructionIndex: 0
_playerOwnedBoardTemplate: undefined # array of arrays that can be filled with unit card ids the player owns at start of challenge
prerequisiteChallengeTypes: null # list of challenge types that must be completed before this challenge is enabled
_opponentAgent:null
_opponentOwnedBoardTemplate: undefined # array of arrays that can be filled with unit card ids the player owns at start of challenge
otkChallengeFailureCount: null # Integer representing quantity of times otk challenge has been failed
otkChallengeFailureMessages: null # Array of strings, advances each time challenge has been failed
otkChallengeStartMessage: null # String to display when starting otk challenge
requiredMulliganHandIndices: null
showCardInstructionalTextForTurns: 0 # integer - will show instructional ui on cards for this many turns
customBoard: true # whether challenge uses a custom board, when true will start board completely empty except for generals
skipMulligan: true
snapShotOnPlayerTurn: null
startingHandSize: null # (Integer, optional) number of cards to have in hand at start of challenge (0-6)
startingHandSizePlayer: null # (Integer, optional) number of cards to have in player hand at start of challenge (0-6)
startingHandSizeOpponent: null # (Integer, optional) number of cards to have in opponent hand at start of challenge (0-6)
startingMana: null # (Integer, optional) starting amount of mana, +1 for player 2
startingManaPlayer: null # (Integer, optional) starting amount of mana for player, +1 when player 2
startingManaOpponent: null # (Integer, optional) starting amount of mana for opponent, +1 when player 2
unmulliganableHandIndices: null
userIsPlayer1: true
usesResetTurn: true # (boolean) If true, end turn functionality will be replaced with resetting OTK
###*
# Challenge constructor.
# @public
###
constructor:()->
@_eventBus = EventBus.create()
@_instructions = []
@hiddenUIElements = ["SignatureCard"]
@_instructionsByTurnIndex = []
@_nextInstructionIndex = 0
@unmulliganableHandIndices = []
@requiredMulliganHandIndices = []
@prerequisiteChallengeTypes = []
@otkChallengeFailureCount = 0
###*
* SDK event handler. Do not call this method manually.
###
onEvent: (event) ->
if event.type == EVENTS.validate_game_over
@_onValidateGameOver(event)
else if event.type == EVENTS.start_turn
@_onStartTurn(event)
if @_currentInstruction?
@_currentInstruction.onEvent(event)
###*
# Get the event bus for this challenge.
# @public
###
getEventBus:()->
return @_eventBus
getType: () ->
return @type
getSkipMulligan: () ->
return @skipMulligan
###*
# Get an array of all the instructions for this challenge.
# @public
# @return {Array} Array of Instruction objects.
###
getInstructions:()->
return @_instructions
###*
# Get current instruction for this challenge.
# @public
# @return {Instruction} Current instruction.
###
getCurrentInstruction:()->
return @_currentInstruction
###*
# Get opponent agent for this challenge.
# @public
# @return {BaseAgent} Current instruction.
###
getOpponentAgent:()->
return @_opponentAgent
###*
* Returns deck data for my player.
* @param {GameSession} gameSession
* @returns {Array}
###
getMyPlayerDeckData: (gameSession) ->
# override in subclass
return []
###*
* Returns deck data for opponent player
* @param {GameSession} gameSession
* @returns {Array}
###
getOpponentPlayerDeckData: (gameSession) ->
# override in subclass
return []
###*
# Set up the GameSession for this challenge.
# @public
###
setupSession:(gameSession, player1Data, player2Data)->
# set game session challenge
gameSession.setChallenge(@)
# set modes
@setupSessionModes(gameSession)
# set battlemap template
if @battleMapTemplateIndex?
gameSession.setBattleMapTemplate(new BattleMapTemplate(gameSession, @battleMapTemplateIndex))
# get ids and names
if @userIsPlayer1
player1Name = i18next.t("battle.your_name_default_label")
player2Name = i18next.t("battle.opponent_name_default_label")
player1Id = gameSession.getUserId()
player2Id = "CPU"
player1StartingMana = if @startingManaPlayer? then @startingManaPlayer else if @startingMana? then @startingMana else null
player2StartingMana = if @startingManaOpponent? then @startingManaOpponent else if @startingMana? then (@startingMana + 1) else null
player1StartingHandSize = if @startingHandSizePlayer? then @startingHandSizePlayer else @startingHandSize
player2StartingHandSize = if @startingHandSizeOpponent? then @startingHandSizeOpponent else @startingHandSize
player1DeckData = @getMyPlayerDeckData(gameSession)
player2DeckData = @getOpponentPlayerDeckData(gameSession)
else
player1Name = i18next.t("battle.opponent_name_default_label")
player2Name = i18next.t("battle.your_name_default_label")
player1Id = "CPU"
player2Id = gameSession.getUserId()
player1StartingMana = if @startingManaOpponent? then @startingManaOpponent else if @startingMana? then @startingMana else null
player2StartingMana = if @startingManaPlayer? then @startingManaPlayer else if @startingMana? then (@startingMana + 1) else null
player1StartingHandSize = if @startingHandSizeOpponent? then @startingHandSizeOpponent else @startingHandSize
player2StartingHandSize = if @startingHandSizePlayer? then @startingHandSizePlayer else @startingHandSize
player1DeckData = @getOpponentPlayerDeckData(gameSession)
player2DeckData = @getMyPlayerDeckData(gameSession)
# ensure basic player data
player1Data = UtilsJavascript.fastExtend({
userId: player1Id
name: PI:NAME:<NAME>END_PI1PI:NAME:<NAME>END_PI
deck: player1DeckData,
startingHandSize: player1StartingHandSize,
startingMana: player1StartingMana
}, player1Data)
player2Data = UtilsJavascript.fastExtend({
userId: player2Id
name: PI:NAME:<NAME>END_PI
deck: player2DeckData,
startingHandSize: player2StartingHandSize,
startingMana: player2StartingMana
}, player2Data)
# setup session
GameSetup.setupNewSession(gameSession, player1Data, player2Data, @customBoard)
# skip mulligan as needed
if @skipMulligan
gameSession.setStatus(GameStatus.active)
for player in gameSession.players
player.setHasStartingHand(true)
# setup board
@setupBoard(gameSession)
# setup agent
@setupOpponentAgent(gameSession)
# force game session to sync state
# in case any challenges set custom board state or stats
gameSession.syncState()
# snapshot complete session
@_snapShotChallengeIfNeeded()
return gameSession
###*
* Sets up the game session modes before creating any game elements.
* @param {GameSession} gameSession
###
setupSessionModes: (gameSession) ->
gameSession.setGameType(GameType.Challenge)
gameSession.setIsRunningAsAuthoritative(true)
###*
* Sets up the board state.
* @param {GameSession} gameSession
###
setupBoard: (gameSession) ->
# override in subclass
###*
* Creates the opponent agent.
* @param {GameSession} gameSession
###
setupOpponentAgent: (gameSession) ->
# get agent player id
if @userIsPlayer1
cpuPlayer = gameSession.getPlayer2()
cpuPlayerId = cpuPlayer.getPlayerId()
cpuGeneral = gameSession.getGeneralForPlayer2()
else
cpuPlayer = gameSession.getPlayer1()
cpuPlayerId = cpuPlayer.getPlayerId()
cpuGeneral = gameSession.getGeneralForPlayer1()
# create agent
@_opponentAgent = new StaticAgent(cpuPlayerId)
# skip agent mulligan
cpuPlayer.setHasStartingHand(true)
# tag general
@_opponentAgent.addUnitWithTag(cpuGeneral, "general")
###*
# Pushes an instruction onto the queue for a turn
# @param {Object} event event data with format {step:...}
# @private
###
addInstructionToQueueForTurnIndex:(turnIndex, instruction) ->
if not @_instructionsByTurnIndex[turnIndex]
@_instructionsByTurnIndex[turnIndex] = []
@_instructionsByTurnIndex[turnIndex].push(instruction)
##*
#Activates the next instruction if it's the players turn
# TODO: Can check here for if the last instruction was completed to allow for instructions that span multiple steps
#@private
##
activateNextInstruction:()->
if @_currentInstruction
@_currentInstruction = null
if !GameSession.current().isMyTurn()
return
# Get the player turn index
currentTurnIndex = GameSession.current().getNumberOfTurns() # current turn count calculation is ugly
playersTurnIndex = Math.floor(currentTurnIndex / 2) # represents the index of turn for this player
# check for a new turn
if !@_currentPlayerTurn? or @_currentPlayerTurn != playersTurnIndex
@_currentPlayerTurn = playersTurnIndex
@_nextInstructionIndex = 0
nextInstruction = @_instructionsByTurnIndex[playersTurnIndex]?[@_nextInstructionIndex]
if nextInstruction
@_currentInstruction = nextInstruction
@_eventBus.trigger(EVENTS.instruction_triggered, {type: EVENTS.instruction_triggered, instruction:nextInstruction})
@_nextInstructionIndex++
hasInstructionForGameTurn: (gameTurnIndex) ->
playersTurnIndex = Math.floor(gameTurnIndex / 2) # represents the index of turn for this player
return @_instructionsByTurnIndex[playersTurnIndex]?
_onStartTurn: (e) ->
@_snapShotChallengeIfNeeded()
_snapShotChallengeIfNeeded: () ->
if @snapShotOnPlayerTurn? and GameSession.current().getCurrentPlayerId() == GameSession.current().getMyPlayerId()
# Get the player turn index
currentTurnIndex = GameSession.current().getNumberOfTurns() # current turn count calculation is ugly
playersTurnIndex = Math.floor(currentTurnIndex / 2) # represents the index of turn for this player
if playersTurnIndex == @snapShotOnPlayerTurn and !@_snapShotData
gameSession = GameSession.current()
@_snapShotData = gameSession.serializeToJSON(gameSession)
@_eventBus.trigger(EVENTS.challenge_start, {type: EVENTS.challenge_start});
_onValidateGameOver:()->
gameSession = GameSession.current()
myGeneral = gameSession.getGeneralForPlayerId(gameSession.getMyPlayerId())
if @snapShotOnPlayerTurn? and myGeneral.getIsRemoved()
# set general as not removed so that game does not end
myGeneral.setIsRemoved(false)
# trigger challenge loss
@onChallengeLost()
onChallengeLost: () ->
# record loss
@otkChallengeFailureCount++
@isChallengeLost = true
# trigger challenge lost event
@_eventBus.trigger(EVENTS.challenge_lost, {type: EVENTS.challenge_lost, needsRollback:true})
challengeReset: () ->
# trigger challenge loss
@onChallengeLost()
# trigger challenge reset event
@_eventBus.trigger(EVENTS.challenge_reset, {type: EVENTS.challenge_reset})
challengeRollback: () ->
gameSession = GameSession.current()
gameSession._rollbackToSnapshot(@_snapShotData)
# Reset opponent agents action sequence
this._opponentAgent.currentTurnIndex = undefined
this._opponentAgent.currentActionIndexInTurn = 0
@isChallengeLost = false
applyCardToBoard: (cardOrCardData, boardX, boardY, ownerId) ->
gameSession = GameSession.getInstance()
# create card as needed
if !(cardOrCardData instanceof Card)
cardOrCardData = gameSession.getExistingCardFromIndexOrCreateCardFromData(cardOrCardData)
# apply card
if cardOrCardData?
if ownerId? then cardOrCardData.setOwnerId(ownerId)
gameSession.applyCardToBoard(cardOrCardData, boardX, boardY)
if cardOrCardData.refreshExhaustion
cardOrCardData.refreshExhaustion()
return cardOrCardData
module.exports = Challenge
|
[
{
"context": "ormation, please see the LICENSE file\n\n@author Yoav Luft <yoav.luft@gmail.com>\n@copyright 2015 Yoav Luft\n",
"end": 149,
"score": 0.9998993277549744,
"start": 140,
"tag": "NAME",
"value": "Yoav Luft"
},
{
"context": "ease see the LICENSE file\n\n@author Yoav... | test/patterns.test.coffee | Luftzig/jspatterns | 0 | ###
luftzug\jspatterns
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author Yoav Luft <yoav.luft@gmail.com>
@copyright 2015 Yoav Luft
@link
@license http://choosealicense.com/licenses/MIT MIT License
###
should = require 'should'
patterns = require '../src/patterns'
describe 'Function guard predicate', () ->
describe '#guard', () ->
it 'should return a wrapped function', () ->
fn = () ->
'result'
wrapped = patterns.guard (() -> true), fn
should(wrapped).type 'function'
res = wrapped()
res.should.match 'result'
it 'should run function only if predicate is true', () ->
fn = patterns.guard ((a) -> a == 1), ((a) -> a + 2)
res = fn 1
res.should.equal 3
it 'should return the NoMatch object if predicate is false', () ->
fn = patterns.guard ((a) -> a == 1), ((a) -> a + 2)
res = fn 2
res.should.equal patterns.NoMatch
it 'should use Any to accept any argument (but not undefined)', () ->
fn = patterns.guard patterns.Any, ((x) -> x + ' mmmkay')
res = fn 1
res.should.equal '1 mmmkay'
res = fn()
res.should.equal patterns.NoMatch
res = fn 1, 'hello'
res.should.equal patterns.NoMatch
it 'should match '
| 2739 | ###
luftzug\jspatterns
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author <NAME> <<EMAIL>>
@copyright 2015 <NAME>
@link
@license http://choosealicense.com/licenses/MIT MIT License
###
should = require 'should'
patterns = require '../src/patterns'
describe 'Function guard predicate', () ->
describe '#guard', () ->
it 'should return a wrapped function', () ->
fn = () ->
'result'
wrapped = patterns.guard (() -> true), fn
should(wrapped).type 'function'
res = wrapped()
res.should.match 'result'
it 'should run function only if predicate is true', () ->
fn = patterns.guard ((a) -> a == 1), ((a) -> a + 2)
res = fn 1
res.should.equal 3
it 'should return the NoMatch object if predicate is false', () ->
fn = patterns.guard ((a) -> a == 1), ((a) -> a + 2)
res = fn 2
res.should.equal patterns.NoMatch
it 'should use Any to accept any argument (but not undefined)', () ->
fn = patterns.guard patterns.Any, ((x) -> x + ' mmmkay')
res = fn 1
res.should.equal '1 mmmkay'
res = fn()
res.should.equal patterns.NoMatch
res = fn 1, 'hello'
res.should.equal patterns.NoMatch
it 'should match '
| true | ###
luftzug\jspatterns
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@copyright 2015 PI:NAME:<NAME>END_PI
@link
@license http://choosealicense.com/licenses/MIT MIT License
###
should = require 'should'
patterns = require '../src/patterns'
describe 'Function guard predicate', () ->
describe '#guard', () ->
it 'should return a wrapped function', () ->
fn = () ->
'result'
wrapped = patterns.guard (() -> true), fn
should(wrapped).type 'function'
res = wrapped()
res.should.match 'result'
it 'should run function only if predicate is true', () ->
fn = patterns.guard ((a) -> a == 1), ((a) -> a + 2)
res = fn 1
res.should.equal 3
it 'should return the NoMatch object if predicate is false', () ->
fn = patterns.guard ((a) -> a == 1), ((a) -> a + 2)
res = fn 2
res.should.equal patterns.NoMatch
it 'should use Any to accept any argument (but not undefined)', () ->
fn = patterns.guard patterns.Any, ((x) -> x + ' mmmkay')
res = fn 1
res.should.equal '1 mmmkay'
res = fn()
res.should.equal patterns.NoMatch
res = fn 1, 'hello'
res.should.equal patterns.NoMatch
it 'should match '
|
[
{
"context": "expect dgbaB\n expect(result.key).to.equal(\"dgbaB\")\n done()\n\n it \"might be instructed to sk",
"end": 2457,
"score": 0.995441198348999,
"start": 2452,
"tag": "KEY",
"value": "dgbaB"
}
] | test/shortshort_spec.coffee | mcollina/shortshort.js | 3 | expect = require('chai').expect
sinon = require('sinon')
redis = require('redis')
ShortShort = require '../src/shortshort'
describe "ShortShort", ->
beforeEach (done) ->
@client = redis.createClient()
@client.select 12
@client.flushdb =>
@subject = new ShortShort(@client)
done()
afterEach ->
@client.quit()
it "should start numbering the shortened urls from 1", (done) ->
@subject.shorten "http://www.google.it", (err, result) ->
expect(result.key).to.equal("1")
done()
it "should increment the key", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.shorten "http://www.google.it", (err, result) ->
expect(result.key).to.equal("2")
done()
it "should store a shortened url in redis", (done) ->
url = "http://www.google.com"
@subject.shorten url, (err, result) =>
@client.get "ss-key-#{result.key}", (err, value) ->
expect(value).to.equal(url)
done()
it "should not shorten a wrong url ", (done) ->
@subject.shorten "foobar", (err, result) ->
expect(err.message).to.equal("not an url")
done()
it "should increment a global counter when shortening", (done) ->
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "ss-global-counter", (err, value) ->
expect(value).to.equal("1")
done()
it "should increment a global counter when shortening (bis)", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "ss-global-counter", (err, value) ->
expect(value).to.equal("2")
done()
it "should be able to resolve a reference", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.resolve result.key, (err, url) =>
expect(url).to.equal("http://www.google.com")
done()
it "should be able to resolve a wrong refernce", (done) ->
@subject.resolve "abc", (err, url) =>
expect(err.message).to.equal("key not found")
done()
it "should encode the key using a base62 algorithm", (done) ->
@client.set "ss-global-counter", 195948556, =>
@subject.shorten "http://www.google.com", (err, result) =>
# the expected value is 195948557,
# but as it should be encoded in base62,
# we expect dgbaB
expect(result.key).to.equal("dgbaB")
done()
it "might be instructed to skip the url validation", (done) ->
@subject = new ShortShort(@client, validation: false)
@subject.shorten "foobar", (err, result) ->
expect(err).to.equal(null)
done()
it "might have a different global counter", (done) ->
@subject = new ShortShort(@client, globalCounter: "custom-global-counter")
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "custom-global-counter", (err, value) ->
expect(value).to.equal("1")
done()
it "might have a different key prefix", (done) ->
@subject = new ShortShort(@client, keyPrefix: "custom-key-")
url = "http://www.google.it"
@subject.shorten url, (err, result) =>
@client.get "custom-key-#{result.key}", (err, value) ->
expect(value).to.equal(url)
done()
it "should update a key content", (done) ->
firstUrl = "http://www.google.it"
secondUrl = "http://www.matteocollina.com"
@subject.shorten firstUrl, (err, result) =>
@subject.update result.key, secondUrl, (err) =>
@subject.resolve result.key, (err, value) =>
expect(value).to.eql(secondUrl)
done()
it "should not update a key content if it doesn't exist", (done) ->
secondUrl = "http://www.matteocollina.com"
@subject.update "missing-key", secondUrl, (err) ->
expect(err.message).to.equal("key not found")
done()
it "should not update with a wrong url", (done) ->
@subject.shorten "http://www.matteocollina.com", (err, result) =>
@subject.update result.key, "foobar", (err) ->
expect(err.message).to.equal("not an url")
done()
it "might be instructed to skip the url validation for updates", (done) ->
@subject = new ShortShort(@client, validation: false)
first = "aaa"
second = "bbb"
@subject.shorten first, (err, result) =>
@subject.update result.key, second, (err) =>
@subject.resolve result.key, (err, value) =>
expect(err).to.eql(null)
done()
it "should show an empty list of latest urls", (done) ->
@subject.latest (err, result) ->
expect(result).to.eql([])
done()
it "should show a list containing the id of latest url shortened", (done) ->
keys = []
@subject.shorten "http://www.matteocollina.com", (err, result) =>
keys.unshift result.key
@subject.shorten "http://www.google.com", (err, result) =>
keys.unshift result.key
@subject.latest (err, result) ->
expect(result).to.eql(keys)
done()
it "should store the latest list on redis", (done) ->
@subject.shorten "http://www.google.it", (err, result) =>
@client.lrange "ss-latest-list", 0, 1, (err, list) ->
expect(list).to.eql([result.key])
done()
it "should make the latest list key configurable", (done) ->
@subject = new ShortShort(@client, latestList: "AHHA")
@subject.shorten "http://www.google.it", (err, result) =>
@client.lrange "AHHA", 0, 1, (err, list) ->
expect(list).to.eql([result.key])
done()
it "should store a list of the last 10 url shortened", (done) ->
keys = []
counter = 0
next = (callback) =>
currCounter = counter++
@subject.shorten "http://www.g#{currCounter}.com", (err, result) =>
keys.unshift result.key
callback(currCounter)
for i in [0..20]
next (counter) =>
if counter == 20
@subject.latest (err, result) ->
expect(result).to.eql(keys[0...10])
done()
it "should make configurable the length of the list of the latest url shortened", (done) ->
@subject = new ShortShort(@client, latestLength: 15)
keys = []
counter = 0
next = (callback) =>
currCounter = counter++
@subject.shorten "http://www.g#{currCounter}.com", (err, result) =>
keys.unshift result.key
callback(currCounter)
for i in [0..20]
next (counter) =>
if counter == 20
@subject.latest (err, result) ->
expect(result).to.eql(keys[0...15])
done()
| 225191 | expect = require('chai').expect
sinon = require('sinon')
redis = require('redis')
ShortShort = require '../src/shortshort'
describe "ShortShort", ->
beforeEach (done) ->
@client = redis.createClient()
@client.select 12
@client.flushdb =>
@subject = new ShortShort(@client)
done()
afterEach ->
@client.quit()
it "should start numbering the shortened urls from 1", (done) ->
@subject.shorten "http://www.google.it", (err, result) ->
expect(result.key).to.equal("1")
done()
it "should increment the key", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.shorten "http://www.google.it", (err, result) ->
expect(result.key).to.equal("2")
done()
it "should store a shortened url in redis", (done) ->
url = "http://www.google.com"
@subject.shorten url, (err, result) =>
@client.get "ss-key-#{result.key}", (err, value) ->
expect(value).to.equal(url)
done()
it "should not shorten a wrong url ", (done) ->
@subject.shorten "foobar", (err, result) ->
expect(err.message).to.equal("not an url")
done()
it "should increment a global counter when shortening", (done) ->
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "ss-global-counter", (err, value) ->
expect(value).to.equal("1")
done()
it "should increment a global counter when shortening (bis)", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "ss-global-counter", (err, value) ->
expect(value).to.equal("2")
done()
it "should be able to resolve a reference", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.resolve result.key, (err, url) =>
expect(url).to.equal("http://www.google.com")
done()
it "should be able to resolve a wrong refernce", (done) ->
@subject.resolve "abc", (err, url) =>
expect(err.message).to.equal("key not found")
done()
it "should encode the key using a base62 algorithm", (done) ->
@client.set "ss-global-counter", 195948556, =>
@subject.shorten "http://www.google.com", (err, result) =>
# the expected value is 195948557,
# but as it should be encoded in base62,
# we expect dgbaB
expect(result.key).to.equal("<KEY>")
done()
it "might be instructed to skip the url validation", (done) ->
@subject = new ShortShort(@client, validation: false)
@subject.shorten "foobar", (err, result) ->
expect(err).to.equal(null)
done()
it "might have a different global counter", (done) ->
@subject = new ShortShort(@client, globalCounter: "custom-global-counter")
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "custom-global-counter", (err, value) ->
expect(value).to.equal("1")
done()
it "might have a different key prefix", (done) ->
@subject = new ShortShort(@client, keyPrefix: "custom-key-")
url = "http://www.google.it"
@subject.shorten url, (err, result) =>
@client.get "custom-key-#{result.key}", (err, value) ->
expect(value).to.equal(url)
done()
it "should update a key content", (done) ->
firstUrl = "http://www.google.it"
secondUrl = "http://www.matteocollina.com"
@subject.shorten firstUrl, (err, result) =>
@subject.update result.key, secondUrl, (err) =>
@subject.resolve result.key, (err, value) =>
expect(value).to.eql(secondUrl)
done()
it "should not update a key content if it doesn't exist", (done) ->
secondUrl = "http://www.matteocollina.com"
@subject.update "missing-key", secondUrl, (err) ->
expect(err.message).to.equal("key not found")
done()
it "should not update with a wrong url", (done) ->
@subject.shorten "http://www.matteocollina.com", (err, result) =>
@subject.update result.key, "foobar", (err) ->
expect(err.message).to.equal("not an url")
done()
it "might be instructed to skip the url validation for updates", (done) ->
@subject = new ShortShort(@client, validation: false)
first = "aaa"
second = "bbb"
@subject.shorten first, (err, result) =>
@subject.update result.key, second, (err) =>
@subject.resolve result.key, (err, value) =>
expect(err).to.eql(null)
done()
it "should show an empty list of latest urls", (done) ->
@subject.latest (err, result) ->
expect(result).to.eql([])
done()
it "should show a list containing the id of latest url shortened", (done) ->
keys = []
@subject.shorten "http://www.matteocollina.com", (err, result) =>
keys.unshift result.key
@subject.shorten "http://www.google.com", (err, result) =>
keys.unshift result.key
@subject.latest (err, result) ->
expect(result).to.eql(keys)
done()
it "should store the latest list on redis", (done) ->
@subject.shorten "http://www.google.it", (err, result) =>
@client.lrange "ss-latest-list", 0, 1, (err, list) ->
expect(list).to.eql([result.key])
done()
it "should make the latest list key configurable", (done) ->
@subject = new ShortShort(@client, latestList: "AHHA")
@subject.shorten "http://www.google.it", (err, result) =>
@client.lrange "AHHA", 0, 1, (err, list) ->
expect(list).to.eql([result.key])
done()
it "should store a list of the last 10 url shortened", (done) ->
keys = []
counter = 0
next = (callback) =>
currCounter = counter++
@subject.shorten "http://www.g#{currCounter}.com", (err, result) =>
keys.unshift result.key
callback(currCounter)
for i in [0..20]
next (counter) =>
if counter == 20
@subject.latest (err, result) ->
expect(result).to.eql(keys[0...10])
done()
it "should make configurable the length of the list of the latest url shortened", (done) ->
@subject = new ShortShort(@client, latestLength: 15)
keys = []
counter = 0
next = (callback) =>
currCounter = counter++
@subject.shorten "http://www.g#{currCounter}.com", (err, result) =>
keys.unshift result.key
callback(currCounter)
for i in [0..20]
next (counter) =>
if counter == 20
@subject.latest (err, result) ->
expect(result).to.eql(keys[0...15])
done()
| true | expect = require('chai').expect
sinon = require('sinon')
redis = require('redis')
ShortShort = require '../src/shortshort'
describe "ShortShort", ->
beforeEach (done) ->
@client = redis.createClient()
@client.select 12
@client.flushdb =>
@subject = new ShortShort(@client)
done()
afterEach ->
@client.quit()
it "should start numbering the shortened urls from 1", (done) ->
@subject.shorten "http://www.google.it", (err, result) ->
expect(result.key).to.equal("1")
done()
it "should increment the key", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.shorten "http://www.google.it", (err, result) ->
expect(result.key).to.equal("2")
done()
it "should store a shortened url in redis", (done) ->
url = "http://www.google.com"
@subject.shorten url, (err, result) =>
@client.get "ss-key-#{result.key}", (err, value) ->
expect(value).to.equal(url)
done()
it "should not shorten a wrong url ", (done) ->
@subject.shorten "foobar", (err, result) ->
expect(err.message).to.equal("not an url")
done()
it "should increment a global counter when shortening", (done) ->
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "ss-global-counter", (err, value) ->
expect(value).to.equal("1")
done()
it "should increment a global counter when shortening (bis)", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "ss-global-counter", (err, value) ->
expect(value).to.equal("2")
done()
it "should be able to resolve a reference", (done) ->
@subject.shorten "http://www.google.com", (err, result) =>
@subject.resolve result.key, (err, url) =>
expect(url).to.equal("http://www.google.com")
done()
it "should be able to resolve a wrong refernce", (done) ->
@subject.resolve "abc", (err, url) =>
expect(err.message).to.equal("key not found")
done()
it "should encode the key using a base62 algorithm", (done) ->
@client.set "ss-global-counter", 195948556, =>
@subject.shorten "http://www.google.com", (err, result) =>
# the expected value is 195948557,
# but as it should be encoded in base62,
# we expect dgbaB
expect(result.key).to.equal("PI:KEY:<KEY>END_PI")
done()
it "might be instructed to skip the url validation", (done) ->
@subject = new ShortShort(@client, validation: false)
@subject.shorten "foobar", (err, result) ->
expect(err).to.equal(null)
done()
it "might have a different global counter", (done) ->
@subject = new ShortShort(@client, globalCounter: "custom-global-counter")
@subject.shorten "http://www.google.it", (err, result) =>
@client.get "custom-global-counter", (err, value) ->
expect(value).to.equal("1")
done()
it "might have a different key prefix", (done) ->
@subject = new ShortShort(@client, keyPrefix: "custom-key-")
url = "http://www.google.it"
@subject.shorten url, (err, result) =>
@client.get "custom-key-#{result.key}", (err, value) ->
expect(value).to.equal(url)
done()
it "should update a key content", (done) ->
firstUrl = "http://www.google.it"
secondUrl = "http://www.matteocollina.com"
@subject.shorten firstUrl, (err, result) =>
@subject.update result.key, secondUrl, (err) =>
@subject.resolve result.key, (err, value) =>
expect(value).to.eql(secondUrl)
done()
it "should not update a key content if it doesn't exist", (done) ->
secondUrl = "http://www.matteocollina.com"
@subject.update "missing-key", secondUrl, (err) ->
expect(err.message).to.equal("key not found")
done()
it "should not update with a wrong url", (done) ->
@subject.shorten "http://www.matteocollina.com", (err, result) =>
@subject.update result.key, "foobar", (err) ->
expect(err.message).to.equal("not an url")
done()
it "might be instructed to skip the url validation for updates", (done) ->
@subject = new ShortShort(@client, validation: false)
first = "aaa"
second = "bbb"
@subject.shorten first, (err, result) =>
@subject.update result.key, second, (err) =>
@subject.resolve result.key, (err, value) =>
expect(err).to.eql(null)
done()
it "should show an empty list of latest urls", (done) ->
@subject.latest (err, result) ->
expect(result).to.eql([])
done()
it "should show a list containing the id of latest url shortened", (done) ->
keys = []
@subject.shorten "http://www.matteocollina.com", (err, result) =>
keys.unshift result.key
@subject.shorten "http://www.google.com", (err, result) =>
keys.unshift result.key
@subject.latest (err, result) ->
expect(result).to.eql(keys)
done()
it "should store the latest list on redis", (done) ->
@subject.shorten "http://www.google.it", (err, result) =>
@client.lrange "ss-latest-list", 0, 1, (err, list) ->
expect(list).to.eql([result.key])
done()
it "should make the latest list key configurable", (done) ->
@subject = new ShortShort(@client, latestList: "AHHA")
@subject.shorten "http://www.google.it", (err, result) =>
@client.lrange "AHHA", 0, 1, (err, list) ->
expect(list).to.eql([result.key])
done()
it "should store a list of the last 10 url shortened", (done) ->
keys = []
counter = 0
next = (callback) =>
currCounter = counter++
@subject.shorten "http://www.g#{currCounter}.com", (err, result) =>
keys.unshift result.key
callback(currCounter)
for i in [0..20]
next (counter) =>
if counter == 20
@subject.latest (err, result) ->
expect(result).to.eql(keys[0...10])
done()
it "should make configurable the length of the list of the latest url shortened", (done) ->
@subject = new ShortShort(@client, latestLength: 15)
keys = []
counter = 0
next = (callback) =>
currCounter = counter++
@subject.shorten "http://www.g#{currCounter}.com", (err, result) =>
keys.unshift result.key
callback(currCounter)
for i in [0..20]
next (counter) =>
if counter == 20
@subject.latest (err, result) ->
expect(result).to.eql(keys[0...15])
done()
|
[
{
"context": "\n\n await Coconut.database.allDocs\n startkey: \"user\"\n endkey: \"user\\uf000\"\n include_docs: true\n",
"end": 1966,
"score": 0.9820776581764221,
"start": 1962,
"tag": "KEY",
"value": "user"
},
{
"context": "atabase.allDocs\n startkey: \"user\"\n end... | _attachments/app/CaseSummaryDocs.coffee | jongoz/coconut-analytice | 3 | ###
#
# This file is meant to be run on node.js not on the browser
# It allows you to update the "tertiary" index of cases
# These are just documents that follow the naming convention: case_summary_CASE_ID
# It makes it easy to run queries against cases with this index available
#
# It can be run by typing
# > coffee CaseSummaryDocs.coffee --database http://admin:password@localhost:5984/coconut-surveillance-zanzibar -update
#
# A document in the database keeps track of which documents have already been processed
# When a new document appears in the database this script will check it to see if it effects
# the tertiary index and update it accordingly.
#
# Running this file checks for any new documents in the database and updates things accordingly.
# It then listens to the couchdb _changes feed FOREVER and continues to update the index as soon
# as any change is made.
#
#
###
argv = require('minimist')(process.argv.slice(2));
# Make these global so that they can be used from the javascript console
global.Backbone = require 'backbone'
global.PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-upsert'))
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
BackbonePouch = require 'backbone-pouch'
_ = require 'underscore'
moment = require 'moment'
global.Coconut =
database: new PouchDB argv.database,
ajax:
timeout: 1000 * 60 * 10
reportingDatabase: new PouchDB "#{argv.database}-reporting",
ajax:
timeout: 1000 * 60 * 10
# This is a PouchDB - Backbone connector - we only use it for a few things like getting the list of questions
Backbone.sync = BackbonePouch.sync
db: Coconut.database
fetch: 'query'
Coconut.database.get "coconut.config"
.then (doc) ->
Coconut.config = doc
Coconut.config.role_types = if Coconut.config.role_types then Coconut.config.role_types.split(",") else ["admin", "reports"]
await Coconut.database.allDocs
startkey: "user"
endkey: "user\uf000"
include_docs: true
.then (result) =>
Coconut.nameByUsername = {}
for row in result.rows
Coconut.nameByUsername[row.id.replace(/user./,"")] = row.doc.name
Promise.resolve()
QuestionCollection = require './models/QuestionCollection'
#DhisOrganisationUnits = require './models/DhisOrganisationUnits'
GeoHierarchyClass = require './models/GeoHierarchy'
#dhisOrganisationUnits = new DhisOrganisationUnits()
#dhisOrganisationUnits.loadExtendExport
# dhisDocumentName: "dhis2" # This is the document that was exported from DHIS2
# error: (error) -> console.error error
# success: (result) ->
global.GeoHierarchy = new GeoHierarchyClass()
await GeoHierarchy.load()
global.FacilityHierarchy = GeoHierarchy # These have been combined
Coconut.questions = new QuestionCollection()
Coconut.questions.fetch
error: (error) -> console.error error
success: ->
try
Case = require './models/Case'
catch error
console.error error
if argv.update
process.stdout.write "Update: #{moment().format("YYYY-MM-DD hh:mm")} "
Case.updateCaseSummaryDocs()
.catch (error) ->
console.error "ERROR"
console.error error
.then (result) ->
console.log " done."
else if argv.reset
console.log "Resetting"
Case.resetAllCaseSummaryDocs()
.catch (error) =>
console.error "ERROR"
console.error error
.then =>
console.log " done."
else
console.log "No action, try --update"
.catch (error) ->
console.error error
| 19435 | ###
#
# This file is meant to be run on node.js not on the browser
# It allows you to update the "tertiary" index of cases
# These are just documents that follow the naming convention: case_summary_CASE_ID
# It makes it easy to run queries against cases with this index available
#
# It can be run by typing
# > coffee CaseSummaryDocs.coffee --database http://admin:password@localhost:5984/coconut-surveillance-zanzibar -update
#
# A document in the database keeps track of which documents have already been processed
# When a new document appears in the database this script will check it to see if it effects
# the tertiary index and update it accordingly.
#
# Running this file checks for any new documents in the database and updates things accordingly.
# It then listens to the couchdb _changes feed FOREVER and continues to update the index as soon
# as any change is made.
#
#
###
argv = require('minimist')(process.argv.slice(2));
# Make these global so that they can be used from the javascript console
global.Backbone = require 'backbone'
global.PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-upsert'))
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
BackbonePouch = require 'backbone-pouch'
_ = require 'underscore'
moment = require 'moment'
global.Coconut =
database: new PouchDB argv.database,
ajax:
timeout: 1000 * 60 * 10
reportingDatabase: new PouchDB "#{argv.database}-reporting",
ajax:
timeout: 1000 * 60 * 10
# This is a PouchDB - Backbone connector - we only use it for a few things like getting the list of questions
Backbone.sync = BackbonePouch.sync
db: Coconut.database
fetch: 'query'
Coconut.database.get "coconut.config"
.then (doc) ->
Coconut.config = doc
Coconut.config.role_types = if Coconut.config.role_types then Coconut.config.role_types.split(",") else ["admin", "reports"]
await Coconut.database.allDocs
startkey: "<KEY>"
endkey: "<KEY>"
include_docs: true
.then (result) =>
Coconut.nameByUsername = {}
for row in result.rows
Coconut.nameByUsername[row.id.replace(/user./,"")] = row.doc.name
Promise.resolve()
QuestionCollection = require './models/QuestionCollection'
#DhisOrganisationUnits = require './models/DhisOrganisationUnits'
GeoHierarchyClass = require './models/GeoHierarchy'
#dhisOrganisationUnits = new DhisOrganisationUnits()
#dhisOrganisationUnits.loadExtendExport
# dhisDocumentName: "dhis2" # This is the document that was exported from DHIS2
# error: (error) -> console.error error
# success: (result) ->
global.GeoHierarchy = new GeoHierarchyClass()
await GeoHierarchy.load()
global.FacilityHierarchy = GeoHierarchy # These have been combined
Coconut.questions = new QuestionCollection()
Coconut.questions.fetch
error: (error) -> console.error error
success: ->
try
Case = require './models/Case'
catch error
console.error error
if argv.update
process.stdout.write "Update: #{moment().format("YYYY-MM-DD hh:mm")} "
Case.updateCaseSummaryDocs()
.catch (error) ->
console.error "ERROR"
console.error error
.then (result) ->
console.log " done."
else if argv.reset
console.log "Resetting"
Case.resetAllCaseSummaryDocs()
.catch (error) =>
console.error "ERROR"
console.error error
.then =>
console.log " done."
else
console.log "No action, try --update"
.catch (error) ->
console.error error
| true | ###
#
# This file is meant to be run on node.js not on the browser
# It allows you to update the "tertiary" index of cases
# These are just documents that follow the naming convention: case_summary_CASE_ID
# It makes it easy to run queries against cases with this index available
#
# It can be run by typing
# > coffee CaseSummaryDocs.coffee --database http://admin:password@localhost:5984/coconut-surveillance-zanzibar -update
#
# A document in the database keeps track of which documents have already been processed
# When a new document appears in the database this script will check it to see if it effects
# the tertiary index and update it accordingly.
#
# Running this file checks for any new documents in the database and updates things accordingly.
# It then listens to the couchdb _changes feed FOREVER and continues to update the index as soon
# as any change is made.
#
#
###
argv = require('minimist')(process.argv.slice(2));
# Make these global so that they can be used from the javascript console
global.Backbone = require 'backbone'
global.PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-upsert'))
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
BackbonePouch = require 'backbone-pouch'
_ = require 'underscore'
moment = require 'moment'
global.Coconut =
database: new PouchDB argv.database,
ajax:
timeout: 1000 * 60 * 10
reportingDatabase: new PouchDB "#{argv.database}-reporting",
ajax:
timeout: 1000 * 60 * 10
# This is a PouchDB - Backbone connector - we only use it for a few things like getting the list of questions
Backbone.sync = BackbonePouch.sync
db: Coconut.database
fetch: 'query'
Coconut.database.get "coconut.config"
.then (doc) ->
Coconut.config = doc
Coconut.config.role_types = if Coconut.config.role_types then Coconut.config.role_types.split(",") else ["admin", "reports"]
await Coconut.database.allDocs
startkey: "PI:KEY:<KEY>END_PI"
endkey: "PI:KEY:<KEY>END_PI"
include_docs: true
.then (result) =>
Coconut.nameByUsername = {}
for row in result.rows
Coconut.nameByUsername[row.id.replace(/user./,"")] = row.doc.name
Promise.resolve()
QuestionCollection = require './models/QuestionCollection'
#DhisOrganisationUnits = require './models/DhisOrganisationUnits'
GeoHierarchyClass = require './models/GeoHierarchy'
#dhisOrganisationUnits = new DhisOrganisationUnits()
#dhisOrganisationUnits.loadExtendExport
# dhisDocumentName: "dhis2" # This is the document that was exported from DHIS2
# error: (error) -> console.error error
# success: (result) ->
global.GeoHierarchy = new GeoHierarchyClass()
await GeoHierarchy.load()
global.FacilityHierarchy = GeoHierarchy # These have been combined
Coconut.questions = new QuestionCollection()
Coconut.questions.fetch
error: (error) -> console.error error
success: ->
try
Case = require './models/Case'
catch error
console.error error
if argv.update
process.stdout.write "Update: #{moment().format("YYYY-MM-DD hh:mm")} "
Case.updateCaseSummaryDocs()
.catch (error) ->
console.error "ERROR"
console.error error
.then (result) ->
console.log " done."
else if argv.reset
console.log "Resetting"
Case.resetAllCaseSummaryDocs()
.catch (error) =>
console.error "ERROR"
console.error error
.then =>
console.log " done."
else
console.log "No action, try --update"
.catch (error) ->
console.error error
|
[
{
"context": " to be assigned\n# non-interactive roles.\n# @author Jesse Beach\n###\n\n# ------------------------------------------",
"end": 147,
"score": 0.9998770952224731,
"start": 136,
"tag": "NAME",
"value": "Jesse Beach"
}
] | src/tests/rules/no-interactive-element-to-noninteractive-role.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Disallow inherently interactive elements to be assigned
# non-interactive roles.
# @author Jesse Beach
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{configs} = require 'eslint-plugin-jsx-a11y'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require(
'eslint-plugin-jsx-a11y/lib/rules/no-interactive-element-to-noninteractive-role'
)
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
'Interactive elements should not be assigned non-interactive roles.'
expectedError =
message: errorMessage
type: 'JSXAttribute'
ruleName = 'jsx-a11y/no-interactive-element-to-noninteractive-role'
alwaysValid = [
code: '<TestComponent onClick={doFoo} />'
,
code: '<Button onClick={doFoo} />'
,
### Interactive elements ###
code: '<a href="http://x.y.z" role="button" />'
,
code: '<a href="http://x.y.z" tabIndex="0" role="button" />'
,
code: '<button className="foo" role="button" />'
,
### All flavors of input ###
code: '<input role="button" />'
,
code: '<input type="button" role="button" />'
,
code: '<input type="checkbox" role="button" />'
,
code: '<input type="color" role="button" />'
,
code: '<input type="date" role="button" />'
,
code: '<input type="datetime" role="button" />'
,
code: '<input type="datetime-local" role="button" />'
,
code: '<input type="email" role="button" />'
,
code: '<input type="file" role="button" />'
,
code: '<input type="image" role="button" />'
,
code: '<input type="month" role="button" />'
,
code: '<input type="number" role="button" />'
,
code: '<input type="password" role="button" />'
,
code: '<input type="radio" role="button" />'
,
code: '<input type="range" role="button" />'
,
code: '<input type="reset" role="button" />'
,
code: '<input type="search" role="button" />'
,
code: '<input type="submit" role="button" />'
,
code: '<input type="tel" role="button" />'
,
code: '<input type="text" role="button" />'
,
code: '<input type="time" role="button" />'
,
code: '<input type="url" role="button" />'
,
code: '<input type="week" role="button" />'
,
code: '<input type="hidden" role="button" />'
,
### End all flavors of input ###
code: '<menuitem role="button" />'
,
code: '<option className="foo" role="button" />'
,
code: '<select className="foo" role="button" />'
,
code: '<textarea className="foo" role="button" />'
,
code: '<tr role="button" />'
,
### HTML elements with neither an interactive or non-interactive valence (static) ###
code: '<a role="button" />'
,
code: '<a role="img" />'
,
code: '<a tabIndex="0" role="button" />'
,
code: '<a tabIndex="0" role="img" />'
,
code: '<acronym role="button" />'
,
code: '<address role="button" />'
,
code: '<applet role="button" />'
,
code: '<aside role="button" />'
,
code: '<audio role="button" />'
,
code: '<b role="button" />'
,
code: '<base role="button" />'
,
code: '<bdi role="button" />'
,
code: '<bdo role="button" />'
,
code: '<big role="button" />'
,
code: '<blink role="button" />'
,
code: '<blockquote role="button" />'
,
code: '<body role="button" />'
,
code: '<br role="button" />'
,
code: '<canvas role="button" />'
,
code: '<caption role="button" />'
,
code: '<center role="button" />'
,
code: '<cite role="button" />'
,
code: '<code role="button" />'
,
code: '<col role="button" />'
,
code: '<colgroup role="button" />'
,
code: '<content role="button" />'
,
code: '<data role="button" />'
,
code: '<datalist role="button" />'
,
code: '<del role="button" />'
,
code: '<details role="button" />'
,
code: '<dir role="button" />'
,
code: '<div role="button" />'
,
code: '<div className="foo" role="button" />'
,
code: '<div className="foo" {...props} role="button" />'
,
code: '<div aria-hidden role="button" />'
,
code: '<div aria-hidden={true} role="button" />'
,
code: '<div aria-hidden={yes} role="button" />'
,
code: '<div role="button" />'
,
code: '<div role={undefined} role="button" />'
,
code: '<div {...props} role="button" />'
,
code: '<div onKeyUp={() => undefined} aria-hidden={false} role="button" />'
,
code: '<dl role="button" />'
,
code: '<em role="button" />'
,
code: '<embed role="button" />'
,
code: '<figcaption role="button" />'
,
code: '<font role="button" />'
,
code: '<footer role="button" />'
,
code: '<frameset role="button" />'
,
code: '<head role="button" />'
,
code: '<header role="button" />'
,
code: '<hgroup role="button" />'
,
code: '<html role="button" />'
,
code: '<i role="button" />'
,
code: '<iframe role="button" />'
,
code: '<ins role="button" />'
,
code: '<kbd role="button" />'
,
code: '<keygen role="button" />'
,
code: '<label role="button" />'
,
code: '<legend role="button" />'
,
code: '<link role="button" />'
,
code: '<map role="button" />'
,
code: '<mark role="button" />'
,
code: '<marquee role="button" />'
,
code: '<menu role="button" />'
,
code: '<meta role="button" />'
,
code: '<meter role="button" />'
,
code: '<noembed role="button" />'
,
code: '<noscript role="button" />'
,
code: '<object role="button" />'
,
code: '<optgroup role="button" />'
,
code: '<output role="button" />'
,
code: '<p role="button" />'
,
code: '<param role="button" />'
,
code: '<picture role="button" />'
,
code: '<pre role="button" />'
,
code: '<progress role="button" />'
,
code: '<q role="button" />'
,
code: '<rp role="button" />'
,
code: '<rt role="button" />'
,
code: '<rtc role="button" />'
,
code: '<ruby role="button" />'
,
code: '<s role="button" />'
,
code: '<samp role="button" />'
,
code: '<script role="button" />'
,
code: '<section role="button" />'
,
code: '<small role="button" />'
,
code: '<source role="button" />'
,
code: '<spacer role="button" />'
,
code: '<span role="button" />'
,
code: '<strike role="button" />'
,
code: '<strong role="button" />'
,
code: '<style role="button" />'
,
code: '<sub role="button" />'
,
code: '<summary role="button" />'
,
code: '<sup role="button" />'
,
code: '<th role="button" />'
,
code: '<time role="button" />'
,
code: '<title role="button" />'
,
code: '<track role="button" />'
,
code: '<tt role="button" />'
,
code: '<u role="button" />'
,
code: '<var role="button" />'
,
code: '<video role="button" />'
,
code: '<wbr role="button" />'
,
code: '<xmp role="button" />'
,
### HTML elements attributed with an interactive role ###
code: '<div role="button" />'
,
code: '<div role="checkbox" />'
,
code: '<div role="columnheader" />'
,
code: '<div role="combobox" />'
,
code: '<div role="grid" />'
,
code: '<div role="gridcell" />'
,
code: '<div role="link" />'
,
code: '<div role="listbox" />'
,
code: '<div role="menu" />'
,
code: '<div role="menubar" />'
,
code: '<div role="menuitem" />'
,
code: '<div role="menuitemcheckbox" />'
,
code: '<div role="menuitemradio" />'
,
code: '<div role="option" />'
,
code: '<div role="progressbar" />'
,
code: '<div role="radio" />'
,
code: '<div role="radiogroup" />'
,
code: '<div role="row" />'
,
code: '<div role="rowheader" />'
,
code: '<div role="searchbox" />'
,
code: '<div role="slider" />'
,
code: '<div role="spinbutton" />'
,
code: '<div role="switch" />'
,
code: '<div role="tab" />'
,
code: '<div role="textbox" />'
,
code: '<div role="treeitem" />'
,
### Presentation is a special case role that indicates intentional static semantics ###
code: '<div role="presentation" />'
,
### HTML elements attributed with an abstract role ###
code: '<div role="command" />'
,
code: '<div role="composite" />'
,
code: '<div role="input" />'
,
code: '<div role="landmark" />'
,
code: '<div role="range" />'
,
code: '<div role="roletype" />'
,
code: '<div role="section" />'
,
code: '<div role="sectionhead" />'
,
code: '<div role="select" />'
,
code: '<div role="structure" />'
,
code: '<div role="tablist" />'
,
code: '<div role="toolbar" />'
,
code: '<div role="tree" />'
,
code: '<div role="treegrid" />'
,
code: '<div role="widget" />'
,
code: '<div role="window" />'
,
### HTML elements with an inherent, non-interactive role, assigned an
# interactive role. ###
code: '<main role="button" />'
,
code: '<area role="button" />'
,
code: '<article role="button" />'
,
code: '<article role="button" />'
,
code: '<dd role="button" />'
,
code: '<dfn role="button" />'
,
code: '<dt role="button" />'
,
code: '<fieldset role="button" />'
,
code: '<figure role="button" />'
,
code: '<form role="button" />'
,
code: '<frame role="button" />'
,
code: '<h1 role="button" />'
,
code: '<h2 role="button" />'
,
code: '<h3 role="button" />'
,
code: '<h4 role="button" />'
,
code: '<h5 role="button" />'
,
code: '<h6 role="button" />'
,
code: '<hr role="button" />'
,
code: '<img role="button" />'
,
code: '<li role="button" />'
,
code: '<li role="presentation" />'
,
code: '<nav role="button" />'
,
code: '<ol role="button" />'
,
code: '<table role="button" />'
,
code: '<tbody role="button" />'
,
code: '<td role="button" />'
,
code: '<tfoot role="button" />'
,
code: '<thead role="button" />'
,
code: '<ul role="button" />'
,
### HTML elements attributed with a non-interactive role ###
code: '<div role="alert" />'
,
code: '<div role="alertdialog" />'
,
code: '<div role="application" />'
,
code: '<div role="article" />'
,
code: '<div role="banner" />'
,
code: '<div role="cell" />'
,
code: '<div role="complementary" />'
,
code: '<div role="contentinfo" />'
,
code: '<div role="definition" />'
,
code: '<div role="dialog" />'
,
code: '<div role="directory" />'
,
code: '<div role="document" />'
,
code: '<div role="feed" />'
,
code: '<div role="figure" />'
,
code: '<div role="form" />'
,
code: '<div role="group" />'
,
code: '<div role="heading" />'
,
code: '<div role="img" />'
,
code: '<div role="list" />'
,
code: '<div role="listitem" />'
,
code: '<div role="log" />'
,
code: '<div role="main" />'
,
code: '<div role="marquee" />'
,
code: '<div role="math" />'
,
code: '<div role="navigation" />'
,
code: '<div role="note" />'
,
code: '<div role="region" />'
,
code: '<div role="rowgroup" />'
,
code: '<div role="search" />'
,
code: '<div role="separator" />'
,
code: '<div role="scrollbar" />'
,
code: '<div role="status" />'
,
code: '<div role="table" />'
,
code: '<div role="tabpanel" />'
,
code: '<div role="term" />'
,
code: '<div role="timer" />'
,
code: '<div role="tooltip" />'
,
### Namespaced roles are not checked ###
code: '<div mynamespace:role="term" />'
,
code: '<input mynamespace:role="img" />'
]
neverValid = [
### Interactive elements ###
code: '<a href="http://x.y.z" role="img" />', errors: [expectedError]
,
code: '<a href="http://x.y.z" tabIndex="0" role="img" />'
errors: [expectedError]
,
### All flavors of input ###
code: '<input role="img" />', errors: [expectedError]
,
code: '<input type="img" role="img" />', errors: [expectedError]
,
code: '<input type="checkbox" role="img" />', errors: [expectedError]
,
code: '<input type="color" role="img" />', errors: [expectedError]
,
code: '<input type="date" role="img" />', errors: [expectedError]
,
code: '<input type="datetime" role="img" />', errors: [expectedError]
,
code: '<input type="datetime-local" role="img" />', errors: [expectedError]
,
code: '<input type="email" role="img" />', errors: [expectedError]
,
code: '<input type="file" role="img" />', errors: [expectedError]
,
code: '<input type="hidden" role="img" />', errors: [expectedError]
,
code: '<input type="image" role="img" />', errors: [expectedError]
,
code: '<input type="month" role="img" />', errors: [expectedError]
,
code: '<input type="number" role="img" />', errors: [expectedError]
,
code: '<input type="password" role="img" />', errors: [expectedError]
,
code: '<input type="radio" role="img" />', errors: [expectedError]
,
code: '<input type="range" role="img" />', errors: [expectedError]
,
code: '<input type="reset" role="img" />', errors: [expectedError]
,
code: '<input type="search" role="img" />', errors: [expectedError]
,
code: '<input type="submit" role="img" />', errors: [expectedError]
,
code: '<input type="tel" role="img" />', errors: [expectedError]
,
code: '<input type="text" role="img" />', errors: [expectedError]
,
code: '<input type="time" role="img" />', errors: [expectedError]
,
code: '<input type="url" role="img" />', errors: [expectedError]
,
code: '<input type="week" role="img" />', errors: [expectedError]
,
### End all flavors of input ###
code: '<menuitem role="img" />', errors: [expectedError]
,
code: '<option className="foo" role="img" />', errors: [expectedError]
,
code: '<select className="foo" role="img" />', errors: [expectedError]
,
code: '<textarea className="foo" role="img" />', errors: [expectedError]
,
code: '<tr role="img" />', errors: [expectedError]
,
### Interactive elements ###
code: '<a href="http://x.y.z" role="listitem" />', errors: [expectedError]
,
code: '<a href="http://x.y.z" tabIndex="0" role="listitem" />'
errors: [expectedError]
,
### All flavors of input ###
code: '<input role="listitem" />', errors: [expectedError]
,
code: '<input type="listitem" role="listitem" />', errors: [expectedError]
,
code: '<input type="checkbox" role="listitem" />', errors: [expectedError]
,
code: '<input type="color" role="listitem" />', errors: [expectedError]
,
code: '<input type="date" role="listitem" />', errors: [expectedError]
,
code: '<input type="datetime" role="listitem" />', errors: [expectedError]
,
code: '<input type="datetime-local" role="listitem" />'
errors: [expectedError]
,
code: '<input type="email" role="listitem" />', errors: [expectedError]
,
code: '<input type="file" role="listitem" />', errors: [expectedError]
,
code: '<input type="image" role="listitem" />', errors: [expectedError]
,
code: '<input type="month" role="listitem" />', errors: [expectedError]
,
code: '<input type="number" role="listitem" />', errors: [expectedError]
,
code: '<input type="password" role="listitem" />', errors: [expectedError]
,
code: '<input type="radio" role="listitem" />', errors: [expectedError]
,
code: '<input type="range" role="listitem" />', errors: [expectedError]
,
code: '<input type="reset" role="listitem" />', errors: [expectedError]
,
code: '<input type="search" role="listitem" />', errors: [expectedError]
,
code: '<input type="submit" role="listitem" />', errors: [expectedError]
,
code: '<input type="tel" role="listitem" />', errors: [expectedError]
,
code: '<input type="text" role="listitem" />', errors: [expectedError]
,
code: '<input type="time" role="listitem" />', errors: [expectedError]
,
code: '<input type="url" role="listitem" />', errors: [expectedError]
,
code: '<input type="week" role="listitem" />', errors: [expectedError]
,
### End all flavors of input ###
code: '<menuitem role="listitem" />', errors: [expectedError]
,
code: '<option className="foo" role="listitem" />', errors: [expectedError]
,
code: '<select className="foo" role="listitem" />', errors: [expectedError]
,
code: '<textarea className="foo" role="listitem" />', errors: [expectedError]
,
code: '<tr role="listitem" />', errors: [expectedError]
]
recommendedOptions = configs.recommended.rules[ruleName][1] or {}
ruleTester.run "#{ruleName}:recommended", rule,
valid:
[
...alwaysValid
,
code: '<tr role="presentation" />;'
,
code: '<Component role="presentation" />;'
]
.map ruleOptionsMapperFactory recommendedOptions
.map parserOptionsMapper
invalid:
[...neverValid]
.map(ruleOptionsMapperFactory recommendedOptions)
.map parserOptionsMapper
ruleTester.run "#{ruleName}:strict", rule,
valid: [...alwaysValid].map parserOptionsMapper
invalid: [
...neverValid
,
code: '<tr role="presentation" />;', errors: [expectedError]
].map parserOptionsMapper
| 202728 | ### eslint-env jest ###
###*
# @fileoverview Disallow inherently interactive elements to be assigned
# non-interactive roles.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{configs} = require 'eslint-plugin-jsx-a11y'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require(
'eslint-plugin-jsx-a11y/lib/rules/no-interactive-element-to-noninteractive-role'
)
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
'Interactive elements should not be assigned non-interactive roles.'
expectedError =
message: errorMessage
type: 'JSXAttribute'
ruleName = 'jsx-a11y/no-interactive-element-to-noninteractive-role'
alwaysValid = [
code: '<TestComponent onClick={doFoo} />'
,
code: '<Button onClick={doFoo} />'
,
### Interactive elements ###
code: '<a href="http://x.y.z" role="button" />'
,
code: '<a href="http://x.y.z" tabIndex="0" role="button" />'
,
code: '<button className="foo" role="button" />'
,
### All flavors of input ###
code: '<input role="button" />'
,
code: '<input type="button" role="button" />'
,
code: '<input type="checkbox" role="button" />'
,
code: '<input type="color" role="button" />'
,
code: '<input type="date" role="button" />'
,
code: '<input type="datetime" role="button" />'
,
code: '<input type="datetime-local" role="button" />'
,
code: '<input type="email" role="button" />'
,
code: '<input type="file" role="button" />'
,
code: '<input type="image" role="button" />'
,
code: '<input type="month" role="button" />'
,
code: '<input type="number" role="button" />'
,
code: '<input type="password" role="button" />'
,
code: '<input type="radio" role="button" />'
,
code: '<input type="range" role="button" />'
,
code: '<input type="reset" role="button" />'
,
code: '<input type="search" role="button" />'
,
code: '<input type="submit" role="button" />'
,
code: '<input type="tel" role="button" />'
,
code: '<input type="text" role="button" />'
,
code: '<input type="time" role="button" />'
,
code: '<input type="url" role="button" />'
,
code: '<input type="week" role="button" />'
,
code: '<input type="hidden" role="button" />'
,
### End all flavors of input ###
code: '<menuitem role="button" />'
,
code: '<option className="foo" role="button" />'
,
code: '<select className="foo" role="button" />'
,
code: '<textarea className="foo" role="button" />'
,
code: '<tr role="button" />'
,
### HTML elements with neither an interactive or non-interactive valence (static) ###
code: '<a role="button" />'
,
code: '<a role="img" />'
,
code: '<a tabIndex="0" role="button" />'
,
code: '<a tabIndex="0" role="img" />'
,
code: '<acronym role="button" />'
,
code: '<address role="button" />'
,
code: '<applet role="button" />'
,
code: '<aside role="button" />'
,
code: '<audio role="button" />'
,
code: '<b role="button" />'
,
code: '<base role="button" />'
,
code: '<bdi role="button" />'
,
code: '<bdo role="button" />'
,
code: '<big role="button" />'
,
code: '<blink role="button" />'
,
code: '<blockquote role="button" />'
,
code: '<body role="button" />'
,
code: '<br role="button" />'
,
code: '<canvas role="button" />'
,
code: '<caption role="button" />'
,
code: '<center role="button" />'
,
code: '<cite role="button" />'
,
code: '<code role="button" />'
,
code: '<col role="button" />'
,
code: '<colgroup role="button" />'
,
code: '<content role="button" />'
,
code: '<data role="button" />'
,
code: '<datalist role="button" />'
,
code: '<del role="button" />'
,
code: '<details role="button" />'
,
code: '<dir role="button" />'
,
code: '<div role="button" />'
,
code: '<div className="foo" role="button" />'
,
code: '<div className="foo" {...props} role="button" />'
,
code: '<div aria-hidden role="button" />'
,
code: '<div aria-hidden={true} role="button" />'
,
code: '<div aria-hidden={yes} role="button" />'
,
code: '<div role="button" />'
,
code: '<div role={undefined} role="button" />'
,
code: '<div {...props} role="button" />'
,
code: '<div onKeyUp={() => undefined} aria-hidden={false} role="button" />'
,
code: '<dl role="button" />'
,
code: '<em role="button" />'
,
code: '<embed role="button" />'
,
code: '<figcaption role="button" />'
,
code: '<font role="button" />'
,
code: '<footer role="button" />'
,
code: '<frameset role="button" />'
,
code: '<head role="button" />'
,
code: '<header role="button" />'
,
code: '<hgroup role="button" />'
,
code: '<html role="button" />'
,
code: '<i role="button" />'
,
code: '<iframe role="button" />'
,
code: '<ins role="button" />'
,
code: '<kbd role="button" />'
,
code: '<keygen role="button" />'
,
code: '<label role="button" />'
,
code: '<legend role="button" />'
,
code: '<link role="button" />'
,
code: '<map role="button" />'
,
code: '<mark role="button" />'
,
code: '<marquee role="button" />'
,
code: '<menu role="button" />'
,
code: '<meta role="button" />'
,
code: '<meter role="button" />'
,
code: '<noembed role="button" />'
,
code: '<noscript role="button" />'
,
code: '<object role="button" />'
,
code: '<optgroup role="button" />'
,
code: '<output role="button" />'
,
code: '<p role="button" />'
,
code: '<param role="button" />'
,
code: '<picture role="button" />'
,
code: '<pre role="button" />'
,
code: '<progress role="button" />'
,
code: '<q role="button" />'
,
code: '<rp role="button" />'
,
code: '<rt role="button" />'
,
code: '<rtc role="button" />'
,
code: '<ruby role="button" />'
,
code: '<s role="button" />'
,
code: '<samp role="button" />'
,
code: '<script role="button" />'
,
code: '<section role="button" />'
,
code: '<small role="button" />'
,
code: '<source role="button" />'
,
code: '<spacer role="button" />'
,
code: '<span role="button" />'
,
code: '<strike role="button" />'
,
code: '<strong role="button" />'
,
code: '<style role="button" />'
,
code: '<sub role="button" />'
,
code: '<summary role="button" />'
,
code: '<sup role="button" />'
,
code: '<th role="button" />'
,
code: '<time role="button" />'
,
code: '<title role="button" />'
,
code: '<track role="button" />'
,
code: '<tt role="button" />'
,
code: '<u role="button" />'
,
code: '<var role="button" />'
,
code: '<video role="button" />'
,
code: '<wbr role="button" />'
,
code: '<xmp role="button" />'
,
### HTML elements attributed with an interactive role ###
code: '<div role="button" />'
,
code: '<div role="checkbox" />'
,
code: '<div role="columnheader" />'
,
code: '<div role="combobox" />'
,
code: '<div role="grid" />'
,
code: '<div role="gridcell" />'
,
code: '<div role="link" />'
,
code: '<div role="listbox" />'
,
code: '<div role="menu" />'
,
code: '<div role="menubar" />'
,
code: '<div role="menuitem" />'
,
code: '<div role="menuitemcheckbox" />'
,
code: '<div role="menuitemradio" />'
,
code: '<div role="option" />'
,
code: '<div role="progressbar" />'
,
code: '<div role="radio" />'
,
code: '<div role="radiogroup" />'
,
code: '<div role="row" />'
,
code: '<div role="rowheader" />'
,
code: '<div role="searchbox" />'
,
code: '<div role="slider" />'
,
code: '<div role="spinbutton" />'
,
code: '<div role="switch" />'
,
code: '<div role="tab" />'
,
code: '<div role="textbox" />'
,
code: '<div role="treeitem" />'
,
### Presentation is a special case role that indicates intentional static semantics ###
code: '<div role="presentation" />'
,
### HTML elements attributed with an abstract role ###
code: '<div role="command" />'
,
code: '<div role="composite" />'
,
code: '<div role="input" />'
,
code: '<div role="landmark" />'
,
code: '<div role="range" />'
,
code: '<div role="roletype" />'
,
code: '<div role="section" />'
,
code: '<div role="sectionhead" />'
,
code: '<div role="select" />'
,
code: '<div role="structure" />'
,
code: '<div role="tablist" />'
,
code: '<div role="toolbar" />'
,
code: '<div role="tree" />'
,
code: '<div role="treegrid" />'
,
code: '<div role="widget" />'
,
code: '<div role="window" />'
,
### HTML elements with an inherent, non-interactive role, assigned an
# interactive role. ###
code: '<main role="button" />'
,
code: '<area role="button" />'
,
code: '<article role="button" />'
,
code: '<article role="button" />'
,
code: '<dd role="button" />'
,
code: '<dfn role="button" />'
,
code: '<dt role="button" />'
,
code: '<fieldset role="button" />'
,
code: '<figure role="button" />'
,
code: '<form role="button" />'
,
code: '<frame role="button" />'
,
code: '<h1 role="button" />'
,
code: '<h2 role="button" />'
,
code: '<h3 role="button" />'
,
code: '<h4 role="button" />'
,
code: '<h5 role="button" />'
,
code: '<h6 role="button" />'
,
code: '<hr role="button" />'
,
code: '<img role="button" />'
,
code: '<li role="button" />'
,
code: '<li role="presentation" />'
,
code: '<nav role="button" />'
,
code: '<ol role="button" />'
,
code: '<table role="button" />'
,
code: '<tbody role="button" />'
,
code: '<td role="button" />'
,
code: '<tfoot role="button" />'
,
code: '<thead role="button" />'
,
code: '<ul role="button" />'
,
### HTML elements attributed with a non-interactive role ###
code: '<div role="alert" />'
,
code: '<div role="alertdialog" />'
,
code: '<div role="application" />'
,
code: '<div role="article" />'
,
code: '<div role="banner" />'
,
code: '<div role="cell" />'
,
code: '<div role="complementary" />'
,
code: '<div role="contentinfo" />'
,
code: '<div role="definition" />'
,
code: '<div role="dialog" />'
,
code: '<div role="directory" />'
,
code: '<div role="document" />'
,
code: '<div role="feed" />'
,
code: '<div role="figure" />'
,
code: '<div role="form" />'
,
code: '<div role="group" />'
,
code: '<div role="heading" />'
,
code: '<div role="img" />'
,
code: '<div role="list" />'
,
code: '<div role="listitem" />'
,
code: '<div role="log" />'
,
code: '<div role="main" />'
,
code: '<div role="marquee" />'
,
code: '<div role="math" />'
,
code: '<div role="navigation" />'
,
code: '<div role="note" />'
,
code: '<div role="region" />'
,
code: '<div role="rowgroup" />'
,
code: '<div role="search" />'
,
code: '<div role="separator" />'
,
code: '<div role="scrollbar" />'
,
code: '<div role="status" />'
,
code: '<div role="table" />'
,
code: '<div role="tabpanel" />'
,
code: '<div role="term" />'
,
code: '<div role="timer" />'
,
code: '<div role="tooltip" />'
,
### Namespaced roles are not checked ###
code: '<div mynamespace:role="term" />'
,
code: '<input mynamespace:role="img" />'
]
neverValid = [
### Interactive elements ###
code: '<a href="http://x.y.z" role="img" />', errors: [expectedError]
,
code: '<a href="http://x.y.z" tabIndex="0" role="img" />'
errors: [expectedError]
,
### All flavors of input ###
code: '<input role="img" />', errors: [expectedError]
,
code: '<input type="img" role="img" />', errors: [expectedError]
,
code: '<input type="checkbox" role="img" />', errors: [expectedError]
,
code: '<input type="color" role="img" />', errors: [expectedError]
,
code: '<input type="date" role="img" />', errors: [expectedError]
,
code: '<input type="datetime" role="img" />', errors: [expectedError]
,
code: '<input type="datetime-local" role="img" />', errors: [expectedError]
,
code: '<input type="email" role="img" />', errors: [expectedError]
,
code: '<input type="file" role="img" />', errors: [expectedError]
,
code: '<input type="hidden" role="img" />', errors: [expectedError]
,
code: '<input type="image" role="img" />', errors: [expectedError]
,
code: '<input type="month" role="img" />', errors: [expectedError]
,
code: '<input type="number" role="img" />', errors: [expectedError]
,
code: '<input type="password" role="img" />', errors: [expectedError]
,
code: '<input type="radio" role="img" />', errors: [expectedError]
,
code: '<input type="range" role="img" />', errors: [expectedError]
,
code: '<input type="reset" role="img" />', errors: [expectedError]
,
code: '<input type="search" role="img" />', errors: [expectedError]
,
code: '<input type="submit" role="img" />', errors: [expectedError]
,
code: '<input type="tel" role="img" />', errors: [expectedError]
,
code: '<input type="text" role="img" />', errors: [expectedError]
,
code: '<input type="time" role="img" />', errors: [expectedError]
,
code: '<input type="url" role="img" />', errors: [expectedError]
,
code: '<input type="week" role="img" />', errors: [expectedError]
,
### End all flavors of input ###
code: '<menuitem role="img" />', errors: [expectedError]
,
code: '<option className="foo" role="img" />', errors: [expectedError]
,
code: '<select className="foo" role="img" />', errors: [expectedError]
,
code: '<textarea className="foo" role="img" />', errors: [expectedError]
,
code: '<tr role="img" />', errors: [expectedError]
,
### Interactive elements ###
code: '<a href="http://x.y.z" role="listitem" />', errors: [expectedError]
,
code: '<a href="http://x.y.z" tabIndex="0" role="listitem" />'
errors: [expectedError]
,
### All flavors of input ###
code: '<input role="listitem" />', errors: [expectedError]
,
code: '<input type="listitem" role="listitem" />', errors: [expectedError]
,
code: '<input type="checkbox" role="listitem" />', errors: [expectedError]
,
code: '<input type="color" role="listitem" />', errors: [expectedError]
,
code: '<input type="date" role="listitem" />', errors: [expectedError]
,
code: '<input type="datetime" role="listitem" />', errors: [expectedError]
,
code: '<input type="datetime-local" role="listitem" />'
errors: [expectedError]
,
code: '<input type="email" role="listitem" />', errors: [expectedError]
,
code: '<input type="file" role="listitem" />', errors: [expectedError]
,
code: '<input type="image" role="listitem" />', errors: [expectedError]
,
code: '<input type="month" role="listitem" />', errors: [expectedError]
,
code: '<input type="number" role="listitem" />', errors: [expectedError]
,
code: '<input type="password" role="listitem" />', errors: [expectedError]
,
code: '<input type="radio" role="listitem" />', errors: [expectedError]
,
code: '<input type="range" role="listitem" />', errors: [expectedError]
,
code: '<input type="reset" role="listitem" />', errors: [expectedError]
,
code: '<input type="search" role="listitem" />', errors: [expectedError]
,
code: '<input type="submit" role="listitem" />', errors: [expectedError]
,
code: '<input type="tel" role="listitem" />', errors: [expectedError]
,
code: '<input type="text" role="listitem" />', errors: [expectedError]
,
code: '<input type="time" role="listitem" />', errors: [expectedError]
,
code: '<input type="url" role="listitem" />', errors: [expectedError]
,
code: '<input type="week" role="listitem" />', errors: [expectedError]
,
### End all flavors of input ###
code: '<menuitem role="listitem" />', errors: [expectedError]
,
code: '<option className="foo" role="listitem" />', errors: [expectedError]
,
code: '<select className="foo" role="listitem" />', errors: [expectedError]
,
code: '<textarea className="foo" role="listitem" />', errors: [expectedError]
,
code: '<tr role="listitem" />', errors: [expectedError]
]
recommendedOptions = configs.recommended.rules[ruleName][1] or {}
ruleTester.run "#{ruleName}:recommended", rule,
valid:
[
...alwaysValid
,
code: '<tr role="presentation" />;'
,
code: '<Component role="presentation" />;'
]
.map ruleOptionsMapperFactory recommendedOptions
.map parserOptionsMapper
invalid:
[...neverValid]
.map(ruleOptionsMapperFactory recommendedOptions)
.map parserOptionsMapper
ruleTester.run "#{ruleName}:strict", rule,
valid: [...alwaysValid].map parserOptionsMapper
invalid: [
...neverValid
,
code: '<tr role="presentation" />;', errors: [expectedError]
].map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Disallow inherently interactive elements to be assigned
# non-interactive roles.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{configs} = require 'eslint-plugin-jsx-a11y'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require(
'eslint-plugin-jsx-a11y/lib/rules/no-interactive-element-to-noninteractive-role'
)
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
'Interactive elements should not be assigned non-interactive roles.'
expectedError =
message: errorMessage
type: 'JSXAttribute'
ruleName = 'jsx-a11y/no-interactive-element-to-noninteractive-role'
alwaysValid = [
code: '<TestComponent onClick={doFoo} />'
,
code: '<Button onClick={doFoo} />'
,
### Interactive elements ###
code: '<a href="http://x.y.z" role="button" />'
,
code: '<a href="http://x.y.z" tabIndex="0" role="button" />'
,
code: '<button className="foo" role="button" />'
,
### All flavors of input ###
code: '<input role="button" />'
,
code: '<input type="button" role="button" />'
,
code: '<input type="checkbox" role="button" />'
,
code: '<input type="color" role="button" />'
,
code: '<input type="date" role="button" />'
,
code: '<input type="datetime" role="button" />'
,
code: '<input type="datetime-local" role="button" />'
,
code: '<input type="email" role="button" />'
,
code: '<input type="file" role="button" />'
,
code: '<input type="image" role="button" />'
,
code: '<input type="month" role="button" />'
,
code: '<input type="number" role="button" />'
,
code: '<input type="password" role="button" />'
,
code: '<input type="radio" role="button" />'
,
code: '<input type="range" role="button" />'
,
code: '<input type="reset" role="button" />'
,
code: '<input type="search" role="button" />'
,
code: '<input type="submit" role="button" />'
,
code: '<input type="tel" role="button" />'
,
code: '<input type="text" role="button" />'
,
code: '<input type="time" role="button" />'
,
code: '<input type="url" role="button" />'
,
code: '<input type="week" role="button" />'
,
code: '<input type="hidden" role="button" />'
,
### End all flavors of input ###
code: '<menuitem role="button" />'
,
code: '<option className="foo" role="button" />'
,
code: '<select className="foo" role="button" />'
,
code: '<textarea className="foo" role="button" />'
,
code: '<tr role="button" />'
,
### HTML elements with neither an interactive or non-interactive valence (static) ###
code: '<a role="button" />'
,
code: '<a role="img" />'
,
code: '<a tabIndex="0" role="button" />'
,
code: '<a tabIndex="0" role="img" />'
,
code: '<acronym role="button" />'
,
code: '<address role="button" />'
,
code: '<applet role="button" />'
,
code: '<aside role="button" />'
,
code: '<audio role="button" />'
,
code: '<b role="button" />'
,
code: '<base role="button" />'
,
code: '<bdi role="button" />'
,
code: '<bdo role="button" />'
,
code: '<big role="button" />'
,
code: '<blink role="button" />'
,
code: '<blockquote role="button" />'
,
code: '<body role="button" />'
,
code: '<br role="button" />'
,
code: '<canvas role="button" />'
,
code: '<caption role="button" />'
,
code: '<center role="button" />'
,
code: '<cite role="button" />'
,
code: '<code role="button" />'
,
code: '<col role="button" />'
,
code: '<colgroup role="button" />'
,
code: '<content role="button" />'
,
code: '<data role="button" />'
,
code: '<datalist role="button" />'
,
code: '<del role="button" />'
,
code: '<details role="button" />'
,
code: '<dir role="button" />'
,
code: '<div role="button" />'
,
code: '<div className="foo" role="button" />'
,
code: '<div className="foo" {...props} role="button" />'
,
code: '<div aria-hidden role="button" />'
,
code: '<div aria-hidden={true} role="button" />'
,
code: '<div aria-hidden={yes} role="button" />'
,
code: '<div role="button" />'
,
code: '<div role={undefined} role="button" />'
,
code: '<div {...props} role="button" />'
,
code: '<div onKeyUp={() => undefined} aria-hidden={false} role="button" />'
,
code: '<dl role="button" />'
,
code: '<em role="button" />'
,
code: '<embed role="button" />'
,
code: '<figcaption role="button" />'
,
code: '<font role="button" />'
,
code: '<footer role="button" />'
,
code: '<frameset role="button" />'
,
code: '<head role="button" />'
,
code: '<header role="button" />'
,
code: '<hgroup role="button" />'
,
code: '<html role="button" />'
,
code: '<i role="button" />'
,
code: '<iframe role="button" />'
,
code: '<ins role="button" />'
,
code: '<kbd role="button" />'
,
code: '<keygen role="button" />'
,
code: '<label role="button" />'
,
code: '<legend role="button" />'
,
code: '<link role="button" />'
,
code: '<map role="button" />'
,
code: '<mark role="button" />'
,
code: '<marquee role="button" />'
,
code: '<menu role="button" />'
,
code: '<meta role="button" />'
,
code: '<meter role="button" />'
,
code: '<noembed role="button" />'
,
code: '<noscript role="button" />'
,
code: '<object role="button" />'
,
code: '<optgroup role="button" />'
,
code: '<output role="button" />'
,
code: '<p role="button" />'
,
code: '<param role="button" />'
,
code: '<picture role="button" />'
,
code: '<pre role="button" />'
,
code: '<progress role="button" />'
,
code: '<q role="button" />'
,
code: '<rp role="button" />'
,
code: '<rt role="button" />'
,
code: '<rtc role="button" />'
,
code: '<ruby role="button" />'
,
code: '<s role="button" />'
,
code: '<samp role="button" />'
,
code: '<script role="button" />'
,
code: '<section role="button" />'
,
code: '<small role="button" />'
,
code: '<source role="button" />'
,
code: '<spacer role="button" />'
,
code: '<span role="button" />'
,
code: '<strike role="button" />'
,
code: '<strong role="button" />'
,
code: '<style role="button" />'
,
code: '<sub role="button" />'
,
code: '<summary role="button" />'
,
code: '<sup role="button" />'
,
code: '<th role="button" />'
,
code: '<time role="button" />'
,
code: '<title role="button" />'
,
code: '<track role="button" />'
,
code: '<tt role="button" />'
,
code: '<u role="button" />'
,
code: '<var role="button" />'
,
code: '<video role="button" />'
,
code: '<wbr role="button" />'
,
code: '<xmp role="button" />'
,
### HTML elements attributed with an interactive role ###
code: '<div role="button" />'
,
code: '<div role="checkbox" />'
,
code: '<div role="columnheader" />'
,
code: '<div role="combobox" />'
,
code: '<div role="grid" />'
,
code: '<div role="gridcell" />'
,
code: '<div role="link" />'
,
code: '<div role="listbox" />'
,
code: '<div role="menu" />'
,
code: '<div role="menubar" />'
,
code: '<div role="menuitem" />'
,
code: '<div role="menuitemcheckbox" />'
,
code: '<div role="menuitemradio" />'
,
code: '<div role="option" />'
,
code: '<div role="progressbar" />'
,
code: '<div role="radio" />'
,
code: '<div role="radiogroup" />'
,
code: '<div role="row" />'
,
code: '<div role="rowheader" />'
,
code: '<div role="searchbox" />'
,
code: '<div role="slider" />'
,
code: '<div role="spinbutton" />'
,
code: '<div role="switch" />'
,
code: '<div role="tab" />'
,
code: '<div role="textbox" />'
,
code: '<div role="treeitem" />'
,
### Presentation is a special case role that indicates intentional static semantics ###
code: '<div role="presentation" />'
,
### HTML elements attributed with an abstract role ###
code: '<div role="command" />'
,
code: '<div role="composite" />'
,
code: '<div role="input" />'
,
code: '<div role="landmark" />'
,
code: '<div role="range" />'
,
code: '<div role="roletype" />'
,
code: '<div role="section" />'
,
code: '<div role="sectionhead" />'
,
code: '<div role="select" />'
,
code: '<div role="structure" />'
,
code: '<div role="tablist" />'
,
code: '<div role="toolbar" />'
,
code: '<div role="tree" />'
,
code: '<div role="treegrid" />'
,
code: '<div role="widget" />'
,
code: '<div role="window" />'
,
### HTML elements with an inherent, non-interactive role, assigned an
# interactive role. ###
code: '<main role="button" />'
,
code: '<area role="button" />'
,
code: '<article role="button" />'
,
code: '<article role="button" />'
,
code: '<dd role="button" />'
,
code: '<dfn role="button" />'
,
code: '<dt role="button" />'
,
code: '<fieldset role="button" />'
,
code: '<figure role="button" />'
,
code: '<form role="button" />'
,
code: '<frame role="button" />'
,
code: '<h1 role="button" />'
,
code: '<h2 role="button" />'
,
code: '<h3 role="button" />'
,
code: '<h4 role="button" />'
,
code: '<h5 role="button" />'
,
code: '<h6 role="button" />'
,
code: '<hr role="button" />'
,
code: '<img role="button" />'
,
code: '<li role="button" />'
,
code: '<li role="presentation" />'
,
code: '<nav role="button" />'
,
code: '<ol role="button" />'
,
code: '<table role="button" />'
,
code: '<tbody role="button" />'
,
code: '<td role="button" />'
,
code: '<tfoot role="button" />'
,
code: '<thead role="button" />'
,
code: '<ul role="button" />'
,
### HTML elements attributed with a non-interactive role ###
code: '<div role="alert" />'
,
code: '<div role="alertdialog" />'
,
code: '<div role="application" />'
,
code: '<div role="article" />'
,
code: '<div role="banner" />'
,
code: '<div role="cell" />'
,
code: '<div role="complementary" />'
,
code: '<div role="contentinfo" />'
,
code: '<div role="definition" />'
,
code: '<div role="dialog" />'
,
code: '<div role="directory" />'
,
code: '<div role="document" />'
,
code: '<div role="feed" />'
,
code: '<div role="figure" />'
,
code: '<div role="form" />'
,
code: '<div role="group" />'
,
code: '<div role="heading" />'
,
code: '<div role="img" />'
,
code: '<div role="list" />'
,
code: '<div role="listitem" />'
,
code: '<div role="log" />'
,
code: '<div role="main" />'
,
code: '<div role="marquee" />'
,
code: '<div role="math" />'
,
code: '<div role="navigation" />'
,
code: '<div role="note" />'
,
code: '<div role="region" />'
,
code: '<div role="rowgroup" />'
,
code: '<div role="search" />'
,
code: '<div role="separator" />'
,
code: '<div role="scrollbar" />'
,
code: '<div role="status" />'
,
code: '<div role="table" />'
,
code: '<div role="tabpanel" />'
,
code: '<div role="term" />'
,
code: '<div role="timer" />'
,
code: '<div role="tooltip" />'
,
### Namespaced roles are not checked ###
code: '<div mynamespace:role="term" />'
,
code: '<input mynamespace:role="img" />'
]
neverValid = [
### Interactive elements ###
code: '<a href="http://x.y.z" role="img" />', errors: [expectedError]
,
code: '<a href="http://x.y.z" tabIndex="0" role="img" />'
errors: [expectedError]
,
### All flavors of input ###
code: '<input role="img" />', errors: [expectedError]
,
code: '<input type="img" role="img" />', errors: [expectedError]
,
code: '<input type="checkbox" role="img" />', errors: [expectedError]
,
code: '<input type="color" role="img" />', errors: [expectedError]
,
code: '<input type="date" role="img" />', errors: [expectedError]
,
code: '<input type="datetime" role="img" />', errors: [expectedError]
,
code: '<input type="datetime-local" role="img" />', errors: [expectedError]
,
code: '<input type="email" role="img" />', errors: [expectedError]
,
code: '<input type="file" role="img" />', errors: [expectedError]
,
code: '<input type="hidden" role="img" />', errors: [expectedError]
,
code: '<input type="image" role="img" />', errors: [expectedError]
,
code: '<input type="month" role="img" />', errors: [expectedError]
,
code: '<input type="number" role="img" />', errors: [expectedError]
,
code: '<input type="password" role="img" />', errors: [expectedError]
,
code: '<input type="radio" role="img" />', errors: [expectedError]
,
code: '<input type="range" role="img" />', errors: [expectedError]
,
code: '<input type="reset" role="img" />', errors: [expectedError]
,
code: '<input type="search" role="img" />', errors: [expectedError]
,
code: '<input type="submit" role="img" />', errors: [expectedError]
,
code: '<input type="tel" role="img" />', errors: [expectedError]
,
code: '<input type="text" role="img" />', errors: [expectedError]
,
code: '<input type="time" role="img" />', errors: [expectedError]
,
code: '<input type="url" role="img" />', errors: [expectedError]
,
code: '<input type="week" role="img" />', errors: [expectedError]
,
### End all flavors of input ###
code: '<menuitem role="img" />', errors: [expectedError]
,
code: '<option className="foo" role="img" />', errors: [expectedError]
,
code: '<select className="foo" role="img" />', errors: [expectedError]
,
code: '<textarea className="foo" role="img" />', errors: [expectedError]
,
code: '<tr role="img" />', errors: [expectedError]
,
### Interactive elements ###
code: '<a href="http://x.y.z" role="listitem" />', errors: [expectedError]
,
code: '<a href="http://x.y.z" tabIndex="0" role="listitem" />'
errors: [expectedError]
,
### All flavors of input ###
code: '<input role="listitem" />', errors: [expectedError]
,
code: '<input type="listitem" role="listitem" />', errors: [expectedError]
,
code: '<input type="checkbox" role="listitem" />', errors: [expectedError]
,
code: '<input type="color" role="listitem" />', errors: [expectedError]
,
code: '<input type="date" role="listitem" />', errors: [expectedError]
,
code: '<input type="datetime" role="listitem" />', errors: [expectedError]
,
code: '<input type="datetime-local" role="listitem" />'
errors: [expectedError]
,
code: '<input type="email" role="listitem" />', errors: [expectedError]
,
code: '<input type="file" role="listitem" />', errors: [expectedError]
,
code: '<input type="image" role="listitem" />', errors: [expectedError]
,
code: '<input type="month" role="listitem" />', errors: [expectedError]
,
code: '<input type="number" role="listitem" />', errors: [expectedError]
,
code: '<input type="password" role="listitem" />', errors: [expectedError]
,
code: '<input type="radio" role="listitem" />', errors: [expectedError]
,
code: '<input type="range" role="listitem" />', errors: [expectedError]
,
code: '<input type="reset" role="listitem" />', errors: [expectedError]
,
code: '<input type="search" role="listitem" />', errors: [expectedError]
,
code: '<input type="submit" role="listitem" />', errors: [expectedError]
,
code: '<input type="tel" role="listitem" />', errors: [expectedError]
,
code: '<input type="text" role="listitem" />', errors: [expectedError]
,
code: '<input type="time" role="listitem" />', errors: [expectedError]
,
code: '<input type="url" role="listitem" />', errors: [expectedError]
,
code: '<input type="week" role="listitem" />', errors: [expectedError]
,
### End all flavors of input ###
code: '<menuitem role="listitem" />', errors: [expectedError]
,
code: '<option className="foo" role="listitem" />', errors: [expectedError]
,
code: '<select className="foo" role="listitem" />', errors: [expectedError]
,
code: '<textarea className="foo" role="listitem" />', errors: [expectedError]
,
code: '<tr role="listitem" />', errors: [expectedError]
]
recommendedOptions = configs.recommended.rules[ruleName][1] or {}
ruleTester.run "#{ruleName}:recommended", rule,
valid:
[
...alwaysValid
,
code: '<tr role="presentation" />;'
,
code: '<Component role="presentation" />;'
]
.map ruleOptionsMapperFactory recommendedOptions
.map parserOptionsMapper
invalid:
[...neverValid]
.map(ruleOptionsMapperFactory recommendedOptions)
.map parserOptionsMapper
ruleTester.run "#{ruleName}:strict", rule,
valid: [...alwaysValid].map parserOptionsMapper
invalid: [
...neverValid
,
code: '<tr role="presentation" />;', errors: [expectedError]
].map parserOptionsMapper
|
[
{
"context": "osed'\n return\n return\n # Arctic Scroll by Paul Adam Davis\n # https://github.com/PaulAdamDavis/Arctic-Scrol",
"end": 455,
"score": 0.9999010562896729,
"start": 440,
"tag": "NAME",
"value": "Paul Adam Davis"
},
{
"context": " Scroll by Paul Adam Davis\n # h... | source/assets/js/index.coffee | haqqle/ghost_starter_theme | 0 | ###*
# Main JS file for Casper behaviours
###
### globals jQuery, document ###
(($) ->
'use strict'
$document = $(document)
$document.ready ->
$postContent = $('.post-content')
$postContent.fitVids()
$('.scroll-down').arcticScroll()
$('.menu-button, .nav-cover, .nav-close').on 'click', (e) ->
e.preventDefault()
$('body').toggleClass 'nav-opened nav-closed'
return
return
# Arctic Scroll by Paul Adam Davis
# https://github.com/PaulAdamDavis/Arctic-Scroll
$.fn.arcticScroll = (options) ->
defaults =
elem: $(this)
speed: 500
allOptions = $.extend(defaults, options)
allOptions.elem.click (event) ->
event.preventDefault()
$this = $(this)
$htmlBody = $('html, body')
offset = if $this.attr('data-offset') then $this.attr('data-offset') else false
position = if $this.attr('data-position') then $this.attr('data-position') else false
toMove = undefined
if offset
toMove = parseInt(offset)
$htmlBody.stop(true, false).animate { scrollTop: $(@hash).offset().top + toMove }, allOptions.speed
else if position
toMove = parseInt(position)
$htmlBody.stop(true, false).animate { scrollTop: toMove }, allOptions.speed
else
$htmlBody.stop(true, false).animate { scrollTop: $(@hash).offset().top }, allOptions.speed
return
return
return
) jQuery
| 122115 | ###*
# Main JS file for Casper behaviours
###
### globals jQuery, document ###
(($) ->
'use strict'
$document = $(document)
$document.ready ->
$postContent = $('.post-content')
$postContent.fitVids()
$('.scroll-down').arcticScroll()
$('.menu-button, .nav-cover, .nav-close').on 'click', (e) ->
e.preventDefault()
$('body').toggleClass 'nav-opened nav-closed'
return
return
# Arctic Scroll by <NAME>
# https://github.com/PaulAdamDavis/Arctic-Scroll
$.fn.arcticScroll = (options) ->
defaults =
elem: $(this)
speed: 500
allOptions = $.extend(defaults, options)
allOptions.elem.click (event) ->
event.preventDefault()
$this = $(this)
$htmlBody = $('html, body')
offset = if $this.attr('data-offset') then $this.attr('data-offset') else false
position = if $this.attr('data-position') then $this.attr('data-position') else false
toMove = undefined
if offset
toMove = parseInt(offset)
$htmlBody.stop(true, false).animate { scrollTop: $(@hash).offset().top + toMove }, allOptions.speed
else if position
toMove = parseInt(position)
$htmlBody.stop(true, false).animate { scrollTop: toMove }, allOptions.speed
else
$htmlBody.stop(true, false).animate { scrollTop: $(@hash).offset().top }, allOptions.speed
return
return
return
) jQuery
| true | ###*
# Main JS file for Casper behaviours
###
### globals jQuery, document ###
(($) ->
'use strict'
$document = $(document)
$document.ready ->
$postContent = $('.post-content')
$postContent.fitVids()
$('.scroll-down').arcticScroll()
$('.menu-button, .nav-cover, .nav-close').on 'click', (e) ->
e.preventDefault()
$('body').toggleClass 'nav-opened nav-closed'
return
return
# Arctic Scroll by PI:NAME:<NAME>END_PI
# https://github.com/PaulAdamDavis/Arctic-Scroll
$.fn.arcticScroll = (options) ->
defaults =
elem: $(this)
speed: 500
allOptions = $.extend(defaults, options)
allOptions.elem.click (event) ->
event.preventDefault()
$this = $(this)
$htmlBody = $('html, body')
offset = if $this.attr('data-offset') then $this.attr('data-offset') else false
position = if $this.attr('data-position') then $this.attr('data-position') else false
toMove = undefined
if offset
toMove = parseInt(offset)
$htmlBody.stop(true, false).animate { scrollTop: $(@hash).offset().top + toMove }, allOptions.speed
else if position
toMove = parseInt(position)
$htmlBody.stop(true, false).animate { scrollTop: toMove }, allOptions.speed
else
$htmlBody.stop(true, false).animate { scrollTop: $(@hash).offset().top }, allOptions.speed
return
return
return
) jQuery
|
[
{
"context": "rd', outlet: 'confirmPassword'\n # @password 'miniEditor', new TextEditorView(mini: true)\n # @confirm",
"end": 826,
"score": 0.7274978160858154,
"start": 816,
"tag": "PASSWORD",
"value": "miniEditor"
},
{
"context": "torView(mini: true)\n # @confirmPassw... | lib/encryption.coffee | brvier/organized | 137 | crypto = require('crypto')
algorithm = 'aes-256-ctr'
encrypt = (text, password) ->
cipher = crypto.createCipher(algorithm, password)
crypted = cipher.update(text, 'utf8', 'hex')
crypted += cipher.final('hex')
return crypted
decrypt = (text, password) ->
decipher = crypto.createDecipher(algorithm, password)
decrypted = decipher.update(text, 'hex', 'utf8')
decrypted += decipher.final('utf8');
return decrypted
class EncryptDialog extends View
@content: ({prompt} = {}) ->
@div class: 'password-dialog', ->
@p warning, class: 'warningtext', outlet: 'warning'
@label prompt, class: 'icon', outlet: 'promptText'
@input name: 'password', type: 'password', outlet: 'password'
@input name: 'confirmPassword', type: 'password', outlet: 'confirmPassword'
# @password 'miniEditor', new TextEditorView(mini: true)
# @confirmPassword 'miniEditor', new TextEditorView(mini: true)
@div class: 'error-message', outlet: 'errorMessage'
initialize: ({message, iconClass} = {}) ->
@promptText.addClass(iconClass) if iconClass
atom.commands.add @element,
'core:confirm': => @onConfirm(@miniEditor.getText())
'core:cancel': => @cancel()
@miniEditor.on 'blur', => @close() if document.hasFocus()
@miniEditor.getModel().onDidChange => @showError()
@warning = "This will encrypt the current file and delete the original. There is no mechanism to recover this \
file without the password"
attach: ->
@panel = atom.workspace.addModalPanel(item: this.element)
@miniEditor.focus()
@miniEditor.getModel().scrollToCursorPosition()
close: ->
panelToDestroy = @panel
@panel = null
panelToDestroy?.destroy()
atom.workspace.getActivePane().activate()
cancel: ->
@close()
$('.organized').focus()
showError: (message='') ->
@errorMessage.text(message)
@flashError() if message
module.exports = {encrypt, decrypt}
| 49867 | crypto = require('crypto')
algorithm = 'aes-256-ctr'
encrypt = (text, password) ->
cipher = crypto.createCipher(algorithm, password)
crypted = cipher.update(text, 'utf8', 'hex')
crypted += cipher.final('hex')
return crypted
decrypt = (text, password) ->
decipher = crypto.createDecipher(algorithm, password)
decrypted = decipher.update(text, 'hex', 'utf8')
decrypted += decipher.final('utf8');
return decrypted
class EncryptDialog extends View
@content: ({prompt} = {}) ->
@div class: 'password-dialog', ->
@p warning, class: 'warningtext', outlet: 'warning'
@label prompt, class: 'icon', outlet: 'promptText'
@input name: 'password', type: 'password', outlet: 'password'
@input name: 'confirmPassword', type: 'password', outlet: 'confirmPassword'
# @password '<PASSWORD>', new TextEditorView(mini: true)
# @confirmPassword 'mini<PASSWORD>', new TextEditorView(mini: true)
@div class: 'error-message', outlet: 'errorMessage'
initialize: ({message, iconClass} = {}) ->
@promptText.addClass(iconClass) if iconClass
atom.commands.add @element,
'core:confirm': => @onConfirm(@miniEditor.getText())
'core:cancel': => @cancel()
@miniEditor.on 'blur', => @close() if document.hasFocus()
@miniEditor.getModel().onDidChange => @showError()
@warning = "This will encrypt the current file and delete the original. There is no mechanism to recover this \
file without the password"
attach: ->
@panel = atom.workspace.addModalPanel(item: this.element)
@miniEditor.focus()
@miniEditor.getModel().scrollToCursorPosition()
close: ->
panelToDestroy = @panel
@panel = null
panelToDestroy?.destroy()
atom.workspace.getActivePane().activate()
cancel: ->
@close()
$('.organized').focus()
showError: (message='') ->
@errorMessage.text(message)
@flashError() if message
module.exports = {encrypt, decrypt}
| true | crypto = require('crypto')
algorithm = 'aes-256-ctr'
encrypt = (text, password) ->
cipher = crypto.createCipher(algorithm, password)
crypted = cipher.update(text, 'utf8', 'hex')
crypted += cipher.final('hex')
return crypted
decrypt = (text, password) ->
decipher = crypto.createDecipher(algorithm, password)
decrypted = decipher.update(text, 'hex', 'utf8')
decrypted += decipher.final('utf8');
return decrypted
class EncryptDialog extends View
@content: ({prompt} = {}) ->
@div class: 'password-dialog', ->
@p warning, class: 'warningtext', outlet: 'warning'
@label prompt, class: 'icon', outlet: 'promptText'
@input name: 'password', type: 'password', outlet: 'password'
@input name: 'confirmPassword', type: 'password', outlet: 'confirmPassword'
# @password 'PI:PASSWORD:<PASSWORD>END_PI', new TextEditorView(mini: true)
# @confirmPassword 'miniPI:PASSWORD:<PASSWORD>END_PI', new TextEditorView(mini: true)
@div class: 'error-message', outlet: 'errorMessage'
initialize: ({message, iconClass} = {}) ->
@promptText.addClass(iconClass) if iconClass
atom.commands.add @element,
'core:confirm': => @onConfirm(@miniEditor.getText())
'core:cancel': => @cancel()
@miniEditor.on 'blur', => @close() if document.hasFocus()
@miniEditor.getModel().onDidChange => @showError()
@warning = "This will encrypt the current file and delete the original. There is no mechanism to recover this \
file without the password"
attach: ->
@panel = atom.workspace.addModalPanel(item: this.element)
@miniEditor.focus()
@miniEditor.getModel().scrollToCursorPosition()
close: ->
panelToDestroy = @panel
@panel = null
panelToDestroy?.destroy()
atom.workspace.getActivePane().activate()
cancel: ->
@close()
$('.organized').focus()
showError: (message='') ->
@errorMessage.text(message)
@flashError() if message
module.exports = {encrypt, decrypt}
|
[
{
"context": "##*\n# @fileoverview Tests for max-depth.\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------",
"end": 71,
"score": 0.9997890591621399,
"start": 52,
"tag": "NAME",
"value": "Ian Christian Myers"
}
] | src/tests/rules/max-depth.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for max-depth.
# @author Ian Christian Myers
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/max-depth'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'max-depth', rule,
valid: [
code: '''
foo = ->
if true
if false
if true
;
'''
options: [3]
,
code: '''
->
if yes
;
else if no
;
else if yes
;
else if no
;
'''
options: [3]
,
# object property options
code: '''
foo = ->
if true
if false
if true
;
'''
options: [max: 3]
]
invalid: [
code: '''
foo = ->
if true
if false
if true
;
'''
options: [2]
errors: [message: 'Blocks are nested too deeply (3).', type: 'IfStatement']
,
code: '''
->
if yes
;
else
loop
;
'''
options: [1]
errors: [
message: 'Blocks are nested too deeply (2).', type: 'WhileStatement'
]
,
code: '''
->
loop
if true
;
'''
options: [1]
errors: [message: 'Blocks are nested too deeply (2).', type: 'IfStatement']
,
code: '''
foo = ->
for x from foo
if true
;
'''
options: [1]
errors: [message: 'Blocks are nested too deeply (2).', type: 'IfStatement']
,
code: '''
->
while yes
if yes
if no
;
'''
options: [1]
errors: [
message: 'Blocks are nested too deeply (2).', type: 'IfStatement'
,
message: 'Blocks are nested too deeply (3).', type: 'IfStatement'
]
,
code: '''
->
if true
if false
if true
if false
if true
;
'''
errors: [message: 'Blocks are nested too deeply (5).', type: 'IfStatement']
,
# object property options
code: '''
->
if yes
if no
if yes
;
'''
options: [max: 2]
errors: [message: 'Blocks are nested too deeply (3).', type: 'IfStatement']
]
| 86248 | ###*
# @fileoverview Tests for max-depth.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/max-depth'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'max-depth', rule,
valid: [
code: '''
foo = ->
if true
if false
if true
;
'''
options: [3]
,
code: '''
->
if yes
;
else if no
;
else if yes
;
else if no
;
'''
options: [3]
,
# object property options
code: '''
foo = ->
if true
if false
if true
;
'''
options: [max: 3]
]
invalid: [
code: '''
foo = ->
if true
if false
if true
;
'''
options: [2]
errors: [message: 'Blocks are nested too deeply (3).', type: 'IfStatement']
,
code: '''
->
if yes
;
else
loop
;
'''
options: [1]
errors: [
message: 'Blocks are nested too deeply (2).', type: 'WhileStatement'
]
,
code: '''
->
loop
if true
;
'''
options: [1]
errors: [message: 'Blocks are nested too deeply (2).', type: 'IfStatement']
,
code: '''
foo = ->
for x from foo
if true
;
'''
options: [1]
errors: [message: 'Blocks are nested too deeply (2).', type: 'IfStatement']
,
code: '''
->
while yes
if yes
if no
;
'''
options: [1]
errors: [
message: 'Blocks are nested too deeply (2).', type: 'IfStatement'
,
message: 'Blocks are nested too deeply (3).', type: 'IfStatement'
]
,
code: '''
->
if true
if false
if true
if false
if true
;
'''
errors: [message: 'Blocks are nested too deeply (5).', type: 'IfStatement']
,
# object property options
code: '''
->
if yes
if no
if yes
;
'''
options: [max: 2]
errors: [message: 'Blocks are nested too deeply (3).', type: 'IfStatement']
]
| true | ###*
# @fileoverview Tests for max-depth.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/max-depth'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'max-depth', rule,
valid: [
code: '''
foo = ->
if true
if false
if true
;
'''
options: [3]
,
code: '''
->
if yes
;
else if no
;
else if yes
;
else if no
;
'''
options: [3]
,
# object property options
code: '''
foo = ->
if true
if false
if true
;
'''
options: [max: 3]
]
invalid: [
code: '''
foo = ->
if true
if false
if true
;
'''
options: [2]
errors: [message: 'Blocks are nested too deeply (3).', type: 'IfStatement']
,
code: '''
->
if yes
;
else
loop
;
'''
options: [1]
errors: [
message: 'Blocks are nested too deeply (2).', type: 'WhileStatement'
]
,
code: '''
->
loop
if true
;
'''
options: [1]
errors: [message: 'Blocks are nested too deeply (2).', type: 'IfStatement']
,
code: '''
foo = ->
for x from foo
if true
;
'''
options: [1]
errors: [message: 'Blocks are nested too deeply (2).', type: 'IfStatement']
,
code: '''
->
while yes
if yes
if no
;
'''
options: [1]
errors: [
message: 'Blocks are nested too deeply (2).', type: 'IfStatement'
,
message: 'Blocks are nested too deeply (3).', type: 'IfStatement'
]
,
code: '''
->
if true
if false
if true
if false
if true
;
'''
errors: [message: 'Blocks are nested too deeply (5).', type: 'IfStatement']
,
# object property options
code: '''
->
if yes
if no
if yes
;
'''
options: [max: 2]
errors: [message: 'Blocks are nested too deeply (3).', type: 'IfStatement']
]
|
[
{
"context": "next) ->\n userObj = req.body\n userObj.password = rule.md5 userObj.password\n # 存入数据,先判断是否存在用户\n usermodel.f",
"end": 2223,
"score": 0.9971144199371338,
"start": 2215,
"tag": "PASSWORD",
"value": "rule.md5"
},
{
"context": " userName : userObj.name\n pa... | routes/users.coffee | ruicky/node-wiki | 99 | express = require 'express'
path = require 'path'
cookieParser = require 'cookie-parser'
session = require 'express-session'
rule = require '../tools/rule'
querystring = require 'querystring'
_ = require 'underscore'
usermodel = require '../models/users'
render = require '../tools/render'
router = express.Router()
# GET users listing.
router.get '/', (req, res, next) ->
res.send '登陆模块'
return
# 登陆模块
router.get '/login', (req, res, next) ->
if req.loginInfo isnt false
res.redirect req.headers.referer or '/../'
else
if req.headers.referer.indexOf('register') isnt -1
render.login res,
title : '登陆'
reUrl : '/../'
else
render.login res,
title : '登陆'
reUrl : req.headers.referer
return
return
#console.log('login')
router.post '/login', (req, res, next) ->
# 查询用户名并验证密码
usermodel.findByEmail req.body.email,(err,user)->
if err
console.log err
#console.log(user);
if user.length<=0
res
.status 200
.send
status:0
info:'帐号或密码错误'
else
if rule.md5(req.body.password) is user[0].passWord
# 设置登陆的cookie
res.cookie 'name',
user[0].userName ,
maxAge: 60 * 1000 * 60 * 24 * 30
res.cookie 'email',
user[0].email ,
maxAge: 60 * 1000 * 60 * 24 * 30
httpOnly: true
res.cookie 'name_sig',
rule.md5(user[0].email+'this_is_mixin_string'+req.cookies['connect.id']),
maxAge: 60 * 1000 * 60 * 24 * 30
httpOnly: true
res
.status 200
.send
status:1
info:'登录成功'
data:
name:user[0].userName
else
res
.status 200
.send
status:0
info:'帐号或密码错误'
return
return
return
# 登出模块
router.get '/logout', (req, res, next) ->
res.clearCookie 'name'
res.clearCookie 'name_sig'
res.clearCookie 'email'
res.redirect req.headers.referer
# 注册模块
router.get '/register', (req, res, next) ->
render.register res,
title: '注册'
return
router.post '/register', (req, res, next) ->
userObj = req.body
userObj.password = rule.md5 userObj.password
# 存入数据,先判断是否存在用户
usermodel.findByEmail userObj.email, (err,user) ->
if err
console.log err
# 判断用户是否存在
if user.length<=0
_user = new usermodel
userName : userObj.name
passWord : userObj.password
email : userObj.email
role : userObj.role
admin : false
_user.save (err, user) ->
if err
console.log err
res.send
status:1
info:'注册成功'
return
else
res.send
status:0
info:'邮箱已被注册'
return
module.exports = router
| 137930 | express = require 'express'
path = require 'path'
cookieParser = require 'cookie-parser'
session = require 'express-session'
rule = require '../tools/rule'
querystring = require 'querystring'
_ = require 'underscore'
usermodel = require '../models/users'
render = require '../tools/render'
router = express.Router()
# GET users listing.
router.get '/', (req, res, next) ->
res.send '登陆模块'
return
# 登陆模块
router.get '/login', (req, res, next) ->
if req.loginInfo isnt false
res.redirect req.headers.referer or '/../'
else
if req.headers.referer.indexOf('register') isnt -1
render.login res,
title : '登陆'
reUrl : '/../'
else
render.login res,
title : '登陆'
reUrl : req.headers.referer
return
return
#console.log('login')
router.post '/login', (req, res, next) ->
# 查询用户名并验证密码
usermodel.findByEmail req.body.email,(err,user)->
if err
console.log err
#console.log(user);
if user.length<=0
res
.status 200
.send
status:0
info:'帐号或密码错误'
else
if rule.md5(req.body.password) is user[0].passWord
# 设置登陆的cookie
res.cookie 'name',
user[0].userName ,
maxAge: 60 * 1000 * 60 * 24 * 30
res.cookie 'email',
user[0].email ,
maxAge: 60 * 1000 * 60 * 24 * 30
httpOnly: true
res.cookie 'name_sig',
rule.md5(user[0].email+'this_is_mixin_string'+req.cookies['connect.id']),
maxAge: 60 * 1000 * 60 * 24 * 30
httpOnly: true
res
.status 200
.send
status:1
info:'登录成功'
data:
name:user[0].userName
else
res
.status 200
.send
status:0
info:'帐号或密码错误'
return
return
return
# 登出模块
router.get '/logout', (req, res, next) ->
res.clearCookie 'name'
res.clearCookie 'name_sig'
res.clearCookie 'email'
res.redirect req.headers.referer
# 注册模块
router.get '/register', (req, res, next) ->
render.register res,
title: '注册'
return
router.post '/register', (req, res, next) ->
userObj = req.body
userObj.password = <PASSWORD> userObj.password
# 存入数据,先判断是否存在用户
usermodel.findByEmail userObj.email, (err,user) ->
if err
console.log err
# 判断用户是否存在
if user.length<=0
_user = new usermodel
userName : userObj.name
passWord : <PASSWORD>
email : userObj.email
role : userObj.role
admin : false
_user.save (err, user) ->
if err
console.log err
res.send
status:1
info:'注册成功'
return
else
res.send
status:0
info:'邮箱已被注册'
return
module.exports = router
| true | express = require 'express'
path = require 'path'
cookieParser = require 'cookie-parser'
session = require 'express-session'
rule = require '../tools/rule'
querystring = require 'querystring'
_ = require 'underscore'
usermodel = require '../models/users'
render = require '../tools/render'
router = express.Router()
# GET users listing.
router.get '/', (req, res, next) ->
res.send '登陆模块'
return
# 登陆模块
router.get '/login', (req, res, next) ->
if req.loginInfo isnt false
res.redirect req.headers.referer or '/../'
else
if req.headers.referer.indexOf('register') isnt -1
render.login res,
title : '登陆'
reUrl : '/../'
else
render.login res,
title : '登陆'
reUrl : req.headers.referer
return
return
#console.log('login')
router.post '/login', (req, res, next) ->
# 查询用户名并验证密码
usermodel.findByEmail req.body.email,(err,user)->
if err
console.log err
#console.log(user);
if user.length<=0
res
.status 200
.send
status:0
info:'帐号或密码错误'
else
if rule.md5(req.body.password) is user[0].passWord
# 设置登陆的cookie
res.cookie 'name',
user[0].userName ,
maxAge: 60 * 1000 * 60 * 24 * 30
res.cookie 'email',
user[0].email ,
maxAge: 60 * 1000 * 60 * 24 * 30
httpOnly: true
res.cookie 'name_sig',
rule.md5(user[0].email+'this_is_mixin_string'+req.cookies['connect.id']),
maxAge: 60 * 1000 * 60 * 24 * 30
httpOnly: true
res
.status 200
.send
status:1
info:'登录成功'
data:
name:user[0].userName
else
res
.status 200
.send
status:0
info:'帐号或密码错误'
return
return
return
# 登出模块
router.get '/logout', (req, res, next) ->
res.clearCookie 'name'
res.clearCookie 'name_sig'
res.clearCookie 'email'
res.redirect req.headers.referer
# 注册模块
router.get '/register', (req, res, next) ->
render.register res,
title: '注册'
return
router.post '/register', (req, res, next) ->
userObj = req.body
userObj.password = PI:PASSWORD:<PASSWORD>END_PI userObj.password
# 存入数据,先判断是否存在用户
usermodel.findByEmail userObj.email, (err,user) ->
if err
console.log err
# 判断用户是否存在
if user.length<=0
_user = new usermodel
userName : userObj.name
passWord : PI:PASSWORD:<PASSWORD>END_PI
email : userObj.email
role : userObj.role
admin : false
_user.save (err, user) ->
if err
console.log err
res.send
status:1
info:'注册成功'
return
else
res.send
status:0
info:'邮箱已被注册'
return
module.exports = router
|
[
{
"context": "qunit/helpers\n\noccasionsThatDoNotAffectMincha = [\"HataratNedarim\", \"10DaysOfTeshuba\", \"ErubTabshilin\", \"Regel\", \"S",
"end": 99,
"score": 0.9328979849815369,
"start": 85,
"tag": "NAME",
"value": "HataratNedarim"
},
{
"context": "ctMincha = [\"HataratNedarim\",... | source/javascripts/qunit/index/minchaTest.js.coffee | betesh/nahar-shalom-schedule | 0 | #= require index/mincha
#= require qunit/helpers
occasionsThatDoNotAffectMincha = ["HataratNedarim", "10DaysOfTeshuba", "ErubTabshilin", "Regel", "ShabbatHaGadol", "Moed", "MaharHodesh", "ShabbatMevarechim"]
assertTimeEqual = QunitHelpers.assertTimeEqual
minchaTest = (gregorianDate, hours, minutes, sunsetHour = 19) ->
hebrewDate = new HebrewDate(gregorianDate)
plag = moment(gregorianDate).hour(sunsetHour - 1).minute(17).seconds(16)
sunset = moment(gregorianDate).hour(sunsetHour).minute(21).seconds(23)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectMincha.indexOf(e))).join(" / ")
QUnit.test "When plag is at #{plag.format("hh:mm:ss A")} and sunset is at #{sunset.format("hh:mm:ss A")} on #{events}", (assert) ->
mincha = new Mincha(hebrewDate, plag, sunset)
assertTimeEqual assert, mincha.time(), moment(gregorianDate).hour(hours).minute(minutes).second(0), "Mincha"
nullMinchaTest = (gregorianDate) ->
hebrewDate = new HebrewDate(gregorianDate)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectArbit.indexOf(e))).join(" / ")
events = "a regular weekday" if "" == events
QUnit.test "On #{events}", (assert) ->
mincha = new Mincha(hebrewDate, null, null)
assert.equal mincha.time(), null, "Mincha class does not return a time"
$ ->
# Weekday
nullMinchaTest(new Date(2016,4,5))
# Ereb Shabbat (summer)
minchaTest(new Date(2016,4,6), 18, 30)
# Ereb Shabbat (winter)
minchaTest(new Date(2016,4,6), 16, 48, 17)
# Shabbat
minchaTest(new Date(2016,4,7), 18, 35)
# Ereb Pesach
minchaTest(new Date(2017,3,10), 18, 50)
# Ereb Pesach on Shabbat
minchaTest(new Date(2021,2,27), 18, 55)
# Ereb Pesach on Ereb Shabbat
minchaTest(new Date(2016,3,22), 18, 30)
# 6th Day of Pesach
minchaTest(new Date(2017,3,16), 18, 30)
# 6th Day of Pesach on Ereb Shabbat
minchaTest(new Date(2021,3,2), 18, 30)
# 7th Day of Pesach
minchaTest(new Date(2017,3,17), 17, 45)
# 7th Day of Pesach on Shabbat
minchaTest(new Date(2021,3,3), 18, 55)
# 7th Day of Pesach on Ereb Shabbat
minchaTest(new Date(2016,3,29), 18, 30)
# 8th Day of Pesach
minchaTest(new Date(2017,3,18), 18, 55)
# 8th Day of Pesach on Shabbat
minchaTest(new Date(2016,3,30), 18, 35)
# Ereb Shabuot
minchaTest(new Date(2021,4,16), 18, 55)
# Ereb Shabuot on Shabbat
minchaTest(new Date(2016,5,11), 17, 30)
# 1st Day of Shabuot
minchaTest(new Date(2021,4,17), 17, 45)
# 1st Day of Shabuot on Ereb Shabbat
minchaTest(new Date(2020,4,29), 18, 30)
# 2nd Day of Shabuot
minchaTest(new Date(2021,4,18), 18, 55)
# 2nd Day of Shabuot on Shabbat
minchaTest(new Date(2020,4,30), 18, 35)
# Ereb 9 Ab
minchaTest(new Date(2017,6,31), 18, 25)
# Ereb 9 Ab on Shabbat
minchaTest(new Date(2016,7,13), 17, 40)
# 9 Ab
minchaTest(new Date(2017,7,1), 18, 35)
# 9 Ab postponed
minchaTest(new Date(2016,7,14), 18, 35)
# Ereb Rosh Hashana
minchaTest(new Date(2016,9,2), 18, 35)
# Ereb Rosh Hashana on Ereb Shabbat
minchaTest(new Date(2020,8,18), 18, 25)
# 1st Day of Rosh Hashana
minchaTest(new Date(2016,9,3), 18, 20)
# 1st Day of Rosh Hashana on Shabbat
minchaTest(new Date(2020,8,19), 18, 20)
# 2nd Day of Rosh Hashana
minchaTest(new Date(2016,9,4), 18, 40)
# 2nd Day of Rosh Hashana on Ereb Shabbat
minchaTest(new Date(2014,8,26), 18, 20)
# Ereb Yom Kippur
minchaTest(new Date(2016,9,11), 15, 30)
# Ereb Yom Kippur on Ereb Shabbat
minchaTest(new Date(2017,8,29), 15, 30)
# Yom Kippur
minchaTest(new Date(2016,9,12), 16, 5)
# Yom Kippur on Shabbat
minchaTest(new Date(2017,8,30), 16, 5)
# Ereb Sukkot
minchaTest(new Date(2017,9,4), 18, 55)
# Ereb Sukkot on Ereb Shabbat (summer)
minchaTest(new Date(2020,9,2), 18, 45)
# Ereb Sukkot on Ereb Shabbat (winter)
minchaTest(new Date(2020,9,2), 17, 45, 18)
# 1st Day of Sukkot
minchaTest(new Date(2017,9,5), 18, 55)
# 1st Day of Sukkot on Shabbat
minchaTest(new Date(2020,9,3), 18, 55)
# 2nd Day of Sukkot
minchaTest(new Date(2016,9,18), 18, 55)
# 2nd Day of Sukkot on Ereb Shabbat (summer)
minchaTest(new Date(2014,9,10), 18, 40)
# 2nd Day of Sukkot on Ereb Shabbat (winter)
minchaTest(new Date(2014,9,10), 17, 40, 18)
# Asarah B'Tebet
minchaTest(new Date(2015,0,1), 18, 50)
# Asarah B'Tebet on Ereb Shabbat
minchaTest(new Date(2013,11,13), 18, 35)
# Taanit Ester
minchaTest(new Date(2016,2,23), 18, 45)
| 182706 | #= require index/mincha
#= require qunit/helpers
occasionsThatDoNotAffectMincha = ["<NAME>", "10DaysOfTeshuba", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]
assertTimeEqual = QunitHelpers.assertTimeEqual
minchaTest = (gregorianDate, hours, minutes, sunsetHour = 19) ->
hebrewDate = new HebrewDate(gregorianDate)
plag = moment(gregorianDate).hour(sunsetHour - 1).minute(17).seconds(16)
sunset = moment(gregorianDate).hour(sunsetHour).minute(21).seconds(23)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectMincha.indexOf(e))).join(" / ")
QUnit.test "When plag is at #{plag.format("hh:mm:ss A")} and sunset is at #{sunset.format("hh:mm:ss A")} on #{events}", (assert) ->
mincha = new Mincha(hebrewDate, plag, sunset)
assertTimeEqual assert, mincha.time(), moment(gregorianDate).hour(hours).minute(minutes).second(0), "Mincha"
nullMinchaTest = (gregorianDate) ->
hebrewDate = new HebrewDate(gregorianDate)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectArbit.indexOf(e))).join(" / ")
events = "a regular weekday" if "" == events
QUnit.test "On #{events}", (assert) ->
mincha = new Mincha(hebrewDate, null, null)
assert.equal mincha.time(), null, "Mincha class does not return a time"
$ ->
# Weekday
nullMinchaTest(new Date(2016,4,5))
# Ereb Shabbat (summer)
minchaTest(new Date(2016,4,6), 18, 30)
# Ereb Shabbat (winter)
minchaTest(new Date(2016,4,6), 16, 48, 17)
# Shabbat
minchaTest(new Date(2016,4,7), 18, 35)
# Ereb Pesach
minchaTest(new Date(2017,3,10), 18, 50)
# Ereb Pesach on Shabbat
minchaTest(new Date(2021,2,27), 18, 55)
# Ereb Pesach on Ereb Shabbat
minchaTest(new Date(2016,3,22), 18, 30)
# 6th Day of Pesach
minchaTest(new Date(2017,3,16), 18, 30)
# 6th Day of Pesach on Ereb Shabbat
minchaTest(new Date(2021,3,2), 18, 30)
# 7th Day of Pesach
minchaTest(new Date(2017,3,17), 17, 45)
# 7th Day of Pesach on Shabbat
minchaTest(new Date(2021,3,3), 18, 55)
# 7th Day of Pesach on Ereb Shabbat
minchaTest(new Date(2016,3,29), 18, 30)
# 8th Day of Pesach
minchaTest(new Date(2017,3,18), 18, 55)
# 8th Day of Pesach on Shabbat
minchaTest(new Date(2016,3,30), 18, 35)
# Ereb Shabuot
minchaTest(new Date(2021,4,16), 18, 55)
# Ereb Shabuot on Shabbat
minchaTest(new Date(2016,5,11), 17, 30)
# 1st Day of Shabuot
minchaTest(new Date(2021,4,17), 17, 45)
# 1st Day of Shabuot on Ereb Shabbat
minchaTest(new Date(2020,4,29), 18, 30)
# 2nd Day of Shabuot
minchaTest(new Date(2021,4,18), 18, 55)
# 2nd Day of Shabuot on Shabbat
minchaTest(new Date(2020,4,30), 18, 35)
# Ereb 9 Ab
minchaTest(new Date(2017,6,31), 18, 25)
# Ereb 9 Ab on Shabbat
minchaTest(new Date(2016,7,13), 17, 40)
# 9 Ab
minchaTest(new Date(2017,7,1), 18, 35)
# 9 Ab postponed
minchaTest(new Date(2016,7,14), 18, 35)
# <NAME> <NAME>
minchaTest(new Date(2016,9,2), 18, 35)
# Ereb <NAME> on Ereb Shabbat
minchaTest(new Date(2020,8,18), 18, 25)
# 1st Day of <NAME>
minchaTest(new Date(2016,9,3), 18, 20)
# 1st Day of <NAME> on Shabbat
minchaTest(new Date(2020,8,19), 18, 20)
# 2nd Day of <NAME>
minchaTest(new Date(2016,9,4), 18, 40)
# 2nd Day of <NAME> on Ereb Shabbat
minchaTest(new Date(2014,8,26), 18, 20)
# Ereb Y<NAME>
minchaTest(new Date(2016,9,11), 15, 30)
# Ereb Y<NAME> on Ereb Shabbat
minchaTest(new Date(2017,8,29), 15, 30)
# <NAME>
minchaTest(new Date(2016,9,12), 16, 5)
# Yom K<NAME>ur on Shabbat
minchaTest(new Date(2017,8,30), 16, 5)
# Ereb Sukkot
minchaTest(new Date(2017,9,4), 18, 55)
# Ereb S<NAME>kot on Ereb Shabbat (summer)
minchaTest(new Date(2020,9,2), 18, 45)
# Ereb Sukkot on Ereb Shabbat (winter)
minchaTest(new Date(2020,9,2), 17, 45, 18)
# 1st Day of Sukkot
minchaTest(new Date(2017,9,5), 18, 55)
# 1st Day of Sukkot on Shabbat
minchaTest(new Date(2020,9,3), 18, 55)
# 2nd Day of Sukkot
minchaTest(new Date(2016,9,18), 18, 55)
# 2nd Day of Sukkot on Ereb Shabbat (summer)
minchaTest(new Date(2014,9,10), 18, 40)
# 2nd Day of Sukkot on Ereb Shabbat (winter)
minchaTest(new Date(2014,9,10), 17, 40, 18)
# <NAME>
minchaTest(new Date(2015,0,1), 18, 50)
# <NAME> on Ereb Shabbat
minchaTest(new Date(2013,11,13), 18, 35)
# <NAME>
minchaTest(new Date(2016,2,23), 18, 45)
| true | #= require index/mincha
#= require qunit/helpers
occasionsThatDoNotAffectMincha = ["PI:NAME:<NAME>END_PI", "10DaysOfTeshuba", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
assertTimeEqual = QunitHelpers.assertTimeEqual
minchaTest = (gregorianDate, hours, minutes, sunsetHour = 19) ->
hebrewDate = new HebrewDate(gregorianDate)
plag = moment(gregorianDate).hour(sunsetHour - 1).minute(17).seconds(16)
sunset = moment(gregorianDate).hour(sunsetHour).minute(21).seconds(23)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectMincha.indexOf(e))).join(" / ")
QUnit.test "When plag is at #{plag.format("hh:mm:ss A")} and sunset is at #{sunset.format("hh:mm:ss A")} on #{events}", (assert) ->
mincha = new Mincha(hebrewDate, plag, sunset)
assertTimeEqual assert, mincha.time(), moment(gregorianDate).hour(hours).minute(minutes).second(0), "Mincha"
nullMinchaTest = (gregorianDate) ->
hebrewDate = new HebrewDate(gregorianDate)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectArbit.indexOf(e))).join(" / ")
events = "a regular weekday" if "" == events
QUnit.test "On #{events}", (assert) ->
mincha = new Mincha(hebrewDate, null, null)
assert.equal mincha.time(), null, "Mincha class does not return a time"
$ ->
# Weekday
nullMinchaTest(new Date(2016,4,5))
# Ereb Shabbat (summer)
minchaTest(new Date(2016,4,6), 18, 30)
# Ereb Shabbat (winter)
minchaTest(new Date(2016,4,6), 16, 48, 17)
# Shabbat
minchaTest(new Date(2016,4,7), 18, 35)
# Ereb Pesach
minchaTest(new Date(2017,3,10), 18, 50)
# Ereb Pesach on Shabbat
minchaTest(new Date(2021,2,27), 18, 55)
# Ereb Pesach on Ereb Shabbat
minchaTest(new Date(2016,3,22), 18, 30)
# 6th Day of Pesach
minchaTest(new Date(2017,3,16), 18, 30)
# 6th Day of Pesach on Ereb Shabbat
minchaTest(new Date(2021,3,2), 18, 30)
# 7th Day of Pesach
minchaTest(new Date(2017,3,17), 17, 45)
# 7th Day of Pesach on Shabbat
minchaTest(new Date(2021,3,3), 18, 55)
# 7th Day of Pesach on Ereb Shabbat
minchaTest(new Date(2016,3,29), 18, 30)
# 8th Day of Pesach
minchaTest(new Date(2017,3,18), 18, 55)
# 8th Day of Pesach on Shabbat
minchaTest(new Date(2016,3,30), 18, 35)
# Ereb Shabuot
minchaTest(new Date(2021,4,16), 18, 55)
# Ereb Shabuot on Shabbat
minchaTest(new Date(2016,5,11), 17, 30)
# 1st Day of Shabuot
minchaTest(new Date(2021,4,17), 17, 45)
# 1st Day of Shabuot on Ereb Shabbat
minchaTest(new Date(2020,4,29), 18, 30)
# 2nd Day of Shabuot
minchaTest(new Date(2021,4,18), 18, 55)
# 2nd Day of Shabuot on Shabbat
minchaTest(new Date(2020,4,30), 18, 35)
# Ereb 9 Ab
minchaTest(new Date(2017,6,31), 18, 25)
# Ereb 9 Ab on Shabbat
minchaTest(new Date(2016,7,13), 17, 40)
# 9 Ab
minchaTest(new Date(2017,7,1), 18, 35)
# 9 Ab postponed
minchaTest(new Date(2016,7,14), 18, 35)
# PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
minchaTest(new Date(2016,9,2), 18, 35)
# Ereb PI:NAME:<NAME>END_PI on Ereb Shabbat
minchaTest(new Date(2020,8,18), 18, 25)
# 1st Day of PI:NAME:<NAME>END_PI
minchaTest(new Date(2016,9,3), 18, 20)
# 1st Day of PI:NAME:<NAME>END_PI on Shabbat
minchaTest(new Date(2020,8,19), 18, 20)
# 2nd Day of PI:NAME:<NAME>END_PI
minchaTest(new Date(2016,9,4), 18, 40)
# 2nd Day of PI:NAME:<NAME>END_PI on Ereb Shabbat
minchaTest(new Date(2014,8,26), 18, 20)
# Ereb YPI:NAME:<NAME>END_PI
minchaTest(new Date(2016,9,11), 15, 30)
# Ereb YPI:NAME:<NAME>END_PI on Ereb Shabbat
minchaTest(new Date(2017,8,29), 15, 30)
# PI:NAME:<NAME>END_PI
minchaTest(new Date(2016,9,12), 16, 5)
# Yom KPI:NAME:<NAME>END_PIur on Shabbat
minchaTest(new Date(2017,8,30), 16, 5)
# Ereb Sukkot
minchaTest(new Date(2017,9,4), 18, 55)
# Ereb SPI:NAME:<NAME>END_PIkot on Ereb Shabbat (summer)
minchaTest(new Date(2020,9,2), 18, 45)
# Ereb Sukkot on Ereb Shabbat (winter)
minchaTest(new Date(2020,9,2), 17, 45, 18)
# 1st Day of Sukkot
minchaTest(new Date(2017,9,5), 18, 55)
# 1st Day of Sukkot on Shabbat
minchaTest(new Date(2020,9,3), 18, 55)
# 2nd Day of Sukkot
minchaTest(new Date(2016,9,18), 18, 55)
# 2nd Day of Sukkot on Ereb Shabbat (summer)
minchaTest(new Date(2014,9,10), 18, 40)
# 2nd Day of Sukkot on Ereb Shabbat (winter)
minchaTest(new Date(2014,9,10), 17, 40, 18)
# PI:NAME:<NAME>END_PI
minchaTest(new Date(2015,0,1), 18, 50)
# PI:NAME:<NAME>END_PI on Ereb Shabbat
minchaTest(new Date(2013,11,13), 18, 35)
# PI:NAME:<NAME>END_PI
minchaTest(new Date(2016,2,23), 18, 45)
|
[
{
"context": " 'test-get': (done) ->\n Request 'http://127.0.0.1:1338/mobify.js', (err, response) ->\n #",
"end": 983,
"score": 0.7542688250541687,
"start": 975,
"tag": "IP_ADDRESS",
"value": "27.0.0.1"
},
{
"context": "e()\n\n 'test-save': (done) ->\n b... | test/preview.coffee | mobify/mobify-client | 4 | ###
Tests for src/preview.coffee
###
FS = require 'fs'
HTTP = require 'http'
Assert = require 'assert'
Request = require 'request'
Connect = require 'connect'
{Project} = require '../src/project.coffee'
{Environment} = require '../src/build.coffee'
Preview = require '../src/preview.coffee'
Scaffold = require '../src/scaffold.coffee'
STATIC_PORT = 1337
PREVIEW_PORT = 1338
module.exports =
'before': (done) ->
# Static Server
@static = new Connect()
.use(Connect.static "#{__dirname}/fixtures")
@static.listen STATIC_PORT
generated = () ->
# Preview Server
project = Project.load 'test/fixtures-preview/project.json'
environment = project.getEnv()
@preview = Preview.createServer environment
@preview.listen PREVIEW_PORT
done()
Scaffold.generate 'test/fixtures-preview', null, generated
'test-get': (done) ->
Request 'http://127.0.0.1:1338/mobify.js', (err, response) ->
# Assert not response.headers['X-Error'], 'Should not be an error.'
Assert not /Mobify\.js\sError/.test(response.body), 'Should not be an error.'
done()
'test-get-404': (done) ->
Request 'http://127.0.0.1:1338/404', (err, response) ->
Assert.equal response.statusCode, 404
done()
'test-save': (done) ->
body = 'Yo Joe!'
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/mobify.konf'
body: body
}, (err, response) ->
Assert.equal response.statusCode, 200
FS.readFile 'test/fixtures-preview/src/mobify.konf', (err, data) ->
Assert.equal data.toString(), body
done()
'test-save-bad-file': (done) ->
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/../naughty'
body: 'Turtle Power!'
}, (err, response, body) ->
Assert.equal response.statusCode, 400
done()
'test-save-from-location': (done) ->
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/mobify.konf'
headers:
location: 'http://127.0.0.1:1337/fixtures/alert.js'
}, (err, response, body) ->
Assert.equal response.statusCode, 200
done()
| 123423 | ###
Tests for src/preview.coffee
###
FS = require 'fs'
HTTP = require 'http'
Assert = require 'assert'
Request = require 'request'
Connect = require 'connect'
{Project} = require '../src/project.coffee'
{Environment} = require '../src/build.coffee'
Preview = require '../src/preview.coffee'
Scaffold = require '../src/scaffold.coffee'
STATIC_PORT = 1337
PREVIEW_PORT = 1338
module.exports =
'before': (done) ->
# Static Server
@static = new Connect()
.use(Connect.static "#{__dirname}/fixtures")
@static.listen STATIC_PORT
generated = () ->
# Preview Server
project = Project.load 'test/fixtures-preview/project.json'
environment = project.getEnv()
@preview = Preview.createServer environment
@preview.listen PREVIEW_PORT
done()
Scaffold.generate 'test/fixtures-preview', null, generated
'test-get': (done) ->
Request 'http://1172.16.31.10:1338/mobify.js', (err, response) ->
# Assert not response.headers['X-Error'], 'Should not be an error.'
Assert not /Mobify\.js\sError/.test(response.body), 'Should not be an error.'
done()
'test-get-404': (done) ->
Request 'http://127.0.0.1:1338/404', (err, response) ->
Assert.equal response.statusCode, 404
done()
'test-save': (done) ->
body = 'Yo <NAME>!'
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/mobify.konf'
body: body
}, (err, response) ->
Assert.equal response.statusCode, 200
FS.readFile 'test/fixtures-preview/src/mobify.konf', (err, data) ->
Assert.equal data.toString(), body
done()
'test-save-bad-file': (done) ->
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/../naughty'
body: 'Turtle Power!'
}, (err, response, body) ->
Assert.equal response.statusCode, 400
done()
'test-save-from-location': (done) ->
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/mobify.konf'
headers:
location: 'http://127.0.0.1:1337/fixtures/alert.js'
}, (err, response, body) ->
Assert.equal response.statusCode, 200
done()
| true | ###
Tests for src/preview.coffee
###
FS = require 'fs'
HTTP = require 'http'
Assert = require 'assert'
Request = require 'request'
Connect = require 'connect'
{Project} = require '../src/project.coffee'
{Environment} = require '../src/build.coffee'
Preview = require '../src/preview.coffee'
Scaffold = require '../src/scaffold.coffee'
STATIC_PORT = 1337
PREVIEW_PORT = 1338
module.exports =
'before': (done) ->
# Static Server
@static = new Connect()
.use(Connect.static "#{__dirname}/fixtures")
@static.listen STATIC_PORT
generated = () ->
# Preview Server
project = Project.load 'test/fixtures-preview/project.json'
environment = project.getEnv()
@preview = Preview.createServer environment
@preview.listen PREVIEW_PORT
done()
Scaffold.generate 'test/fixtures-preview', null, generated
'test-get': (done) ->
Request 'http://1PI:IP_ADDRESS:172.16.31.10END_PI:1338/mobify.js', (err, response) ->
# Assert not response.headers['X-Error'], 'Should not be an error.'
Assert not /Mobify\.js\sError/.test(response.body), 'Should not be an error.'
done()
'test-get-404': (done) ->
Request 'http://127.0.0.1:1338/404', (err, response) ->
Assert.equal response.statusCode, 404
done()
'test-save': (done) ->
body = 'Yo PI:NAME:<NAME>END_PI!'
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/mobify.konf'
body: body
}, (err, response) ->
Assert.equal response.statusCode, 200
FS.readFile 'test/fixtures-preview/src/mobify.konf', (err, data) ->
Assert.equal data.toString(), body
done()
'test-save-bad-file': (done) ->
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/../naughty'
body: 'Turtle Power!'
}, (err, response, body) ->
Assert.equal response.statusCode, 400
done()
'test-save-from-location': (done) ->
Request {
method: 'PUT'
uri: 'http://127.0.0.1:1338/mobify.konf'
headers:
location: 'http://127.0.0.1:1337/fixtures/alert.js'
}, (err, response, body) ->
Assert.equal response.statusCode, 200
done()
|
[
{
"context": "'\nvalidator = require '../dist/main'\n\nvalidKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJr5NXKYoyFryOzCZ8tTknPV7dtAGJWJ3PmvUvRdY+4ECgWqwHpTbGD5BthPZQA\nfh51twyejF+F6JdbZAGeDFsmlST1AJICIcC3UoHM9A9sB3gJ+xmO7nYSFBmy4tDTdbhP1rzsqpoLIFy2D1rLG5T4qoV5RrFmLkS59\n5cZjWQTlv1SFThNKY8ELxQm7k7pkbYhDqXK6LF+... | test/validate-test.coffee | balena-io-modules/validateSSHjs | 1 | assert = require 'assert'
validator = require '../dist/main'
validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJr5NXKYoyFryOzCZ8tTknPV7dtAGJWJ3PmvUvRdY+4ECgWqwHpTbGD5BthPZQA
fh51twyejF+F6JdbZAGeDFsmlST1AJICIcC3UoHM9A9sB3gJ+xmO7nYSFBmy4tDTdbhP1rzsqpoLIFy2D1rLG5T4qoV5RrFmLkS59
5cZjWQTlv1SFThNKY8ELxQm7k7pkbYhDqXK6LF+6tHkkTO0nL/zR9uY6dWU1EabvSRcMS66RTYX2r2Zaiy5NGMTF3RI+HbN45drvS
TysxTohpCKDPnmVbjCI0BhLNHqleUAPtqgfU2Ld+lU1Z5ZSFoq1PIPJB52nEmyEhqdXnLm2gi0LjH'
describe 'validate function', ->
it 'Should correctly validate generated keys', ->
assert.equal(validator.validate(validKey), true)
| 196337 | assert = require 'assert'
validator = require '../dist/main'
validKey = '<KEY>'
describe 'validate function', ->
it 'Should correctly validate generated keys', ->
assert.equal(validator.validate(validKey), true)
| true | assert = require 'assert'
validator = require '../dist/main'
validKey = 'PI:KEY:<KEY>END_PI'
describe 'validate function', ->
it 'Should correctly validate generated keys', ->
assert.equal(validator.validate(validKey), true)
|
[
{
"context": "m-element manipulation\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\nElement.include\n\n #\n # Clones the element wit",
"end": 96,
"score": 0.9998887777328491,
"start": 79,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/dom/src/element/manipulation.coffee | lovely-io/lovely.io-stl | 2 | #
# This file handles the dom-element manipulation
#
# Copyright (C) 2011-2013 Nikolay Nemshilov
#
Element.include
#
# Clones the element with all it's content
#
# @return {Element} a clone
#
clone: ->
new Element(@_.cloneNode(true))
#
# Removes all the child nodes out of the element
#
# @return {Element} this
#
clear: ->
while @_.firstChild
@_.removeChild(@_.firstChild)
return @
#
# Checks if the element doesn't have any actual content in it
#
# @return {Boolean} check result
#
empty: ->
/^\s*$/.test(@html())
#
# Sets of gets the html content of the element as a string
#
# @param {String} html content if setting
# @return {String|Element} this element or html content
#
html: (content)->
if content is undefined then @_.innerHTML else @update(content)
#
# Sets of gets the element's content as a plain text
#
# @param {String} textual content if setting
# @return {String|Element} this element or textual content
#
text: (text) ->
if text is undefined then @_.textContent
else @update(document.createTextNode(text))
#
# Removes the element out of the dom-tree
#
# @return {Element}
#
remove: ->
@_.parentNode && @_.parentNode.removeChild(@_)
return @
#
# Replaces the element with coven content
#
# @param {String|Element|Iterable} content
# @return {Element} this
#
replace: (content)->
@insert(content, 'instead')
#
# Replaces the element content
#
# @param {String|Element|Iterable} content
# @return {Element} this
#
update: (content) ->
if typeof(content) isnt 'object'
[content, scripts] = extract_scripts(''+ content)
try
@_.innerHTML = content
catch e # IE crashes here on some elements
return @clear().insert(content)
global_eval(scripts)
else @clear().insert(content)
return @
#
# Inserts the given content into the given position
#
# @param {String|Element|Iterable} content
# @param {String} optional position 'bottom'/'top'/'before'/'after'/'instead'
# @return {Element} this
#
insert: (content, position) ->
element = @_
position = 'bottom' if position is undefined
if typeof(content) isnt 'object'
[content, scripts] = extract_scripts(''+content)
content = content._ if `content._ != null`
content = Element_create_fragment(
(if position in ['bottom', 'top'] then element
else element.parentNode), content
) if content.nodeType is undefined
Element_insert[position](element, content)
global_eval(scripts) if scripts isnt null
return @
#
# Inserts this element into the given one at given position
#
# @param {Element|HTMLElement|String} destination or '#element-id' string
# @param {String} optional position
# @return {Element} this
#
insertTo: (element, position) ->
Element.resolve(element).insert(@, position)
return @
#
# Appends the argument elements to this element
#
# @param {String|Element} content
# ....
# @return {Element} this
#
append: (first) ->
@insert if typeof(first) is "string" then A(arguments).join('') else arguments
# private
# various element insertion handlers
Element_insert =
bottom: (target, content)->
target.appendChild(content)
top: (target, content)->
if target.firstChild is null
target.appendChild(content)
else
target.insertBefore(content, target.firstChild)
after: (target, content)->
if target.nextSibling is null
target.parentNode.appendChild(content)
else
target.parentNode.insertBefore(content, target.nextSibling)
before: (target, content)->
target.parentNode.insertBefore(content, target)
instead: (target, content)->
target.parentNode.replaceChild(content, target)
# makes a document fragment object out of given content
Element_create_fragment = (context, content)->
if typeof(content) is 'string'
tag = context.tagName
tmp = Element_tmp_cont
block = if tag of Element_wraps then Element_wraps[tag] else ['', '', 1]
depth = block[2]
tmp.innerHTML = block[0] + '<'+ tag + '>' + content + '</'+ tag + '>' + block[1]
while depth-- isnt 0
tmp = tmp.firstChild
content = tmp.childNodes
while content.length isnt 0
Element_fragment.appendChild(content[0])
else # converting iterables into a framgent
`for (var i=0, length = content.length, node; i < length; i++) {
node = content[content.length === length ? i : 0];
Element_fragment.appendChild(node._ || node);
}`
return Element_fragment
# caching the fragment and temporary context objects
Element_fragment = document.createDocumentFragment()
Element_tmp_cont = document.createElement('div')
# Various trouble elements wrapping blocks
Element_wraps =
TBODY: ['<TABLE>', '</TABLE>', 2]
TR: ['<TABLE><TBODY>', '</TBODY></TABLE>', 3]
TD: ['<TABLE><TBODY><TR>', '</TR></TBODY></TABLE>', 4]
COL: ['<TABLE><COLGROUP>', '</COLGROUP><TBODY></TBODY></TABLE>', 2]
LEGEND: ['<FIELDSET>', '</FIELDSET>', 2]
AREA: ['<map>', '</map>', 2]
OPTION: ['<SELECT>', '</SELECT>', 2]
Element_wraps.OPTGROUP = Element_wraps.OPTION
Element_wraps.THEAD = Element_wraps.TBODY
Element_wraps.TFOOT = Element_wraps.TBODY
Element_wraps.TH = Element_wraps.TD | 30004 | #
# This file handles the dom-element manipulation
#
# Copyright (C) 2011-2013 <NAME>
#
Element.include
#
# Clones the element with all it's content
#
# @return {Element} a clone
#
clone: ->
new Element(@_.cloneNode(true))
#
# Removes all the child nodes out of the element
#
# @return {Element} this
#
clear: ->
while @_.firstChild
@_.removeChild(@_.firstChild)
return @
#
# Checks if the element doesn't have any actual content in it
#
# @return {Boolean} check result
#
empty: ->
/^\s*$/.test(@html())
#
# Sets of gets the html content of the element as a string
#
# @param {String} html content if setting
# @return {String|Element} this element or html content
#
html: (content)->
if content is undefined then @_.innerHTML else @update(content)
#
# Sets of gets the element's content as a plain text
#
# @param {String} textual content if setting
# @return {String|Element} this element or textual content
#
text: (text) ->
if text is undefined then @_.textContent
else @update(document.createTextNode(text))
#
# Removes the element out of the dom-tree
#
# @return {Element}
#
remove: ->
@_.parentNode && @_.parentNode.removeChild(@_)
return @
#
# Replaces the element with coven content
#
# @param {String|Element|Iterable} content
# @return {Element} this
#
replace: (content)->
@insert(content, 'instead')
#
# Replaces the element content
#
# @param {String|Element|Iterable} content
# @return {Element} this
#
update: (content) ->
if typeof(content) isnt 'object'
[content, scripts] = extract_scripts(''+ content)
try
@_.innerHTML = content
catch e # IE crashes here on some elements
return @clear().insert(content)
global_eval(scripts)
else @clear().insert(content)
return @
#
# Inserts the given content into the given position
#
# @param {String|Element|Iterable} content
# @param {String} optional position 'bottom'/'top'/'before'/'after'/'instead'
# @return {Element} this
#
insert: (content, position) ->
element = @_
position = 'bottom' if position is undefined
if typeof(content) isnt 'object'
[content, scripts] = extract_scripts(''+content)
content = content._ if `content._ != null`
content = Element_create_fragment(
(if position in ['bottom', 'top'] then element
else element.parentNode), content
) if content.nodeType is undefined
Element_insert[position](element, content)
global_eval(scripts) if scripts isnt null
return @
#
# Inserts this element into the given one at given position
#
# @param {Element|HTMLElement|String} destination or '#element-id' string
# @param {String} optional position
# @return {Element} this
#
insertTo: (element, position) ->
Element.resolve(element).insert(@, position)
return @
#
# Appends the argument elements to this element
#
# @param {String|Element} content
# ....
# @return {Element} this
#
append: (first) ->
@insert if typeof(first) is "string" then A(arguments).join('') else arguments
# private
# various element insertion handlers
Element_insert =
bottom: (target, content)->
target.appendChild(content)
top: (target, content)->
if target.firstChild is null
target.appendChild(content)
else
target.insertBefore(content, target.firstChild)
after: (target, content)->
if target.nextSibling is null
target.parentNode.appendChild(content)
else
target.parentNode.insertBefore(content, target.nextSibling)
before: (target, content)->
target.parentNode.insertBefore(content, target)
instead: (target, content)->
target.parentNode.replaceChild(content, target)
# makes a document fragment object out of given content
Element_create_fragment = (context, content)->
if typeof(content) is 'string'
tag = context.tagName
tmp = Element_tmp_cont
block = if tag of Element_wraps then Element_wraps[tag] else ['', '', 1]
depth = block[2]
tmp.innerHTML = block[0] + '<'+ tag + '>' + content + '</'+ tag + '>' + block[1]
while depth-- isnt 0
tmp = tmp.firstChild
content = tmp.childNodes
while content.length isnt 0
Element_fragment.appendChild(content[0])
else # converting iterables into a framgent
`for (var i=0, length = content.length, node; i < length; i++) {
node = content[content.length === length ? i : 0];
Element_fragment.appendChild(node._ || node);
}`
return Element_fragment
# caching the fragment and temporary context objects
Element_fragment = document.createDocumentFragment()
Element_tmp_cont = document.createElement('div')
# Various trouble elements wrapping blocks
Element_wraps =
TBODY: ['<TABLE>', '</TABLE>', 2]
TR: ['<TABLE><TBODY>', '</TBODY></TABLE>', 3]
TD: ['<TABLE><TBODY><TR>', '</TR></TBODY></TABLE>', 4]
COL: ['<TABLE><COLGROUP>', '</COLGROUP><TBODY></TBODY></TABLE>', 2]
LEGEND: ['<FIELDSET>', '</FIELDSET>', 2]
AREA: ['<map>', '</map>', 2]
OPTION: ['<SELECT>', '</SELECT>', 2]
Element_wraps.OPTGROUP = Element_wraps.OPTION
Element_wraps.THEAD = Element_wraps.TBODY
Element_wraps.TFOOT = Element_wraps.TBODY
Element_wraps.TH = Element_wraps.TD | true | #
# This file handles the dom-element manipulation
#
# Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI
#
Element.include
#
# Clones the element with all it's content
#
# @return {Element} a clone
#
clone: ->
new Element(@_.cloneNode(true))
#
# Removes all the child nodes out of the element
#
# @return {Element} this
#
clear: ->
while @_.firstChild
@_.removeChild(@_.firstChild)
return @
#
# Checks if the element doesn't have any actual content in it
#
# @return {Boolean} check result
#
empty: ->
/^\s*$/.test(@html())
#
# Sets of gets the html content of the element as a string
#
# @param {String} html content if setting
# @return {String|Element} this element or html content
#
html: (content)->
if content is undefined then @_.innerHTML else @update(content)
#
# Sets of gets the element's content as a plain text
#
# @param {String} textual content if setting
# @return {String|Element} this element or textual content
#
text: (text) ->
if text is undefined then @_.textContent
else @update(document.createTextNode(text))
#
# Removes the element out of the dom-tree
#
# @return {Element}
#
remove: ->
@_.parentNode && @_.parentNode.removeChild(@_)
return @
#
# Replaces the element with coven content
#
# @param {String|Element|Iterable} content
# @return {Element} this
#
replace: (content)->
@insert(content, 'instead')
#
# Replaces the element content
#
# @param {String|Element|Iterable} content
# @return {Element} this
#
update: (content) ->
if typeof(content) isnt 'object'
[content, scripts] = extract_scripts(''+ content)
try
@_.innerHTML = content
catch e # IE crashes here on some elements
return @clear().insert(content)
global_eval(scripts)
else @clear().insert(content)
return @
#
# Inserts the given content into the given position
#
# @param {String|Element|Iterable} content
# @param {String} optional position 'bottom'/'top'/'before'/'after'/'instead'
# @return {Element} this
#
insert: (content, position) ->
element = @_
position = 'bottom' if position is undefined
if typeof(content) isnt 'object'
[content, scripts] = extract_scripts(''+content)
content = content._ if `content._ != null`
content = Element_create_fragment(
(if position in ['bottom', 'top'] then element
else element.parentNode), content
) if content.nodeType is undefined
Element_insert[position](element, content)
global_eval(scripts) if scripts isnt null
return @
#
# Inserts this element into the given one at given position
#
# @param {Element|HTMLElement|String} destination or '#element-id' string
# @param {String} optional position
# @return {Element} this
#
insertTo: (element, position) ->
Element.resolve(element).insert(@, position)
return @
#
# Appends the argument elements to this element
#
# @param {String|Element} content
# ....
# @return {Element} this
#
append: (first) ->
@insert if typeof(first) is "string" then A(arguments).join('') else arguments
# private
# various element insertion handlers
Element_insert =
bottom: (target, content)->
target.appendChild(content)
top: (target, content)->
if target.firstChild is null
target.appendChild(content)
else
target.insertBefore(content, target.firstChild)
after: (target, content)->
if target.nextSibling is null
target.parentNode.appendChild(content)
else
target.parentNode.insertBefore(content, target.nextSibling)
before: (target, content)->
target.parentNode.insertBefore(content, target)
instead: (target, content)->
target.parentNode.replaceChild(content, target)
# makes a document fragment object out of given content
Element_create_fragment = (context, content)->
if typeof(content) is 'string'
tag = context.tagName
tmp = Element_tmp_cont
block = if tag of Element_wraps then Element_wraps[tag] else ['', '', 1]
depth = block[2]
tmp.innerHTML = block[0] + '<'+ tag + '>' + content + '</'+ tag + '>' + block[1]
while depth-- isnt 0
tmp = tmp.firstChild
content = tmp.childNodes
while content.length isnt 0
Element_fragment.appendChild(content[0])
else # converting iterables into a framgent
`for (var i=0, length = content.length, node; i < length; i++) {
node = content[content.length === length ? i : 0];
Element_fragment.appendChild(node._ || node);
}`
return Element_fragment
# caching the fragment and temporary context objects
Element_fragment = document.createDocumentFragment()
Element_tmp_cont = document.createElement('div')
# Various trouble elements wrapping blocks
Element_wraps =
TBODY: ['<TABLE>', '</TABLE>', 2]
TR: ['<TABLE><TBODY>', '</TBODY></TABLE>', 3]
TD: ['<TABLE><TBODY><TR>', '</TR></TBODY></TABLE>', 4]
COL: ['<TABLE><COLGROUP>', '</COLGROUP><TBODY></TBODY></TABLE>', 2]
LEGEND: ['<FIELDSET>', '</FIELDSET>', 2]
AREA: ['<map>', '</map>', 2]
OPTION: ['<SELECT>', '</SELECT>', 2]
Element_wraps.OPTGROUP = Element_wraps.OPTION
Element_wraps.THEAD = Element_wraps.TBODY
Element_wraps.TFOOT = Element_wraps.TBODY
Element_wraps.TH = Element_wraps.TD |
[
{
"context": "[iOrder](http://neocotic.com/iOrder) \r\n# (c) 2013 Alasdair Mercer \r\n# Freely distributable under the MIT license. ",
"end": 68,
"score": 0.999874472618103,
"start": 53,
"tag": "NAME",
"value": "Alasdair Mercer"
}
] | chrome/src/lib/install.coffee | neocotic/iOrder | 0 | # [iOrder](http://neocotic.com/iOrder)
# (c) 2013 Alasdair Mercer
# Freely distributable under the MIT license.
# For all details and documentation:
# <http://neocotic.com/iOrder>
# Helpers
# -------
# Convenient shorthand the `sendMessage` method in the chrome API which supports the old
# `sendRequest` variation for backwards compatibility.
sendMessage = (args...) ->
base = chrome.extension
(base.sendMessage or base.sendRequest).apply base, args
# Functionality
# -------------
# Wrap the functionality in a message for iOrder's details in order to get the ID in use.
sendMessage type: 'info', (data) ->
# Names of the classes to be added to the targeted elements.
newClasses = ['disabled']
# Names of the classes to be removed from the targeted elements.
oldClasses = ['chrome_install_button']
# Disable all "Install" links on the homepage for iOrder.
for link in document.querySelectorAll "a.#{oldClasses[0]}[href$=#{data.id}]"
link.innerHTML = link.innerHTML.replace 'Install', 'Installed'
link.classList.add cls for cls in newClasses
link.classList.remove cls for cls in oldClasses | 170302 | # [iOrder](http://neocotic.com/iOrder)
# (c) 2013 <NAME>
# Freely distributable under the MIT license.
# For all details and documentation:
# <http://neocotic.com/iOrder>
# Helpers
# -------
# Convenient shorthand the `sendMessage` method in the chrome API which supports the old
# `sendRequest` variation for backwards compatibility.
sendMessage = (args...) ->
base = chrome.extension
(base.sendMessage or base.sendRequest).apply base, args
# Functionality
# -------------
# Wrap the functionality in a message for iOrder's details in order to get the ID in use.
sendMessage type: 'info', (data) ->
# Names of the classes to be added to the targeted elements.
newClasses = ['disabled']
# Names of the classes to be removed from the targeted elements.
oldClasses = ['chrome_install_button']
# Disable all "Install" links on the homepage for iOrder.
for link in document.querySelectorAll "a.#{oldClasses[0]}[href$=#{data.id}]"
link.innerHTML = link.innerHTML.replace 'Install', 'Installed'
link.classList.add cls for cls in newClasses
link.classList.remove cls for cls in oldClasses | true | # [iOrder](http://neocotic.com/iOrder)
# (c) 2013 PI:NAME:<NAME>END_PI
# Freely distributable under the MIT license.
# For all details and documentation:
# <http://neocotic.com/iOrder>
# Helpers
# -------
# Convenient shorthand the `sendMessage` method in the chrome API which supports the old
# `sendRequest` variation for backwards compatibility.
sendMessage = (args...) ->
base = chrome.extension
(base.sendMessage or base.sendRequest).apply base, args
# Functionality
# -------------
# Wrap the functionality in a message for iOrder's details in order to get the ID in use.
sendMessage type: 'info', (data) ->
# Names of the classes to be added to the targeted elements.
newClasses = ['disabled']
# Names of the classes to be removed from the targeted elements.
oldClasses = ['chrome_install_button']
# Disable all "Install" links on the homepage for iOrder.
for link in document.querySelectorAll "a.#{oldClasses[0]}[href$=#{data.id}]"
link.innerHTML = link.innerHTML.replace 'Install', 'Installed'
link.classList.add cls for cls in newClasses
link.classList.remove cls for cls in oldClasses |
[
{
"context": "ORGANIZATION_1 = name : \"McDonald's\"\nORGANIZATION_2 = name : 'Twitter'\nORGANIZATION_3",
"end": 35,
"score": 0.9997755885124207,
"start": 25,
"tag": "NAME",
"value": "McDonald's"
}
] | client/organization/service.coffee | armw4/smart-table-clean-architecture | 0 | ORGANIZATION_1 = name : "McDonald's"
ORGANIZATION_2 = name : 'Twitter'
ORGANIZATION_3 = name : 'Google'
ORGANIZATION_4 = name : 'Github'
ORGANIZATION_5 = name : 'Netflix'
ORGANIZATIONS = [
ORGANIZATION_1,
ORGANIZATION_2,
ORGANIZATION_3,
ORGANIZATION_4,
ORGANIZATION_5
]
angular
.module 'organization', []
.service 'organization', ($q) ->
get: ->
deferred = $q.defer()
deferred.resolve ORGANIZATIONS
deferred.promise
| 129783 | ORGANIZATION_1 = name : "<NAME>"
ORGANIZATION_2 = name : 'Twitter'
ORGANIZATION_3 = name : 'Google'
ORGANIZATION_4 = name : 'Github'
ORGANIZATION_5 = name : 'Netflix'
ORGANIZATIONS = [
ORGANIZATION_1,
ORGANIZATION_2,
ORGANIZATION_3,
ORGANIZATION_4,
ORGANIZATION_5
]
angular
.module 'organization', []
.service 'organization', ($q) ->
get: ->
deferred = $q.defer()
deferred.resolve ORGANIZATIONS
deferred.promise
| true | ORGANIZATION_1 = name : "PI:NAME:<NAME>END_PI"
ORGANIZATION_2 = name : 'Twitter'
ORGANIZATION_3 = name : 'Google'
ORGANIZATION_4 = name : 'Github'
ORGANIZATION_5 = name : 'Netflix'
ORGANIZATIONS = [
ORGANIZATION_1,
ORGANIZATION_2,
ORGANIZATION_3,
ORGANIZATION_4,
ORGANIZATION_5
]
angular
.module 'organization', []
.service 'organization', ($q) ->
get: ->
deferred = $q.defer()
deferred.resolve ORGANIZATIONS
deferred.promise
|
[
{
"context": " unread: \"未読数\"\n heat: \"勢い\"\n name: \"名前\"\n mail: \"メール\"\n message: \"本文\"\n crea",
"end": 1271,
"score": 0.9963585138320923,
"start": 1269,
"tag": "NAME",
"value": "名前"
}
] | src/ui/ThreadList.coffee | readcrx-2/read.crx-2 | 38 | import ContextMenu from "./ContextMenu.coffee"
import TableSearch from "./TableSearch.coffee"
###*
@class ThreadList
@constructor
@param {Element} table
@param {Object} option
@param {Boolean} [option.bookmark=false]
@param {Boolean} [option.title=false]
@param {Boolean} [option.boardTitle=false]
@param {Boolean} [option.res=false]
@param {Boolean} [option.unread=false]
@param {Boolean} [option.heat=false]
@param {Boolean} [option.createdDate=false]
@param {Boolean} [option.viewedDate=false]
@param {Boolean} [option.bookmarkAddRm=false]
@param {Element} [option.searchbox]
###
export default class ThreadList
constructor: (@table, option) ->
###*
@property _flg
@type Object
@private
###
@_flg =
bookmark: false
title: false
boardTitle: false
res: false
writtenRes: false
unread: false
heat: false
name: false
mail: false
message: false
createdDate: false
viewedDate: false
writtenDate: false
bookmarkAddRm: !!option.bookmarkAddRm
searchbox: undefined
keyToLabel =
bookmark: "★"
title: "タイトル"
boardTitle: "板名"
res: "レス数"
writtenRes: "レス番号"
unread: "未読数"
heat: "勢い"
name: "名前"
mail: "メール"
message: "本文"
createdDate: "作成日時"
viewedDate: "閲覧日時"
writtenDate: "書込日時"
$table = @table
$thead = $__("thead")
$table.addLast($thead, $__("tbody"))
$tr = $__("tr")
$thead.addLast($tr)
#項目のツールチップ表示
$table.on("mouseenter", ({target}) ->
if target.tagName is "TD"
await app.defer()
target.title = target.textContent
return
, true)
$table.on("mouseleave", ({target}) ->
if target.tagName is "TD"
target.removeAttr("title")
return
, true)
$cols = $_F()
selector = {}
column = {}
i = 0
for key, val of keyToLabel when key in option.th
i++
className = key.replace(/([A-Z])/g, ($0, $1) -> "_" + $1.toLowerCase())
$th = $__("th").addClass(className)
$th.textContent = val
$th.dataset.key = className
$tr.addLast($th)
@_flg[key] = true
selector[key] = "td:nth-child(#{i})"
column[key] = i
$col = $__("col").addClass(className)
$col.span = 1
$cols.addLast($col)
$table.addFirst($cols)
#ブックマーク更新時処理
app.message.on("bookmark_updated", ({type, bookmark}) =>
return if bookmark.type isnt "thread"
if type is "expired"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
if $tr?
if bookmark.expired
$tr.addClass("expired")
if app.config.isOn("bookmark_show_dat")
$tr.removeClass("hidden")
else
$tr.addClass("hidden")
else
$tr.removeClass("expired")
if type is "errored"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.addClass("errored")
if type is "updated"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.removeClass("errored")
if @_flg.bookmark
if type is "added"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.bookmark).textContent = "★"
else if type is "removed"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.bookmark).textContent = ""
if @_flg.bookmarkAddRm
if type is "added"
url = new app.URL.URL(bookmark.url)
boardUrl = url.toBoard()
try
boardTitle = await app.BoardTitleSolver.ask(boardUrl)
catch
boardTitle = ""
@addItem({
title: bookmark.title
url: bookmark.url
resCount: bookmark.resCount or 0
readState: bookmark.readState or null
createdAt: /\/(\d+)\/$/.exec(url.pathname)[1] * 1000
boardUrl: boardUrl.href
boardTitle
expired: bookmark.expired
isHttps: url.isHttps()
})
else if type is "removed"
$table.$("tr[data-href=\"#{bookmark.url}\"]").remove()
if @_flg.res and type is "res_count"
tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
if tr
td = tr.$(selector.res)
oldResCount = +td.textContent
td.textContent = bookmark.resCount
td.dataset.beforeres = oldResCount
if @_flg.unread
td = tr.$(selector.unread)
oldUnread = +td.textContent
unread = oldUnread + (bookmark.resCount - oldResCount)
td.textContent = unread or ""
if unread > 0
tr.addClass("updated")
else
tr.removeClass("updated")
if @_flg.heat
td = tr.$(selector.heat)
td.textContent = ThreadList._calcHeat(
Date.now()
/\/(\d+)\/$/.exec(bookmark.url)[1] * 1000
bookmark.resCount
)
if @_flg.title and type is "title"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.title).textContent = bookmark.title
return
)
#未読数更新
if @_flg.unread
app.message.on("read_state_updated", ({read_state}) ->
tr = $table.$("tr[data-href=\"#{read_state.url}\"]")
if tr
res = tr.$(selector.res)
if +res.textContent < read_state.received
res.textContent = read_state.received
unread = tr.$(selector.unread)
unreadCount = Math.max(+res.textContent - read_state.read, 0)
unread.textContent = unreadCount or ""
if unreadCount > 0
tr.addClass("updated")
else
tr.removeClass("updated")
return
)
app.message.on("read_state_removed", ({url}) ->
tr = $table.$("tr[data-href=\"#{url}\"]")
if tr
tr.$(selector.unread).textContent = ""
tr.removeClass("updated")
return
)
#リスト内検索
if typeof option.searchbox is "object"
titleIndex = column.title
$searchbox = option.searchbox
$searchbox.on("compositionend", ->
@emit(new Event("input"))
return
)
$searchbox.on("input", ({isComposing}) ->
return if isComposing
if @value isnt ""
TableSearch($table, "search",
query: @value, target_col: titleIndex)
hitCount = $table.dataset.tableSearchHitCount
for dom in @parent().child() when dom.hasClass("hit_count")
dom.textContent = hitCount + "hit"
else
TableSearch($table, "clear")
for dom in @parent().child() when dom.hasClass("hit_count")
dom.textContent = ""
return
)
$searchbox.on("keyup", ({key}) ->
if key is "Escape"
@value = ""
@emit(new Event("input"))
return
)
#コンテキストメニュー
if @_flg.bookmark or @_flg.bookmarkAddRm or @_flg.writtenRes or @_flg.viewedDate
do =>
$table.on("contextmenu", (e) =>
$tr = e.target.closest("tbody > tr")
return unless $tr
e.preventDefault()
await app.defer()
$menu = $$.I("template_thread_list_contextmenu").content.$(".thread_list_contextmenu").cloneNode(true)
$table.closest(".view").addLast($menu)
url = $tr.dataset.href
if app.bookmark.get(url)
$menu.C("add_bookmark")[0]?.remove()
else
$menu.C("del_bookmark")[0]?.remove()
if (
not @_flg.unread or
not /^\d+$/.test($tr.$(selector.unread).textContent) or
app.bookmark.get(url)?
)
$menu.C("del_read_state")[0]?.remove()
$menu.on("click", fn = ({target}) ->
return if target.tagName isnt "LI"
$menu.off("click", fn)
return unless $tr?
threadURL = $tr.dataset.href
threadTitle = $tr.$(selector.title)?.textContent
threadRes = parseInt($tr.$(selector.res)?.textContent ? 0)
threadWrittenRes = parseInt($tr.$(selector.writtenRes)?.textContent ? 0)
dateValue = $tr.$(selector.viewedDate)?.getAttr("date-value")
switch
when target.hasClass("add_bookmark")
app.bookmark.add(threadURL, threadTitle, threadRes)
when target.hasClass("del_bookmark")
app.bookmark.remove(threadURL)
when target.hasClass("del_history")
app.History.remove(threadURL, +dateValue)
$tr.remove()
when target.hasClass("del_writehistory")
app.WriteHistory.remove(threadURL, threadWrittenRes)
$tr.remove()
when target.hasClass("ignore_res_number")
$tr.setAttr("ignore-res-number", "on")
$tr.emit(new Event("mousedown", {bubbles: true}))
when target.hasClass("del_read_state")
app.ReadState.remove(threadURL)
@remove()
return
)
ContextMenu($menu, e.clientX, e.clientY)
return
)
return
return
###*
@method _calcHeat
@static
@private
@param {Number} now
@param {Number} created
@param {Number} resCount
@return {String}
###
@_calcHeat: (now, created, resCount) ->
if not /^\d+$/.test(created)
created = (new Date(created)).getTime()
if created > now
return "0.0"
elapsed = Math.max((now - created) / 1000, 1) / (24 * 60 * 60)
return (resCount / elapsed).toFixed(1)
###*
@method _dateToString
@static
@private
@param {Date}
@return {String}
###
@_dateToString: do ->
fn = (a) -> (if a < 10 then "0" else "") + a
return (date) ->
return date.getFullYear() +
"/" + fn(date.getMonth() + 1) +
"/" + fn(date.getDate()) +
" " + fn(date.getHours()) +
":" + fn(date.getMinutes())
###*
@method addItem
@param {Object|Array}
###
addItem: (arg) ->
unless Array.isArray(arg) then arg = [arg]
$tbody = @table.$("tbody")
now = Date.now()
$fragment = $_F()
for item in arg
$tr = $__("tr").addClass("open_in_rcrx")
$tr.addClass("expired") if item.expired
$tr.addClass("ng_thread") if item.ng
$tr.addClass("net") if item.isNet
$tr.addClass("https") if item.isHttps
if item.expired and not app.config.isOn("bookmark_show_dat")
$tr.addClass("hidden")
$tr.dataset.href = app.escapeHtml(item.url)
$tr.dataset.title = app.escapeHtml(item.title)
if item.threadNumber?
$tr.dataset.threadNumber = app.escapeHtml(""+item.threadNumber)
if @_flg.writtenRes and item.res > 0
$tr.dataset.writtenResNum = item.res
#ブックマーク状況
if @_flg.bookmark
$td = $__("td")
if app.bookmark.get(item.url)
$td.textContent = "★"
$tr.addLast($td)
#タイトル
if @_flg.title
$td = $__("td")
$td.textContent = item.title
$tr.addLast($td)
#板名
if @_flg.boardTitle
$td = $__("td")
$td.textContent = item.boardTitle
$tr.addLast($td)
#レス数
if @_flg.res
$td = $__("td")
if item.resCount > 0
$td.textContent = item.resCount
$tr.addLast($td)
#レス番号
if @_flg.writtenRes
$td = $__("td")
if item.res > 0
$td.textContent = item.res
$tr.addLast($td)
#未読数
if @_flg.unread
$td = $__("td")
if item.readState and item.resCount > item.readState.read
$td.textContent = (item.resCount - item.readState.read)
$tr.addClass("updated")
$tr.addLast($td)
#勢い
if @_flg.heat
$td = $__("td")
$td.textContent = ThreadList._calcHeat(now, item.createdAt, item.resCount)
$tr.addLast($td)
#名前
if @_flg.name
$td = $__("td")
$td.textContent = item.name
$tr.addLast($td)
#メール
if @_flg.mail
$td = $__("td")
$td.textContent = item.mail
$tr.addLast($td)
#本文
if @_flg.message
$td = $__("td")
$td.textContent = item.message
$tr.addLast($td)
#作成日時
if @_flg.createdDate
$td = $__("td")
$td.textContent = ThreadList._dateToString(new Date(item.createdAt))
$tr.addLast($td)
#閲覧日時
if @_flg.viewedDate
$td = $__("td")
$td.setAttr("date-value", item.date)
$td.textContent = ThreadList._dateToString(new Date(item.date))
$tr.addLast($td)
#書込日時
if @_flg.writtenDate
$td = $__("td")
$td.textContent = ThreadList._dateToString(new Date(item.date))
$tr.addLast($td)
$fragment.addLast($tr)
$tbody.addLast($fragment)
return
###*
@method empty
###
empty: ->
@table.$("tbody").innerHTML = ""
return
###*
@method getSelected
@return {Element|null}
###
getSelected: ->
return @table.$("tr.selected")
###*
@method select
@param {Element|number} tr
###
select: (target) ->
@clearSelect()
if typeof target is "number"
target = @table.$("tbody > tr:nth-child(#{target}), tbody > tr:last-child")
return unless target
target.addClass("selected")
target.scrollIntoView(behavior: "instant", block: "center", inline: "center")
return
###*
@method selectNext
@param {number} [repeat = 1]
###
selectNext: (repeat = 1) ->
current = @getSelected()
if current
for [0...repeat]
prevCurrent = current
current = current.next()
while current and current.offsetHeight is 0
current = current.next()
if not current
current = prevCurrent
break
else
current = @table.$("tbody > tr")
if current
@select(current)
return
###*
@method selectPrev
@param {number} [repeat = 1]
###
selectPrev: (repeat = 1) ->
current = @getSelected()
if current
for [0...repeat]
prevCurrent = current
current = current.prev()
while current and current.offsetHeight is 0
current = current.prev()
if not current
current = prevCurrent
break
else
current = @table.$("tbody > tr")
if current
@select(current)
return
###*
@method clearSelect
###
clearSelect: ->
@getSelected()?.removeClass("selected")
return
| 165160 | import ContextMenu from "./ContextMenu.coffee"
import TableSearch from "./TableSearch.coffee"
###*
@class ThreadList
@constructor
@param {Element} table
@param {Object} option
@param {Boolean} [option.bookmark=false]
@param {Boolean} [option.title=false]
@param {Boolean} [option.boardTitle=false]
@param {Boolean} [option.res=false]
@param {Boolean} [option.unread=false]
@param {Boolean} [option.heat=false]
@param {Boolean} [option.createdDate=false]
@param {Boolean} [option.viewedDate=false]
@param {Boolean} [option.bookmarkAddRm=false]
@param {Element} [option.searchbox]
###
export default class ThreadList
constructor: (@table, option) ->
###*
@property _flg
@type Object
@private
###
@_flg =
bookmark: false
title: false
boardTitle: false
res: false
writtenRes: false
unread: false
heat: false
name: false
mail: false
message: false
createdDate: false
viewedDate: false
writtenDate: false
bookmarkAddRm: !!option.bookmarkAddRm
searchbox: undefined
keyToLabel =
bookmark: "★"
title: "タイトル"
boardTitle: "板名"
res: "レス数"
writtenRes: "レス番号"
unread: "未読数"
heat: "勢い"
name: "<NAME>"
mail: "メール"
message: "本文"
createdDate: "作成日時"
viewedDate: "閲覧日時"
writtenDate: "書込日時"
$table = @table
$thead = $__("thead")
$table.addLast($thead, $__("tbody"))
$tr = $__("tr")
$thead.addLast($tr)
#項目のツールチップ表示
$table.on("mouseenter", ({target}) ->
if target.tagName is "TD"
await app.defer()
target.title = target.textContent
return
, true)
$table.on("mouseleave", ({target}) ->
if target.tagName is "TD"
target.removeAttr("title")
return
, true)
$cols = $_F()
selector = {}
column = {}
i = 0
for key, val of keyToLabel when key in option.th
i++
className = key.replace(/([A-Z])/g, ($0, $1) -> "_" + $1.toLowerCase())
$th = $__("th").addClass(className)
$th.textContent = val
$th.dataset.key = className
$tr.addLast($th)
@_flg[key] = true
selector[key] = "td:nth-child(#{i})"
column[key] = i
$col = $__("col").addClass(className)
$col.span = 1
$cols.addLast($col)
$table.addFirst($cols)
#ブックマーク更新時処理
app.message.on("bookmark_updated", ({type, bookmark}) =>
return if bookmark.type isnt "thread"
if type is "expired"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
if $tr?
if bookmark.expired
$tr.addClass("expired")
if app.config.isOn("bookmark_show_dat")
$tr.removeClass("hidden")
else
$tr.addClass("hidden")
else
$tr.removeClass("expired")
if type is "errored"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.addClass("errored")
if type is "updated"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.removeClass("errored")
if @_flg.bookmark
if type is "added"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.bookmark).textContent = "★"
else if type is "removed"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.bookmark).textContent = ""
if @_flg.bookmarkAddRm
if type is "added"
url = new app.URL.URL(bookmark.url)
boardUrl = url.toBoard()
try
boardTitle = await app.BoardTitleSolver.ask(boardUrl)
catch
boardTitle = ""
@addItem({
title: bookmark.title
url: bookmark.url
resCount: bookmark.resCount or 0
readState: bookmark.readState or null
createdAt: /\/(\d+)\/$/.exec(url.pathname)[1] * 1000
boardUrl: boardUrl.href
boardTitle
expired: bookmark.expired
isHttps: url.isHttps()
})
else if type is "removed"
$table.$("tr[data-href=\"#{bookmark.url}\"]").remove()
if @_flg.res and type is "res_count"
tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
if tr
td = tr.$(selector.res)
oldResCount = +td.textContent
td.textContent = bookmark.resCount
td.dataset.beforeres = oldResCount
if @_flg.unread
td = tr.$(selector.unread)
oldUnread = +td.textContent
unread = oldUnread + (bookmark.resCount - oldResCount)
td.textContent = unread or ""
if unread > 0
tr.addClass("updated")
else
tr.removeClass("updated")
if @_flg.heat
td = tr.$(selector.heat)
td.textContent = ThreadList._calcHeat(
Date.now()
/\/(\d+)\/$/.exec(bookmark.url)[1] * 1000
bookmark.resCount
)
if @_flg.title and type is "title"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.title).textContent = bookmark.title
return
)
#未読数更新
if @_flg.unread
app.message.on("read_state_updated", ({read_state}) ->
tr = $table.$("tr[data-href=\"#{read_state.url}\"]")
if tr
res = tr.$(selector.res)
if +res.textContent < read_state.received
res.textContent = read_state.received
unread = tr.$(selector.unread)
unreadCount = Math.max(+res.textContent - read_state.read, 0)
unread.textContent = unreadCount or ""
if unreadCount > 0
tr.addClass("updated")
else
tr.removeClass("updated")
return
)
app.message.on("read_state_removed", ({url}) ->
tr = $table.$("tr[data-href=\"#{url}\"]")
if tr
tr.$(selector.unread).textContent = ""
tr.removeClass("updated")
return
)
#リスト内検索
if typeof option.searchbox is "object"
titleIndex = column.title
$searchbox = option.searchbox
$searchbox.on("compositionend", ->
@emit(new Event("input"))
return
)
$searchbox.on("input", ({isComposing}) ->
return if isComposing
if @value isnt ""
TableSearch($table, "search",
query: @value, target_col: titleIndex)
hitCount = $table.dataset.tableSearchHitCount
for dom in @parent().child() when dom.hasClass("hit_count")
dom.textContent = hitCount + "hit"
else
TableSearch($table, "clear")
for dom in @parent().child() when dom.hasClass("hit_count")
dom.textContent = ""
return
)
$searchbox.on("keyup", ({key}) ->
if key is "Escape"
@value = ""
@emit(new Event("input"))
return
)
#コンテキストメニュー
if @_flg.bookmark or @_flg.bookmarkAddRm or @_flg.writtenRes or @_flg.viewedDate
do =>
$table.on("contextmenu", (e) =>
$tr = e.target.closest("tbody > tr")
return unless $tr
e.preventDefault()
await app.defer()
$menu = $$.I("template_thread_list_contextmenu").content.$(".thread_list_contextmenu").cloneNode(true)
$table.closest(".view").addLast($menu)
url = $tr.dataset.href
if app.bookmark.get(url)
$menu.C("add_bookmark")[0]?.remove()
else
$menu.C("del_bookmark")[0]?.remove()
if (
not @_flg.unread or
not /^\d+$/.test($tr.$(selector.unread).textContent) or
app.bookmark.get(url)?
)
$menu.C("del_read_state")[0]?.remove()
$menu.on("click", fn = ({target}) ->
return if target.tagName isnt "LI"
$menu.off("click", fn)
return unless $tr?
threadURL = $tr.dataset.href
threadTitle = $tr.$(selector.title)?.textContent
threadRes = parseInt($tr.$(selector.res)?.textContent ? 0)
threadWrittenRes = parseInt($tr.$(selector.writtenRes)?.textContent ? 0)
dateValue = $tr.$(selector.viewedDate)?.getAttr("date-value")
switch
when target.hasClass("add_bookmark")
app.bookmark.add(threadURL, threadTitle, threadRes)
when target.hasClass("del_bookmark")
app.bookmark.remove(threadURL)
when target.hasClass("del_history")
app.History.remove(threadURL, +dateValue)
$tr.remove()
when target.hasClass("del_writehistory")
app.WriteHistory.remove(threadURL, threadWrittenRes)
$tr.remove()
when target.hasClass("ignore_res_number")
$tr.setAttr("ignore-res-number", "on")
$tr.emit(new Event("mousedown", {bubbles: true}))
when target.hasClass("del_read_state")
app.ReadState.remove(threadURL)
@remove()
return
)
ContextMenu($menu, e.clientX, e.clientY)
return
)
return
return
###*
@method _calcHeat
@static
@private
@param {Number} now
@param {Number} created
@param {Number} resCount
@return {String}
###
@_calcHeat: (now, created, resCount) ->
if not /^\d+$/.test(created)
created = (new Date(created)).getTime()
if created > now
return "0.0"
elapsed = Math.max((now - created) / 1000, 1) / (24 * 60 * 60)
return (resCount / elapsed).toFixed(1)
###*
@method _dateToString
@static
@private
@param {Date}
@return {String}
###
@_dateToString: do ->
fn = (a) -> (if a < 10 then "0" else "") + a
return (date) ->
return date.getFullYear() +
"/" + fn(date.getMonth() + 1) +
"/" + fn(date.getDate()) +
" " + fn(date.getHours()) +
":" + fn(date.getMinutes())
###*
@method addItem
@param {Object|Array}
###
addItem: (arg) ->
unless Array.isArray(arg) then arg = [arg]
$tbody = @table.$("tbody")
now = Date.now()
$fragment = $_F()
for item in arg
$tr = $__("tr").addClass("open_in_rcrx")
$tr.addClass("expired") if item.expired
$tr.addClass("ng_thread") if item.ng
$tr.addClass("net") if item.isNet
$tr.addClass("https") if item.isHttps
if item.expired and not app.config.isOn("bookmark_show_dat")
$tr.addClass("hidden")
$tr.dataset.href = app.escapeHtml(item.url)
$tr.dataset.title = app.escapeHtml(item.title)
if item.threadNumber?
$tr.dataset.threadNumber = app.escapeHtml(""+item.threadNumber)
if @_flg.writtenRes and item.res > 0
$tr.dataset.writtenResNum = item.res
#ブックマーク状況
if @_flg.bookmark
$td = $__("td")
if app.bookmark.get(item.url)
$td.textContent = "★"
$tr.addLast($td)
#タイトル
if @_flg.title
$td = $__("td")
$td.textContent = item.title
$tr.addLast($td)
#板名
if @_flg.boardTitle
$td = $__("td")
$td.textContent = item.boardTitle
$tr.addLast($td)
#レス数
if @_flg.res
$td = $__("td")
if item.resCount > 0
$td.textContent = item.resCount
$tr.addLast($td)
#レス番号
if @_flg.writtenRes
$td = $__("td")
if item.res > 0
$td.textContent = item.res
$tr.addLast($td)
#未読数
if @_flg.unread
$td = $__("td")
if item.readState and item.resCount > item.readState.read
$td.textContent = (item.resCount - item.readState.read)
$tr.addClass("updated")
$tr.addLast($td)
#勢い
if @_flg.heat
$td = $__("td")
$td.textContent = ThreadList._calcHeat(now, item.createdAt, item.resCount)
$tr.addLast($td)
#名前
if @_flg.name
$td = $__("td")
$td.textContent = item.name
$tr.addLast($td)
#メール
if @_flg.mail
$td = $__("td")
$td.textContent = item.mail
$tr.addLast($td)
#本文
if @_flg.message
$td = $__("td")
$td.textContent = item.message
$tr.addLast($td)
#作成日時
if @_flg.createdDate
$td = $__("td")
$td.textContent = ThreadList._dateToString(new Date(item.createdAt))
$tr.addLast($td)
#閲覧日時
if @_flg.viewedDate
$td = $__("td")
$td.setAttr("date-value", item.date)
$td.textContent = ThreadList._dateToString(new Date(item.date))
$tr.addLast($td)
#書込日時
if @_flg.writtenDate
$td = $__("td")
$td.textContent = ThreadList._dateToString(new Date(item.date))
$tr.addLast($td)
$fragment.addLast($tr)
$tbody.addLast($fragment)
return
###*
@method empty
###
empty: ->
@table.$("tbody").innerHTML = ""
return
###*
@method getSelected
@return {Element|null}
###
getSelected: ->
return @table.$("tr.selected")
###*
@method select
@param {Element|number} tr
###
select: (target) ->
@clearSelect()
if typeof target is "number"
target = @table.$("tbody > tr:nth-child(#{target}), tbody > tr:last-child")
return unless target
target.addClass("selected")
target.scrollIntoView(behavior: "instant", block: "center", inline: "center")
return
###*
@method selectNext
@param {number} [repeat = 1]
###
selectNext: (repeat = 1) ->
current = @getSelected()
if current
for [0...repeat]
prevCurrent = current
current = current.next()
while current and current.offsetHeight is 0
current = current.next()
if not current
current = prevCurrent
break
else
current = @table.$("tbody > tr")
if current
@select(current)
return
###*
@method selectPrev
@param {number} [repeat = 1]
###
selectPrev: (repeat = 1) ->
current = @getSelected()
if current
for [0...repeat]
prevCurrent = current
current = current.prev()
while current and current.offsetHeight is 0
current = current.prev()
if not current
current = prevCurrent
break
else
current = @table.$("tbody > tr")
if current
@select(current)
return
###*
@method clearSelect
###
clearSelect: ->
@getSelected()?.removeClass("selected")
return
| true | import ContextMenu from "./ContextMenu.coffee"
import TableSearch from "./TableSearch.coffee"
###*
@class ThreadList
@constructor
@param {Element} table
@param {Object} option
@param {Boolean} [option.bookmark=false]
@param {Boolean} [option.title=false]
@param {Boolean} [option.boardTitle=false]
@param {Boolean} [option.res=false]
@param {Boolean} [option.unread=false]
@param {Boolean} [option.heat=false]
@param {Boolean} [option.createdDate=false]
@param {Boolean} [option.viewedDate=false]
@param {Boolean} [option.bookmarkAddRm=false]
@param {Element} [option.searchbox]
###
export default class ThreadList
constructor: (@table, option) ->
###*
@property _flg
@type Object
@private
###
@_flg =
bookmark: false
title: false
boardTitle: false
res: false
writtenRes: false
unread: false
heat: false
name: false
mail: false
message: false
createdDate: false
viewedDate: false
writtenDate: false
bookmarkAddRm: !!option.bookmarkAddRm
searchbox: undefined
keyToLabel =
bookmark: "★"
title: "タイトル"
boardTitle: "板名"
res: "レス数"
writtenRes: "レス番号"
unread: "未読数"
heat: "勢い"
name: "PI:NAME:<NAME>END_PI"
mail: "メール"
message: "本文"
createdDate: "作成日時"
viewedDate: "閲覧日時"
writtenDate: "書込日時"
$table = @table
$thead = $__("thead")
$table.addLast($thead, $__("tbody"))
$tr = $__("tr")
$thead.addLast($tr)
#項目のツールチップ表示
$table.on("mouseenter", ({target}) ->
if target.tagName is "TD"
await app.defer()
target.title = target.textContent
return
, true)
$table.on("mouseleave", ({target}) ->
if target.tagName is "TD"
target.removeAttr("title")
return
, true)
$cols = $_F()
selector = {}
column = {}
i = 0
for key, val of keyToLabel when key in option.th
i++
className = key.replace(/([A-Z])/g, ($0, $1) -> "_" + $1.toLowerCase())
$th = $__("th").addClass(className)
$th.textContent = val
$th.dataset.key = className
$tr.addLast($th)
@_flg[key] = true
selector[key] = "td:nth-child(#{i})"
column[key] = i
$col = $__("col").addClass(className)
$col.span = 1
$cols.addLast($col)
$table.addFirst($cols)
#ブックマーク更新時処理
app.message.on("bookmark_updated", ({type, bookmark}) =>
return if bookmark.type isnt "thread"
if type is "expired"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
if $tr?
if bookmark.expired
$tr.addClass("expired")
if app.config.isOn("bookmark_show_dat")
$tr.removeClass("hidden")
else
$tr.addClass("hidden")
else
$tr.removeClass("expired")
if type is "errored"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.addClass("errored")
if type is "updated"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.removeClass("errored")
if @_flg.bookmark
if type is "added"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.bookmark).textContent = "★"
else if type is "removed"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.bookmark).textContent = ""
if @_flg.bookmarkAddRm
if type is "added"
url = new app.URL.URL(bookmark.url)
boardUrl = url.toBoard()
try
boardTitle = await app.BoardTitleSolver.ask(boardUrl)
catch
boardTitle = ""
@addItem({
title: bookmark.title
url: bookmark.url
resCount: bookmark.resCount or 0
readState: bookmark.readState or null
createdAt: /\/(\d+)\/$/.exec(url.pathname)[1] * 1000
boardUrl: boardUrl.href
boardTitle
expired: bookmark.expired
isHttps: url.isHttps()
})
else if type is "removed"
$table.$("tr[data-href=\"#{bookmark.url}\"]").remove()
if @_flg.res and type is "res_count"
tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
if tr
td = tr.$(selector.res)
oldResCount = +td.textContent
td.textContent = bookmark.resCount
td.dataset.beforeres = oldResCount
if @_flg.unread
td = tr.$(selector.unread)
oldUnread = +td.textContent
unread = oldUnread + (bookmark.resCount - oldResCount)
td.textContent = unread or ""
if unread > 0
tr.addClass("updated")
else
tr.removeClass("updated")
if @_flg.heat
td = tr.$(selector.heat)
td.textContent = ThreadList._calcHeat(
Date.now()
/\/(\d+)\/$/.exec(bookmark.url)[1] * 1000
bookmark.resCount
)
if @_flg.title and type is "title"
$tr = $table.$("tr[data-href=\"#{bookmark.url}\"]")
$tr?.$(selector.title).textContent = bookmark.title
return
)
#未読数更新
if @_flg.unread
app.message.on("read_state_updated", ({read_state}) ->
tr = $table.$("tr[data-href=\"#{read_state.url}\"]")
if tr
res = tr.$(selector.res)
if +res.textContent < read_state.received
res.textContent = read_state.received
unread = tr.$(selector.unread)
unreadCount = Math.max(+res.textContent - read_state.read, 0)
unread.textContent = unreadCount or ""
if unreadCount > 0
tr.addClass("updated")
else
tr.removeClass("updated")
return
)
app.message.on("read_state_removed", ({url}) ->
tr = $table.$("tr[data-href=\"#{url}\"]")
if tr
tr.$(selector.unread).textContent = ""
tr.removeClass("updated")
return
)
#リスト内検索
if typeof option.searchbox is "object"
titleIndex = column.title
$searchbox = option.searchbox
$searchbox.on("compositionend", ->
@emit(new Event("input"))
return
)
$searchbox.on("input", ({isComposing}) ->
return if isComposing
if @value isnt ""
TableSearch($table, "search",
query: @value, target_col: titleIndex)
hitCount = $table.dataset.tableSearchHitCount
for dom in @parent().child() when dom.hasClass("hit_count")
dom.textContent = hitCount + "hit"
else
TableSearch($table, "clear")
for dom in @parent().child() when dom.hasClass("hit_count")
dom.textContent = ""
return
)
$searchbox.on("keyup", ({key}) ->
if key is "Escape"
@value = ""
@emit(new Event("input"))
return
)
#コンテキストメニュー
if @_flg.bookmark or @_flg.bookmarkAddRm or @_flg.writtenRes or @_flg.viewedDate
do =>
$table.on("contextmenu", (e) =>
$tr = e.target.closest("tbody > tr")
return unless $tr
e.preventDefault()
await app.defer()
$menu = $$.I("template_thread_list_contextmenu").content.$(".thread_list_contextmenu").cloneNode(true)
$table.closest(".view").addLast($menu)
url = $tr.dataset.href
if app.bookmark.get(url)
$menu.C("add_bookmark")[0]?.remove()
else
$menu.C("del_bookmark")[0]?.remove()
if (
not @_flg.unread or
not /^\d+$/.test($tr.$(selector.unread).textContent) or
app.bookmark.get(url)?
)
$menu.C("del_read_state")[0]?.remove()
$menu.on("click", fn = ({target}) ->
return if target.tagName isnt "LI"
$menu.off("click", fn)
return unless $tr?
threadURL = $tr.dataset.href
threadTitle = $tr.$(selector.title)?.textContent
threadRes = parseInt($tr.$(selector.res)?.textContent ? 0)
threadWrittenRes = parseInt($tr.$(selector.writtenRes)?.textContent ? 0)
dateValue = $tr.$(selector.viewedDate)?.getAttr("date-value")
switch
when target.hasClass("add_bookmark")
app.bookmark.add(threadURL, threadTitle, threadRes)
when target.hasClass("del_bookmark")
app.bookmark.remove(threadURL)
when target.hasClass("del_history")
app.History.remove(threadURL, +dateValue)
$tr.remove()
when target.hasClass("del_writehistory")
app.WriteHistory.remove(threadURL, threadWrittenRes)
$tr.remove()
when target.hasClass("ignore_res_number")
$tr.setAttr("ignore-res-number", "on")
$tr.emit(new Event("mousedown", {bubbles: true}))
when target.hasClass("del_read_state")
app.ReadState.remove(threadURL)
@remove()
return
)
ContextMenu($menu, e.clientX, e.clientY)
return
)
return
return
###*
@method _calcHeat
@static
@private
@param {Number} now
@param {Number} created
@param {Number} resCount
@return {String}
###
@_calcHeat: (now, created, resCount) ->
if not /^\d+$/.test(created)
created = (new Date(created)).getTime()
if created > now
return "0.0"
elapsed = Math.max((now - created) / 1000, 1) / (24 * 60 * 60)
return (resCount / elapsed).toFixed(1)
###*
@method _dateToString
@static
@private
@param {Date}
@return {String}
###
@_dateToString: do ->
fn = (a) -> (if a < 10 then "0" else "") + a
return (date) ->
return date.getFullYear() +
"/" + fn(date.getMonth() + 1) +
"/" + fn(date.getDate()) +
" " + fn(date.getHours()) +
":" + fn(date.getMinutes())
###*
@method addItem
@param {Object|Array}
###
addItem: (arg) ->
unless Array.isArray(arg) then arg = [arg]
$tbody = @table.$("tbody")
now = Date.now()
$fragment = $_F()
for item in arg
$tr = $__("tr").addClass("open_in_rcrx")
$tr.addClass("expired") if item.expired
$tr.addClass("ng_thread") if item.ng
$tr.addClass("net") if item.isNet
$tr.addClass("https") if item.isHttps
if item.expired and not app.config.isOn("bookmark_show_dat")
$tr.addClass("hidden")
$tr.dataset.href = app.escapeHtml(item.url)
$tr.dataset.title = app.escapeHtml(item.title)
if item.threadNumber?
$tr.dataset.threadNumber = app.escapeHtml(""+item.threadNumber)
if @_flg.writtenRes and item.res > 0
$tr.dataset.writtenResNum = item.res
#ブックマーク状況
if @_flg.bookmark
$td = $__("td")
if app.bookmark.get(item.url)
$td.textContent = "★"
$tr.addLast($td)
#タイトル
if @_flg.title
$td = $__("td")
$td.textContent = item.title
$tr.addLast($td)
#板名
if @_flg.boardTitle
$td = $__("td")
$td.textContent = item.boardTitle
$tr.addLast($td)
#レス数
if @_flg.res
$td = $__("td")
if item.resCount > 0
$td.textContent = item.resCount
$tr.addLast($td)
#レス番号
if @_flg.writtenRes
$td = $__("td")
if item.res > 0
$td.textContent = item.res
$tr.addLast($td)
#未読数
if @_flg.unread
$td = $__("td")
if item.readState and item.resCount > item.readState.read
$td.textContent = (item.resCount - item.readState.read)
$tr.addClass("updated")
$tr.addLast($td)
#勢い
if @_flg.heat
$td = $__("td")
$td.textContent = ThreadList._calcHeat(now, item.createdAt, item.resCount)
$tr.addLast($td)
#名前
if @_flg.name
$td = $__("td")
$td.textContent = item.name
$tr.addLast($td)
#メール
if @_flg.mail
$td = $__("td")
$td.textContent = item.mail
$tr.addLast($td)
#本文
if @_flg.message
$td = $__("td")
$td.textContent = item.message
$tr.addLast($td)
#作成日時
if @_flg.createdDate
$td = $__("td")
$td.textContent = ThreadList._dateToString(new Date(item.createdAt))
$tr.addLast($td)
#閲覧日時
if @_flg.viewedDate
$td = $__("td")
$td.setAttr("date-value", item.date)
$td.textContent = ThreadList._dateToString(new Date(item.date))
$tr.addLast($td)
#書込日時
if @_flg.writtenDate
$td = $__("td")
$td.textContent = ThreadList._dateToString(new Date(item.date))
$tr.addLast($td)
$fragment.addLast($tr)
$tbody.addLast($fragment)
return
###*
@method empty
###
empty: ->
@table.$("tbody").innerHTML = ""
return
###*
@method getSelected
@return {Element|null}
###
getSelected: ->
return @table.$("tr.selected")
###*
@method select
@param {Element|number} tr
###
select: (target) ->
@clearSelect()
if typeof target is "number"
target = @table.$("tbody > tr:nth-child(#{target}), tbody > tr:last-child")
return unless target
target.addClass("selected")
target.scrollIntoView(behavior: "instant", block: "center", inline: "center")
return
###*
@method selectNext
@param {number} [repeat = 1]
###
selectNext: (repeat = 1) ->
current = @getSelected()
if current
for [0...repeat]
prevCurrent = current
current = current.next()
while current and current.offsetHeight is 0
current = current.next()
if not current
current = prevCurrent
break
else
current = @table.$("tbody > tr")
if current
@select(current)
return
###*
@method selectPrev
@param {number} [repeat = 1]
###
selectPrev: (repeat = 1) ->
current = @getSelected()
if current
for [0...repeat]
prevCurrent = current
current = current.prev()
while current and current.offsetHeight is 0
current = current.prev()
if not current
current = prevCurrent
break
else
current = @table.$("tbody > tr")
if current
@select(current)
return
###*
@method clearSelect
###
clearSelect: ->
@getSelected()?.removeClass("selected")
return
|
[
{
"context": " #{adjective}!\n \"\"\"\n\n# alert greet \"GREG\", \"COOL\"\n\nalert anotherStr\n\nexport default \"I am ",
"end": 420,
"score": 0.9154752492904663,
"start": 416,
"tag": "NAME",
"value": "GREG"
}
] | playground/src/test.coffee | admbradford/packem | 0 | # This is a test CoffeeScript file used by `packem-coffeescript-plugin`
# Demo comments
import * as anotherStr from './another-test.js'
upperCaseExpr = (textParts, expressions...) ->
textParts.reduce (text, textPart, i) ->
text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) ->
upperCaseExpr"""
Hi #{name}. You look #{adjective}!
"""
# alert greet "GREG", "COOL"
alert anotherStr
export default "I am CoffeeScript"
| 61965 | # This is a test CoffeeScript file used by `packem-coffeescript-plugin`
# Demo comments
import * as anotherStr from './another-test.js'
upperCaseExpr = (textParts, expressions...) ->
textParts.reduce (text, textPart, i) ->
text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) ->
upperCaseExpr"""
Hi #{name}. You look #{adjective}!
"""
# alert greet "<NAME>", "COOL"
alert anotherStr
export default "I am CoffeeScript"
| true | # This is a test CoffeeScript file used by `packem-coffeescript-plugin`
# Demo comments
import * as anotherStr from './another-test.js'
upperCaseExpr = (textParts, expressions...) ->
textParts.reduce (text, textPart, i) ->
text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) ->
upperCaseExpr"""
Hi #{name}. You look #{adjective}!
"""
# alert greet "PI:NAME:<NAME>END_PI", "COOL"
alert anotherStr
export default "I am CoffeeScript"
|
[
{
"context": "or core library\n# mdo_prototype\n# \n# Created by Dmitry Shvetsov.\n# Copyright 2014 Dmitry Shvetsov. All rights re",
"end": 79,
"score": 0.9998875260353088,
"start": 64,
"tag": "NAME",
"value": "Dmitry Shvetsov"
},
{
"context": " \n# Created by Dmitry Shvetsov.\n... | test/core_test.coffee | shvetsovdm/mdo_prototype | 0 | #
# Tests for core library
# mdo_prototype
#
# Created by Dmitry Shvetsov.
# Copyright 2014 Dmitry Shvetsov. All rights reserved.
#
chai = require 'chai'
should = chai.should()
expect = chai.expect
_ = require 'underscore'
UUId = require('node-uuid')
libCore = require '../lib/core.js'
libDuel = require '../lib/duel.js'
libPlayer = require '../lib/player.js'
describe 'Core class', ->
describe 'handleNewPlayer function', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
testSetOfDuels = []
it 'should initialize new duel with current player if no waitingFor duel', ->
it 'should initialize new duel with current player if no duels at all', ->
it 'should add current player to waitingFor duel if its exist', ->
describe 'createNewDuel function', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
duel = core.createNewDuel player
it 'should create duel with the inital wait status', ->
duel.state.should.be.equal('wait')
it 'shoult create duel with only initial player', ->
playersObject = {}
playersObject[playerId] = player
_.size(duel.players).should.be.equal(1)
duel.players.should.deep.equal(playersObject)
it 'should add the duel to set of duels', ->
core.setOfDuels.should.include.keys(duel.id)
it 'should set the created duel as waiting for opponent', ->
core.setOfDuels.waitingFor.id.should.be.equal(duel.id)
describe 'joinToWaitingFor function', ->
core = _.extend {}, libCore
core.abracadabra = 1
firstPlayerId = UUId()
secondPlayerId = UUId()
firstPlayer = new libPlayer firstPlayerId, 30
secondPlayer = new libPlayer secondPlayerId, 30
waitingForDuelId = UUId()
waitingForDuel = new libDuel waitingForDuelId, { firstPlayerId: firstPlayer }, 'wait'
core.setOfDuels.waitingFor = waitingForDuel
core.setOfDuels[waitingForDuelId] = waitingForDuel
it 'should add second player to waiting for duel', ->
_.size(core.setOfDuels.waitingFor.players).should.be.equal(1)
core.joinToWaitingFor(secondPlayer)
_.size(core.setOfDuels.waitingFor.players).should.be.equal(2)
waitingForDuel.players.should.contain(firstPlayerId)
waitingForDuel.players.should.contain(secondPlayerId) | 43373 | #
# Tests for core library
# mdo_prototype
#
# Created by <NAME>.
# Copyright 2014 <NAME>. All rights reserved.
#
chai = require 'chai'
should = chai.should()
expect = chai.expect
_ = require 'underscore'
UUId = require('node-uuid')
libCore = require '../lib/core.js'
libDuel = require '../lib/duel.js'
libPlayer = require '../lib/player.js'
describe 'Core class', ->
describe 'handleNewPlayer function', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
testSetOfDuels = []
it 'should initialize new duel with current player if no waitingFor duel', ->
it 'should initialize new duel with current player if no duels at all', ->
it 'should add current player to waitingFor duel if its exist', ->
describe 'createNewDuel function', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
duel = core.createNewDuel player
it 'should create duel with the inital wait status', ->
duel.state.should.be.equal('wait')
it 'shoult create duel with only initial player', ->
playersObject = {}
playersObject[playerId] = player
_.size(duel.players).should.be.equal(1)
duel.players.should.deep.equal(playersObject)
it 'should add the duel to set of duels', ->
core.setOfDuels.should.include.keys(duel.id)
it 'should set the created duel as waiting for opponent', ->
core.setOfDuels.waitingFor.id.should.be.equal(duel.id)
describe 'joinToWaitingFor function', ->
core = _.extend {}, libCore
core.abracadabra = 1
firstPlayerId = UUId()
secondPlayerId = UUId()
firstPlayer = new libPlayer firstPlayerId, 30
secondPlayer = new libPlayer secondPlayerId, 30
waitingForDuelId = UUId()
waitingForDuel = new libDuel waitingForDuelId, { firstPlayerId: firstPlayer }, 'wait'
core.setOfDuels.waitingFor = waitingForDuel
core.setOfDuels[waitingForDuelId] = waitingForDuel
it 'should add second player to waiting for duel', ->
_.size(core.setOfDuels.waitingFor.players).should.be.equal(1)
core.joinToWaitingFor(secondPlayer)
_.size(core.setOfDuels.waitingFor.players).should.be.equal(2)
waitingForDuel.players.should.contain(firstPlayerId)
waitingForDuel.players.should.contain(secondPlayerId) | true | #
# Tests for core library
# mdo_prototype
#
# Created by PI:NAME:<NAME>END_PI.
# Copyright 2014 PI:NAME:<NAME>END_PI. All rights reserved.
#
chai = require 'chai'
should = chai.should()
expect = chai.expect
_ = require 'underscore'
UUId = require('node-uuid')
libCore = require '../lib/core.js'
libDuel = require '../lib/duel.js'
libPlayer = require '../lib/player.js'
describe 'Core class', ->
describe 'handleNewPlayer function', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
testSetOfDuels = []
it 'should initialize new duel with current player if no waitingFor duel', ->
it 'should initialize new duel with current player if no duels at all', ->
it 'should add current player to waitingFor duel if its exist', ->
describe 'createNewDuel function', ->
core = _.extend {}, libCore
playerId = UUId()
player = new libPlayer playerId, 30
duel = core.createNewDuel player
it 'should create duel with the inital wait status', ->
duel.state.should.be.equal('wait')
it 'shoult create duel with only initial player', ->
playersObject = {}
playersObject[playerId] = player
_.size(duel.players).should.be.equal(1)
duel.players.should.deep.equal(playersObject)
it 'should add the duel to set of duels', ->
core.setOfDuels.should.include.keys(duel.id)
it 'should set the created duel as waiting for opponent', ->
core.setOfDuels.waitingFor.id.should.be.equal(duel.id)
describe 'joinToWaitingFor function', ->
core = _.extend {}, libCore
core.abracadabra = 1
firstPlayerId = UUId()
secondPlayerId = UUId()
firstPlayer = new libPlayer firstPlayerId, 30
secondPlayer = new libPlayer secondPlayerId, 30
waitingForDuelId = UUId()
waitingForDuel = new libDuel waitingForDuelId, { firstPlayerId: firstPlayer }, 'wait'
core.setOfDuels.waitingFor = waitingForDuel
core.setOfDuels[waitingForDuelId] = waitingForDuel
it 'should add second player to waiting for duel', ->
_.size(core.setOfDuels.waitingFor.players).should.be.equal(1)
core.joinToWaitingFor(secondPlayer)
_.size(core.setOfDuels.waitingFor.players).should.be.equal(2)
waitingForDuel.players.should.contain(firstPlayerId)
waitingForDuel.players.should.contain(secondPlayerId) |
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998881220817566,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/utils.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: utils.coffee
###
nl2br = (str) =>
breakTag = '<br />'
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2')
bindMethods = (object) =>
dependencies = _.keys(object)
methods = []
_.forIn object, (value, key) =>
if key not in dependencies
methods.push(key)
_.bindAll(object, methods)
bindOnce = (scope, attr, continuation) =>
val = scope.$eval(attr)
if val != undefined
return continuation(val)
delBind = null
delBind = scope.$watch attr, (val) ->
return if val is undefined
continuation(val)
delBind() if delBind
mixOf = (base, mixins...) ->
class Mixed extends base
for mixin in mixins by -1 #earlier mixins override later ones
for name, method of mixin::
Mixed::[name] = method
Mixed
trim = (data, char) ->
return _.str.trim(data, char)
slugify = (data) ->
return _.str.slugify(data)
unslugify = (data) ->
if data
return _.str.capitalize(data.replace(/-/g, ' '))
return data
toggleText = (element, texts) ->
nextTextPosition = element.data('nextTextPosition')
nextTextPosition = 0 if not nextTextPosition? or nextTextPosition >= texts.length
text = texts[nextTextPosition]
element.data('nextTextPosition', nextTextPosition + 1)
element.text(text)
groupBy = (coll, pred) ->
result = {}
for item in coll
result[pred(item)] = item
return result
timeout = (wait, continuation) ->
return window.setTimeout(continuation, wait)
cancelTimeout = (timeoutVar) ->
window.clearTimeout(timeoutVar)
scopeDefer = (scope, func) ->
_.defer =>
scope.$apply(func)
toString = (value) ->
if _.isNumber(value)
return value + ""
else if _.isString(value)
return value
else if _.isPlainObject(value)
return JSON.stringify(value)
else if _.isUndefined(value)
return ""
return value.toString()
joinStr = (str, coll) ->
return _.str.join(str, coll)
debounce = (wait, func) ->
return _.debounce(func, wait, {leading: true, trailing: false})
debounceLeading = (wait, func) ->
return _.debounce(func, wait, {leading: false, trailing: true})
startswith = (str1, str2) ->
return _.str.startsWith(str1, str2)
sizeFormat = (input, precision=1) ->
if isNaN(parseFloat(input)) or not isFinite(input)
return "-"
if input == 0
return "0 bytes"
units = ["bytes", "KB", "MB", "GB", "TB", "PB"]
number = Math.floor(Math.log(input) / Math.log(1024))
if number > 5
number = 5
size = (input / Math.pow(1024, number)).toFixed(precision)
return "#{size} #{units[number]}"
taiga = @.taiga
taiga.nl2br = nl2br
taiga.bindMethods = bindMethods
taiga.bindOnce = bindOnce
taiga.mixOf = mixOf
taiga.trim = trim
taiga.slugify = slugify
taiga.unslugify = unslugify
taiga.toggleText = toggleText
taiga.groupBy = groupBy
taiga.timeout = timeout
taiga.cancelTimeout = cancelTimeout
taiga.scopeDefer = scopeDefer
taiga.toString = toString
taiga.joinStr = joinStr
taiga.debounce = debounce
taiga.debounceLeading = debounceLeading
taiga.startswith = startswith
taiga.sizeFormat = sizeFormat
| 24254 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: utils.coffee
###
nl2br = (str) =>
breakTag = '<br />'
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2')
bindMethods = (object) =>
dependencies = _.keys(object)
methods = []
_.forIn object, (value, key) =>
if key not in dependencies
methods.push(key)
_.bindAll(object, methods)
bindOnce = (scope, attr, continuation) =>
val = scope.$eval(attr)
if val != undefined
return continuation(val)
delBind = null
delBind = scope.$watch attr, (val) ->
return if val is undefined
continuation(val)
delBind() if delBind
mixOf = (base, mixins...) ->
class Mixed extends base
for mixin in mixins by -1 #earlier mixins override later ones
for name, method of mixin::
Mixed::[name] = method
Mixed
trim = (data, char) ->
return _.str.trim(data, char)
slugify = (data) ->
return _.str.slugify(data)
unslugify = (data) ->
if data
return _.str.capitalize(data.replace(/-/g, ' '))
return data
toggleText = (element, texts) ->
nextTextPosition = element.data('nextTextPosition')
nextTextPosition = 0 if not nextTextPosition? or nextTextPosition >= texts.length
text = texts[nextTextPosition]
element.data('nextTextPosition', nextTextPosition + 1)
element.text(text)
groupBy = (coll, pred) ->
result = {}
for item in coll
result[pred(item)] = item
return result
timeout = (wait, continuation) ->
return window.setTimeout(continuation, wait)
cancelTimeout = (timeoutVar) ->
window.clearTimeout(timeoutVar)
scopeDefer = (scope, func) ->
_.defer =>
scope.$apply(func)
toString = (value) ->
if _.isNumber(value)
return value + ""
else if _.isString(value)
return value
else if _.isPlainObject(value)
return JSON.stringify(value)
else if _.isUndefined(value)
return ""
return value.toString()
joinStr = (str, coll) ->
return _.str.join(str, coll)
debounce = (wait, func) ->
return _.debounce(func, wait, {leading: true, trailing: false})
debounceLeading = (wait, func) ->
return _.debounce(func, wait, {leading: false, trailing: true})
startswith = (str1, str2) ->
return _.str.startsWith(str1, str2)
sizeFormat = (input, precision=1) ->
if isNaN(parseFloat(input)) or not isFinite(input)
return "-"
if input == 0
return "0 bytes"
units = ["bytes", "KB", "MB", "GB", "TB", "PB"]
number = Math.floor(Math.log(input) / Math.log(1024))
if number > 5
number = 5
size = (input / Math.pow(1024, number)).toFixed(precision)
return "#{size} #{units[number]}"
taiga = @.taiga
taiga.nl2br = nl2br
taiga.bindMethods = bindMethods
taiga.bindOnce = bindOnce
taiga.mixOf = mixOf
taiga.trim = trim
taiga.slugify = slugify
taiga.unslugify = unslugify
taiga.toggleText = toggleText
taiga.groupBy = groupBy
taiga.timeout = timeout
taiga.cancelTimeout = cancelTimeout
taiga.scopeDefer = scopeDefer
taiga.toString = toString
taiga.joinStr = joinStr
taiga.debounce = debounce
taiga.debounceLeading = debounceLeading
taiga.startswith = startswith
taiga.sizeFormat = sizeFormat
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: utils.coffee
###
nl2br = (str) =>
breakTag = '<br />'
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2')
bindMethods = (object) =>
dependencies = _.keys(object)
methods = []
_.forIn object, (value, key) =>
if key not in dependencies
methods.push(key)
_.bindAll(object, methods)
bindOnce = (scope, attr, continuation) =>
val = scope.$eval(attr)
if val != undefined
return continuation(val)
delBind = null
delBind = scope.$watch attr, (val) ->
return if val is undefined
continuation(val)
delBind() if delBind
mixOf = (base, mixins...) ->
class Mixed extends base
for mixin in mixins by -1 #earlier mixins override later ones
for name, method of mixin::
Mixed::[name] = method
Mixed
trim = (data, char) ->
return _.str.trim(data, char)
slugify = (data) ->
return _.str.slugify(data)
unslugify = (data) ->
if data
return _.str.capitalize(data.replace(/-/g, ' '))
return data
toggleText = (element, texts) ->
nextTextPosition = element.data('nextTextPosition')
nextTextPosition = 0 if not nextTextPosition? or nextTextPosition >= texts.length
text = texts[nextTextPosition]
element.data('nextTextPosition', nextTextPosition + 1)
element.text(text)
groupBy = (coll, pred) ->
result = {}
for item in coll
result[pred(item)] = item
return result
timeout = (wait, continuation) ->
return window.setTimeout(continuation, wait)
cancelTimeout = (timeoutVar) ->
window.clearTimeout(timeoutVar)
scopeDefer = (scope, func) ->
_.defer =>
scope.$apply(func)
toString = (value) ->
if _.isNumber(value)
return value + ""
else if _.isString(value)
return value
else if _.isPlainObject(value)
return JSON.stringify(value)
else if _.isUndefined(value)
return ""
return value.toString()
joinStr = (str, coll) ->
return _.str.join(str, coll)
debounce = (wait, func) ->
return _.debounce(func, wait, {leading: true, trailing: false})
debounceLeading = (wait, func) ->
return _.debounce(func, wait, {leading: false, trailing: true})
startswith = (str1, str2) ->
return _.str.startsWith(str1, str2)
sizeFormat = (input, precision=1) ->
if isNaN(parseFloat(input)) or not isFinite(input)
return "-"
if input == 0
return "0 bytes"
units = ["bytes", "KB", "MB", "GB", "TB", "PB"]
number = Math.floor(Math.log(input) / Math.log(1024))
if number > 5
number = 5
size = (input / Math.pow(1024, number)).toFixed(precision)
return "#{size} #{units[number]}"
taiga = @.taiga
taiga.nl2br = nl2br
taiga.bindMethods = bindMethods
taiga.bindOnce = bindOnce
taiga.mixOf = mixOf
taiga.trim = trim
taiga.slugify = slugify
taiga.unslugify = unslugify
taiga.toggleText = toggleText
taiga.groupBy = groupBy
taiga.timeout = timeout
taiga.cancelTimeout = cancelTimeout
taiga.scopeDefer = scopeDefer
taiga.toString = toString
taiga.joinStr = joinStr
taiga.debounce = debounce
taiga.debounceLeading = debounceLeading
taiga.startswith = startswith
taiga.sizeFormat = sizeFormat
|
[
{
"context": "if it\n # looks like her, it's her.\n name = 'dusya'\n\n if /minus/i.test(name)\n # Another one fond",
"end": 1945,
"score": 0.9883548617362976,
"start": 1940,
"tag": "NAME",
"value": "dusya"
}
] | scripts/ayp.coffee | elg3cko/arrakis-hubot | 0 | # Scaffolds for AYP
# That good, handmade shit.
fs = require 'fs'
path = require 'path'
Url = require 'url'
Redis = require 'redis'
GD = require 'node-gd'
S3 = require 'node-s3'
## Knobs and buttons
# S3 Keys
AYP_AWS_KEY = process.env.AYP_AWS_KEY
AYP_AWS_SECRET = process.env.AYP_AWS_SECRET
AYP_AWS_BUCKET = process.env.AYP_AWS_BUCKET
# AYP The website hooks
AYP_SITE = process.env.AYP_SITE or "http://ayp.wtf.cat/"
AYP_ENDPOINT = "#{AYP_SITE}new/"
AYP_SECRET = process.env.AYP_SECRET
# The size of single panel
AYP_PANEL_WIDTH = 348
AYP_PANEL_HEIGHT = 348
# The ammount of padding on each side of a panel
AYP_PANEL_PADDING = 6
# Space left between stacked speech bubbles
# and the sides of the panel and the speech bubbles
AYP_BUBBLE_PADDING_VERTICAL = 3
AYP_BUBBLE_PADDING_HORIZONTAL = 3
# Maximum width of the speech bubble, after text becomes wider
# it is wrapped to a new line
AYP_BUBBLE_MAX_WIDTH = AYP_PANEL_WIDTH - 18
# Padding on each side of the text bubble
AYP_TEXT_PADDING = 2
# The size anf font of the text to use in the text bubbles
AYP_FONT_SIZE = 12
AYP_FONT_FILE = "DroidSans.ttf"
## Paths to find media
ROOT = path.resolve(__dirname, '..')
IMG_BASE = path.resolve(ROOT, 'ayp-template-images')
BG_BASE = path.resolve(IMG_BASE, 'bg')
AVATAR_BASE = path.resolve(IMG_BASE, 'avatars')
FONT_PATH = path.resolve(IMG_BASE, AYP_FONT_FILE)
## S3 Storage
s3 = S3("s3://#{AYP_AWS_KEY}:#{AYP_AWS_SECRET}@#{AYP_AWS_BUCKET}.s3.amazonaws.com/")
## Content filters. These can be used to change the text from the logging
## engine to be whatever is better for AGGGHHHHHHT reasons. Such as removing URLs
## or mapping a pattern of names into a single, consistent one.
# Make any changes required to the name
filterName = (name) ->
if /dusya/i.test(name)
# She likes to change her name A LOT. We can assume if it
# looks like her, it's her.
name = 'dusya'
if /minus/i.test(name)
# Another one fond of aliases
name = 'minusx'
if /laura/i.test(name)
# Some kind of laura is one kind of laura
name = 'laura'
if /arbo/i.test(name)
# Bouncers are hard or something, whatever.
name = 'arbo'
return name
# Make any changes required to the text
filterText = (text) ->
# Urls are secret. Not for you. Not for anyone.
text = text.replace(/(https?:\/\/[^\s]+)/, "[redacted]")
# Emails 'R' Secret
text = text.replace(/(?![^@\s]+@)[^@\s]+\.[^@\s]+/, "[redacted]")
# Twitter length, then truncate with `...`
limit = 140
suffix = '...'
if text.length > limit
text = text.slice(0, (limit - suffix.length))
text += suffix
return text
## Robot event bindings
module.exports = (robot) ->
buffer = new PantsBuffer()
# We listen to everything.
# Everything.
robot.catchAll (msg) ->
return if !msg.message.text
buffer.store(
msg.message.user.name.trim(),
msg.message.text.trim()
)
# Ask for what currently serves as "output"
robot.respond /ayp(\s+(me)?)?\s*$/i, (msg) ->
buffer.get 6, (err, lines) ->
# Build a strip of AYP
new AYPStrip lines, (err, image) ->
return msg.reply "SOMETHING TERRIBLE HAPPENED: #{err}" if err
# Save locally, upload, cleanup
now = Date.now()
name = "ayp-#{now}.jpg"
outPath = path.resolve("/tmp", name)
image.saveJpeg outPath, 95, (err) ->
return console.error "Failed to write result:", err if err
fs.readFile outPath, (err, data) ->
# We can unlink unconditionally now that we have it or failed
fs.unlink(outPath, ->)
return msg.reply "I somehow lost the file I just put down at #{outpath}. Like a moron :(" if err
return msg.reply "You hve no S3 creds bub" unless [AYP_AWS_KEY, AYP_AWS_SECRET, AYP_AWS_BUCKET].every (p) -> p?.length
info =
headers:
'Content-Type': 'image/jpeg'
body: data
s3.put name, info, (err) ->
return msg.reply "Woooops! Failed to upload: #{err}" if err
strip_url = "http://s3.amazonaws.com/#{AYP_AWS_BUCKET}/#{name}"
# Now let's tell `ayp.wtf.cat` about our great work here
return msg.reply "I'd update the site, but I don't know the secret :( Though, the image is #{strip_url}" unless AYP_SECRET
robot.http(AYP_ENDPOINT).
header('Content-Type', 'application/json').
post JSON.stringify(url: strip_url, time: now, secret: AYP_SECRET), (err, res, body) ->
return msg.reply "Bad news. I was fed shit when I tried to update the site: #{err}" if err
prefix = msg.random [
"GOOD NEWS EVERYONE:",
"This is awkward...",
"Turns out,",
"Despite my best efforts",
]
msg.reply "#{prefix} #{AYP_SITE}at/#{now}/ is now -> #{strip_url}"
# This wraps up everything that builds the image strips of the comic
#
# Usage:
# `new AYPStrip script, (err, image) -> ...`
# Will invoke the callback with the completed
# strip when it's ready.
class AYPStrip
# Constructor just stores the script and callback
# and passes flow to the builder.
constructor: (@script, @ready) ->
do @buildComic
# Build a comic and invoke the @ready(err, res) callback with res
# being the resulting image. `err` will be true if an error
# is encountered.
buildComic: =>
@buildPanels (err, panels) =>
return @ready(err, null) if err
loaders =
png: GD.openPng
jpg: GD.openJpeg
jpeg: GD.openJpeg
fs.readdir BG_BASE, (err, files) =>
return @ready(err, null) if err
# No hidden files
files = files.filter (f) -> f[0] != '.'
# No files we can't load
files = files.filter (f) -> loaders[f[-3..]]
selected = files[Math.round(Math.random() * (files.length - 1))]
ext = selected[-3..].toLowerCase()
loader = loaders[ext]
loader path.resolve(BG_BASE, selected), (err, bg) =>
return @ready(err, bg) if err
totalPadding = (AYP_PANEL_PADDING * 2)
left = 0
top = Math.round(totalPadding / 2)
for panel in panels
do (panel) =>
@compositeImage bg, panel, Math.round(left += (totalPadding / 2)), top
left += panel.width # Panel width
left += Math.round(totalPadding / 2)
@ready(false, bg)
# Turn the `@script` into 3 panels
# using two lines per panel, then invokes `cb`.
#
# callback invoked as `cb(err, [image, image, image])`
# Error will only be set on failure.
buildPanels: (cb) =>
failed = false
panels = [null, null, null]
# Handler for when a panel fails to build.
fail = (err) ->
cb(err, [])
return failed = true
# Handler for panel completion, store in the list, see if we're done,
# invoke callback if we are.
finishPanel = (err, n, panel) ->
# No one cares if we already lost.
return if failed
return fail(err) if err
panels[n] = panel
cb(false, panels) if panels.every (p) -> p
# TODO: There's a loop here, somewhere
@buildPanel @script[0..1], (err, panel) -> finishPanel(err, 0, panel)
@buildPanel @script[2..3], (err, panel) -> finishPanel(err, 1, panel)
@buildPanel @script[4..5], (err, panel) -> finishPanel(err, 2, panel)
# Build a single panel out of (UP TO) two lines of dialog
# cb invoked as `cb(err, image)`. `err` is only set on failure
buildPanel: (lines, cb) =>
# Setup a transparant frame that we'll composite characters and text into.
frame = GD.createTrueColor(AYP_PANEL_WIDTH, AYP_PANEL_WIDTH)
frame.saveAlpha(1)
clear = frame.colorAllocateAlpha(0, 0, 0, 127)
frame.fill(0, 0, clear)
# We can just return the empty transperant
# frame if we get no lines
return cb(false, frame) unless lines.length > 0
names = (l[0] for l in lines).
filter((v, i, a) -> a.indexOf(v) == i) # De-dupe
@loadAvatars names, (err, avatars) =>
return cb(err, null) if err
if names.length == 1
# The only person speaking is centered in the frame
char = avatars[names[0]]
left = (frame.width / 2) - (char.width / 2)
top = (frame.height - char.height)
@compositeImage frame, char, left, top
else
# We have two speakers
first = true
for line in lines
[who, what] = line
char = avatars[who]
top = (frame.height - char.height)
if first
left = 0
first = false
else
left = frame.width - char.width
@compositeImage frame, char, left, top
# Add the text after all the avatars are painted on
@drawPanelText frame, lines
# Return the frame to the caller
return cb(false, frame)
# Draw the text into a `frame` described by
# the `@script`
# No character drawing is done, just bubbles being placed.
# The avatars should already be painted, in case the text
# needs to overlap them.
drawPanelText: (frame, lines) =>
# I can render all the text unconditionally
# since it looks the same regardless of the number
# of speakers. (i.e. left -> right, top -> bottom)
first = true
top = 0
left = AYP_BUBBLE_PADDING_HORIZONTAL
topPad = AYP_BUBBLE_PADDING_VERTICAL
for line in lines
[who, what] = line
bubble = @textBubble what
if not first
left = frame.width - bubble.width - AYP_BUBBLE_PADDING_HORIZONTAL
else
first = false
@compositeImage frame, bubble, left, top
top += bubble.height + topPad
# Produce a text bubble that contains `msg` printed in the
# font `font` in the size `size`. The bubble will be at most
# `max` pixels wide, and will be padded according to `AYP_TEXT_PADDING`
#
# The return value will be a GD image.
textBubble: (msg, font=FONT_PATH, size=AYP_FONT_SIZE, max=AYP_BUBBLE_MAX_WIDTH) =>
msg = @formatForTextBubble(msg, font, size, max)
[w, h] = @textSize(msg, font, size)
frame = GD.createTrueColor(
w + (AYP_TEXT_PADDING * 2),
h + (AYP_TEXT_PADDING * 2)
)
frame.saveAlpha(1)
white = frame.colorAllocate(0xff, 0xff, 0xff)
black = frame.colorAllocate(0x00, 0x00, 0x00)
frame.fill(0, 0, white)
frame.stringFT(black, font, size,
0, # Rotation angle
AYP_TEXT_PADDING, # x
AYP_TEXT_PADDING + size + 1, # y
msg
)
return frame
##
## Helpers and utilities
# Load avatars for `names` and invoke `cb` as:
# `cb(err, {"Nickname": avatarImg, ...})`
# mapping each name to an avatar image that
# can be used to represent it.
#
# `err` is only set on failure
loadAvatars: (names, cb) =>
# Prepare requirements
names = names.map (n) -> {name: n, img: null, err: null}
failed = false
fail = (err) ->
cb(err, null)
return faliled = true
charPathForNick = (nick) ->
potential = path.resolve(AVATAR_BASE, "#{nick.toLowerCase()}.png")
return potential if (try fs.statSync(potential))
return path.resolve(AVATAR_BASE, "default.png")
for nameObj in names
do (nameObj) ->
GD.openPng charPathForNick(nameObj.name), (err, img) ->
return if failed
return fail(err) if err
nameObj.img = img unless err
# Are we done? Then build up a dictionary
# and tell the caller.
if names.every((o) -> o.img)
avatars = {}
for obj in names
avatars[obj.name] = obj.img
cb(null, avatars)
# Returns the bounding box of `msg`
# When printed using `font` of `size`
# in the form [width, height]
textSize: (msg, font, size) ->
img = GD.create(1,1)
black = img.colorAllocate(0, 0, 0)
bb = img.stringFTBBox(black, font, size, 0, 0, 0, msg)
[
bb[2] - bb[0],
bb[1] - bb[7]
]
# Splits the input `msg` into a list of
# `splits` chunks performing word wrapping on
# each chunk as in ["Hello", "World"]
chunkInputInto: (msg, splits) ->
stepSize = Math.round(msg.length / splits)
chunks = []
for n in [0...splits]
chunks[n] = msg[...stepSize]
msg = msg[stepSize..]
# Shift words down until the last space in this line and
# give them back to the buffer
while not /\s$/.test(chunks[n])
chunkLen = chunks[n].length
msg = "#{chunks[n][chunkLen - 1]}#{msg}"
chunks[n] = chunks[n][...-1]
# If we somehow have some message left over, shove it
# into the last chunk.
if msg.length
chunks[chunks.length - 1] += msg
return chunks.map (c) -> c.trim()
# Prpares a string `msg` for prtinting with `font`
# at size `size` that will fit into `max`. The string
# will be broken into multiple lines so that it does not
# exceed `max` pixels
formatForTextBubble: (msg, font, size, max) =>
msg = msg.trim()
[w, h] = @textSize(msg, font, size)
if w > max
splits = Math.round(w / max)
splits += 1 if w % max
msg = @chunkInputInto(msg, splits).join "\n"
else
msg
# Composite `sprite` onto `dst` in full.
# Offsets `sprite` `+left` from the left
# and `+top` from the top
compositeImage: (dst, sprite, left, top) ->
dim = [sprite.width, sprite.height]
left = Math.round(left)
top = Math.round(top)
sprite.copyResampled dst,
left, top, # dst x, y
0, 0, # src x, y
dim..., dim... # No size change
return dst
# PantsBuffer is the abstraction of "The Logs".
#
# It keeps a ringbuffer of logs configured on construction
# and fed by `.store(who, what)` which computes timestamps
# and allows you to get n random lines with `.get`.
#
# Fetches are asyncronous, because NODE JS NINJA REDIS
class PantsBuffer
# The zset that stores the buffer of logs
key: -> "#{@options.prefix}:buffer"
# Get an array of `n` lines from the log.
# When data arrives the callback will be called
# as cb(err, data). `err` will be only be set on
# error. `res` will be an array of lines.
get: (n, callback) ->
# This wraps the supplied `callback` to process the resulting
# list into a list of [[who, what], ...] to save the consumer
# a step.
# In case of error, the result is untouched
resultWrapper = (err, res) ->
return callback(err, res) if err
res = res.map (line) ->
[_, who, what] = line.toString('utf8').match(/^([^\s]+): (.+)$/)
[filterName(who), filterText(what)]
callback(err, res)
@storage.zcard @key(), (err, count) =>
return console.error("Failed zcard of #{@key()}: #{err}") if err
# If we don't have enough lines, return all the lines we have
return @storage.zrange @key(), 0, -1, resultWrapper if count <= n
# Get a random offset where we can grab n lines otherwise
start = Math.round(Math.random() * (count - n))
return @storage.zrange @key(), start, (start + (n - 1)), resultWrapper
# Store and timestamp `who` saying `what`.
# Also trims the set with `@trim` to the configured
# length
store: (who, what) ->
do @trim
stamp = Date.now()
body = "#{who}: #{what}"
@storage.zadd [@key(), stamp, body], (err, response) =>
return console.error "WARNING: Failed to store: '#{who}: #{what}' @ #{stmp}: #{err}" if err
# Trim the logging buffer to `@options.days` since we don't care about
# being a general purpose logger.
trim: ->
days = @options.days
end = Date.now() - (
days * # Days
24 * # Hours
60 * # Minutes
60 * # Seconds
1000 # ms
)
@storage.zremrangebyscore @key(), 0, end, (err, response) =>
return console.error "WARNING: Failed to trim '#{@key()}': #{err}" if err
# Constructor for `PantsBuffer`
#
# Options:
# prefix: The redis prefix to use for the ringbuffer.
# days: The number of days to keep logs in the buffer
constructor: (@options={}) ->
# Connect to redis
info = Url.parse process.env.REDISTOGO_URL or
process.env.REDISCLOUD_URL or
process.env.BOXEN_REDIS_URL or
'redis://localhost:6379'
@storage = Redis.createClient(info.port, info.hostname)
@storage.auth info.auth.split(":")[1] if info.auth
# Defaults for options
@options.prefix ?= "ayp:"
@options.days ?= 3
| 129567 | # Scaffolds for AYP
# That good, handmade shit.
fs = require 'fs'
path = require 'path'
Url = require 'url'
Redis = require 'redis'
GD = require 'node-gd'
S3 = require 'node-s3'
## Knobs and buttons
# S3 Keys
AYP_AWS_KEY = process.env.AYP_AWS_KEY
AYP_AWS_SECRET = process.env.AYP_AWS_SECRET
AYP_AWS_BUCKET = process.env.AYP_AWS_BUCKET
# AYP The website hooks
AYP_SITE = process.env.AYP_SITE or "http://ayp.wtf.cat/"
AYP_ENDPOINT = "#{AYP_SITE}new/"
AYP_SECRET = process.env.AYP_SECRET
# The size of single panel
AYP_PANEL_WIDTH = 348
AYP_PANEL_HEIGHT = 348
# The ammount of padding on each side of a panel
AYP_PANEL_PADDING = 6
# Space left between stacked speech bubbles
# and the sides of the panel and the speech bubbles
AYP_BUBBLE_PADDING_VERTICAL = 3
AYP_BUBBLE_PADDING_HORIZONTAL = 3
# Maximum width of the speech bubble, after text becomes wider
# it is wrapped to a new line
AYP_BUBBLE_MAX_WIDTH = AYP_PANEL_WIDTH - 18
# Padding on each side of the text bubble
AYP_TEXT_PADDING = 2
# The size anf font of the text to use in the text bubbles
AYP_FONT_SIZE = 12
AYP_FONT_FILE = "DroidSans.ttf"
## Paths to find media
ROOT = path.resolve(__dirname, '..')
IMG_BASE = path.resolve(ROOT, 'ayp-template-images')
BG_BASE = path.resolve(IMG_BASE, 'bg')
AVATAR_BASE = path.resolve(IMG_BASE, 'avatars')
FONT_PATH = path.resolve(IMG_BASE, AYP_FONT_FILE)
## S3 Storage
s3 = S3("s3://#{AYP_AWS_KEY}:#{AYP_AWS_SECRET}@#{AYP_AWS_BUCKET}.s3.amazonaws.com/")
## Content filters. These can be used to change the text from the logging
## engine to be whatever is better for AGGGHHHHHHT reasons. Such as removing URLs
## or mapping a pattern of names into a single, consistent one.
# Make any changes required to the name
filterName = (name) ->
if /dusya/i.test(name)
# She likes to change her name A LOT. We can assume if it
# looks like her, it's her.
name = '<NAME>'
if /minus/i.test(name)
# Another one fond of aliases
name = 'minusx'
if /laura/i.test(name)
# Some kind of laura is one kind of laura
name = 'laura'
if /arbo/i.test(name)
# Bouncers are hard or something, whatever.
name = 'arbo'
return name
# Make any changes required to the text
filterText = (text) ->
# Urls are secret. Not for you. Not for anyone.
text = text.replace(/(https?:\/\/[^\s]+)/, "[redacted]")
# Emails 'R' Secret
text = text.replace(/(?![^@\s]+@)[^@\s]+\.[^@\s]+/, "[redacted]")
# Twitter length, then truncate with `...`
limit = 140
suffix = '...'
if text.length > limit
text = text.slice(0, (limit - suffix.length))
text += suffix
return text
## Robot event bindings
module.exports = (robot) ->
buffer = new PantsBuffer()
# We listen to everything.
# Everything.
robot.catchAll (msg) ->
return if !msg.message.text
buffer.store(
msg.message.user.name.trim(),
msg.message.text.trim()
)
# Ask for what currently serves as "output"
robot.respond /ayp(\s+(me)?)?\s*$/i, (msg) ->
buffer.get 6, (err, lines) ->
# Build a strip of AYP
new AYPStrip lines, (err, image) ->
return msg.reply "SOMETHING TERRIBLE HAPPENED: #{err}" if err
# Save locally, upload, cleanup
now = Date.now()
name = "ayp-#{now}.jpg"
outPath = path.resolve("/tmp", name)
image.saveJpeg outPath, 95, (err) ->
return console.error "Failed to write result:", err if err
fs.readFile outPath, (err, data) ->
# We can unlink unconditionally now that we have it or failed
fs.unlink(outPath, ->)
return msg.reply "I somehow lost the file I just put down at #{outpath}. Like a moron :(" if err
return msg.reply "You hve no S3 creds bub" unless [AYP_AWS_KEY, AYP_AWS_SECRET, AYP_AWS_BUCKET].every (p) -> p?.length
info =
headers:
'Content-Type': 'image/jpeg'
body: data
s3.put name, info, (err) ->
return msg.reply "Woooops! Failed to upload: #{err}" if err
strip_url = "http://s3.amazonaws.com/#{AYP_AWS_BUCKET}/#{name}"
# Now let's tell `ayp.wtf.cat` about our great work here
return msg.reply "I'd update the site, but I don't know the secret :( Though, the image is #{strip_url}" unless AYP_SECRET
robot.http(AYP_ENDPOINT).
header('Content-Type', 'application/json').
post JSON.stringify(url: strip_url, time: now, secret: AYP_SECRET), (err, res, body) ->
return msg.reply "Bad news. I was fed shit when I tried to update the site: #{err}" if err
prefix = msg.random [
"GOOD NEWS EVERYONE:",
"This is awkward...",
"Turns out,",
"Despite my best efforts",
]
msg.reply "#{prefix} #{AYP_SITE}at/#{now}/ is now -> #{strip_url}"
# This wraps up everything that builds the image strips of the comic
#
# Usage:
# `new AYPStrip script, (err, image) -> ...`
# Will invoke the callback with the completed
# strip when it's ready.
class AYPStrip
# Constructor just stores the script and callback
# and passes flow to the builder.
constructor: (@script, @ready) ->
do @buildComic
# Build a comic and invoke the @ready(err, res) callback with res
# being the resulting image. `err` will be true if an error
# is encountered.
buildComic: =>
@buildPanels (err, panels) =>
return @ready(err, null) if err
loaders =
png: GD.openPng
jpg: GD.openJpeg
jpeg: GD.openJpeg
fs.readdir BG_BASE, (err, files) =>
return @ready(err, null) if err
# No hidden files
files = files.filter (f) -> f[0] != '.'
# No files we can't load
files = files.filter (f) -> loaders[f[-3..]]
selected = files[Math.round(Math.random() * (files.length - 1))]
ext = selected[-3..].toLowerCase()
loader = loaders[ext]
loader path.resolve(BG_BASE, selected), (err, bg) =>
return @ready(err, bg) if err
totalPadding = (AYP_PANEL_PADDING * 2)
left = 0
top = Math.round(totalPadding / 2)
for panel in panels
do (panel) =>
@compositeImage bg, panel, Math.round(left += (totalPadding / 2)), top
left += panel.width # Panel width
left += Math.round(totalPadding / 2)
@ready(false, bg)
# Turn the `@script` into 3 panels
# using two lines per panel, then invokes `cb`.
#
# callback invoked as `cb(err, [image, image, image])`
# Error will only be set on failure.
buildPanels: (cb) =>
failed = false
panels = [null, null, null]
# Handler for when a panel fails to build.
fail = (err) ->
cb(err, [])
return failed = true
# Handler for panel completion, store in the list, see if we're done,
# invoke callback if we are.
finishPanel = (err, n, panel) ->
# No one cares if we already lost.
return if failed
return fail(err) if err
panels[n] = panel
cb(false, panels) if panels.every (p) -> p
# TODO: There's a loop here, somewhere
@buildPanel @script[0..1], (err, panel) -> finishPanel(err, 0, panel)
@buildPanel @script[2..3], (err, panel) -> finishPanel(err, 1, panel)
@buildPanel @script[4..5], (err, panel) -> finishPanel(err, 2, panel)
# Build a single panel out of (UP TO) two lines of dialog
# cb invoked as `cb(err, image)`. `err` is only set on failure
buildPanel: (lines, cb) =>
# Setup a transparant frame that we'll composite characters and text into.
frame = GD.createTrueColor(AYP_PANEL_WIDTH, AYP_PANEL_WIDTH)
frame.saveAlpha(1)
clear = frame.colorAllocateAlpha(0, 0, 0, 127)
frame.fill(0, 0, clear)
# We can just return the empty transperant
# frame if we get no lines
return cb(false, frame) unless lines.length > 0
names = (l[0] for l in lines).
filter((v, i, a) -> a.indexOf(v) == i) # De-dupe
@loadAvatars names, (err, avatars) =>
return cb(err, null) if err
if names.length == 1
# The only person speaking is centered in the frame
char = avatars[names[0]]
left = (frame.width / 2) - (char.width / 2)
top = (frame.height - char.height)
@compositeImage frame, char, left, top
else
# We have two speakers
first = true
for line in lines
[who, what] = line
char = avatars[who]
top = (frame.height - char.height)
if first
left = 0
first = false
else
left = frame.width - char.width
@compositeImage frame, char, left, top
# Add the text after all the avatars are painted on
@drawPanelText frame, lines
# Return the frame to the caller
return cb(false, frame)
# Draw the text into a `frame` described by
# the `@script`
# No character drawing is done, just bubbles being placed.
# The avatars should already be painted, in case the text
# needs to overlap them.
drawPanelText: (frame, lines) =>
# I can render all the text unconditionally
# since it looks the same regardless of the number
# of speakers. (i.e. left -> right, top -> bottom)
first = true
top = 0
left = AYP_BUBBLE_PADDING_HORIZONTAL
topPad = AYP_BUBBLE_PADDING_VERTICAL
for line in lines
[who, what] = line
bubble = @textBubble what
if not first
left = frame.width - bubble.width - AYP_BUBBLE_PADDING_HORIZONTAL
else
first = false
@compositeImage frame, bubble, left, top
top += bubble.height + topPad
# Produce a text bubble that contains `msg` printed in the
# font `font` in the size `size`. The bubble will be at most
# `max` pixels wide, and will be padded according to `AYP_TEXT_PADDING`
#
# The return value will be a GD image.
textBubble: (msg, font=FONT_PATH, size=AYP_FONT_SIZE, max=AYP_BUBBLE_MAX_WIDTH) =>
msg = @formatForTextBubble(msg, font, size, max)
[w, h] = @textSize(msg, font, size)
frame = GD.createTrueColor(
w + (AYP_TEXT_PADDING * 2),
h + (AYP_TEXT_PADDING * 2)
)
frame.saveAlpha(1)
white = frame.colorAllocate(0xff, 0xff, 0xff)
black = frame.colorAllocate(0x00, 0x00, 0x00)
frame.fill(0, 0, white)
frame.stringFT(black, font, size,
0, # Rotation angle
AYP_TEXT_PADDING, # x
AYP_TEXT_PADDING + size + 1, # y
msg
)
return frame
##
## Helpers and utilities
# Load avatars for `names` and invoke `cb` as:
# `cb(err, {"Nickname": avatarImg, ...})`
# mapping each name to an avatar image that
# can be used to represent it.
#
# `err` is only set on failure
loadAvatars: (names, cb) =>
# Prepare requirements
names = names.map (n) -> {name: n, img: null, err: null}
failed = false
fail = (err) ->
cb(err, null)
return faliled = true
charPathForNick = (nick) ->
potential = path.resolve(AVATAR_BASE, "#{nick.toLowerCase()}.png")
return potential if (try fs.statSync(potential))
return path.resolve(AVATAR_BASE, "default.png")
for nameObj in names
do (nameObj) ->
GD.openPng charPathForNick(nameObj.name), (err, img) ->
return if failed
return fail(err) if err
nameObj.img = img unless err
# Are we done? Then build up a dictionary
# and tell the caller.
if names.every((o) -> o.img)
avatars = {}
for obj in names
avatars[obj.name] = obj.img
cb(null, avatars)
# Returns the bounding box of `msg`
# When printed using `font` of `size`
# in the form [width, height]
textSize: (msg, font, size) ->
img = GD.create(1,1)
black = img.colorAllocate(0, 0, 0)
bb = img.stringFTBBox(black, font, size, 0, 0, 0, msg)
[
bb[2] - bb[0],
bb[1] - bb[7]
]
# Splits the input `msg` into a list of
# `splits` chunks performing word wrapping on
# each chunk as in ["Hello", "World"]
chunkInputInto: (msg, splits) ->
stepSize = Math.round(msg.length / splits)
chunks = []
for n in [0...splits]
chunks[n] = msg[...stepSize]
msg = msg[stepSize..]
# Shift words down until the last space in this line and
# give them back to the buffer
while not /\s$/.test(chunks[n])
chunkLen = chunks[n].length
msg = "#{chunks[n][chunkLen - 1]}#{msg}"
chunks[n] = chunks[n][...-1]
# If we somehow have some message left over, shove it
# into the last chunk.
if msg.length
chunks[chunks.length - 1] += msg
return chunks.map (c) -> c.trim()
# Prpares a string `msg` for prtinting with `font`
# at size `size` that will fit into `max`. The string
# will be broken into multiple lines so that it does not
# exceed `max` pixels
formatForTextBubble: (msg, font, size, max) =>
msg = msg.trim()
[w, h] = @textSize(msg, font, size)
if w > max
splits = Math.round(w / max)
splits += 1 if w % max
msg = @chunkInputInto(msg, splits).join "\n"
else
msg
# Composite `sprite` onto `dst` in full.
# Offsets `sprite` `+left` from the left
# and `+top` from the top
compositeImage: (dst, sprite, left, top) ->
dim = [sprite.width, sprite.height]
left = Math.round(left)
top = Math.round(top)
sprite.copyResampled dst,
left, top, # dst x, y
0, 0, # src x, y
dim..., dim... # No size change
return dst
# PantsBuffer is the abstraction of "The Logs".
#
# It keeps a ringbuffer of logs configured on construction
# and fed by `.store(who, what)` which computes timestamps
# and allows you to get n random lines with `.get`.
#
# Fetches are asyncronous, because NODE JS NINJA REDIS
class PantsBuffer
# The zset that stores the buffer of logs
key: -> "#{@options.prefix}:buffer"
# Get an array of `n` lines from the log.
# When data arrives the callback will be called
# as cb(err, data). `err` will be only be set on
# error. `res` will be an array of lines.
get: (n, callback) ->
# This wraps the supplied `callback` to process the resulting
# list into a list of [[who, what], ...] to save the consumer
# a step.
# In case of error, the result is untouched
resultWrapper = (err, res) ->
return callback(err, res) if err
res = res.map (line) ->
[_, who, what] = line.toString('utf8').match(/^([^\s]+): (.+)$/)
[filterName(who), filterText(what)]
callback(err, res)
@storage.zcard @key(), (err, count) =>
return console.error("Failed zcard of #{@key()}: #{err}") if err
# If we don't have enough lines, return all the lines we have
return @storage.zrange @key(), 0, -1, resultWrapper if count <= n
# Get a random offset where we can grab n lines otherwise
start = Math.round(Math.random() * (count - n))
return @storage.zrange @key(), start, (start + (n - 1)), resultWrapper
# Store and timestamp `who` saying `what`.
# Also trims the set with `@trim` to the configured
# length
store: (who, what) ->
do @trim
stamp = Date.now()
body = "#{who}: #{what}"
@storage.zadd [@key(), stamp, body], (err, response) =>
return console.error "WARNING: Failed to store: '#{who}: #{what}' @ #{stmp}: #{err}" if err
# Trim the logging buffer to `@options.days` since we don't care about
# being a general purpose logger.
trim: ->
days = @options.days
end = Date.now() - (
days * # Days
24 * # Hours
60 * # Minutes
60 * # Seconds
1000 # ms
)
@storage.zremrangebyscore @key(), 0, end, (err, response) =>
return console.error "WARNING: Failed to trim '#{@key()}': #{err}" if err
# Constructor for `PantsBuffer`
#
# Options:
# prefix: The redis prefix to use for the ringbuffer.
# days: The number of days to keep logs in the buffer
constructor: (@options={}) ->
# Connect to redis
info = Url.parse process.env.REDISTOGO_URL or
process.env.REDISCLOUD_URL or
process.env.BOXEN_REDIS_URL or
'redis://localhost:6379'
@storage = Redis.createClient(info.port, info.hostname)
@storage.auth info.auth.split(":")[1] if info.auth
# Defaults for options
@options.prefix ?= "ayp:"
@options.days ?= 3
| true | # Scaffolds for AYP
# That good, handmade shit.
fs = require 'fs'
path = require 'path'
Url = require 'url'
Redis = require 'redis'
GD = require 'node-gd'
S3 = require 'node-s3'
## Knobs and buttons
# S3 Keys
AYP_AWS_KEY = process.env.AYP_AWS_KEY
AYP_AWS_SECRET = process.env.AYP_AWS_SECRET
AYP_AWS_BUCKET = process.env.AYP_AWS_BUCKET
# AYP The website hooks
AYP_SITE = process.env.AYP_SITE or "http://ayp.wtf.cat/"
AYP_ENDPOINT = "#{AYP_SITE}new/"
AYP_SECRET = process.env.AYP_SECRET
# The size of single panel
AYP_PANEL_WIDTH = 348
AYP_PANEL_HEIGHT = 348
# The ammount of padding on each side of a panel
AYP_PANEL_PADDING = 6
# Space left between stacked speech bubbles
# and the sides of the panel and the speech bubbles
AYP_BUBBLE_PADDING_VERTICAL = 3
AYP_BUBBLE_PADDING_HORIZONTAL = 3
# Maximum width of the speech bubble, after text becomes wider
# it is wrapped to a new line
AYP_BUBBLE_MAX_WIDTH = AYP_PANEL_WIDTH - 18
# Padding on each side of the text bubble
AYP_TEXT_PADDING = 2
# The size anf font of the text to use in the text bubbles
AYP_FONT_SIZE = 12
AYP_FONT_FILE = "DroidSans.ttf"
## Paths to find media
ROOT = path.resolve(__dirname, '..')
IMG_BASE = path.resolve(ROOT, 'ayp-template-images')
BG_BASE = path.resolve(IMG_BASE, 'bg')
AVATAR_BASE = path.resolve(IMG_BASE, 'avatars')
FONT_PATH = path.resolve(IMG_BASE, AYP_FONT_FILE)
## S3 Storage
s3 = S3("s3://#{AYP_AWS_KEY}:#{AYP_AWS_SECRET}@#{AYP_AWS_BUCKET}.s3.amazonaws.com/")
## Content filters. These can be used to change the text from the logging
## engine to be whatever is better for AGGGHHHHHHT reasons. Such as removing URLs
## or mapping a pattern of names into a single, consistent one.
# Make any changes required to the name
filterName = (name) ->
if /dusya/i.test(name)
# She likes to change her name A LOT. We can assume if it
# looks like her, it's her.
name = 'PI:NAME:<NAME>END_PI'
if /minus/i.test(name)
# Another one fond of aliases
name = 'minusx'
if /laura/i.test(name)
# Some kind of laura is one kind of laura
name = 'laura'
if /arbo/i.test(name)
# Bouncers are hard or something, whatever.
name = 'arbo'
return name
# Make any changes required to the text
filterText = (text) ->
# Urls are secret. Not for you. Not for anyone.
text = text.replace(/(https?:\/\/[^\s]+)/, "[redacted]")
# Emails 'R' Secret
text = text.replace(/(?![^@\s]+@)[^@\s]+\.[^@\s]+/, "[redacted]")
# Twitter length, then truncate with `...`
limit = 140
suffix = '...'
if text.length > limit
text = text.slice(0, (limit - suffix.length))
text += suffix
return text
## Robot event bindings
module.exports = (robot) ->
buffer = new PantsBuffer()
# We listen to everything.
# Everything.
robot.catchAll (msg) ->
return if !msg.message.text
buffer.store(
msg.message.user.name.trim(),
msg.message.text.trim()
)
# Ask for what currently serves as "output"
robot.respond /ayp(\s+(me)?)?\s*$/i, (msg) ->
buffer.get 6, (err, lines) ->
# Build a strip of AYP
new AYPStrip lines, (err, image) ->
return msg.reply "SOMETHING TERRIBLE HAPPENED: #{err}" if err
# Save locally, upload, cleanup
now = Date.now()
name = "ayp-#{now}.jpg"
outPath = path.resolve("/tmp", name)
image.saveJpeg outPath, 95, (err) ->
return console.error "Failed to write result:", err if err
fs.readFile outPath, (err, data) ->
# We can unlink unconditionally now that we have it or failed
fs.unlink(outPath, ->)
return msg.reply "I somehow lost the file I just put down at #{outpath}. Like a moron :(" if err
return msg.reply "You hve no S3 creds bub" unless [AYP_AWS_KEY, AYP_AWS_SECRET, AYP_AWS_BUCKET].every (p) -> p?.length
info =
headers:
'Content-Type': 'image/jpeg'
body: data
s3.put name, info, (err) ->
return msg.reply "Woooops! Failed to upload: #{err}" if err
strip_url = "http://s3.amazonaws.com/#{AYP_AWS_BUCKET}/#{name}"
# Now let's tell `ayp.wtf.cat` about our great work here
return msg.reply "I'd update the site, but I don't know the secret :( Though, the image is #{strip_url}" unless AYP_SECRET
robot.http(AYP_ENDPOINT).
header('Content-Type', 'application/json').
post JSON.stringify(url: strip_url, time: now, secret: AYP_SECRET), (err, res, body) ->
return msg.reply "Bad news. I was fed shit when I tried to update the site: #{err}" if err
prefix = msg.random [
"GOOD NEWS EVERYONE:",
"This is awkward...",
"Turns out,",
"Despite my best efforts",
]
msg.reply "#{prefix} #{AYP_SITE}at/#{now}/ is now -> #{strip_url}"
# This wraps up everything that builds the image strips of the comic
#
# Usage:
# `new AYPStrip script, (err, image) -> ...`
# Will invoke the callback with the completed
# strip when it's ready.
class AYPStrip
# Constructor just stores the script and callback
# and passes flow to the builder.
constructor: (@script, @ready) ->
do @buildComic
# Build a comic and invoke the @ready(err, res) callback with res
# being the resulting image. `err` will be true if an error
# is encountered.
buildComic: =>
@buildPanels (err, panels) =>
return @ready(err, null) if err
loaders =
png: GD.openPng
jpg: GD.openJpeg
jpeg: GD.openJpeg
fs.readdir BG_BASE, (err, files) =>
return @ready(err, null) if err
# No hidden files
files = files.filter (f) -> f[0] != '.'
# No files we can't load
files = files.filter (f) -> loaders[f[-3..]]
selected = files[Math.round(Math.random() * (files.length - 1))]
ext = selected[-3..].toLowerCase()
loader = loaders[ext]
loader path.resolve(BG_BASE, selected), (err, bg) =>
return @ready(err, bg) if err
totalPadding = (AYP_PANEL_PADDING * 2)
left = 0
top = Math.round(totalPadding / 2)
for panel in panels
do (panel) =>
@compositeImage bg, panel, Math.round(left += (totalPadding / 2)), top
left += panel.width # Panel width
left += Math.round(totalPadding / 2)
@ready(false, bg)
# Turn the `@script` into 3 panels
# using two lines per panel, then invokes `cb`.
#
# callback invoked as `cb(err, [image, image, image])`
# Error will only be set on failure.
buildPanels: (cb) =>
failed = false
panels = [null, null, null]
# Handler for when a panel fails to build.
fail = (err) ->
cb(err, [])
return failed = true
# Handler for panel completion, store in the list, see if we're done,
# invoke callback if we are.
finishPanel = (err, n, panel) ->
# No one cares if we already lost.
return if failed
return fail(err) if err
panels[n] = panel
cb(false, panels) if panels.every (p) -> p
# TODO: There's a loop here, somewhere
@buildPanel @script[0..1], (err, panel) -> finishPanel(err, 0, panel)
@buildPanel @script[2..3], (err, panel) -> finishPanel(err, 1, panel)
@buildPanel @script[4..5], (err, panel) -> finishPanel(err, 2, panel)
# Build a single panel out of (UP TO) two lines of dialog
# cb invoked as `cb(err, image)`. `err` is only set on failure
buildPanel: (lines, cb) =>
# Setup a transparant frame that we'll composite characters and text into.
frame = GD.createTrueColor(AYP_PANEL_WIDTH, AYP_PANEL_WIDTH)
frame.saveAlpha(1)
clear = frame.colorAllocateAlpha(0, 0, 0, 127)
frame.fill(0, 0, clear)
# We can just return the empty transperant
# frame if we get no lines
return cb(false, frame) unless lines.length > 0
names = (l[0] for l in lines).
filter((v, i, a) -> a.indexOf(v) == i) # De-dupe
@loadAvatars names, (err, avatars) =>
return cb(err, null) if err
if names.length == 1
# The only person speaking is centered in the frame
char = avatars[names[0]]
left = (frame.width / 2) - (char.width / 2)
top = (frame.height - char.height)
@compositeImage frame, char, left, top
else
# We have two speakers
first = true
for line in lines
[who, what] = line
char = avatars[who]
top = (frame.height - char.height)
if first
left = 0
first = false
else
left = frame.width - char.width
@compositeImage frame, char, left, top
# Add the text after all the avatars are painted on
@drawPanelText frame, lines
# Return the frame to the caller
return cb(false, frame)
# Draw the text into a `frame` described by
# the `@script`
# No character drawing is done, just bubbles being placed.
# The avatars should already be painted, in case the text
# needs to overlap them.
drawPanelText: (frame, lines) =>
# I can render all the text unconditionally
# since it looks the same regardless of the number
# of speakers. (i.e. left -> right, top -> bottom)
first = true
top = 0
left = AYP_BUBBLE_PADDING_HORIZONTAL
topPad = AYP_BUBBLE_PADDING_VERTICAL
for line in lines
[who, what] = line
bubble = @textBubble what
if not first
left = frame.width - bubble.width - AYP_BUBBLE_PADDING_HORIZONTAL
else
first = false
@compositeImage frame, bubble, left, top
top += bubble.height + topPad
# Produce a text bubble that contains `msg` printed in the
# font `font` in the size `size`. The bubble will be at most
# `max` pixels wide, and will be padded according to `AYP_TEXT_PADDING`
#
# The return value will be a GD image.
textBubble: (msg, font=FONT_PATH, size=AYP_FONT_SIZE, max=AYP_BUBBLE_MAX_WIDTH) =>
msg = @formatForTextBubble(msg, font, size, max)
[w, h] = @textSize(msg, font, size)
frame = GD.createTrueColor(
w + (AYP_TEXT_PADDING * 2),
h + (AYP_TEXT_PADDING * 2)
)
frame.saveAlpha(1)
white = frame.colorAllocate(0xff, 0xff, 0xff)
black = frame.colorAllocate(0x00, 0x00, 0x00)
frame.fill(0, 0, white)
frame.stringFT(black, font, size,
0, # Rotation angle
AYP_TEXT_PADDING, # x
AYP_TEXT_PADDING + size + 1, # y
msg
)
return frame
##
## Helpers and utilities
# Load avatars for `names` and invoke `cb` as:
# `cb(err, {"Nickname": avatarImg, ...})`
# mapping each name to an avatar image that
# can be used to represent it.
#
# `err` is only set on failure
loadAvatars: (names, cb) =>
# Prepare requirements
names = names.map (n) -> {name: n, img: null, err: null}
failed = false
fail = (err) ->
cb(err, null)
return faliled = true
charPathForNick = (nick) ->
potential = path.resolve(AVATAR_BASE, "#{nick.toLowerCase()}.png")
return potential if (try fs.statSync(potential))
return path.resolve(AVATAR_BASE, "default.png")
for nameObj in names
do (nameObj) ->
GD.openPng charPathForNick(nameObj.name), (err, img) ->
return if failed
return fail(err) if err
nameObj.img = img unless err
# Are we done? Then build up a dictionary
# and tell the caller.
if names.every((o) -> o.img)
avatars = {}
for obj in names
avatars[obj.name] = obj.img
cb(null, avatars)
# Returns the bounding box of `msg`
# When printed using `font` of `size`
# in the form [width, height]
textSize: (msg, font, size) ->
img = GD.create(1,1)
black = img.colorAllocate(0, 0, 0)
bb = img.stringFTBBox(black, font, size, 0, 0, 0, msg)
[
bb[2] - bb[0],
bb[1] - bb[7]
]
# Splits the input `msg` into a list of
# `splits` chunks performing word wrapping on
# each chunk as in ["Hello", "World"]
chunkInputInto: (msg, splits) ->
stepSize = Math.round(msg.length / splits)
chunks = []
for n in [0...splits]
chunks[n] = msg[...stepSize]
msg = msg[stepSize..]
# Shift words down until the last space in this line and
# give them back to the buffer
while not /\s$/.test(chunks[n])
chunkLen = chunks[n].length
msg = "#{chunks[n][chunkLen - 1]}#{msg}"
chunks[n] = chunks[n][...-1]
# If we somehow have some message left over, shove it
# into the last chunk.
if msg.length
chunks[chunks.length - 1] += msg
return chunks.map (c) -> c.trim()
# Prpares a string `msg` for prtinting with `font`
# at size `size` that will fit into `max`. The string
# will be broken into multiple lines so that it does not
# exceed `max` pixels
formatForTextBubble: (msg, font, size, max) =>
msg = msg.trim()
[w, h] = @textSize(msg, font, size)
if w > max
splits = Math.round(w / max)
splits += 1 if w % max
msg = @chunkInputInto(msg, splits).join "\n"
else
msg
# Composite `sprite` onto `dst` in full.
# Offsets `sprite` `+left` from the left
# and `+top` from the top
compositeImage: (dst, sprite, left, top) ->
dim = [sprite.width, sprite.height]
left = Math.round(left)
top = Math.round(top)
sprite.copyResampled dst,
left, top, # dst x, y
0, 0, # src x, y
dim..., dim... # No size change
return dst
# PantsBuffer is the abstraction of "The Logs".
#
# It keeps a ringbuffer of logs configured on construction
# and fed by `.store(who, what)` which computes timestamps
# and allows you to get n random lines with `.get`.
#
# Fetches are asyncronous, because NODE JS NINJA REDIS
class PantsBuffer
# The zset that stores the buffer of logs
key: -> "#{@options.prefix}:buffer"
# Get an array of `n` lines from the log.
# When data arrives the callback will be called
# as cb(err, data). `err` will be only be set on
# error. `res` will be an array of lines.
get: (n, callback) ->
# This wraps the supplied `callback` to process the resulting
# list into a list of [[who, what], ...] to save the consumer
# a step.
# In case of error, the result is untouched
resultWrapper = (err, res) ->
return callback(err, res) if err
res = res.map (line) ->
[_, who, what] = line.toString('utf8').match(/^([^\s]+): (.+)$/)
[filterName(who), filterText(what)]
callback(err, res)
@storage.zcard @key(), (err, count) =>
return console.error("Failed zcard of #{@key()}: #{err}") if err
# If we don't have enough lines, return all the lines we have
return @storage.zrange @key(), 0, -1, resultWrapper if count <= n
# Get a random offset where we can grab n lines otherwise
start = Math.round(Math.random() * (count - n))
return @storage.zrange @key(), start, (start + (n - 1)), resultWrapper
# Store and timestamp `who` saying `what`.
# Also trims the set with `@trim` to the configured
# length
store: (who, what) ->
do @trim
stamp = Date.now()
body = "#{who}: #{what}"
@storage.zadd [@key(), stamp, body], (err, response) =>
return console.error "WARNING: Failed to store: '#{who}: #{what}' @ #{stmp}: #{err}" if err
# Trim the logging buffer to `@options.days` since we don't care about
# being a general purpose logger.
trim: ->
days = @options.days
end = Date.now() - (
days * # Days
24 * # Hours
60 * # Minutes
60 * # Seconds
1000 # ms
)
@storage.zremrangebyscore @key(), 0, end, (err, response) =>
return console.error "WARNING: Failed to trim '#{@key()}': #{err}" if err
# Constructor for `PantsBuffer`
#
# Options:
# prefix: The redis prefix to use for the ringbuffer.
# days: The number of days to keep logs in the buffer
constructor: (@options={}) ->
# Connect to redis
info = Url.parse process.env.REDISTOGO_URL or
process.env.REDISCLOUD_URL or
process.env.BOXEN_REDIS_URL or
'redis://localhost:6379'
@storage = Redis.createClient(info.port, info.hostname)
@storage.auth info.auth.split(":")[1] if info.auth
# Defaults for options
@options.prefix ?= "ayp:"
@options.days ?= 3
|
[
{
"context": "nCents\n currency: 'usd'\n name: 'Untitler'\n email: scope.email\n descripti",
"end": 712,
"score": 0.998164176940918,
"start": 704,
"tag": "NAME",
"value": "Untitler"
}
] | app/scripts/ng-modules/stripe/directives/stripe-checkout.coffee | willow/price-buddy-ui | 0 | 'use strict'
angular.module('stripe.directives')
.directive "stripeCheckout", (StripeCheckout, AppConfig) ->
restrict: 'A'
transclude: false
scope:
amount: '@'
description: '@'
image: '@'
email: '@'
paymentCallback: '&'
link: (scope, elem, attrs) ->
amountInCents = parseInt(scope.amount * 100)
elem.on 'click', ->
displayCheckout()
scope.$on "payment:checkout:display", (event, args)->
displayCheckout()
displayCheckout = ->
elem.attr 'disabled', 'disabled'
StripeCheckout.open
key: AppConfig.STRIPE_PUBLIC_KEY
amount: amountInCents
currency: 'usd'
name: 'Untitler'
email: scope.email
description: scope.description
image: scope.image
closed: ->
(scope.$apply ->
elem.removeAttr 'disabled') unless scope.paid?
token: (token) ->
#there is a bug with stripe checkout where it will fire multiple `token` callbacks
unless scope.paid
scope.$apply ->
scope.paid = true
scope.paymentCallback token: token
| 88238 | 'use strict'
angular.module('stripe.directives')
.directive "stripeCheckout", (StripeCheckout, AppConfig) ->
restrict: 'A'
transclude: false
scope:
amount: '@'
description: '@'
image: '@'
email: '@'
paymentCallback: '&'
link: (scope, elem, attrs) ->
amountInCents = parseInt(scope.amount * 100)
elem.on 'click', ->
displayCheckout()
scope.$on "payment:checkout:display", (event, args)->
displayCheckout()
displayCheckout = ->
elem.attr 'disabled', 'disabled'
StripeCheckout.open
key: AppConfig.STRIPE_PUBLIC_KEY
amount: amountInCents
currency: 'usd'
name: '<NAME>'
email: scope.email
description: scope.description
image: scope.image
closed: ->
(scope.$apply ->
elem.removeAttr 'disabled') unless scope.paid?
token: (token) ->
#there is a bug with stripe checkout where it will fire multiple `token` callbacks
unless scope.paid
scope.$apply ->
scope.paid = true
scope.paymentCallback token: token
| true | 'use strict'
angular.module('stripe.directives')
.directive "stripeCheckout", (StripeCheckout, AppConfig) ->
restrict: 'A'
transclude: false
scope:
amount: '@'
description: '@'
image: '@'
email: '@'
paymentCallback: '&'
link: (scope, elem, attrs) ->
amountInCents = parseInt(scope.amount * 100)
elem.on 'click', ->
displayCheckout()
scope.$on "payment:checkout:display", (event, args)->
displayCheckout()
displayCheckout = ->
elem.attr 'disabled', 'disabled'
StripeCheckout.open
key: AppConfig.STRIPE_PUBLIC_KEY
amount: amountInCents
currency: 'usd'
name: 'PI:NAME:<NAME>END_PI'
email: scope.email
description: scope.description
image: scope.image
closed: ->
(scope.$apply ->
elem.removeAttr 'disabled') unless scope.paid?
token: (token) ->
#there is a bug with stripe checkout where it will fire multiple `token` callbacks
unless scope.paid
scope.$apply ->
scope.paid = true
scope.paymentCallback token: token
|
[
{
"context": "'name': 'Ever Notedown - Literal Coffee Extended (MathJax)'\n'scopeName':",
"end": 22,
"score": 0.728930652141571,
"start": 9,
"tag": "NAME",
"value": "Ever Notedown"
}
] | lib/grammars/evnd-litcoffee-mathjax.cson | vicyork/ever-notedown | 170 | 'name': 'Ever Notedown - Literal Coffee Extended (MathJax)'
'scopeName': 'text.markdown.evnd.mathjax.source.litcoffee.inline.html'
'fileTypes': [
'markdown'
'md'
'mdown'
'mkd'
'mkdown'
'rmd'
'ron'
]
'patterns': [
{
'match': '(\\$)(?!=\\$)([^\\$]+?)(\\$)(?!\\$)'
'name': 'string.other.math.latex'
'captures':
'1':
'name': 'punctuation.definition.tag'
'2':
'name': 'markup.mathjax.inline.string.quoted'
'3':
'name': 'punctuation.definition.tag'
}
{
'begin': '\\$\\$(?!\\$)'
'beginCaptures':
'0':
'name': 'punctuation.definition.tag'
'end': '\\$\\$(?!\\$)'
'endCaptures':
'0':
'name': 'punctuation.definition.tag'
'name': 'markup.mathjax.string.quoted'
'contentName': 'markup.math.mathjax.latex.string.quoted'
}
{
'match': '^\\s*?\\[(?:TOC|toc)\\]\\s*?$'
'name': 'markup.keyword.bold.heading.toc'
}
{
'include': 'source.litcoffee'
}
{
'include': 'evnd.inline.html'
}
]
| 175132 | 'name': '<NAME> - Literal Coffee Extended (MathJax)'
'scopeName': 'text.markdown.evnd.mathjax.source.litcoffee.inline.html'
'fileTypes': [
'markdown'
'md'
'mdown'
'mkd'
'mkdown'
'rmd'
'ron'
]
'patterns': [
{
'match': '(\\$)(?!=\\$)([^\\$]+?)(\\$)(?!\\$)'
'name': 'string.other.math.latex'
'captures':
'1':
'name': 'punctuation.definition.tag'
'2':
'name': 'markup.mathjax.inline.string.quoted'
'3':
'name': 'punctuation.definition.tag'
}
{
'begin': '\\$\\$(?!\\$)'
'beginCaptures':
'0':
'name': 'punctuation.definition.tag'
'end': '\\$\\$(?!\\$)'
'endCaptures':
'0':
'name': 'punctuation.definition.tag'
'name': 'markup.mathjax.string.quoted'
'contentName': 'markup.math.mathjax.latex.string.quoted'
}
{
'match': '^\\s*?\\[(?:TOC|toc)\\]\\s*?$'
'name': 'markup.keyword.bold.heading.toc'
}
{
'include': 'source.litcoffee'
}
{
'include': 'evnd.inline.html'
}
]
| true | 'name': 'PI:NAME:<NAME>END_PI - Literal Coffee Extended (MathJax)'
'scopeName': 'text.markdown.evnd.mathjax.source.litcoffee.inline.html'
'fileTypes': [
'markdown'
'md'
'mdown'
'mkd'
'mkdown'
'rmd'
'ron'
]
'patterns': [
{
'match': '(\\$)(?!=\\$)([^\\$]+?)(\\$)(?!\\$)'
'name': 'string.other.math.latex'
'captures':
'1':
'name': 'punctuation.definition.tag'
'2':
'name': 'markup.mathjax.inline.string.quoted'
'3':
'name': 'punctuation.definition.tag'
}
{
'begin': '\\$\\$(?!\\$)'
'beginCaptures':
'0':
'name': 'punctuation.definition.tag'
'end': '\\$\\$(?!\\$)'
'endCaptures':
'0':
'name': 'punctuation.definition.tag'
'name': 'markup.mathjax.string.quoted'
'contentName': 'markup.math.mathjax.latex.string.quoted'
}
{
'match': '^\\s*?\\[(?:TOC|toc)\\]\\s*?$'
'name': 'markup.keyword.bold.heading.toc'
}
{
'include': 'source.litcoffee'
}
{
'include': 'evnd.inline.html'
}
]
|
[
{
"context": "ll the badge titles and the badges\n#\n# Author:\n# therealklanni\n# Maintainer:\n# drh4kor\n\n\nbadgeList = [\n '13ma",
"end": 550,
"score": 0.9986392855644226,
"start": 537,
"tag": "USERNAME",
"value": "therealklanni"
},
{
"context": "es\n#\n# Author:\n# therea... | src/badges.coffee | therealklanni/hubot-ingress | 14 | # Description
# Ingress helper commands for Hubot
#
# Dependencies:
# None
#
# Commands:
# hubot I have the <badge> badge - add/remove badges (say don't to remove)
# hubot I don't have any badges - remove your badges completely
# hubot what badges do I have? - show off your Ingress badges—you worked hard for them!
# hubot what badges does <person> have? - check another agent's badges
# hubot list badges - list the badges available
# hubot display badges - displays all the badge titles and the badges
#
# Author:
# therealklanni
# Maintainer:
# drh4kor
badgeList = [
'13magnus',
'abaddon',
'acolyte',
'acolyte-2017',
'acolyte-2018',
'ada',
'ada-2016',
'ada-2017',
'aegis-nova',
'akira-tsukasa',
'akira-2017',
'builder1', 'builder2', 'builder3', 'builder4', 'builder5',
'campbell-2018',
'cassandra-prime',
'connector1', 'connector2', 'connector3', 'connector4', 'connector5',
'darsana',
'devra-bogdanovich',
'devra-2017',
'edgar-allan-wright',
'engineer1', 'engineer2', 'engineer3', 'engineer4', 'engineer5',
'eve',
'exo5',
'exo-five1','exo-five2','exo-five3',
'explorer1', 'explorer2', 'explorer3', 'explorer4', 'explorer5',
'founder',
'goruck',
'goruck-stealth',
'goruck-urban',
'guardian1', 'guardian2', 'guardian3', 'guardian4', 'guardian5',
'hacker1', 'hacker2', 'hacker3', 'hacker4', 'hacker5',
'hank-johnson',
'hank-johnson-2016',
'hankjohnson-prime-2018',
'hank-2017',
'hank-2018',
'helios',
'illuminator1', 'illuminator2', 'illuminator3', 'illuminator4','illuminator5',
'initio',
'innovator1', 'innovator2', 'innovator3', 'innovator4', 'innovator5'
'intelops',
'interitus',
'jahan',
'jarvis-prime-2018',
'klue',
'klue-2016',
'kodama-2017',
'kodama-smiles',
'liberator1', 'liberator2', 'liberator3', 'liberator4', 'liberator5',
'luminary1', 'luminary2', 'luminary3', 'luminary4', 'luminary5',
'magnus1', 'magnus2',
'mindcontroller1', 'mindcontroller2', 'mindcontroller3', 'mindcontroller4', 'mindcontroller5',
'missionday1', 'missionday2', 'missionday3', 'missionday4', 'missionday5',
'mistyhannah-2017',
'neutralizer1','neutralizer2','neutralizer3',
'nl-1331',
'nl-1331-2016',
'nl-1331e-2017',
'nl-1331e',
'nl-1131-meetup1','nl-1131-meetup2','nl-1131-meetup3','nl-1131-meetup4','nl-1131-meetup5',
'nl-prime',
'nla-2017',
'nlprime-2017',
'olw-2017',
'olw-2018',
'olw-prime-2018',
'oliver-lynton-wolfe',
'oliver-lynton-wolfe-2016',
'obsidian',
'operationclearfield',
'operationclearfield-2018',
'oprlive',
'osiris',
'ouroboros1',
'ouroboros2',
'ouroboros3',
'ouroboros4',
'ouroboros5',
'pachapeau-2017',
'pachapeau-2018',
'pachapeau-prime-2018',
'p-a-chapeau', 'p-a-chapeau-2016',
'persepolis',
'pioneer1', 'pioneer2', 'pioneer3', 'pioneer4', 'pioneer5',
'prime',
'primechallenge',
'purifier1', 'purifier2', 'purifier3', 'purifier4', 'purifier5',
'recharger1', 'recharger2', 'recharger3', 'recharger4', 'recharger5',
'recon1','recon2','recon3','recon4','recon5',
'recursion',
'recruiter0', 'recruiter1', 'recruiter2', 'recruiter3', 'recruiter4', 'recruiter5',
'sage1','sage2','sage3','sage4','sage5',
'seer1', 'seer2', 'seer3', 'seer4', 'seer5',
'shonin',
'simulacrum',
'sojourner1', 'sojourner2', 'sojourner3', 'sojourner4', 'sojourner5',
'specops1', 'specops2', 'specops3', 'specops4', 'specops5',
'stella-vyctory',
'susanna-moyer',
'susanna-moyer-2016',
'trekker1', 'trekker2', 'trekker3', 'trekker4', 'trekker5',
'translator1', 'translator2', 'translator3', 'translator4', 'translator5',
'verified',
'vanguard1', 'vanguard2', 'vanguard3', 'vanguard4', 'vanguard5',
'via-lux-adventurer',
'via-lux-odyssey',
'via-lux',
'via-noir'
]
badgeNameUpdateVersion = 1
badgeNameUpdateMap = {
'ada-1': 'ada'
'ada-2': 'ada-2016'
'aegis': 'aegis-nova'
'akira': 'akira-tsukasa'
'devra-1': 'devra-bogdanovich'
'goruckstealh': 'goruck-stealth'
'goruckurban': 'goruck-urban'
'nl-1331-1': 'nl-1331'
'nl-1331-2': 'nl-1331-2016'
'oliver-lynton-wolfe-2': 'oliver-lynton-wolfe-2016'
'p-a-chapeau-2': 'p-a-chapeau-2016'
'susanna-moyer1': 'susanna-moyer'
'susanna-moyer2': 'susanna-moyer-2016'
}
colorList= {
'': '',
'locked': 0,
'bronze': 1,
'silver': 2,
'gold': 3,
'platinum': 4,
'black': 5,
'onyx': 5
}
badgeTypes = {
'13magnus': 1,
'abaddon': 1,
'acolyte': 1,
'acolyte-2017': 1,
'acolyte-2018': 1,
'ada': 1,
'ada-2016': 1,
'ada-2017': 1,
'aegis-nova': 1,
'akira-tsukasa': 1,
'akira-2017': 1,
'builder': 5,
'campbell-2018': 1,
'cassandra-prime': 1,
'connector': 5,
'darsana': 1,
'devra-bogdanovich': 1,
'devra-2017': 1,
'edgar-allan-wright': 1,
'engineer': 5,
'eve': 1,
'exo5': 1,
'exo-five': 3,
'explorer': 5,
'founder': 1,
'goruck': 1,
'goruck-stealth': 1,
'goruck-urban': 1,
'guardian': 5,
'hacker': 5,
'hank-johnson': 1,
'hank-johnson-2016': 1,
'hankjohnson-prime-2018': 1,
'hank-2017': 1,
'hank-2018': 1,
'helios': 1,
'illuminator': 5,
'initio': 1,
'innovator': 5,
'intelops': 1,
'interitus': 1,
'jahan': 1,
'jarvis-prime-2018': 1,
'klue': 1,
'klue-2016': 1,
'kodama-2017': 1,
'kodama-smiles': 1,
'liberator': 5,
'luminary': 5,
'magnus': 2,
'mindcontroller': 5,
'missionday': 5,
'mistyhannah-2017': 1,
'neutralizer': 3,
'nl-1331': 1,
'nl-1331-2016': 1,
'nl-1331e-2017': 1,
'nl-1331e': 1,
'nl-1131-meetup': 5,
'nl-prime': 1,
'nla-2017': 1,
'nlprime-2017': 1,
'olw-2017': 1,
'olw-2018': 1,
'olw-prime-2018': 1,
'oliver-lynton-wolfe': 1,
'oliver-lynton-wolfe-2016': 1,
'obsidian': 1,
'operationclearfield': 1,
'operationclearfield-2018': 1,
'oprlive': 1,
'osiris': 1,
'ouroboros': 5,
'pachapeau-2017': 1,
'pachapeau-2018': 1,
'pachapeau-prime-2018': 1,
'p-a-chapeau': 1,
'p-a-chapeau-2016': 1,
'persepolis': 1,
'pioneer': 5,
'prime': 1,
'primechallenge': 1,
'purifier': 5,
'recharger': 5,
'recon': 5,
'recursion': 1,
'recruiter': 6,
'sage': 5,
'seer': 5,
'shonin': 1,
'simulacrum':1,
'sojourner': 5,
'specops': 5,
'stella-vyctory': 1,
'susanna-moyer': 1,
'susanna-moyer-2016': 1,
'trekker': 5,
'translator': 5,
'verified': 1,
'vanguard': 5,
'via-lux-adventurer': 1,
'via-lux-odyssey': 1,
'via-lux': 1,
'via-noir': 1
}
module.exports = (robot) ->
badges =
add: (user, badgeNames...) ->
for badgeName in badgeNames
# only replace tiered badges - allows having all of the character badges
if not badgeTypes[badgeName]?
toRemove = badgeList.filter (x) ->
(x.replace /\d+/, '') is (badgeName.replace /\d+/, '')
@del user, badge for badge in toRemove
userBadges = robot.brain.data.ingressBadges[user.id] ?= []
userBadges.push ":#{badgeName}:" unless ":#{badgeName}:" in (badges.forUser user)
del: (user, badgeName) ->
robot.brain.data.ingressBadges[user.id] = (badges.forUser user).filter (x) ->
x isnt ":#{badgeName}:"
updateNames: ->
robot.brain.data.ingressBadgeNameUpdateVersion ?= 0
if robot.brain.data.ingressBadgeNameUpdateVersion < badgeNameUpdateVersion
for userId, userBadges of robot.brain.data.ingressBadges
for oldBadgeName, newBadgeName of badgeNameUpdateMap
index = userBadges.indexOf ":#{oldBadgeName}:"
userBadges[index] = ":#{newBadgeName}:" if index isnt -1
robot.brain.data.ingressBadgeNameUpdateVersion = badgeNameUpdateVersion
clear: (user) ->
robot.brain.data.ingressBadges[user.id] = []
forUser: (user) ->
robot.brain.data.ingressBadges[user.id] ?= []
robot.brain.on 'loaded', ->
robot.brain.data.ingressBadges ?= {}
badges.updateNames()
robot.respond /(@?[.\w\-]+) (?:have|has|got|earned)(?: the)? :?([\-\w,\s]+):? badges?/i, (msg) ->
who = msg.match[1].toLowerCase().replace '@', ''
badgeNames = (msg.match[2].toLowerCase()).split ','
if who == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
invalidNames = []
validNames = []
for rawBadgeName in badgeNames
colorNames = Object.keys(colorList).join '|'
badgeNameParts = rawBadgeName.match /// ^
\s* # Leading spaces
(#{colorNames})?
\s* # Actual space
([\-\w]+) # Badge Name
\s* # Trailing space
$ ///i
continue unless badgeNameParts?
badgeName = badgeNameParts[2].toLowerCase()
colorName = 'bronze'
colorName = badgeNameParts[1] if badgeNameParts[1]
colorName = '' if badgeName in badgeList
badgeName += colorList[colorName.toLowerCase()]
if badgeName in badgeList
validNames.push badgeName
else
invalidNames.push badgeName
msg.reply "invalid badge name(s): #{invalidNames.join ', '}." if invalidNames.length > 0
if validNames.length > 0
for badgeName in validNames
badges.add who, badgeName
userBadges = badges.forUser who
validNames = validNames.filter (x) ->
":#{x}:" in userBadges
if who.name == msg.envelope.user.name
msg.reply "congrats on earning the :#{validNames.join ': :'}:
badge#{if validNames.length > 1 then 's' else ''}!"
else
msg.send "@#{who.name}: congrats on earning the :#{validNames.join ': :'}:
badge#{if validNames.length > 1 then 's' else ''}!"
robot.respond /wh(?:at|ich) badges? do(?:es)? (@?[.\w\-]+) have/i, (msg) ->
who = msg.match[1].replace '@', ''
if who.toLowerCase() == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
userBadges = badges.forUser who
you = if who? and who.name == msg.envelope.user.name then true else false
whowhat = "#{if you then 'You have' else who.name + ' has'}"
if who? and userBadges.length > 0
msg.reply "#{whowhat} the following badges: #{userBadges.join ' '}"
else
msg.reply "#{whowhat} no badges."
robot.respond /(@?[.\w\-]+) (?:do(?:n't|esn't| not)) have the :?([\-\w]+):? badge/i, (msg) ->
who = msg.match[1].toLowerCase().replace '@', ''
badgeName = msg.match[2].toLowerCase()
if who == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
if ":#{badgeName}:" in badges.forUser who
badges.del who, badgeName
msg.reply "removed the :#{badgeName}: badge"
robot.respond /I (?:do(?:n't| not)) have any badges?/i, (msg) ->
badges.clear msg.envelope.user
msg.reply 'OK, removed all your badges'
robot.respond /list badges ?.*/i, (msg) ->
message = ""
for badgeType of badgeTypes
message += "#{badgeType}, "
msg.send message
robot.respond /display badges ?.*/i, (msg) ->
message = "The available badges are:\n"
for badgeType, badgeNum of badgeTypes
if badgeNum == 1
message += "#{badgeType}: :#{badgeType}:\n"
else if badgeNum == 2
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2:\n"
else if badgeNum == 3
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3:\n"
else if badgeNum == 5
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3: :#{badgeType}4: :#{badgeType}5:\n"
else if badgeNum == 6
message += "#{badgeType}: :#{badgeType}0: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3: :#{badgeType}4: :#{badgeType}5:\n"
msg.send message
| 222044 | # Description
# Ingress helper commands for Hubot
#
# Dependencies:
# None
#
# Commands:
# hubot I have the <badge> badge - add/remove badges (say don't to remove)
# hubot I don't have any badges - remove your badges completely
# hubot what badges do I have? - show off your Ingress badges—you worked hard for them!
# hubot what badges does <person> have? - check another agent's badges
# hubot list badges - list the badges available
# hubot display badges - displays all the badge titles and the badges
#
# Author:
# therealklanni
# Maintainer:
# drh4kor
badgeList = [
'13magnus',
'abaddon',
'acolyte',
'acolyte-2017',
'acolyte-2018',
'ada',
'ada-2016',
'ada-2017',
'aegis-nova',
'akira-tsukasa',
'akira-2017',
'builder1', 'builder2', 'builder3', 'builder4', 'builder5',
'campbell-2018',
'cassandra-prime',
'connector1', 'connector2', 'connector3', 'connector4', 'connector5',
'darsana',
'devra-bogdanovich',
'devra-2017',
'edgar-allan-wright',
'engineer1', 'engineer2', 'engineer3', 'engineer4', 'engineer5',
'eve',
'exo5',
'exo-five1','exo-five2','exo-five3',
'explorer1', 'explorer2', 'explorer3', 'explorer4', 'explorer5',
'founder',
'goruck',
'goruck-stealth',
'goruck-urban',
'guardian1', 'guardian2', 'guardian3', 'guardian4', 'guardian5',
'hacker1', 'hacker2', 'hacker3', 'hacker4', 'hacker5',
'<NAME>',
'hank-johnson-2016',
'hankjohnson-prime-2018',
'hank-2017',
'hank-2018',
'helios',
'illuminator1', 'illuminator2', 'illuminator3', 'illuminator4','illuminator5',
'initio',
'innovator1', 'innovator2', 'innovator3', 'innovator4', 'innovator5'
'intelops',
'interitus',
'jahan',
'jarvis-prime-2018',
'klue',
'klue-2016',
'kodama-2017',
'kodama-smiles',
'liberator1', 'liberator2', 'liberator3', 'liberator4', 'liberator5',
'luminary1', 'luminary2', 'luminary3', 'luminary4', 'luminary5',
'magnus1', 'magnus2',
'mindcontroller1', 'mindcontroller2', 'mindcontroller3', 'mindcontroller4', 'mindcontroller5',
'missionday1', 'missionday2', 'missionday3', 'missionday4', 'missionday5',
'mistyhannah-2017',
'neutralizer1','neutralizer2','neutralizer3',
'nl-1331',
'nl-1331-2016',
'nl-1331e-2017',
'nl-1331e',
'nl-1131-meetup1','nl-1131-meetup2','nl-1131-meetup3','nl-1131-meetup4','nl-1131-meetup5',
'nl-prime',
'nla-2017',
'nlprime-2017',
'olw-2017',
'olw-2018',
'olw-prime-2018',
'oliver-lynton-wolfe',
'oliver-lynton-wolfe-2016',
'obsidian',
'operationclearfield',
'operationclearfield-2018',
'oprlive',
'osiris',
'ouroboros1',
'ouroboros2',
'ouroboros3',
'ouroboros4',
'ouroboros5',
'pachapeau-2017',
'pachapeau-2018',
'pachapeau-prime-2018',
'p-a-chapeau', 'p-a-chapeau-2016',
'persepolis',
'pioneer1', 'pioneer2', 'pioneer3', 'pioneer4', 'pioneer5',
'prime',
'primechallenge',
'purifier1', 'purifier2', 'purifier3', 'purifier4', 'purifier5',
'recharger1', 'recharger2', 'recharger3', 'recharger4', 'recharger5',
'recon1','recon2','recon3','recon4','recon5',
'recursion',
'recruiter0', 'recruiter1', 'recruiter2', 'recruiter3', 'recruiter4', 'recruiter5',
'sage1','sage2','sage3','sage4','sage5',
'seer1', 'seer2', 'seer3', 'seer4', 'seer5',
'shonin',
'simulacrum',
'sojourner1', 'sojourner2', 'sojourner3', 'sojourner4', 'sojourner5',
'specops1', 'specops2', 'specops3', 'specops4', 'specops5',
'stella-vyctory',
'susanna-moyer',
'susanna-moyer-2016',
'trekker1', 'trekker2', 'trekker3', 'trekker4', 'trekker5',
'translator1', 'translator2', 'translator3', 'translator4', 'translator5',
'verified',
'vanguard1', 'vanguard2', 'vanguard3', 'vanguard4', 'vanguard5',
'via-lux-adventurer',
'via-lux-odyssey',
'via-lux',
'via-noir'
]
badgeNameUpdateVersion = 1
badgeNameUpdateMap = {
'ada-1': 'ada'
'ada-2': 'ada-2016'
'aegis': 'aegis-nova'
'akira': 'akira-tsukasa'
'devra-1': 'devra-bogdanovich'
'goruckstealh': 'goruck-stealth'
'goruckurban': 'goruck-urban'
'nl-1331-1': 'nl-1331'
'nl-1331-2': 'nl-1331-2016'
'oliver-lynton-wolfe-2': 'oliver-lynton-wolfe-2016'
'p-a-chapeau-2': 'p-a-chapeau-2016'
'susanna-moyer1': 'susanna-moyer'
'susanna-moyer2': 'susanna-moyer-2016'
}
colorList= {
'': '',
'locked': 0,
'bronze': 1,
'silver': 2,
'gold': 3,
'platinum': 4,
'black': 5,
'onyx': 5
}
badgeTypes = {
'13magnus': 1,
'abaddon': 1,
'acolyte': 1,
'acolyte-2017': 1,
'acolyte-2018': 1,
'ada': 1,
'ada-2016': 1,
'ada-2017': 1,
'aegis-nova': 1,
'akira-tsukasa': 1,
'akira-2017': 1,
'builder': 5,
'campbell-2018': 1,
'cassandra-prime': 1,
'connector': 5,
'<NAME>': 1,
'<NAME>': 1,
'devra-2017': 1,
'<NAME>': 1,
'engineer': 5,
'eve': 1,
'exo5': 1,
'exo-five': 3,
'explorer': 5,
'founder': 1,
'goruck': 1,
'goruck-stealth': 1,
'goruck-urban': 1,
'guardian': 5,
'hacker': 5,
'<NAME>': 1,
'hank-johnson-2016': 1,
'hankjohnson-prime-2018': 1,
'hank-2017': 1,
'hank-2018': 1,
'helios': 1,
'illuminator': 5,
'initio': 1,
'innovator': 5,
'intelops': 1,
'interitus': 1,
'jahan': 1,
'jarvis-prime-2018': 1,
'klue': 1,
'klue-2016': 1,
'kodama-2017': 1,
'kodama-smiles': 1,
'liberator': 5,
'luminary': 5,
'magnus': 2,
'mindcontroller': 5,
'missionday': 5,
'mistyhannah-2017': 1,
'neutralizer': 3,
'nl-1331': 1,
'nl-1331-2016': 1,
'nl-1331e-2017': 1,
'nl-1331e': 1,
'nl-1131-meetup': 5,
'nl-prime': 1,
'nla-2017': 1,
'nlprime-2017': 1,
'olw-2017': 1,
'olw-2018': 1,
'olw-prime-2018': 1,
'oliver-lynton-wolfe': 1,
'oliver-lynton-wolfe-2016': 1,
'obsidian': 1,
'operationclearfield': 1,
'operationclearfield-2018': 1,
'oprlive': 1,
'osiris': 1,
'ouroboros': 5,
'pachapeau-2017': 1,
'pachapeau-2018': 1,
'pachapeau-prime-2018': 1,
'p-a-chapeau': 1,
'p-a-chapeau-2016': 1,
'persepolis': 1,
'pioneer': 5,
'prime': 1,
'primechallenge': 1,
'purifier': 5,
'recharger': 5,
'recon': 5,
'recursion': 1,
'recruiter': 6,
'sage': 5,
'seer': 5,
'shonin': 1,
'simulacrum':1,
'sojourner': 5,
'specops': 5,
'stella-vyctory': 1,
'susanna-moyer': 1,
'susanna-moyer-2016': 1,
'trekker': 5,
'translator': 5,
'verified': 1,
'vanguard': 5,
'via-lux-adventurer': 1,
'via-lux-odyssey': 1,
'via-lux': 1,
'via-noir': 1
}
module.exports = (robot) ->
badges =
add: (user, badgeNames...) ->
for badgeName in badgeNames
# only replace tiered badges - allows having all of the character badges
if not badgeTypes[badgeName]?
toRemove = badgeList.filter (x) ->
(x.replace /\d+/, '') is (badgeName.replace /\d+/, '')
@del user, badge for badge in toRemove
userBadges = robot.brain.data.ingressBadges[user.id] ?= []
userBadges.push ":#{badgeName}:" unless ":#{badgeName}:" in (badges.forUser user)
del: (user, badgeName) ->
robot.brain.data.ingressBadges[user.id] = (badges.forUser user).filter (x) ->
x isnt ":#{badgeName}:"
updateNames: ->
robot.brain.data.ingressBadgeNameUpdateVersion ?= 0
if robot.brain.data.ingressBadgeNameUpdateVersion < badgeNameUpdateVersion
for userId, userBadges of robot.brain.data.ingressBadges
for oldBadgeName, newBadgeName of badgeNameUpdateMap
index = userBadges.indexOf ":#{oldBadgeName}:"
userBadges[index] = ":#{newBadgeName}:" if index isnt -1
robot.brain.data.ingressBadgeNameUpdateVersion = badgeNameUpdateVersion
clear: (user) ->
robot.brain.data.ingressBadges[user.id] = []
forUser: (user) ->
robot.brain.data.ingressBadges[user.id] ?= []
robot.brain.on 'loaded', ->
robot.brain.data.ingressBadges ?= {}
badges.updateNames()
robot.respond /(@?[.\w\-]+) (?:have|has|got|earned)(?: the)? :?([\-\w,\s]+):? badges?/i, (msg) ->
who = msg.match[1].toLowerCase().replace '@', ''
badgeNames = (msg.match[2].toLowerCase()).split ','
if who == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
invalidNames = []
validNames = []
for rawBadgeName in badgeNames
colorNames = Object.keys(colorList).join '|'
badgeNameParts = rawBadgeName.match /// ^
\s* # Leading spaces
(#{colorNames})?
\s* # Actual space
([\-\w]+) # Badge Name
\s* # Trailing space
$ ///i
continue unless badgeNameParts?
badgeName = badgeNameParts[2].toLowerCase()
colorName = 'bronze'
colorName = badgeNameParts[1] if badgeNameParts[1]
colorName = '' if badgeName in badgeList
badgeName += colorList[colorName.toLowerCase()]
if badgeName in badgeList
validNames.push badgeName
else
invalidNames.push badgeName
msg.reply "invalid badge name(s): #{invalidNames.join ', '}." if invalidNames.length > 0
if validNames.length > 0
for badgeName in validNames
badges.add who, badgeName
userBadges = badges.forUser who
validNames = validNames.filter (x) ->
":#{x}:" in userBadges
if who.name == msg.envelope.user.name
msg.reply "congrats on earning the :#{validNames.join ': :'}:
badge#{if validNames.length > 1 then 's' else ''}!"
else
msg.send "@#{who.name}: congrats on earning the :#{validNames.join ': :'}:
badge#{if validNames.length > 1 then 's' else ''}!"
robot.respond /wh(?:at|ich) badges? do(?:es)? (@?[.\w\-]+) have/i, (msg) ->
who = msg.match[1].replace '@', ''
if who.toLowerCase() == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
userBadges = badges.forUser who
you = if who? and who.name == msg.envelope.user.name then true else false
whowhat = "#{if you then 'You have' else who.name + ' has'}"
if who? and userBadges.length > 0
msg.reply "#{whowhat} the following badges: #{userBadges.join ' '}"
else
msg.reply "#{whowhat} no badges."
robot.respond /(@?[.\w\-]+) (?:do(?:n't|esn't| not)) have the :?([\-\w]+):? badge/i, (msg) ->
who = msg.match[1].toLowerCase().replace '@', ''
badgeName = msg.match[2].toLowerCase()
if who == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
if ":#{badgeName}:" in badges.forUser who
badges.del who, badgeName
msg.reply "removed the :#{badgeName}: badge"
robot.respond /I (?:do(?:n't| not)) have any badges?/i, (msg) ->
badges.clear msg.envelope.user
msg.reply 'OK, removed all your badges'
robot.respond /list badges ?.*/i, (msg) ->
message = ""
for badgeType of badgeTypes
message += "#{badgeType}, "
msg.send message
robot.respond /display badges ?.*/i, (msg) ->
message = "The available badges are:\n"
for badgeType, badgeNum of badgeTypes
if badgeNum == 1
message += "#{badgeType}: :#{badgeType}:\n"
else if badgeNum == 2
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2:\n"
else if badgeNum == 3
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3:\n"
else if badgeNum == 5
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3: :#{badgeType}4: :#{badgeType}5:\n"
else if badgeNum == 6
message += "#{badgeType}: :#{badgeType}0: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3: :#{badgeType}4: :#{badgeType}5:\n"
msg.send message
| true | # Description
# Ingress helper commands for Hubot
#
# Dependencies:
# None
#
# Commands:
# hubot I have the <badge> badge - add/remove badges (say don't to remove)
# hubot I don't have any badges - remove your badges completely
# hubot what badges do I have? - show off your Ingress badges—you worked hard for them!
# hubot what badges does <person> have? - check another agent's badges
# hubot list badges - list the badges available
# hubot display badges - displays all the badge titles and the badges
#
# Author:
# therealklanni
# Maintainer:
# drh4kor
badgeList = [
'13magnus',
'abaddon',
'acolyte',
'acolyte-2017',
'acolyte-2018',
'ada',
'ada-2016',
'ada-2017',
'aegis-nova',
'akira-tsukasa',
'akira-2017',
'builder1', 'builder2', 'builder3', 'builder4', 'builder5',
'campbell-2018',
'cassandra-prime',
'connector1', 'connector2', 'connector3', 'connector4', 'connector5',
'darsana',
'devra-bogdanovich',
'devra-2017',
'edgar-allan-wright',
'engineer1', 'engineer2', 'engineer3', 'engineer4', 'engineer5',
'eve',
'exo5',
'exo-five1','exo-five2','exo-five3',
'explorer1', 'explorer2', 'explorer3', 'explorer4', 'explorer5',
'founder',
'goruck',
'goruck-stealth',
'goruck-urban',
'guardian1', 'guardian2', 'guardian3', 'guardian4', 'guardian5',
'hacker1', 'hacker2', 'hacker3', 'hacker4', 'hacker5',
'PI:NAME:<NAME>END_PI',
'hank-johnson-2016',
'hankjohnson-prime-2018',
'hank-2017',
'hank-2018',
'helios',
'illuminator1', 'illuminator2', 'illuminator3', 'illuminator4','illuminator5',
'initio',
'innovator1', 'innovator2', 'innovator3', 'innovator4', 'innovator5'
'intelops',
'interitus',
'jahan',
'jarvis-prime-2018',
'klue',
'klue-2016',
'kodama-2017',
'kodama-smiles',
'liberator1', 'liberator2', 'liberator3', 'liberator4', 'liberator5',
'luminary1', 'luminary2', 'luminary3', 'luminary4', 'luminary5',
'magnus1', 'magnus2',
'mindcontroller1', 'mindcontroller2', 'mindcontroller3', 'mindcontroller4', 'mindcontroller5',
'missionday1', 'missionday2', 'missionday3', 'missionday4', 'missionday5',
'mistyhannah-2017',
'neutralizer1','neutralizer2','neutralizer3',
'nl-1331',
'nl-1331-2016',
'nl-1331e-2017',
'nl-1331e',
'nl-1131-meetup1','nl-1131-meetup2','nl-1131-meetup3','nl-1131-meetup4','nl-1131-meetup5',
'nl-prime',
'nla-2017',
'nlprime-2017',
'olw-2017',
'olw-2018',
'olw-prime-2018',
'oliver-lynton-wolfe',
'oliver-lynton-wolfe-2016',
'obsidian',
'operationclearfield',
'operationclearfield-2018',
'oprlive',
'osiris',
'ouroboros1',
'ouroboros2',
'ouroboros3',
'ouroboros4',
'ouroboros5',
'pachapeau-2017',
'pachapeau-2018',
'pachapeau-prime-2018',
'p-a-chapeau', 'p-a-chapeau-2016',
'persepolis',
'pioneer1', 'pioneer2', 'pioneer3', 'pioneer4', 'pioneer5',
'prime',
'primechallenge',
'purifier1', 'purifier2', 'purifier3', 'purifier4', 'purifier5',
'recharger1', 'recharger2', 'recharger3', 'recharger4', 'recharger5',
'recon1','recon2','recon3','recon4','recon5',
'recursion',
'recruiter0', 'recruiter1', 'recruiter2', 'recruiter3', 'recruiter4', 'recruiter5',
'sage1','sage2','sage3','sage4','sage5',
'seer1', 'seer2', 'seer3', 'seer4', 'seer5',
'shonin',
'simulacrum',
'sojourner1', 'sojourner2', 'sojourner3', 'sojourner4', 'sojourner5',
'specops1', 'specops2', 'specops3', 'specops4', 'specops5',
'stella-vyctory',
'susanna-moyer',
'susanna-moyer-2016',
'trekker1', 'trekker2', 'trekker3', 'trekker4', 'trekker5',
'translator1', 'translator2', 'translator3', 'translator4', 'translator5',
'verified',
'vanguard1', 'vanguard2', 'vanguard3', 'vanguard4', 'vanguard5',
'via-lux-adventurer',
'via-lux-odyssey',
'via-lux',
'via-noir'
]
badgeNameUpdateVersion = 1
badgeNameUpdateMap = {
'ada-1': 'ada'
'ada-2': 'ada-2016'
'aegis': 'aegis-nova'
'akira': 'akira-tsukasa'
'devra-1': 'devra-bogdanovich'
'goruckstealh': 'goruck-stealth'
'goruckurban': 'goruck-urban'
'nl-1331-1': 'nl-1331'
'nl-1331-2': 'nl-1331-2016'
'oliver-lynton-wolfe-2': 'oliver-lynton-wolfe-2016'
'p-a-chapeau-2': 'p-a-chapeau-2016'
'susanna-moyer1': 'susanna-moyer'
'susanna-moyer2': 'susanna-moyer-2016'
}
colorList= {
'': '',
'locked': 0,
'bronze': 1,
'silver': 2,
'gold': 3,
'platinum': 4,
'black': 5,
'onyx': 5
}
badgeTypes = {
'13magnus': 1,
'abaddon': 1,
'acolyte': 1,
'acolyte-2017': 1,
'acolyte-2018': 1,
'ada': 1,
'ada-2016': 1,
'ada-2017': 1,
'aegis-nova': 1,
'akira-tsukasa': 1,
'akira-2017': 1,
'builder': 5,
'campbell-2018': 1,
'cassandra-prime': 1,
'connector': 5,
'PI:NAME:<NAME>END_PI': 1,
'PI:NAME:<NAME>END_PI': 1,
'devra-2017': 1,
'PI:NAME:<NAME>END_PI': 1,
'engineer': 5,
'eve': 1,
'exo5': 1,
'exo-five': 3,
'explorer': 5,
'founder': 1,
'goruck': 1,
'goruck-stealth': 1,
'goruck-urban': 1,
'guardian': 5,
'hacker': 5,
'PI:NAME:<NAME>END_PI': 1,
'hank-johnson-2016': 1,
'hankjohnson-prime-2018': 1,
'hank-2017': 1,
'hank-2018': 1,
'helios': 1,
'illuminator': 5,
'initio': 1,
'innovator': 5,
'intelops': 1,
'interitus': 1,
'jahan': 1,
'jarvis-prime-2018': 1,
'klue': 1,
'klue-2016': 1,
'kodama-2017': 1,
'kodama-smiles': 1,
'liberator': 5,
'luminary': 5,
'magnus': 2,
'mindcontroller': 5,
'missionday': 5,
'mistyhannah-2017': 1,
'neutralizer': 3,
'nl-1331': 1,
'nl-1331-2016': 1,
'nl-1331e-2017': 1,
'nl-1331e': 1,
'nl-1131-meetup': 5,
'nl-prime': 1,
'nla-2017': 1,
'nlprime-2017': 1,
'olw-2017': 1,
'olw-2018': 1,
'olw-prime-2018': 1,
'oliver-lynton-wolfe': 1,
'oliver-lynton-wolfe-2016': 1,
'obsidian': 1,
'operationclearfield': 1,
'operationclearfield-2018': 1,
'oprlive': 1,
'osiris': 1,
'ouroboros': 5,
'pachapeau-2017': 1,
'pachapeau-2018': 1,
'pachapeau-prime-2018': 1,
'p-a-chapeau': 1,
'p-a-chapeau-2016': 1,
'persepolis': 1,
'pioneer': 5,
'prime': 1,
'primechallenge': 1,
'purifier': 5,
'recharger': 5,
'recon': 5,
'recursion': 1,
'recruiter': 6,
'sage': 5,
'seer': 5,
'shonin': 1,
'simulacrum':1,
'sojourner': 5,
'specops': 5,
'stella-vyctory': 1,
'susanna-moyer': 1,
'susanna-moyer-2016': 1,
'trekker': 5,
'translator': 5,
'verified': 1,
'vanguard': 5,
'via-lux-adventurer': 1,
'via-lux-odyssey': 1,
'via-lux': 1,
'via-noir': 1
}
module.exports = (robot) ->
badges =
add: (user, badgeNames...) ->
for badgeName in badgeNames
# only replace tiered badges - allows having all of the character badges
if not badgeTypes[badgeName]?
toRemove = badgeList.filter (x) ->
(x.replace /\d+/, '') is (badgeName.replace /\d+/, '')
@del user, badge for badge in toRemove
userBadges = robot.brain.data.ingressBadges[user.id] ?= []
userBadges.push ":#{badgeName}:" unless ":#{badgeName}:" in (badges.forUser user)
del: (user, badgeName) ->
robot.brain.data.ingressBadges[user.id] = (badges.forUser user).filter (x) ->
x isnt ":#{badgeName}:"
updateNames: ->
robot.brain.data.ingressBadgeNameUpdateVersion ?= 0
if robot.brain.data.ingressBadgeNameUpdateVersion < badgeNameUpdateVersion
for userId, userBadges of robot.brain.data.ingressBadges
for oldBadgeName, newBadgeName of badgeNameUpdateMap
index = userBadges.indexOf ":#{oldBadgeName}:"
userBadges[index] = ":#{newBadgeName}:" if index isnt -1
robot.brain.data.ingressBadgeNameUpdateVersion = badgeNameUpdateVersion
clear: (user) ->
robot.brain.data.ingressBadges[user.id] = []
forUser: (user) ->
robot.brain.data.ingressBadges[user.id] ?= []
robot.brain.on 'loaded', ->
robot.brain.data.ingressBadges ?= {}
badges.updateNames()
robot.respond /(@?[.\w\-]+) (?:have|has|got|earned)(?: the)? :?([\-\w,\s]+):? badges?/i, (msg) ->
who = msg.match[1].toLowerCase().replace '@', ''
badgeNames = (msg.match[2].toLowerCase()).split ','
if who == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
invalidNames = []
validNames = []
for rawBadgeName in badgeNames
colorNames = Object.keys(colorList).join '|'
badgeNameParts = rawBadgeName.match /// ^
\s* # Leading spaces
(#{colorNames})?
\s* # Actual space
([\-\w]+) # Badge Name
\s* # Trailing space
$ ///i
continue unless badgeNameParts?
badgeName = badgeNameParts[2].toLowerCase()
colorName = 'bronze'
colorName = badgeNameParts[1] if badgeNameParts[1]
colorName = '' if badgeName in badgeList
badgeName += colorList[colorName.toLowerCase()]
if badgeName in badgeList
validNames.push badgeName
else
invalidNames.push badgeName
msg.reply "invalid badge name(s): #{invalidNames.join ', '}." if invalidNames.length > 0
if validNames.length > 0
for badgeName in validNames
badges.add who, badgeName
userBadges = badges.forUser who
validNames = validNames.filter (x) ->
":#{x}:" in userBadges
if who.name == msg.envelope.user.name
msg.reply "congrats on earning the :#{validNames.join ': :'}:
badge#{if validNames.length > 1 then 's' else ''}!"
else
msg.send "@#{who.name}: congrats on earning the :#{validNames.join ': :'}:
badge#{if validNames.length > 1 then 's' else ''}!"
robot.respond /wh(?:at|ich) badges? do(?:es)? (@?[.\w\-]+) have/i, (msg) ->
who = msg.match[1].replace '@', ''
if who.toLowerCase() == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
userBadges = badges.forUser who
you = if who? and who.name == msg.envelope.user.name then true else false
whowhat = "#{if you then 'You have' else who.name + ' has'}"
if who? and userBadges.length > 0
msg.reply "#{whowhat} the following badges: #{userBadges.join ' '}"
else
msg.reply "#{whowhat} no badges."
robot.respond /(@?[.\w\-]+) (?:do(?:n't|esn't| not)) have the :?([\-\w]+):? badge/i, (msg) ->
who = msg.match[1].toLowerCase().replace '@', ''
badgeName = msg.match[2].toLowerCase()
if who == 'i'
who = msg.envelope.user
else
who = robot.brain.userForName who
if ":#{badgeName}:" in badges.forUser who
badges.del who, badgeName
msg.reply "removed the :#{badgeName}: badge"
robot.respond /I (?:do(?:n't| not)) have any badges?/i, (msg) ->
badges.clear msg.envelope.user
msg.reply 'OK, removed all your badges'
robot.respond /list badges ?.*/i, (msg) ->
message = ""
for badgeType of badgeTypes
message += "#{badgeType}, "
msg.send message
robot.respond /display badges ?.*/i, (msg) ->
message = "The available badges are:\n"
for badgeType, badgeNum of badgeTypes
if badgeNum == 1
message += "#{badgeType}: :#{badgeType}:\n"
else if badgeNum == 2
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2:\n"
else if badgeNum == 3
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3:\n"
else if badgeNum == 5
message += "#{badgeType}: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3: :#{badgeType}4: :#{badgeType}5:\n"
else if badgeNum == 6
message += "#{badgeType}: :#{badgeType}0: :#{badgeType}1: :#{badgeType}2: :#{badgeType}3: :#{badgeType}4: :#{badgeType}5:\n"
msg.send message
|
[
{
"context": "##\n#\n# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache Licen",
"end": 26,
"score": 0.8581363558769226,
"start": 23,
"tag": "NAME",
"value": "Net"
}
] | web-ui/public/coffee/apps/mapreduce.coffee | krishnachaitanyareddy/inviso | 162 | ##
#
# Copyright 2014 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
colors=
MAP: 'blue'
REDUCE: 'orange'
RUNNING: 'green'
KILLED: 'lightgray'
FAILED: 'red'
localityColors=
NODE_LOCAL: 'green'
RACK_LOCAL: 'orange'
OFF_SWITCH: 'red'
statusMap=
RUNNING: { text: 'RUNNING', class: 'label label-success'}
INITED: { text: 'SUCCEEDED', class: 'label label-default'}
SUCCEEDED: { text: 'SUCCEEDED', class: 'label label-default'}
SUCCESS: { text: 'SUCCEEDED', class: 'label label-default'}
KILLED: { text: 'KILLED', class: 'label label-warning'}
FAILED: { text: 'FAILED', class: 'label label-danger'}
undefined: { text: 'UNKNOWN', class: 'label label-default'}
class MapReduceBase extends Application
constructor: (version) ->
@version = version
@template =
tooltip: {}
self = this
Handlebars.registerHelper('hhmmss', (start, stop) -> hhmmss(stop - start))
Handlebars.registerHelper('logLink', (job, entry) ->
return "<a class=\"log-link\" href=\"#{self.logLink(job, entry)}\" target=\"_blank\">Open Logs</a>"
)
Handlebars.registerHelper('amLogLink', (job) ->
return "<a class=\"log-link\" href=\"#{self.amLogLink(job)}\" target=\"_blank\">Open Logs</a>"
)
Handlebars.registerHelper('properties', (attempt) ->
tbody = ''
for k,v of attempt
if k == 'counters' or k == 'entries'
continue
if k.toLowerCase().contains('time') or k.toLowerCase().contains('finished')
v = moment(v).format('YYYY-MM-DD HH:mm:ss (UTC ZZ)')
tbody += "<tr><td>#{k.replace('_',' ')}</td><td>#{v}</td></tr>"
return tbody
)
Handlebars.registerHelper('counters', (counters) ->
tbody = ''
for gname, group of counters
tbody += "<tr class=\"counter-group\"><td>#{gname}</td><td></td></tr>"
for cname in _.keys(group).sort()
tbody += "<tr><td>#{cname}</td><td>#{group[cname].toLocaleString()}</td></tr>"
return tbody
)
$.get('template/job-tooltip.html', (source) ->
self.template.tooltip.job = Handlebars.compile(source);
)
$.get('template/task-tooltip.html', (source) ->
self.template.tooltip.task = Handlebars.compile(source);
)
load: (job, callback) ->
console.log "Starting data load " + job.id + new Date()
url = "/inviso/#{@version}/v0/trace/load/#{job.id}?counters=true"
if settings.directHistoryPath or job.incremental
url += "&path=#{encodeURIComponent(job['history.uri'])}"
$.ajax
url: url
type: 'GET'
dataType: 'json'
success: (traceData) =>
jobDetails=
workflowId: traceData.workflowId
id: @getId(traceData)
name: @getName(traceData)
type: 'trace'
data: @processTrace(traceData)
version: @version
info: job
app: this
xLabel: 'Task Execution Times'
yLabel: 'Task Attempts'
legend:
'Map': colors.MAP
'Reduce': colors.REDUCE
'Killed': colors.KILLED
'Failed': colors.FAILED
console.log "Trace build complete for: #{job.id}"
addChart(jobDetails)
callback(true)
error: (xhr, status, e) ->
console.log e
callback(false)
renderSearchResult: (col, r) ->
$td = $('<td></td>')
switch col.id
when 'start'
t = r[col.id]
if not t? then $td.text(time_format(r.timestamp))
if t > 0 then $td.text(time_format(t))
when 'stop'
t = r[col.id]
if t > 0 then $td.text(time_format(t))
when 'duration'
stop = r['stop']
start = r['start']
if not start? or not stop? then break
stop = if stop > 0 then stop else Date.now()
$td.text(hhmmss(stop - r['start']))
when 'job_status'
s = statusMap[r[col.id]] || {class:'label label-default', text:r[col.id]}
$td.append($("<span class=\"#{s?.class}\" >#{s?.text}</span>"))
when 'workflow_id'
id = r.genie_id || r.query_id
if ! id?
break;
$td.append($a = $("<a>#{id}</a>"))
$a.attr
href: "?workflow=#{id}#profiler"
target: "_blank"
when 'genie_id'
id = r.genie_id || r.query_id
if not id? then break
$td.append($a = $("<a>#{id}</a>"))
$a.attr
href: "?workflow=#{id}#profiler"
target: "_blank"
when 'job_id'
$td.append($a = $("<a>#{r.job_id}</a>"))
$a.attr
href: "?job=#{r.job_id}#profiler"
target: "_blank"
when 'links'
if 'job_tracker' of r || 'yarn_proxy' of r
$a = $('<a/>',
href: @getHistoryAddress(r)
target: "_blank"
).append($('<img/>', {src: 'img/hadoop.gif', class: 'hadoop-icon'}))
$td.append($('<div/>').append($a))
if 'genie_id' of r
linkVersion = if r.genie_version then r.genie_version else ''
apiVersion = if r.genie_version then r.genie_version else 0
$a = $('<a/>',
href: "http://go/genie#{linkVersion}-prod/genie/v#{apiVersion}/jobs/#{r.genie_id}"
target: "_blank"
).append($('<img/>', {src: 'img/genie.gif', class: 'genie-icon'}))
$td.append($('<div/>').append($a))
if 'lipstick_url' of r
url = r.lipstick_url.split(',').random()
$a = $('<a/>',
href: "#{url}/graph.html#graph/#{r.genie_id ? r.lipstick_id}"
target: "_blank"
).append($('<img/>', {src: 'img/lipstick.png', class: 'lipstick-icon'}))
$td.append($('<div/>').append($a))
when 'version'
$td.text(r[col.id] ? 'mr1')
else
$td.text(r[col.id])
return $td
render: (data, $div) ->
$.get('template/mapreduce.html', (t) ->
$div.append($(t))
$div.find('.panel-title').text(data.id)
$chart = $div.find('.timeseries')
$chart.series({'series': data})
$actions = $div.find('.chart-actions')
$actions.find('.align-time').click(() -> $chart.series('option', 'flat', false))
$actions.find('.align-left').click(() -> $chart.series('option', 'flat', true))
$actions.find('.locality').click(() ->
@toggle = !@toggle;
if @toggle
@colorsave = $chart.series('option', 'color')
$chart.series('option', 'color', (d) ->
return localityColors[d.attempt.locality] || 'gray'
)
$chart.series('option', 'legend', localityColors)
else
$chart.series('option', 'color', @colorsave)
$chart.series('option', 'legend', null)
)
$actions.find('.zoom-in').click(()->
zoom = $chart.series('option', 'barHeight')
$chart.series('option', 'barHeight', zoom+1)
)
$actions.find('.zoom-out').click(()->
zoom = $chart.series('option', 'barHeight')
if zoom <= 1
return
$chart.series('option', 'barHeight', zoom-1)
)
$actions.find('.toggle-legend').click(()->
$chart.series('option', 'showLegend', !$chart.series('option', 'showLegend'))
)
$actions.find('.close').click(()->$div.remove())
)
tooltip: (job, entry) ->
if ! entry?
tt = @template.tooltip.job({ job: job })
else
tt = @template.tooltip.task( { job: job, entry: entry })
return tt
class @MapReduce1 extends MapReduceBase
constructor: ->
super('mr1')
getId: (job) -> job.id
getName: (job) -> job.name
getHistoryAddress: (r) -> "http://#{r.job_tracker.split(':')[0]}:9100/jobdetails.jsp?jobid=#{r.job_id}"
processTrace: (trace) ->
data =
status: trace.status,
counters: trace.counters,
submit_time: trace.submit_time,
start_time: trace.launch_time,
stop_time: trace.finish_time,
entries: []
for taskId,task of trace.tasks
for attemptId,attempt of task.attempts
data.entries.push
id: attemptId
label: attemptId
start: attempt.start_time
stop: attempt.finish_time ? Date.now()
color: colors[attempt.task_status] ? colors[attempt.task_type] ? 'gray'
task: task
attempt: attempt
group: 1
data.entries.sort((l,r) -> l.task.start_time - r.task.start_time)
return @normalize(data)
class @MapReduce2 extends MapReduceBase
constructor: ->
super('mr2')
getId: (job) -> job.jobid
getName: (job) -> job.jobName
getHistoryAddress: (r) -> "http://#{r.yarn_proxy}/proxy/#{r.job_id.replace('job', 'application')}"
processTrace: (trace) ->
data =
username: trace.userName
status: trace.jobStatus,
counters: trace.totalCounters,
submit_time: trace.submitTime,
start_time: trace.launchTime,
stop_time: trace.finishTime,
amContainer: trace.containerId,
amNode: trace.nodeManagerHost,
amPort: trace.nodeManagerPort
entries: []
for attemptId,attempt of trace.tasks.taskid.attempts
data.entries.push
id: attemptId
label: attemptId
start: attempt.startTime
stop: attempt.finishTime ? Date.now()
color: colors[attempt.status] ? colors[attempt.taskType] ? 'gray'
task: trace.tasks[attempt.taskid]
attempt: attempt
group: 1
data.entries.sort((l,r) -> l.task.startTime - r.task.startTime)
return @normalize(data)
logLink: (job, attempt) ->
root = job.info['yarn.nodemanager.remote-app-log-dir'];
owner = job.data.username;
appId = job.id.replace('job', 'application');
containerId = attempt.attempt.containerId;
nodeId = attempt.attempt.hostname+':'+attempt.attempt.port;
fs = job.info['fs.defaultFS'];
return "/inviso/mr2/v0/log/load/#{owner}/#{appId}/#{containerId}/#{nodeId}?fs=#{fs}&root=#{root}";
amLogLink: (job) ->
root = job.info['yarn.nodemanager.remote-app-log-dir']
owner = job.data.username
appId = job.id.replace('job', 'application')
containerId = job.data.amContainer
nodeId = job.data.amNode+":"+job.data.amPort
fs = job.info['fs.defaultFS'];
return "/inviso/mr2/v0/log/load/#{owner}/#{appId}/#{containerId}/#{nodeId}?fs=#{fs}&root=#{root}";
| 200353 | ##
#
# Copyright 2014 <NAME>flix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
colors=
MAP: 'blue'
REDUCE: 'orange'
RUNNING: 'green'
KILLED: 'lightgray'
FAILED: 'red'
localityColors=
NODE_LOCAL: 'green'
RACK_LOCAL: 'orange'
OFF_SWITCH: 'red'
statusMap=
RUNNING: { text: 'RUNNING', class: 'label label-success'}
INITED: { text: 'SUCCEEDED', class: 'label label-default'}
SUCCEEDED: { text: 'SUCCEEDED', class: 'label label-default'}
SUCCESS: { text: 'SUCCEEDED', class: 'label label-default'}
KILLED: { text: 'KILLED', class: 'label label-warning'}
FAILED: { text: 'FAILED', class: 'label label-danger'}
undefined: { text: 'UNKNOWN', class: 'label label-default'}
class MapReduceBase extends Application
constructor: (version) ->
@version = version
@template =
tooltip: {}
self = this
Handlebars.registerHelper('hhmmss', (start, stop) -> hhmmss(stop - start))
Handlebars.registerHelper('logLink', (job, entry) ->
return "<a class=\"log-link\" href=\"#{self.logLink(job, entry)}\" target=\"_blank\">Open Logs</a>"
)
Handlebars.registerHelper('amLogLink', (job) ->
return "<a class=\"log-link\" href=\"#{self.amLogLink(job)}\" target=\"_blank\">Open Logs</a>"
)
Handlebars.registerHelper('properties', (attempt) ->
tbody = ''
for k,v of attempt
if k == 'counters' or k == 'entries'
continue
if k.toLowerCase().contains('time') or k.toLowerCase().contains('finished')
v = moment(v).format('YYYY-MM-DD HH:mm:ss (UTC ZZ)')
tbody += "<tr><td>#{k.replace('_',' ')}</td><td>#{v}</td></tr>"
return tbody
)
Handlebars.registerHelper('counters', (counters) ->
tbody = ''
for gname, group of counters
tbody += "<tr class=\"counter-group\"><td>#{gname}</td><td></td></tr>"
for cname in _.keys(group).sort()
tbody += "<tr><td>#{cname}</td><td>#{group[cname].toLocaleString()}</td></tr>"
return tbody
)
$.get('template/job-tooltip.html', (source) ->
self.template.tooltip.job = Handlebars.compile(source);
)
$.get('template/task-tooltip.html', (source) ->
self.template.tooltip.task = Handlebars.compile(source);
)
load: (job, callback) ->
console.log "Starting data load " + job.id + new Date()
url = "/inviso/#{@version}/v0/trace/load/#{job.id}?counters=true"
if settings.directHistoryPath or job.incremental
url += "&path=#{encodeURIComponent(job['history.uri'])}"
$.ajax
url: url
type: 'GET'
dataType: 'json'
success: (traceData) =>
jobDetails=
workflowId: traceData.workflowId
id: @getId(traceData)
name: @getName(traceData)
type: 'trace'
data: @processTrace(traceData)
version: @version
info: job
app: this
xLabel: 'Task Execution Times'
yLabel: 'Task Attempts'
legend:
'Map': colors.MAP
'Reduce': colors.REDUCE
'Killed': colors.KILLED
'Failed': colors.FAILED
console.log "Trace build complete for: #{job.id}"
addChart(jobDetails)
callback(true)
error: (xhr, status, e) ->
console.log e
callback(false)
renderSearchResult: (col, r) ->
$td = $('<td></td>')
switch col.id
when 'start'
t = r[col.id]
if not t? then $td.text(time_format(r.timestamp))
if t > 0 then $td.text(time_format(t))
when 'stop'
t = r[col.id]
if t > 0 then $td.text(time_format(t))
when 'duration'
stop = r['stop']
start = r['start']
if not start? or not stop? then break
stop = if stop > 0 then stop else Date.now()
$td.text(hhmmss(stop - r['start']))
when 'job_status'
s = statusMap[r[col.id]] || {class:'label label-default', text:r[col.id]}
$td.append($("<span class=\"#{s?.class}\" >#{s?.text}</span>"))
when 'workflow_id'
id = r.genie_id || r.query_id
if ! id?
break;
$td.append($a = $("<a>#{id}</a>"))
$a.attr
href: "?workflow=#{id}#profiler"
target: "_blank"
when 'genie_id'
id = r.genie_id || r.query_id
if not id? then break
$td.append($a = $("<a>#{id}</a>"))
$a.attr
href: "?workflow=#{id}#profiler"
target: "_blank"
when 'job_id'
$td.append($a = $("<a>#{r.job_id}</a>"))
$a.attr
href: "?job=#{r.job_id}#profiler"
target: "_blank"
when 'links'
if 'job_tracker' of r || 'yarn_proxy' of r
$a = $('<a/>',
href: @getHistoryAddress(r)
target: "_blank"
).append($('<img/>', {src: 'img/hadoop.gif', class: 'hadoop-icon'}))
$td.append($('<div/>').append($a))
if 'genie_id' of r
linkVersion = if r.genie_version then r.genie_version else ''
apiVersion = if r.genie_version then r.genie_version else 0
$a = $('<a/>',
href: "http://go/genie#{linkVersion}-prod/genie/v#{apiVersion}/jobs/#{r.genie_id}"
target: "_blank"
).append($('<img/>', {src: 'img/genie.gif', class: 'genie-icon'}))
$td.append($('<div/>').append($a))
if 'lipstick_url' of r
url = r.lipstick_url.split(',').random()
$a = $('<a/>',
href: "#{url}/graph.html#graph/#{r.genie_id ? r.lipstick_id}"
target: "_blank"
).append($('<img/>', {src: 'img/lipstick.png', class: 'lipstick-icon'}))
$td.append($('<div/>').append($a))
when 'version'
$td.text(r[col.id] ? 'mr1')
else
$td.text(r[col.id])
return $td
render: (data, $div) ->
$.get('template/mapreduce.html', (t) ->
$div.append($(t))
$div.find('.panel-title').text(data.id)
$chart = $div.find('.timeseries')
$chart.series({'series': data})
$actions = $div.find('.chart-actions')
$actions.find('.align-time').click(() -> $chart.series('option', 'flat', false))
$actions.find('.align-left').click(() -> $chart.series('option', 'flat', true))
$actions.find('.locality').click(() ->
@toggle = !@toggle;
if @toggle
@colorsave = $chart.series('option', 'color')
$chart.series('option', 'color', (d) ->
return localityColors[d.attempt.locality] || 'gray'
)
$chart.series('option', 'legend', localityColors)
else
$chart.series('option', 'color', @colorsave)
$chart.series('option', 'legend', null)
)
$actions.find('.zoom-in').click(()->
zoom = $chart.series('option', 'barHeight')
$chart.series('option', 'barHeight', zoom+1)
)
$actions.find('.zoom-out').click(()->
zoom = $chart.series('option', 'barHeight')
if zoom <= 1
return
$chart.series('option', 'barHeight', zoom-1)
)
$actions.find('.toggle-legend').click(()->
$chart.series('option', 'showLegend', !$chart.series('option', 'showLegend'))
)
$actions.find('.close').click(()->$div.remove())
)
tooltip: (job, entry) ->
if ! entry?
tt = @template.tooltip.job({ job: job })
else
tt = @template.tooltip.task( { job: job, entry: entry })
return tt
class @MapReduce1 extends MapReduceBase
constructor: ->
super('mr1')
getId: (job) -> job.id
getName: (job) -> job.name
getHistoryAddress: (r) -> "http://#{r.job_tracker.split(':')[0]}:9100/jobdetails.jsp?jobid=#{r.job_id}"
processTrace: (trace) ->
data =
status: trace.status,
counters: trace.counters,
submit_time: trace.submit_time,
start_time: trace.launch_time,
stop_time: trace.finish_time,
entries: []
for taskId,task of trace.tasks
for attemptId,attempt of task.attempts
data.entries.push
id: attemptId
label: attemptId
start: attempt.start_time
stop: attempt.finish_time ? Date.now()
color: colors[attempt.task_status] ? colors[attempt.task_type] ? 'gray'
task: task
attempt: attempt
group: 1
data.entries.sort((l,r) -> l.task.start_time - r.task.start_time)
return @normalize(data)
class @MapReduce2 extends MapReduceBase
constructor: ->
super('mr2')
getId: (job) -> job.jobid
getName: (job) -> job.jobName
getHistoryAddress: (r) -> "http://#{r.yarn_proxy}/proxy/#{r.job_id.replace('job', 'application')}"
processTrace: (trace) ->
data =
username: trace.userName
status: trace.jobStatus,
counters: trace.totalCounters,
submit_time: trace.submitTime,
start_time: trace.launchTime,
stop_time: trace.finishTime,
amContainer: trace.containerId,
amNode: trace.nodeManagerHost,
amPort: trace.nodeManagerPort
entries: []
for attemptId,attempt of trace.tasks.taskid.attempts
data.entries.push
id: attemptId
label: attemptId
start: attempt.startTime
stop: attempt.finishTime ? Date.now()
color: colors[attempt.status] ? colors[attempt.taskType] ? 'gray'
task: trace.tasks[attempt.taskid]
attempt: attempt
group: 1
data.entries.sort((l,r) -> l.task.startTime - r.task.startTime)
return @normalize(data)
logLink: (job, attempt) ->
root = job.info['yarn.nodemanager.remote-app-log-dir'];
owner = job.data.username;
appId = job.id.replace('job', 'application');
containerId = attempt.attempt.containerId;
nodeId = attempt.attempt.hostname+':'+attempt.attempt.port;
fs = job.info['fs.defaultFS'];
return "/inviso/mr2/v0/log/load/#{owner}/#{appId}/#{containerId}/#{nodeId}?fs=#{fs}&root=#{root}";
amLogLink: (job) ->
root = job.info['yarn.nodemanager.remote-app-log-dir']
owner = job.data.username
appId = job.id.replace('job', 'application')
containerId = job.data.amContainer
nodeId = job.data.amNode+":"+job.data.amPort
fs = job.info['fs.defaultFS'];
return "/inviso/mr2/v0/log/load/#{owner}/#{appId}/#{containerId}/#{nodeId}?fs=#{fs}&root=#{root}";
| true | ##
#
# Copyright 2014 PI:NAME:<NAME>END_PIflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
colors=
MAP: 'blue'
REDUCE: 'orange'
RUNNING: 'green'
KILLED: 'lightgray'
FAILED: 'red'
localityColors=
NODE_LOCAL: 'green'
RACK_LOCAL: 'orange'
OFF_SWITCH: 'red'
statusMap=
RUNNING: { text: 'RUNNING', class: 'label label-success'}
INITED: { text: 'SUCCEEDED', class: 'label label-default'}
SUCCEEDED: { text: 'SUCCEEDED', class: 'label label-default'}
SUCCESS: { text: 'SUCCEEDED', class: 'label label-default'}
KILLED: { text: 'KILLED', class: 'label label-warning'}
FAILED: { text: 'FAILED', class: 'label label-danger'}
undefined: { text: 'UNKNOWN', class: 'label label-default'}
class MapReduceBase extends Application
constructor: (version) ->
@version = version
@template =
tooltip: {}
self = this
Handlebars.registerHelper('hhmmss', (start, stop) -> hhmmss(stop - start))
Handlebars.registerHelper('logLink', (job, entry) ->
return "<a class=\"log-link\" href=\"#{self.logLink(job, entry)}\" target=\"_blank\">Open Logs</a>"
)
Handlebars.registerHelper('amLogLink', (job) ->
return "<a class=\"log-link\" href=\"#{self.amLogLink(job)}\" target=\"_blank\">Open Logs</a>"
)
Handlebars.registerHelper('properties', (attempt) ->
tbody = ''
for k,v of attempt
if k == 'counters' or k == 'entries'
continue
if k.toLowerCase().contains('time') or k.toLowerCase().contains('finished')
v = moment(v).format('YYYY-MM-DD HH:mm:ss (UTC ZZ)')
tbody += "<tr><td>#{k.replace('_',' ')}</td><td>#{v}</td></tr>"
return tbody
)
Handlebars.registerHelper('counters', (counters) ->
tbody = ''
for gname, group of counters
tbody += "<tr class=\"counter-group\"><td>#{gname}</td><td></td></tr>"
for cname in _.keys(group).sort()
tbody += "<tr><td>#{cname}</td><td>#{group[cname].toLocaleString()}</td></tr>"
return tbody
)
$.get('template/job-tooltip.html', (source) ->
self.template.tooltip.job = Handlebars.compile(source);
)
$.get('template/task-tooltip.html', (source) ->
self.template.tooltip.task = Handlebars.compile(source);
)
load: (job, callback) ->
console.log "Starting data load " + job.id + new Date()
url = "/inviso/#{@version}/v0/trace/load/#{job.id}?counters=true"
if settings.directHistoryPath or job.incremental
url += "&path=#{encodeURIComponent(job['history.uri'])}"
$.ajax
url: url
type: 'GET'
dataType: 'json'
success: (traceData) =>
jobDetails=
workflowId: traceData.workflowId
id: @getId(traceData)
name: @getName(traceData)
type: 'trace'
data: @processTrace(traceData)
version: @version
info: job
app: this
xLabel: 'Task Execution Times'
yLabel: 'Task Attempts'
legend:
'Map': colors.MAP
'Reduce': colors.REDUCE
'Killed': colors.KILLED
'Failed': colors.FAILED
console.log "Trace build complete for: #{job.id}"
addChart(jobDetails)
callback(true)
error: (xhr, status, e) ->
console.log e
callback(false)
renderSearchResult: (col, r) ->
$td = $('<td></td>')
switch col.id
when 'start'
t = r[col.id]
if not t? then $td.text(time_format(r.timestamp))
if t > 0 then $td.text(time_format(t))
when 'stop'
t = r[col.id]
if t > 0 then $td.text(time_format(t))
when 'duration'
stop = r['stop']
start = r['start']
if not start? or not stop? then break
stop = if stop > 0 then stop else Date.now()
$td.text(hhmmss(stop - r['start']))
when 'job_status'
s = statusMap[r[col.id]] || {class:'label label-default', text:r[col.id]}
$td.append($("<span class=\"#{s?.class}\" >#{s?.text}</span>"))
when 'workflow_id'
id = r.genie_id || r.query_id
if ! id?
break;
$td.append($a = $("<a>#{id}</a>"))
$a.attr
href: "?workflow=#{id}#profiler"
target: "_blank"
when 'genie_id'
id = r.genie_id || r.query_id
if not id? then break
$td.append($a = $("<a>#{id}</a>"))
$a.attr
href: "?workflow=#{id}#profiler"
target: "_blank"
when 'job_id'
$td.append($a = $("<a>#{r.job_id}</a>"))
$a.attr
href: "?job=#{r.job_id}#profiler"
target: "_blank"
when 'links'
if 'job_tracker' of r || 'yarn_proxy' of r
$a = $('<a/>',
href: @getHistoryAddress(r)
target: "_blank"
).append($('<img/>', {src: 'img/hadoop.gif', class: 'hadoop-icon'}))
$td.append($('<div/>').append($a))
if 'genie_id' of r
linkVersion = if r.genie_version then r.genie_version else ''
apiVersion = if r.genie_version then r.genie_version else 0
$a = $('<a/>',
href: "http://go/genie#{linkVersion}-prod/genie/v#{apiVersion}/jobs/#{r.genie_id}"
target: "_blank"
).append($('<img/>', {src: 'img/genie.gif', class: 'genie-icon'}))
$td.append($('<div/>').append($a))
if 'lipstick_url' of r
url = r.lipstick_url.split(',').random()
$a = $('<a/>',
href: "#{url}/graph.html#graph/#{r.genie_id ? r.lipstick_id}"
target: "_blank"
).append($('<img/>', {src: 'img/lipstick.png', class: 'lipstick-icon'}))
$td.append($('<div/>').append($a))
when 'version'
$td.text(r[col.id] ? 'mr1')
else
$td.text(r[col.id])
return $td
render: (data, $div) ->
$.get('template/mapreduce.html', (t) ->
$div.append($(t))
$div.find('.panel-title').text(data.id)
$chart = $div.find('.timeseries')
$chart.series({'series': data})
$actions = $div.find('.chart-actions')
$actions.find('.align-time').click(() -> $chart.series('option', 'flat', false))
$actions.find('.align-left').click(() -> $chart.series('option', 'flat', true))
$actions.find('.locality').click(() ->
@toggle = !@toggle;
if @toggle
@colorsave = $chart.series('option', 'color')
$chart.series('option', 'color', (d) ->
return localityColors[d.attempt.locality] || 'gray'
)
$chart.series('option', 'legend', localityColors)
else
$chart.series('option', 'color', @colorsave)
$chart.series('option', 'legend', null)
)
$actions.find('.zoom-in').click(()->
zoom = $chart.series('option', 'barHeight')
$chart.series('option', 'barHeight', zoom+1)
)
$actions.find('.zoom-out').click(()->
zoom = $chart.series('option', 'barHeight')
if zoom <= 1
return
$chart.series('option', 'barHeight', zoom-1)
)
$actions.find('.toggle-legend').click(()->
$chart.series('option', 'showLegend', !$chart.series('option', 'showLegend'))
)
$actions.find('.close').click(()->$div.remove())
)
tooltip: (job, entry) ->
if ! entry?
tt = @template.tooltip.job({ job: job })
else
tt = @template.tooltip.task( { job: job, entry: entry })
return tt
class @MapReduce1 extends MapReduceBase
constructor: ->
super('mr1')
getId: (job) -> job.id
getName: (job) -> job.name
getHistoryAddress: (r) -> "http://#{r.job_tracker.split(':')[0]}:9100/jobdetails.jsp?jobid=#{r.job_id}"
processTrace: (trace) ->
data =
status: trace.status,
counters: trace.counters,
submit_time: trace.submit_time,
start_time: trace.launch_time,
stop_time: trace.finish_time,
entries: []
for taskId,task of trace.tasks
for attemptId,attempt of task.attempts
data.entries.push
id: attemptId
label: attemptId
start: attempt.start_time
stop: attempt.finish_time ? Date.now()
color: colors[attempt.task_status] ? colors[attempt.task_type] ? 'gray'
task: task
attempt: attempt
group: 1
data.entries.sort((l,r) -> l.task.start_time - r.task.start_time)
return @normalize(data)
class @MapReduce2 extends MapReduceBase
constructor: ->
super('mr2')
getId: (job) -> job.jobid
getName: (job) -> job.jobName
getHistoryAddress: (r) -> "http://#{r.yarn_proxy}/proxy/#{r.job_id.replace('job', 'application')}"
processTrace: (trace) ->
data =
username: trace.userName
status: trace.jobStatus,
counters: trace.totalCounters,
submit_time: trace.submitTime,
start_time: trace.launchTime,
stop_time: trace.finishTime,
amContainer: trace.containerId,
amNode: trace.nodeManagerHost,
amPort: trace.nodeManagerPort
entries: []
for attemptId,attempt of trace.tasks.taskid.attempts
data.entries.push
id: attemptId
label: attemptId
start: attempt.startTime
stop: attempt.finishTime ? Date.now()
color: colors[attempt.status] ? colors[attempt.taskType] ? 'gray'
task: trace.tasks[attempt.taskid]
attempt: attempt
group: 1
data.entries.sort((l,r) -> l.task.startTime - r.task.startTime)
return @normalize(data)
logLink: (job, attempt) ->
root = job.info['yarn.nodemanager.remote-app-log-dir'];
owner = job.data.username;
appId = job.id.replace('job', 'application');
containerId = attempt.attempt.containerId;
nodeId = attempt.attempt.hostname+':'+attempt.attempt.port;
fs = job.info['fs.defaultFS'];
return "/inviso/mr2/v0/log/load/#{owner}/#{appId}/#{containerId}/#{nodeId}?fs=#{fs}&root=#{root}";
amLogLink: (job) ->
root = job.info['yarn.nodemanager.remote-app-log-dir']
owner = job.data.username
appId = job.id.replace('job', 'application')
containerId = job.data.amContainer
nodeId = job.data.amNode+":"+job.data.amPort
fs = job.info['fs.defaultFS'];
return "/inviso/mr2/v0/log/load/#{owner}/#{appId}/#{containerId}/#{nodeId}?fs=#{fs}&root=#{root}";
|
[
{
"context": "or for the JavaScript generation.\n#\n# Developed by Dan Knox.\n# This project rocks and uses the MIT License.\n#",
"end": 98,
"score": 0.9998367428779602,
"start": 90,
"tag": "NAME",
"value": "Dan Knox"
}
] | coffee/gen_x_path.js.coffee | DanKnox/GenXPath | 2 | ###
# GenXPath - A simple xpath generator for the JavaScript generation.
#
# Developed by Dan Knox.
# This project rocks and uses the MIT License.
#
# Usage:
#
# You can pass GenXPath a jQuery object or plain DOM element.
#
# xpath = new GenXPath( $('#target') )
# xpath = new GenXPath( document.getElementById('target') )
#
# GenXPath will generate and store the element's xpath and a few
# other useful pieces of information.
#
# xpath.path # '//HTML[1]/BODY[1]/DIV[2]/UL[1]/LI[3]'
# xpath.parents # An array of DOM elements
# xpath.position # A jQuery position() object
# xpath.tagName # The element's tagName
###
class GenXPath
constructor: (element,debug=false) ->
if element.jquery?
@domElement = element.get(0)
@jqueryElement = element
else
@domElement = element
@jqueryElement = $(element)
@path = ""
@tagName = @domElement.tagName
@parents = @jqueryElement.parents().get()
@position = @jqueryElement.position()
console.log this if debug
@buildXPath()
buildXPath: =>
@path = @path.concat @mergeParentTags()
@path = @path.concat @elementIndex(@domElement)
mergeParentTags: =>
parentPath = "/"
$.each @parents.reverse(), (i, parent) =>
parentPath = parentPath.concat @elementIndex(parent)
parentPath
elementIndex: (element) ->
tagName = element.tagName
prevSiblings = $(element).prev(tagName)
position = prevSiblings.length + 1
"/#{tagName}[#{position}]"
$ ->
window.GenXPath = GenXPath
| 7250 | ###
# GenXPath - A simple xpath generator for the JavaScript generation.
#
# Developed by <NAME>.
# This project rocks and uses the MIT License.
#
# Usage:
#
# You can pass GenXPath a jQuery object or plain DOM element.
#
# xpath = new GenXPath( $('#target') )
# xpath = new GenXPath( document.getElementById('target') )
#
# GenXPath will generate and store the element's xpath and a few
# other useful pieces of information.
#
# xpath.path # '//HTML[1]/BODY[1]/DIV[2]/UL[1]/LI[3]'
# xpath.parents # An array of DOM elements
# xpath.position # A jQuery position() object
# xpath.tagName # The element's tagName
###
class GenXPath
constructor: (element,debug=false) ->
if element.jquery?
@domElement = element.get(0)
@jqueryElement = element
else
@domElement = element
@jqueryElement = $(element)
@path = ""
@tagName = @domElement.tagName
@parents = @jqueryElement.parents().get()
@position = @jqueryElement.position()
console.log this if debug
@buildXPath()
buildXPath: =>
@path = @path.concat @mergeParentTags()
@path = @path.concat @elementIndex(@domElement)
mergeParentTags: =>
parentPath = "/"
$.each @parents.reverse(), (i, parent) =>
parentPath = parentPath.concat @elementIndex(parent)
parentPath
elementIndex: (element) ->
tagName = element.tagName
prevSiblings = $(element).prev(tagName)
position = prevSiblings.length + 1
"/#{tagName}[#{position}]"
$ ->
window.GenXPath = GenXPath
| true | ###
# GenXPath - A simple xpath generator for the JavaScript generation.
#
# Developed by PI:NAME:<NAME>END_PI.
# This project rocks and uses the MIT License.
#
# Usage:
#
# You can pass GenXPath a jQuery object or plain DOM element.
#
# xpath = new GenXPath( $('#target') )
# xpath = new GenXPath( document.getElementById('target') )
#
# GenXPath will generate and store the element's xpath and a few
# other useful pieces of information.
#
# xpath.path # '//HTML[1]/BODY[1]/DIV[2]/UL[1]/LI[3]'
# xpath.parents # An array of DOM elements
# xpath.position # A jQuery position() object
# xpath.tagName # The element's tagName
###
class GenXPath
constructor: (element,debug=false) ->
if element.jquery?
@domElement = element.get(0)
@jqueryElement = element
else
@domElement = element
@jqueryElement = $(element)
@path = ""
@tagName = @domElement.tagName
@parents = @jqueryElement.parents().get()
@position = @jqueryElement.position()
console.log this if debug
@buildXPath()
buildXPath: =>
@path = @path.concat @mergeParentTags()
@path = @path.concat @elementIndex(@domElement)
mergeParentTags: =>
parentPath = "/"
$.each @parents.reverse(), (i, parent) =>
parentPath = parentPath.concat @elementIndex(parent)
parentPath
elementIndex: (element) ->
tagName = element.tagName
prevSiblings = $(element).prev(tagName)
position = prevSiblings.length + 1
"/#{tagName}[#{position}]"
$ ->
window.GenXPath = GenXPath
|
[
{
"context": "ush(heatmapLayer)\n\n map = L.map id,\n # Gitega, Burundi\n center: new L.LatLng -3.4314318,",
"end": 2533,
"score": 0.9751127362251282,
"start": 2527,
"tag": "NAME",
"value": "Gitega"
},
{
"context": "mapLayer)\n\n map = L.map id,\n # Git... | app/scripts/services.coffee | taarifa/Actuality | 0 | 'use strict'
angular.module('actualityApp')
.factory 'ApiResource', ($resource, $http, flash) ->
(resource, args) ->
Resource = $resource "/api/#{resource}/:id"
, # Default arguments
args
, # Override methods
query:
method: 'GET'
isArray: false
Resource.update = (id, data) ->
# We need to remove special attributes starting with _ since they are
# not defined in the schema and the data will not validate and the
# update be rejected
putdata = {}
for k, v of data when k[0] != '_'
putdata[k] = v
$http.put("/api/#{resource}/"+id, putdata,
headers: {'If-Match': data._etag})
.success (res, status) ->
if status == 200 and res._status == 'OK'
flash.success = "#{resource} successfully updated!"
data._etag = res._etag
if status == 200 and res._status == 'ERR'
for field, message of res._issues
flash.error = "#{field}: #{message}"
Resource.patch = (id, data, etag) ->
$http
method: 'PATCH'
url: "/api/#{resource}/"+id
data: data
headers: {'If-Match': etag}
return Resource
.factory 'Facility', (ApiResource) ->
ApiResource 'facilities'
.factory 'Vehicle', (ApiResource) ->
ApiResource 'vehicles'
.factory 'Movement', (ApiResource) ->
ApiResource 'movements'
.factory 'Map', ($filter) ->
(id, opts) =>
defaults =
markerType: "regular"
heatmap: false
showScale: false
options = _.extend(defaults, opts)
osmLayer = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: '(c) OpenStreetMap')
satLayer = L.tileLayer(
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
attribution: '(c) Esri')
baseMaps =
"Open Street Map": osmLayer
"Satellite": satLayer
overlays = {}
markerLayer = L.featureGroup()
overlays.Routes = markerLayer
defaultLayers = [osmLayer, markerLayer]
if options.heatmap
heatmapLayer = new HeatmapOverlay
radius: 15
maxOpacity: .7
scaleRadius: false
useLocalExtrema: true
overlays["Routes Heatmap"] = heatmapLayer
# we add the heatmap layer by default
defaultLayers.push(heatmapLayer)
map = L.map id,
# Gitega, Burundi
center: new L.LatLng -3.4314318, 29.9254274
zoom: 5
fullscreenControl: true
layers: defaultLayers
if options.heatmap
# FIXME: remove the heatmap layer again to workaround
# https://github.com/pa7/heatmap.js/issues/130
map.removeLayer(heatmapLayer)
# add a layer selector
layerSelector = L.control.layers(baseMaps, overlays).addTo(map)
# add a distance scale
if options.showScale
scale = L.control.scale().addTo(map)
makePopup = (mv) ->
cleanKey = (k) ->
$filter('titlecase')(k.replace("_"," "))
cleanValue = (k,v) ->
if v instanceof Date
v.getFullYear()
else if k == "location"
v.coordinates.toString()
else
v
header = '<h5>Vehicle ' + mv.license_plate + ' (<a href="#/movements/' + mv._id + '">Edit</a>)</h5>' +
'<span class="popup-key">Status</span>: ' + mv.status + '<br />' +
'<a href="#/movements/?license_plate=' + mv.license_plate + '">Show movements</a> | ' +
'<a href="#/movements/new?license_plate=' + mv.license_plate + '">Submit report</a>' +
'<hr style="margin-top:10px; margin-bottom: 10px;" />'
# FIXME: can't this be offloaded to angular somehow?
fields = _.keys(mv).sort().map((k) ->
'<span class="popup-key">' + cleanKey(k) + '</span>: ' +
'<span class="popup-value">' + String(cleanValue(k,mv[k])) + '</span>'
).join('<br />')
html = '<div class="popup">' + header + fields + '</div>'
@clearMarkers = () ->
markerLayer.clearLayers()
# FIXME: more hardcoded statusses
makeAwesomeIcon = (status) ->
if status == 'legitimate'
color = 'green'
else if status == 'illegal'
color = 'red'
else
color = 'black'
icon = L.AwesomeMarkers.icon
prefix: 'glyphicon',
icon: 'tint',
markerColor: color
makeMarker = (mv) ->
[lng,lat] = mv.location.coordinates
mt = options.markerType
if mt == "circle"
m = L.circleMarker L.latLng(lat,lng),
stroke: false
radius: 5
fillOpacity: 1
fillColor: {legitimate: 'green', illegal: 'red', unknown: 'black'}[mv.status]
else
m = L.marker L.latLng(lat,lng),
icon: makeAwesomeIcon(mv.status)
@addMovements = (mvs) ->
mvs.forEach (mv) ->
[lng,lat] = mv.location.coordinates
m = makeMarker(mv)
popup = makePopup(mv)
m.bindPopup popup
markerLayer.addLayer(m)
if options.coverage
coords = mvs.map (x) -> [x.location.coordinates[1], x.location.coordinates[0]]
coverageLayer.setData coords
if options.heatmap
costMap =
unknown: 0
legitimate: -1
illegal: 1
coords = []
mvs.forEach (x) ->
coords.push
lat: x.location.coordinates[1]
lng: x.location.coordinates[0]
value: costMap[x.status]
heatmapLayer.setData
data: coords
@zoomToMarkers = () ->
bounds = markerLayer.getBounds()
if bounds.isValid()
map.fitBounds(bounds)
return this
# Get an angular-dynamic-forms compatible form description from a Facility
# given a facility code
.factory 'FacilityForm', (Facility) ->
(facility_code) ->
Facility.get(where: {facility_code: facility_code})
# Return a promise since dynamic-forms needs the form template in
# scope when the controller is invoked
.$promise.then (facility) ->
mkfield = (type, label, step) ->
type: type
label: label
step: step
class: "form-control"
wrapper: '<div class="form-group"></div>'
fields = {}
for f, v of facility._items[0].fields
if v.type == 'point'
fields.longitude = mkfield 'number', 'longitude', 'any'
fields.latitude = mkfield 'number', 'latitude', 'any'
fields.longitude.model = 'location.coordinates[0]'
fields.latitude.model = 'location.coordinates[1]'
else
# Use the field name as label if no label was specified
fields[f] = mkfield v.input || v.type, v.label || f
if v.type in ['float', 'number']
fields[f].step = 'any'
if v.allowed?
fields[f].type = 'select'
options = {}
options[label] = label: label for label in v.allowed
fields[f].options = options
fields.submit =
type: "submit"
label: "Save"
class: "btn btn-primary"
return fields
.factory 'FacilityCreate', (FacilityForm, Map, flash, geolocation, $location) ->
(scope, facility, facility_code, name) ->
scope.formTemplate = FacilityForm facility_code
d = new Date()
d.setSeconds(0)
d.setMilliseconds(0)
scope.form =
facility_code: facility_code
date_recorded: d
_.extend(scope.form, $location.search())
geolocation.getLocation().then (data) ->
flash.success = "Geolocation succeeded: got coordinates" + " #{data.coords.longitude.toPrecision(4)}, #{data.coords.latitude.toPrecision(4)}"
scope.form.location = coordinates: [data.coords.longitude, data.coords.latitude]
map = Map("editMap", {})
map.clearMarkers()
map.addMovements([scope.form])
map.zoomToMarkers()
, (reason) ->
flash.error = "Geolocation failed:" + " #{reason}"
scope.save = () ->
form = {}
for k, v of scope.form
if v != null
form[k] = if v instanceof Date then v.toGMTString() else v
if v.coordinates
form[k].type = 'Point'
console.log form
facility.save form, (f) ->
if f._status == 'OK'
console.log "Successfully created #{name}", f
flash.success = "#{name} successfully created!"
if f._status == 'ERR'
console.log "Failed to create #{name}", f
for field, message of f._issues
flash.error = "#{field}: #{message}"
.factory 'FacilityEdit', (FacilityForm, Map, $routeParams) ->
(scope, facility, facility_code) ->
map = Map("editMap", {})
facility.get id: $routeParams.id, (f) ->
# We are editing a facility so set the date_recorded
# field to today, should it be saved.
d = new Date()
d.setSeconds(0)
d.setMilliseconds(0)
f.date_recorded = d
scope.form = f
map.clearMarkers()
map.addMovements([f])
map.zoomToMarkers()
scope.formTemplate = FacilityForm facility_code
scope.save = () ->
for f of scope.form
if scope.form[f] instanceof Date
scope.form[f] = scope.form[f].toGMTString()
facility.update(id, scope.form)
| 84494 | 'use strict'
angular.module('actualityApp')
.factory 'ApiResource', ($resource, $http, flash) ->
(resource, args) ->
Resource = $resource "/api/#{resource}/:id"
, # Default arguments
args
, # Override methods
query:
method: 'GET'
isArray: false
Resource.update = (id, data) ->
# We need to remove special attributes starting with _ since they are
# not defined in the schema and the data will not validate and the
# update be rejected
putdata = {}
for k, v of data when k[0] != '_'
putdata[k] = v
$http.put("/api/#{resource}/"+id, putdata,
headers: {'If-Match': data._etag})
.success (res, status) ->
if status == 200 and res._status == 'OK'
flash.success = "#{resource} successfully updated!"
data._etag = res._etag
if status == 200 and res._status == 'ERR'
for field, message of res._issues
flash.error = "#{field}: #{message}"
Resource.patch = (id, data, etag) ->
$http
method: 'PATCH'
url: "/api/#{resource}/"+id
data: data
headers: {'If-Match': etag}
return Resource
.factory 'Facility', (ApiResource) ->
ApiResource 'facilities'
.factory 'Vehicle', (ApiResource) ->
ApiResource 'vehicles'
.factory 'Movement', (ApiResource) ->
ApiResource 'movements'
.factory 'Map', ($filter) ->
(id, opts) =>
defaults =
markerType: "regular"
heatmap: false
showScale: false
options = _.extend(defaults, opts)
osmLayer = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: '(c) OpenStreetMap')
satLayer = L.tileLayer(
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
attribution: '(c) Esri')
baseMaps =
"Open Street Map": osmLayer
"Satellite": satLayer
overlays = {}
markerLayer = L.featureGroup()
overlays.Routes = markerLayer
defaultLayers = [osmLayer, markerLayer]
if options.heatmap
heatmapLayer = new HeatmapOverlay
radius: 15
maxOpacity: .7
scaleRadius: false
useLocalExtrema: true
overlays["Routes Heatmap"] = heatmapLayer
# we add the heatmap layer by default
defaultLayers.push(heatmapLayer)
map = L.map id,
# <NAME>, <NAME>
center: new L.LatLng -3.4314318, 29.9254274
zoom: 5
fullscreenControl: true
layers: defaultLayers
if options.heatmap
# FIXME: remove the heatmap layer again to workaround
# https://github.com/pa7/heatmap.js/issues/130
map.removeLayer(heatmapLayer)
# add a layer selector
layerSelector = L.control.layers(baseMaps, overlays).addTo(map)
# add a distance scale
if options.showScale
scale = L.control.scale().addTo(map)
makePopup = (mv) ->
cleanKey = (k) ->
$filter('titlecase')(k.replace("_"," "))
cleanValue = (k,v) ->
if v instanceof Date
v.getFullYear()
else if k == "location"
v.coordinates.toString()
else
v
header = '<h5>Vehicle ' + mv.license_plate + ' (<a href="#/movements/' + mv._id + '">Edit</a>)</h5>' +
'<span class="popup-key">Status</span>: ' + mv.status + '<br />' +
'<a href="#/movements/?license_plate=' + mv.license_plate + '">Show movements</a> | ' +
'<a href="#/movements/new?license_plate=' + mv.license_plate + '">Submit report</a>' +
'<hr style="margin-top:10px; margin-bottom: 10px;" />'
# FIXME: can't this be offloaded to angular somehow?
fields = _.keys(mv).sort().map((k) ->
'<span class="popup-key">' + cleanKey(k) + '</span>: ' +
'<span class="popup-value">' + String(cleanValue(k,mv[k])) + '</span>'
).join('<br />')
html = '<div class="popup">' + header + fields + '</div>'
@clearMarkers = () ->
markerLayer.clearLayers()
# FIXME: more hardcoded statusses
makeAwesomeIcon = (status) ->
if status == 'legitimate'
color = 'green'
else if status == 'illegal'
color = 'red'
else
color = 'black'
icon = L.AwesomeMarkers.icon
prefix: 'glyphicon',
icon: 'tint',
markerColor: color
makeMarker = (mv) ->
[lng,lat] = mv.location.coordinates
mt = options.markerType
if mt == "circle"
m = L.circleMarker L.latLng(lat,lng),
stroke: false
radius: 5
fillOpacity: 1
fillColor: {legitimate: 'green', illegal: 'red', unknown: 'black'}[mv.status]
else
m = L.marker L.latLng(lat,lng),
icon: makeAwesomeIcon(mv.status)
@addMovements = (mvs) ->
mvs.forEach (mv) ->
[lng,lat] = mv.location.coordinates
m = makeMarker(mv)
popup = makePopup(mv)
m.bindPopup popup
markerLayer.addLayer(m)
if options.coverage
coords = mvs.map (x) -> [x.location.coordinates[1], x.location.coordinates[0]]
coverageLayer.setData coords
if options.heatmap
costMap =
unknown: 0
legitimate: -1
illegal: 1
coords = []
mvs.forEach (x) ->
coords.push
lat: x.location.coordinates[1]
lng: x.location.coordinates[0]
value: costMap[x.status]
heatmapLayer.setData
data: coords
@zoomToMarkers = () ->
bounds = markerLayer.getBounds()
if bounds.isValid()
map.fitBounds(bounds)
return this
# Get an angular-dynamic-forms compatible form description from a Facility
# given a facility code
.factory 'FacilityForm', (Facility) ->
(facility_code) ->
Facility.get(where: {facility_code: facility_code})
# Return a promise since dynamic-forms needs the form template in
# scope when the controller is invoked
.$promise.then (facility) ->
mkfield = (type, label, step) ->
type: type
label: label
step: step
class: "form-control"
wrapper: '<div class="form-group"></div>'
fields = {}
for f, v of facility._items[0].fields
if v.type == 'point'
fields.longitude = mkfield 'number', 'longitude', 'any'
fields.latitude = mkfield 'number', 'latitude', 'any'
fields.longitude.model = 'location.coordinates[0]'
fields.latitude.model = 'location.coordinates[1]'
else
# Use the field name as label if no label was specified
fields[f] = mkfield v.input || v.type, v.label || f
if v.type in ['float', 'number']
fields[f].step = 'any'
if v.allowed?
fields[f].type = 'select'
options = {}
options[label] = label: label for label in v.allowed
fields[f].options = options
fields.submit =
type: "submit"
label: "Save"
class: "btn btn-primary"
return fields
.factory 'FacilityCreate', (FacilityForm, Map, flash, geolocation, $location) ->
(scope, facility, facility_code, name) ->
scope.formTemplate = FacilityForm facility_code
d = new Date()
d.setSeconds(0)
d.setMilliseconds(0)
scope.form =
facility_code: facility_code
date_recorded: d
_.extend(scope.form, $location.search())
geolocation.getLocation().then (data) ->
flash.success = "Geolocation succeeded: got coordinates" + " #{data.coords.longitude.toPrecision(4)}, #{data.coords.latitude.toPrecision(4)}"
scope.form.location = coordinates: [data.coords.longitude, data.coords.latitude]
map = Map("editMap", {})
map.clearMarkers()
map.addMovements([scope.form])
map.zoomToMarkers()
, (reason) ->
flash.error = "Geolocation failed:" + " #{reason}"
scope.save = () ->
form = {}
for k, v of scope.form
if v != null
form[k] = if v instanceof Date then v.toGMTString() else v
if v.coordinates
form[k].type = 'Point'
console.log form
facility.save form, (f) ->
if f._status == 'OK'
console.log "Successfully created #{name}", f
flash.success = "#{name} successfully created!"
if f._status == 'ERR'
console.log "Failed to create #{name}", f
for field, message of f._issues
flash.error = "#{field}: #{message}"
.factory 'FacilityEdit', (FacilityForm, Map, $routeParams) ->
(scope, facility, facility_code) ->
map = Map("editMap", {})
facility.get id: $routeParams.id, (f) ->
# We are editing a facility so set the date_recorded
# field to today, should it be saved.
d = new Date()
d.setSeconds(0)
d.setMilliseconds(0)
f.date_recorded = d
scope.form = f
map.clearMarkers()
map.addMovements([f])
map.zoomToMarkers()
scope.formTemplate = FacilityForm facility_code
scope.save = () ->
for f of scope.form
if scope.form[f] instanceof Date
scope.form[f] = scope.form[f].toGMTString()
facility.update(id, scope.form)
| true | 'use strict'
angular.module('actualityApp')
.factory 'ApiResource', ($resource, $http, flash) ->
(resource, args) ->
Resource = $resource "/api/#{resource}/:id"
, # Default arguments
args
, # Override methods
query:
method: 'GET'
isArray: false
Resource.update = (id, data) ->
# We need to remove special attributes starting with _ since they are
# not defined in the schema and the data will not validate and the
# update be rejected
putdata = {}
for k, v of data when k[0] != '_'
putdata[k] = v
$http.put("/api/#{resource}/"+id, putdata,
headers: {'If-Match': data._etag})
.success (res, status) ->
if status == 200 and res._status == 'OK'
flash.success = "#{resource} successfully updated!"
data._etag = res._etag
if status == 200 and res._status == 'ERR'
for field, message of res._issues
flash.error = "#{field}: #{message}"
Resource.patch = (id, data, etag) ->
$http
method: 'PATCH'
url: "/api/#{resource}/"+id
data: data
headers: {'If-Match': etag}
return Resource
.factory 'Facility', (ApiResource) ->
ApiResource 'facilities'
.factory 'Vehicle', (ApiResource) ->
ApiResource 'vehicles'
.factory 'Movement', (ApiResource) ->
ApiResource 'movements'
.factory 'Map', ($filter) ->
(id, opts) =>
defaults =
markerType: "regular"
heatmap: false
showScale: false
options = _.extend(defaults, opts)
osmLayer = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: '(c) OpenStreetMap')
satLayer = L.tileLayer(
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
attribution: '(c) Esri')
baseMaps =
"Open Street Map": osmLayer
"Satellite": satLayer
overlays = {}
markerLayer = L.featureGroup()
overlays.Routes = markerLayer
defaultLayers = [osmLayer, markerLayer]
if options.heatmap
heatmapLayer = new HeatmapOverlay
radius: 15
maxOpacity: .7
scaleRadius: false
useLocalExtrema: true
overlays["Routes Heatmap"] = heatmapLayer
# we add the heatmap layer by default
defaultLayers.push(heatmapLayer)
map = L.map id,
# PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
center: new L.LatLng -3.4314318, 29.9254274
zoom: 5
fullscreenControl: true
layers: defaultLayers
if options.heatmap
# FIXME: remove the heatmap layer again to workaround
# https://github.com/pa7/heatmap.js/issues/130
map.removeLayer(heatmapLayer)
# add a layer selector
layerSelector = L.control.layers(baseMaps, overlays).addTo(map)
# add a distance scale
if options.showScale
scale = L.control.scale().addTo(map)
makePopup = (mv) ->
cleanKey = (k) ->
$filter('titlecase')(k.replace("_"," "))
cleanValue = (k,v) ->
if v instanceof Date
v.getFullYear()
else if k == "location"
v.coordinates.toString()
else
v
header = '<h5>Vehicle ' + mv.license_plate + ' (<a href="#/movements/' + mv._id + '">Edit</a>)</h5>' +
'<span class="popup-key">Status</span>: ' + mv.status + '<br />' +
'<a href="#/movements/?license_plate=' + mv.license_plate + '">Show movements</a> | ' +
'<a href="#/movements/new?license_plate=' + mv.license_plate + '">Submit report</a>' +
'<hr style="margin-top:10px; margin-bottom: 10px;" />'
# FIXME: can't this be offloaded to angular somehow?
fields = _.keys(mv).sort().map((k) ->
'<span class="popup-key">' + cleanKey(k) + '</span>: ' +
'<span class="popup-value">' + String(cleanValue(k,mv[k])) + '</span>'
).join('<br />')
html = '<div class="popup">' + header + fields + '</div>'
@clearMarkers = () ->
markerLayer.clearLayers()
# FIXME: more hardcoded statusses
makeAwesomeIcon = (status) ->
if status == 'legitimate'
color = 'green'
else if status == 'illegal'
color = 'red'
else
color = 'black'
icon = L.AwesomeMarkers.icon
prefix: 'glyphicon',
icon: 'tint',
markerColor: color
makeMarker = (mv) ->
[lng,lat] = mv.location.coordinates
mt = options.markerType
if mt == "circle"
m = L.circleMarker L.latLng(lat,lng),
stroke: false
radius: 5
fillOpacity: 1
fillColor: {legitimate: 'green', illegal: 'red', unknown: 'black'}[mv.status]
else
m = L.marker L.latLng(lat,lng),
icon: makeAwesomeIcon(mv.status)
@addMovements = (mvs) ->
mvs.forEach (mv) ->
[lng,lat] = mv.location.coordinates
m = makeMarker(mv)
popup = makePopup(mv)
m.bindPopup popup
markerLayer.addLayer(m)
if options.coverage
coords = mvs.map (x) -> [x.location.coordinates[1], x.location.coordinates[0]]
coverageLayer.setData coords
if options.heatmap
costMap =
unknown: 0
legitimate: -1
illegal: 1
coords = []
mvs.forEach (x) ->
coords.push
lat: x.location.coordinates[1]
lng: x.location.coordinates[0]
value: costMap[x.status]
heatmapLayer.setData
data: coords
@zoomToMarkers = () ->
bounds = markerLayer.getBounds()
if bounds.isValid()
map.fitBounds(bounds)
return this
# Get an angular-dynamic-forms compatible form description from a Facility
# given a facility code
.factory 'FacilityForm', (Facility) ->
(facility_code) ->
Facility.get(where: {facility_code: facility_code})
# Return a promise since dynamic-forms needs the form template in
# scope when the controller is invoked
.$promise.then (facility) ->
mkfield = (type, label, step) ->
type: type
label: label
step: step
class: "form-control"
wrapper: '<div class="form-group"></div>'
fields = {}
for f, v of facility._items[0].fields
if v.type == 'point'
fields.longitude = mkfield 'number', 'longitude', 'any'
fields.latitude = mkfield 'number', 'latitude', 'any'
fields.longitude.model = 'location.coordinates[0]'
fields.latitude.model = 'location.coordinates[1]'
else
# Use the field name as label if no label was specified
fields[f] = mkfield v.input || v.type, v.label || f
if v.type in ['float', 'number']
fields[f].step = 'any'
if v.allowed?
fields[f].type = 'select'
options = {}
options[label] = label: label for label in v.allowed
fields[f].options = options
fields.submit =
type: "submit"
label: "Save"
class: "btn btn-primary"
return fields
.factory 'FacilityCreate', (FacilityForm, Map, flash, geolocation, $location) ->
(scope, facility, facility_code, name) ->
scope.formTemplate = FacilityForm facility_code
d = new Date()
d.setSeconds(0)
d.setMilliseconds(0)
scope.form =
facility_code: facility_code
date_recorded: d
_.extend(scope.form, $location.search())
geolocation.getLocation().then (data) ->
flash.success = "Geolocation succeeded: got coordinates" + " #{data.coords.longitude.toPrecision(4)}, #{data.coords.latitude.toPrecision(4)}"
scope.form.location = coordinates: [data.coords.longitude, data.coords.latitude]
map = Map("editMap", {})
map.clearMarkers()
map.addMovements([scope.form])
map.zoomToMarkers()
, (reason) ->
flash.error = "Geolocation failed:" + " #{reason}"
scope.save = () ->
form = {}
for k, v of scope.form
if v != null
form[k] = if v instanceof Date then v.toGMTString() else v
if v.coordinates
form[k].type = 'Point'
console.log form
facility.save form, (f) ->
if f._status == 'OK'
console.log "Successfully created #{name}", f
flash.success = "#{name} successfully created!"
if f._status == 'ERR'
console.log "Failed to create #{name}", f
for field, message of f._issues
flash.error = "#{field}: #{message}"
.factory 'FacilityEdit', (FacilityForm, Map, $routeParams) ->
(scope, facility, facility_code) ->
map = Map("editMap", {})
facility.get id: $routeParams.id, (f) ->
# We are editing a facility so set the date_recorded
# field to today, should it be saved.
d = new Date()
d.setSeconds(0)
d.setMilliseconds(0)
f.date_recorded = d
scope.form = f
map.clearMarkers()
map.addMovements([f])
map.zoomToMarkers()
scope.formTemplate = FacilityForm facility_code
scope.save = () ->
for f of scope.form
if scope.form[f] instanceof Date
scope.form[f] = scope.form[f].toGMTString()
facility.update(id, scope.form)
|
[
{
"context": "---------------------------------------------\n@hamt = ( n, show ) -> new Promise ( resolve ) =>\n ham",
"end": 6342,
"score": 0.6143583655357361,
"start": 6341,
"tag": "USERNAME",
"value": "t"
},
{
"context": "-----------------------------------------------\n@mori = (... | dev/letsfreezethat/src/main.benchmarks.coffee | loveencounterflow/hengist | 0 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'LFT'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#...........................................................................................................
PATH = require 'path'
FS = require 'fs'
DATA = require '../../../lib/data-providers'
test = require 'guy-test'
{ jr } = CND
BM = require '../../../lib/benchmarks'
data_cache = null
#-----------------------------------------------------------------------------------------------------------
@get_data = ( n ) ->
return data_cache if data_cache?
probes_A = DATA.get_random_nested_objects n, null, true
probes_B = DATA.get_random_nested_objects n, null, true
# debug '^3342^', probes_A
# debug '^3342^', probes_B
# debug '^3342^', probes_C
### NOTE could count number of actual properties in nested objects ###
data_cache = { probes_A, probes_B, }
return ( require '../../../apps/letsfreezethat' ).freeze data_cache
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v3_lets = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
if lft_cfg.freeze then lets = require '../../../apps/letsfreezethat/freeze'
else lets = require '../../../apps/letsfreezethat/nofreeze'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = lets probe
probe = lets probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return null
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v3_f1_lets = ( n, show ) -> @_letsfreezethat_v3_lets n, show, { freeze: true, }
@letsfreezethat_v3_f0_lets = ( n, show ) -> @_letsfreezethat_v3_lets n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v3_freezethaw = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
if lft_cfg.freeze then lets = require '../../../apps/letsfreezethat/freeze'
else lets = require '../../../apps/letsfreezethat/nofreeze'
{ thaw
freeze } = lets
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = thaw probe
for k, v of probes_B[ idx ]
probe[ k ] = v
probe = freeze probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v3_f1_freezethaw = ( n, show ) -> @_letsfreezethat_v3_freezethaw n, show, { freeze: true, }
@letsfreezethat_v3_f0_freezethaw = ( n, show ) -> @_letsfreezethat_v3_freezethaw n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v2_lets = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
LFT = require '../letsfreezethat@2.2.5'
if lft_cfg.freeze then { lets } = LFT
else { lets } = LFT.nofreeze
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = lets probe
probe = lets probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return null
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v2_f1_lets = ( n, show ) -> @_letsfreezethat_v2_lets n, show, { freeze: true, }
@letsfreezethat_v2_f0_lets = ( n, show ) -> @_letsfreezethat_v2_lets n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v2_freezethaw = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
LFT = require '../letsfreezethat@2.2.5'
if lft_cfg.freeze then { freeze, } = LFT
else { freeze, } = LFT.nofreeze
### Bug (or feature?) of LFTv2: in nofreeze mode, `thaw()` does not copy object ###
{ thaw, } = LFT
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = thaw probe
for k, v of probes_B[ idx ]
probe[ k ] = v
probe = freeze probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v2_f1_freezethaw = ( n, show ) -> @_letsfreezethat_v2_freezethaw n, show, { freeze: true, }
@letsfreezethat_v2_f0_freezethaw = ( n, show ) -> @_letsfreezethat_v2_freezethaw n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@immutable = ( n, show ) -> new Promise ( resolve ) =>
{ Map } = require 'immutable'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = Map probe
for k, v of probes_B[ idx ]
probe = probe.set k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@hamt = ( n, show ) -> new Promise ( resolve ) =>
hamt = require 'hamt'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = hamt.empty
probe = probe.set k, v for k, v of probe ### NOTE must always iterate over facets, no bulk `set()` ###
for k, v of probes_B[ idx ]
probe = probe.set k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@mori = ( n, show ) -> new Promise ( resolve ) =>
M = require 'mori'
count = 0
{ probes_A
probes_B } = @get_data n
probes_A_entries = []
for probe in probes_A
probes_A_entries.push ( [ k, v, ] for k, v of probe )
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A_entries
probe = M.hashMap probe...
for k, v of probes_B[ idx ]
probe = M.assoc probe, k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@immer = ( n, show ) -> new Promise ( resolve ) =>
IMMER = require 'immer'
{ produce, } = IMMER
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = produce probe, ( probe ) -> probe
probe = produce probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@plainjs_mutable = ( n, show ) -> new Promise ( resolve ) =>
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = Object.assign {}, probe
for k, v of probes_B[ idx ]
probe[ k ] = v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@demo_immutable = ->
```
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
```
help map1.get('b') + " vs. " + map2.get('b'); # 2 vs. 50
whisper Object.keys map1
whisper [ map1.keys()..., ]
return null
#-----------------------------------------------------------------------------------------------------------
@demo_hamt = ->
```
var hamt = require('hamt');
// Keys can be any string and the map can store any value.
var h = hamt.empty
.set('key', 'value')
.set('object', { prop: 1 })
.set('falsy', null);
h.size === 0
h.has('key') === true
h.has('falsy') === true
h.get('key') === 'value'
// Iteration
for (let [key, value] of h)
console.log(key, value);
// Array.from(h.values()) === [{ prop: 1 }, 'value'], null];
// The data structure is fully immutable
var h2 = h.delete('key');
h2.get('key') === undefined
h.get('key') === 'value'
```
urge '^33387^', h
return null
#-----------------------------------------------------------------------------------------------------------
@demo_mori = ->
M = require 'mori'
debug ( k for k of M ).sort()
debug M.vector 'a', 42
d = M.hashMap()
# d = M.mutable.thaw d
for n in [ 1 .. 100 ]
d = M.assoc d, n, n ** 2
# d = M.mutable.freeze d
d = M.assoc d, 'helo', 'world'
urge d
help M.toClj d
urge M.toJs d
return null
#-----------------------------------------------------------------------------------------------------------
@demo_letsfreezethat_new_api = ->
lets = require '../../../apps/letsfreezethat'
d1 = lets { first: 1, }, { second: 2, }
d2 = lets.set d1, 'foo', 42
d3 = lets.assign d2, { foo: 108, bar: 'baz', }, { gnu: 'gnat', }
urge Object.isFrozen d1
urge Object.isFrozen d2
urge Object.isFrozen d3
help d1
help d2
help d3
urge d1 is d2
urge lets.get d1, 'foo'
urge lets.get d2, 'foo'
urge Object.keys d2
urge ( k for k of d2 )
urge Object.keys d3
return null
#-----------------------------------------------------------------------------------------------------------
@run_benchmarks = ->
bench = BM.new_benchmarks()
# n = 100000
n = 100
n = 10
n = 1000
show = false
repetitions = 3
test_names = [
'immer'
'letsfreezethat_v3_f1_lets'
'letsfreezethat_v3_f0_lets'
'letsfreezethat_v2_f1_lets'
'letsfreezethat_v2_f0_lets'
'letsfreezethat_v3_f1_freezethaw'
'letsfreezethat_v3_f0_freezethaw'
'letsfreezethat_v2_f1_freezethaw'
'letsfreezethat_v2_f0_freezethaw'
'immutable'
'hamt'
'mori'
'plainjs_mutable'
]
global.gc() if global.gc?
for _ in [ 1 .. repetitions ]
whisper '-'.repeat 108
for test_name in CND.shuffle test_names
data_cache = null
global.gc() if global.gc?
await BM.benchmark bench, n, show, @, test_name
BM.show_totals bench
############################################################################################################
if require.main is module then do =>
await @run_benchmarks()
###
# To Do
* ramda (https://www.skypack.dev/search?q=ramda&p=1)
* rambda (Lightweight and faster alternative to Ramda)
* ramdax
###
###
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f0_freezethaw 116,513 Hz 100.0 % │████████████▌│
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f1_freezethaw 97,101 Hz 83.3 % │██████████▍ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f0_lets 93,101 Hz 79.9 % │██████████ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f1_lets 76,045 Hz 65.3 % │████████▏ │
00:11 HENGIST/BENCHMARKS ▶ plainjs_mutable 28,035 Hz 24.1 % │███ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f0_lets 22,410 Hz 19.2 % │██▍ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f0_freezethaw 16,854 Hz 14.5 % │█▊ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f1_freezethaw 16,443 Hz 14.1 % │█▊ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f1_lets 13,648 Hz 11.7 % │█▌ │
00:11 HENGIST/BENCHMARKS ▶ immutable 8,359 Hz 7.2 % │▉ │
00:11 HENGIST/BENCHMARKS ▶ mori 7,845 Hz 6.7 % │▉ │
00:11 HENGIST/BENCHMARKS ▶ hamt 7,449 Hz 6.4 % │▊ │
00:11 HENGIST/BENCHMARKS ▶ immer 4,943 Hz 4.2 % │▌ │
###
| 64687 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'LFT'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#...........................................................................................................
PATH = require 'path'
FS = require 'fs'
DATA = require '../../../lib/data-providers'
test = require 'guy-test'
{ jr } = CND
BM = require '../../../lib/benchmarks'
data_cache = null
#-----------------------------------------------------------------------------------------------------------
@get_data = ( n ) ->
return data_cache if data_cache?
probes_A = DATA.get_random_nested_objects n, null, true
probes_B = DATA.get_random_nested_objects n, null, true
# debug '^3342^', probes_A
# debug '^3342^', probes_B
# debug '^3342^', probes_C
### NOTE could count number of actual properties in nested objects ###
data_cache = { probes_A, probes_B, }
return ( require '../../../apps/letsfreezethat' ).freeze data_cache
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v3_lets = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
if lft_cfg.freeze then lets = require '../../../apps/letsfreezethat/freeze'
else lets = require '../../../apps/letsfreezethat/nofreeze'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = lets probe
probe = lets probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return null
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v3_f1_lets = ( n, show ) -> @_letsfreezethat_v3_lets n, show, { freeze: true, }
@letsfreezethat_v3_f0_lets = ( n, show ) -> @_letsfreezethat_v3_lets n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v3_freezethaw = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
if lft_cfg.freeze then lets = require '../../../apps/letsfreezethat/freeze'
else lets = require '../../../apps/letsfreezethat/nofreeze'
{ thaw
freeze } = lets
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = thaw probe
for k, v of probes_B[ idx ]
probe[ k ] = v
probe = freeze probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v3_f1_freezethaw = ( n, show ) -> @_letsfreezethat_v3_freezethaw n, show, { freeze: true, }
@letsfreezethat_v3_f0_freezethaw = ( n, show ) -> @_letsfreezethat_v3_freezethaw n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v2_lets = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
LFT = require '../letsfreezethat@2.2.5'
if lft_cfg.freeze then { lets } = LFT
else { lets } = LFT.nofreeze
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = lets probe
probe = lets probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return null
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v2_f1_lets = ( n, show ) -> @_letsfreezethat_v2_lets n, show, { freeze: true, }
@letsfreezethat_v2_f0_lets = ( n, show ) -> @_letsfreezethat_v2_lets n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v2_freezethaw = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
LFT = require '../letsfreezethat@2.2.5'
if lft_cfg.freeze then { freeze, } = LFT
else { freeze, } = LFT.nofreeze
### Bug (or feature?) of LFTv2: in nofreeze mode, `thaw()` does not copy object ###
{ thaw, } = LFT
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = thaw probe
for k, v of probes_B[ idx ]
probe[ k ] = v
probe = freeze probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v2_f1_freezethaw = ( n, show ) -> @_letsfreezethat_v2_freezethaw n, show, { freeze: true, }
@letsfreezethat_v2_f0_freezethaw = ( n, show ) -> @_letsfreezethat_v2_freezethaw n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@immutable = ( n, show ) -> new Promise ( resolve ) =>
{ Map } = require 'immutable'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = Map probe
for k, v of probes_B[ idx ]
probe = probe.set k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@hamt = ( n, show ) -> new Promise ( resolve ) =>
hamt = require 'hamt'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = hamt.empty
probe = probe.set k, v for k, v of probe ### NOTE must always iterate over facets, no bulk `set()` ###
for k, v of probes_B[ idx ]
probe = probe.set k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@mori = ( n, show ) -> new Promise ( resolve ) =>
M = require 'mori'
count = 0
{ probes_A
probes_B } = @get_data n
probes_A_entries = []
for probe in probes_A
probes_A_entries.push ( [ k, v, ] for k, v of probe )
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A_entries
probe = M.hashMap probe...
for k, v of probes_B[ idx ]
probe = M.assoc probe, k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@immer = ( n, show ) -> new Promise ( resolve ) =>
IMMER = require 'immer'
{ produce, } = IMMER
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = produce probe, ( probe ) -> probe
probe = produce probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@plainjs_mutable = ( n, show ) -> new Promise ( resolve ) =>
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = Object.assign {}, probe
for k, v of probes_B[ idx ]
probe[ k ] = v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@demo_immutable = ->
```
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
```
help map1.get('b') + " vs. " + map2.get('b'); # 2 vs. 50
whisper Object.keys map1
whisper [ map1.keys()..., ]
return null
#-----------------------------------------------------------------------------------------------------------
@demo_hamt = ->
```
var hamt = require('hamt');
// Keys can be any string and the map can store any value.
var h = hamt.empty
.set('key', 'value')
.set('object', { prop: 1 })
.set('falsy', null);
h.size === 0
h.has('key') === true
h.has('falsy') === true
h.get('key') === 'value'
// Iteration
for (let [key, value] of h)
console.log(key, value);
// Array.from(h.values()) === [{ prop: 1 }, 'value'], null];
// The data structure is fully immutable
var h2 = h.delete('key');
h2.get('key') === undefined
h.get('key') === 'value'
```
urge '^33387^', h
return null
#-----------------------------------------------------------------------------------------------------------
@demo_mori = ->
M = require 'mori'
debug ( k for k of M ).sort()
debug M.vector 'a', 42
d = M.hashMap()
# d = M.mutable.thaw d
for n in [ 1 .. 100 ]
d = M.assoc d, n, n ** 2
# d = M.mutable.freeze d
d = M.assoc d, 'helo', 'world'
urge d
help M.toClj d
urge M.toJs d
return null
#-----------------------------------------------------------------------------------------------------------
@demo_letsfreezethat_new_api = ->
lets = require '../../../apps/letsfreezethat'
d1 = lets { first: 1, }, { second: 2, }
d2 = lets.set d1, 'foo', 42
d3 = lets.assign d2, { foo: 108, bar: 'baz', }, { gnu: 'gnat', }
urge Object.isFrozen d1
urge Object.isFrozen d2
urge Object.isFrozen d3
help d1
help d2
help d3
urge d1 is d2
urge lets.get d1, 'foo'
urge lets.get d2, 'foo'
urge Object.keys d2
urge ( k for k of d2 )
urge Object.keys d3
return null
#-----------------------------------------------------------------------------------------------------------
@run_benchmarks = ->
bench = BM.new_benchmarks()
# n = 100000
n = 100
n = 10
n = 1000
show = false
repetitions = 3
test_names = [
'<NAME> <NAME>'
'letsfreezethat_v3_f1_lets'
'letsfreezethat_v3_f0_lets'
'letsfreezethat_v2_f1_lets'
'letsfreezethat_v2_f0_lets'
'letsfreezethat_v3_f1_freezethaw'
'letsfreezethat_v3_f0_freezethaw'
'letsfreezethat_v2_f1_freezethaw'
'letsfreezethat_v2_f0_freezethaw'
'immutable'
'hamt'
'mori'
'plainjs_mutable'
]
global.gc() if global.gc?
for _ in [ 1 .. repetitions ]
whisper '-'.repeat 108
for test_name in CND.shuffle test_names
data_cache = null
global.gc() if global.gc?
await BM.benchmark bench, n, show, @, test_name
BM.show_totals bench
############################################################################################################
if require.main is module then do =>
await @run_benchmarks()
###
# To Do
* ramda (https://www.skypack.dev/search?q=ramda&p=1)
* rambda (Lightweight and faster alternative to Ramda)
* ramdax
###
###
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f0_freezethaw 116,513 Hz 100.0 % │████████████▌│
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f1_freezethaw 97,101 Hz 83.3 % │██████████▍ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f0_lets 93,101 Hz 79.9 % │██████████ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f1_lets 76,045 Hz 65.3 % │████████▏ │
00:11 HENGIST/BENCHMARKS ▶ plainjs_mutable 28,035 Hz 24.1 % │███ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f0_lets 22,410 Hz 19.2 % │██▍ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f0_freezethaw 16,854 Hz 14.5 % │█▊ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f1_freezethaw 16,443 Hz 14.1 % │█▊ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f1_lets 13,648 Hz 11.7 % │█▌ │
00:11 HENGIST/BENCHMARKS ▶ immutable 8,359 Hz 7.2 % │▉ │
00:11 HENGIST/BENCHMARKS ▶ mori 7,845 Hz 6.7 % │▉ │
00:11 HENGIST/BENCHMARKS ▶ hamt 7,449 Hz 6.4 % │▊ │
00:11 HENGIST/BENCHMARKS ▶ immer 4,943 Hz 4.2 % │▌ │
###
| true |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'LFT'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#...........................................................................................................
PATH = require 'path'
FS = require 'fs'
DATA = require '../../../lib/data-providers'
test = require 'guy-test'
{ jr } = CND
BM = require '../../../lib/benchmarks'
data_cache = null
#-----------------------------------------------------------------------------------------------------------
@get_data = ( n ) ->
return data_cache if data_cache?
probes_A = DATA.get_random_nested_objects n, null, true
probes_B = DATA.get_random_nested_objects n, null, true
# debug '^3342^', probes_A
# debug '^3342^', probes_B
# debug '^3342^', probes_C
### NOTE could count number of actual properties in nested objects ###
data_cache = { probes_A, probes_B, }
return ( require '../../../apps/letsfreezethat' ).freeze data_cache
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v3_lets = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
if lft_cfg.freeze then lets = require '../../../apps/letsfreezethat/freeze'
else lets = require '../../../apps/letsfreezethat/nofreeze'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = lets probe
probe = lets probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return null
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v3_f1_lets = ( n, show ) -> @_letsfreezethat_v3_lets n, show, { freeze: true, }
@letsfreezethat_v3_f0_lets = ( n, show ) -> @_letsfreezethat_v3_lets n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v3_freezethaw = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
if lft_cfg.freeze then lets = require '../../../apps/letsfreezethat/freeze'
else lets = require '../../../apps/letsfreezethat/nofreeze'
{ thaw
freeze } = lets
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = thaw probe
for k, v of probes_B[ idx ]
probe[ k ] = v
probe = freeze probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v3_f1_freezethaw = ( n, show ) -> @_letsfreezethat_v3_freezethaw n, show, { freeze: true, }
@letsfreezethat_v3_f0_freezethaw = ( n, show ) -> @_letsfreezethat_v3_freezethaw n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v2_lets = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
LFT = require '../letsfreezethat@2.2.5'
if lft_cfg.freeze then { lets } = LFT
else { lets } = LFT.nofreeze
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = lets probe
probe = lets probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return null
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v2_f1_lets = ( n, show ) -> @_letsfreezethat_v2_lets n, show, { freeze: true, }
@letsfreezethat_v2_f0_lets = ( n, show ) -> @_letsfreezethat_v2_lets n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@_letsfreezethat_v2_freezethaw = ( n, show, lft_cfg ) -> new Promise ( resolve ) =>
LFT = require '../letsfreezethat@2.2.5'
if lft_cfg.freeze then { freeze, } = LFT
else { freeze, } = LFT.nofreeze
### Bug (or feature?) of LFTv2: in nofreeze mode, `thaw()` does not copy object ###
{ thaw, } = LFT
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = thaw probe
for k, v of probes_B[ idx ]
probe[ k ] = v
probe = freeze probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@letsfreezethat_v2_f1_freezethaw = ( n, show ) -> @_letsfreezethat_v2_freezethaw n, show, { freeze: true, }
@letsfreezethat_v2_f0_freezethaw = ( n, show ) -> @_letsfreezethat_v2_freezethaw n, show, { freeze: false, }
#-----------------------------------------------------------------------------------------------------------
@immutable = ( n, show ) -> new Promise ( resolve ) =>
{ Map } = require 'immutable'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = Map probe
for k, v of probes_B[ idx ]
probe = probe.set k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@hamt = ( n, show ) -> new Promise ( resolve ) =>
hamt = require 'hamt'
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = hamt.empty
probe = probe.set k, v for k, v of probe ### NOTE must always iterate over facets, no bulk `set()` ###
for k, v of probes_B[ idx ]
probe = probe.set k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@mori = ( n, show ) -> new Promise ( resolve ) =>
M = require 'mori'
count = 0
{ probes_A
probes_B } = @get_data n
probes_A_entries = []
for probe in probes_A
probes_A_entries.push ( [ k, v, ] for k, v of probe )
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A_entries
probe = M.hashMap probe...
for k, v of probes_B[ idx ]
probe = M.assoc probe, k, v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@immer = ( n, show ) -> new Promise ( resolve ) =>
IMMER = require 'immer'
{ produce, } = IMMER
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = produce probe, ( probe ) -> probe
probe = produce probe, ( probe ) ->
for k, v of probes_B[ idx ]
probe[ k ] = v
return probe
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@plainjs_mutable = ( n, show ) -> new Promise ( resolve ) =>
count = 0
{ probes_A
probes_B } = @get_data n
resolve => new Promise ( resolve ) =>
for probe, idx in probes_A
probe = Object.assign {}, probe
for k, v of probes_B[ idx ]
probe[ k ] = v
count++
resolve count
return null
#-----------------------------------------------------------------------------------------------------------
@demo_immutable = ->
```
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
```
help map1.get('b') + " vs. " + map2.get('b'); # 2 vs. 50
whisper Object.keys map1
whisper [ map1.keys()..., ]
return null
#-----------------------------------------------------------------------------------------------------------
@demo_hamt = ->
```
var hamt = require('hamt');
// Keys can be any string and the map can store any value.
var h = hamt.empty
.set('key', 'value')
.set('object', { prop: 1 })
.set('falsy', null);
h.size === 0
h.has('key') === true
h.has('falsy') === true
h.get('key') === 'value'
// Iteration
for (let [key, value] of h)
console.log(key, value);
// Array.from(h.values()) === [{ prop: 1 }, 'value'], null];
// The data structure is fully immutable
var h2 = h.delete('key');
h2.get('key') === undefined
h.get('key') === 'value'
```
urge '^33387^', h
return null
#-----------------------------------------------------------------------------------------------------------
@demo_mori = ->
M = require 'mori'
debug ( k for k of M ).sort()
debug M.vector 'a', 42
d = M.hashMap()
# d = M.mutable.thaw d
for n in [ 1 .. 100 ]
d = M.assoc d, n, n ** 2
# d = M.mutable.freeze d
d = M.assoc d, 'helo', 'world'
urge d
help M.toClj d
urge M.toJs d
return null
#-----------------------------------------------------------------------------------------------------------
@demo_letsfreezethat_new_api = ->
lets = require '../../../apps/letsfreezethat'
d1 = lets { first: 1, }, { second: 2, }
d2 = lets.set d1, 'foo', 42
d3 = lets.assign d2, { foo: 108, bar: 'baz', }, { gnu: 'gnat', }
urge Object.isFrozen d1
urge Object.isFrozen d2
urge Object.isFrozen d3
help d1
help d2
help d3
urge d1 is d2
urge lets.get d1, 'foo'
urge lets.get d2, 'foo'
urge Object.keys d2
urge ( k for k of d2 )
urge Object.keys d3
return null
#-----------------------------------------------------------------------------------------------------------
@run_benchmarks = ->
bench = BM.new_benchmarks()
# n = 100000
n = 100
n = 10
n = 1000
show = false
repetitions = 3
test_names = [
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
'letsfreezethat_v3_f1_lets'
'letsfreezethat_v3_f0_lets'
'letsfreezethat_v2_f1_lets'
'letsfreezethat_v2_f0_lets'
'letsfreezethat_v3_f1_freezethaw'
'letsfreezethat_v3_f0_freezethaw'
'letsfreezethat_v2_f1_freezethaw'
'letsfreezethat_v2_f0_freezethaw'
'immutable'
'hamt'
'mori'
'plainjs_mutable'
]
global.gc() if global.gc?
for _ in [ 1 .. repetitions ]
whisper '-'.repeat 108
for test_name in CND.shuffle test_names
data_cache = null
global.gc() if global.gc?
await BM.benchmark bench, n, show, @, test_name
BM.show_totals bench
############################################################################################################
if require.main is module then do =>
await @run_benchmarks()
###
# To Do
* ramda (https://www.skypack.dev/search?q=ramda&p=1)
* rambda (Lightweight and faster alternative to Ramda)
* ramdax
###
###
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f0_freezethaw 116,513 Hz 100.0 % │████████████▌│
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f1_freezethaw 97,101 Hz 83.3 % │██████████▍ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f0_lets 93,101 Hz 79.9 % │██████████ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v3_f1_lets 76,045 Hz 65.3 % │████████▏ │
00:11 HENGIST/BENCHMARKS ▶ plainjs_mutable 28,035 Hz 24.1 % │███ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f0_lets 22,410 Hz 19.2 % │██▍ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f0_freezethaw 16,854 Hz 14.5 % │█▊ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f1_freezethaw 16,443 Hz 14.1 % │█▊ │
00:11 HENGIST/BENCHMARKS ▶ letsfreezethat_v2_f1_lets 13,648 Hz 11.7 % │█▌ │
00:11 HENGIST/BENCHMARKS ▶ immutable 8,359 Hz 7.2 % │▉ │
00:11 HENGIST/BENCHMARKS ▶ mori 7,845 Hz 6.7 % │▉ │
00:11 HENGIST/BENCHMARKS ▶ hamt 7,449 Hz 6.4 % │▊ │
00:11 HENGIST/BENCHMARKS ▶ immer 4,943 Hz 4.2 % │▌ │
###
|
[
{
"context": ": \"PUT\", to: \"/posts\", id: \"10\", data: {\"title\": \"A Post\"}}]\nclass Tower.StoreBatch extends Tower.Cla",
"end": 243,
"score": 0.8446823954582214,
"start": 242,
"tag": "NAME",
"value": "A"
}
] | node_modules/tower/packages/tower-store/shared/batch.coffee | MagicPower2/Power | 1 | # @todo
# This is what's sent to the server from the client in a batch/bulk update.
# /posts/batch
# perhaps even one global batch method that routes it to sub controllers:
# /batch
# [{method: "PUT", to: "/posts", id: "10", data: {"title": "A Post"}}]
class Tower.StoreBatch extends Tower.Class
@reopen
# By default the store will persist the data.
#
# If you set this to false, then you have full control
# over when the data is finally committed to the database.
autocommit: Tower.isServer
# If bulk is true, and there are multiple records preparing, it
# will try and group them into optimal batch database operations.
bulk: false
init: ->
@_super arguments...
Ember.set @, 'buckets',
clean: Ember.Map.create()
created: Ember.Map.create()
updated: Ember.Map.create()
deleted: Ember.Map.create()
removeCleanRecords: ->
clean = @getBucket("clean")
clean.forEach (type, records) =>
records.forEach (record) =>
@remove(record)
add: (record) ->
# Tower.assert !Ember.get(record, 'isDirty'), 'store.transaction.dirty'
#recordTransaction = Ember.get(record, 'transaction')
#defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
# Tower.assert recordTransaction != defaultTransaction, 'store.transaction.unique'
@adopt record
remove: (record) ->
defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
defaultTransaction.adopt(record)
adopt: (record) ->
oldTransaction = record.get('transaction')
oldTransaction.removeFromBucket('clean', record) if oldTransaction
@addToBucket 'clean', record
record.set('transaction', @)
# @private
addToBucket: (kind, record) ->
bucket = Ember.get(Ember.get(@, 'buckets'), kind)
type = @getType(record)
records = bucket.get(type)
unless records
records = Ember.OrderedSet.create()
bucket.set(type, records)
records.add(record)
# @private
removeFromBucket: (kind, record) ->
bucket = @getBucket(kind)
type = @getType(record)
records = bucket.get(type)
records.remove(record) if records
getBucket: (kind) ->
Ember.get(Ember.get(@, 'buckets'), kind)
getType: (recordOrCursor) ->
if recordOrCursor instanceof Tower.ModelCursor
recordOrCursor.getType()
else
recordOrCursor.constructor
recordBecameClean: (kind, record) ->
@removeFromBucket kind, record
defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
defaultTransaction.adopt(record) if defaultTransaction
recordBecameDirty: (kind, record) ->
@removeFromBucket 'clean', record
@addToBucket kind, record
commit: (callback) ->
iterate = (bucketType, fn, binding) =>
dirty = @getBucket(bucketType)
dirty.forEach (type, records) ->
return if records.isEmpty()
array = []
records.forEach (record) ->
record.send("willCommit")
array.push(record)
fn.call(binding, type, array)
commitDetails =
updated:
eachType: (fn, binding) ->
iterate("updated", fn, binding)
created:
eachType: (fn, binding) ->
iterate("created", fn, binding)
deleted:
eachType: (fn, binding) ->
iterate("deleted", fn, binding)
@removeCleanRecords()
store = Ember.get(@, "store")
store.commit(commitDetails, callback)
module.exports = Tower.StoreBatch
| 122324 | # @todo
# This is what's sent to the server from the client in a batch/bulk update.
# /posts/batch
# perhaps even one global batch method that routes it to sub controllers:
# /batch
# [{method: "PUT", to: "/posts", id: "10", data: {"title": "<NAME> Post"}}]
class Tower.StoreBatch extends Tower.Class
@reopen
# By default the store will persist the data.
#
# If you set this to false, then you have full control
# over when the data is finally committed to the database.
autocommit: Tower.isServer
# If bulk is true, and there are multiple records preparing, it
# will try and group them into optimal batch database operations.
bulk: false
init: ->
@_super arguments...
Ember.set @, 'buckets',
clean: Ember.Map.create()
created: Ember.Map.create()
updated: Ember.Map.create()
deleted: Ember.Map.create()
removeCleanRecords: ->
clean = @getBucket("clean")
clean.forEach (type, records) =>
records.forEach (record) =>
@remove(record)
add: (record) ->
# Tower.assert !Ember.get(record, 'isDirty'), 'store.transaction.dirty'
#recordTransaction = Ember.get(record, 'transaction')
#defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
# Tower.assert recordTransaction != defaultTransaction, 'store.transaction.unique'
@adopt record
remove: (record) ->
defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
defaultTransaction.adopt(record)
adopt: (record) ->
oldTransaction = record.get('transaction')
oldTransaction.removeFromBucket('clean', record) if oldTransaction
@addToBucket 'clean', record
record.set('transaction', @)
# @private
addToBucket: (kind, record) ->
bucket = Ember.get(Ember.get(@, 'buckets'), kind)
type = @getType(record)
records = bucket.get(type)
unless records
records = Ember.OrderedSet.create()
bucket.set(type, records)
records.add(record)
# @private
removeFromBucket: (kind, record) ->
bucket = @getBucket(kind)
type = @getType(record)
records = bucket.get(type)
records.remove(record) if records
getBucket: (kind) ->
Ember.get(Ember.get(@, 'buckets'), kind)
getType: (recordOrCursor) ->
if recordOrCursor instanceof Tower.ModelCursor
recordOrCursor.getType()
else
recordOrCursor.constructor
recordBecameClean: (kind, record) ->
@removeFromBucket kind, record
defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
defaultTransaction.adopt(record) if defaultTransaction
recordBecameDirty: (kind, record) ->
@removeFromBucket 'clean', record
@addToBucket kind, record
commit: (callback) ->
iterate = (bucketType, fn, binding) =>
dirty = @getBucket(bucketType)
dirty.forEach (type, records) ->
return if records.isEmpty()
array = []
records.forEach (record) ->
record.send("willCommit")
array.push(record)
fn.call(binding, type, array)
commitDetails =
updated:
eachType: (fn, binding) ->
iterate("updated", fn, binding)
created:
eachType: (fn, binding) ->
iterate("created", fn, binding)
deleted:
eachType: (fn, binding) ->
iterate("deleted", fn, binding)
@removeCleanRecords()
store = Ember.get(@, "store")
store.commit(commitDetails, callback)
module.exports = Tower.StoreBatch
| true | # @todo
# This is what's sent to the server from the client in a batch/bulk update.
# /posts/batch
# perhaps even one global batch method that routes it to sub controllers:
# /batch
# [{method: "PUT", to: "/posts", id: "10", data: {"title": "PI:NAME:<NAME>END_PI Post"}}]
class Tower.StoreBatch extends Tower.Class
@reopen
# By default the store will persist the data.
#
# If you set this to false, then you have full control
# over when the data is finally committed to the database.
autocommit: Tower.isServer
# If bulk is true, and there are multiple records preparing, it
# will try and group them into optimal batch database operations.
bulk: false
init: ->
@_super arguments...
Ember.set @, 'buckets',
clean: Ember.Map.create()
created: Ember.Map.create()
updated: Ember.Map.create()
deleted: Ember.Map.create()
removeCleanRecords: ->
clean = @getBucket("clean")
clean.forEach (type, records) =>
records.forEach (record) =>
@remove(record)
add: (record) ->
# Tower.assert !Ember.get(record, 'isDirty'), 'store.transaction.dirty'
#recordTransaction = Ember.get(record, 'transaction')
#defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
# Tower.assert recordTransaction != defaultTransaction, 'store.transaction.unique'
@adopt record
remove: (record) ->
defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
defaultTransaction.adopt(record)
adopt: (record) ->
oldTransaction = record.get('transaction')
oldTransaction.removeFromBucket('clean', record) if oldTransaction
@addToBucket 'clean', record
record.set('transaction', @)
# @private
addToBucket: (kind, record) ->
bucket = Ember.get(Ember.get(@, 'buckets'), kind)
type = @getType(record)
records = bucket.get(type)
unless records
records = Ember.OrderedSet.create()
bucket.set(type, records)
records.add(record)
# @private
removeFromBucket: (kind, record) ->
bucket = @getBucket(kind)
type = @getType(record)
records = bucket.get(type)
records.remove(record) if records
getBucket: (kind) ->
Ember.get(Ember.get(@, 'buckets'), kind)
getType: (recordOrCursor) ->
if recordOrCursor instanceof Tower.ModelCursor
recordOrCursor.getType()
else
recordOrCursor.constructor
recordBecameClean: (kind, record) ->
@removeFromBucket kind, record
defaultTransaction = Ember.getPath(@, 'store.defaultTransaction')
defaultTransaction.adopt(record) if defaultTransaction
recordBecameDirty: (kind, record) ->
@removeFromBucket 'clean', record
@addToBucket kind, record
commit: (callback) ->
iterate = (bucketType, fn, binding) =>
dirty = @getBucket(bucketType)
dirty.forEach (type, records) ->
return if records.isEmpty()
array = []
records.forEach (record) ->
record.send("willCommit")
array.push(record)
fn.call(binding, type, array)
commitDetails =
updated:
eachType: (fn, binding) ->
iterate("updated", fn, binding)
created:
eachType: (fn, binding) ->
iterate("created", fn, binding)
deleted:
eachType: (fn, binding) ->
iterate("deleted", fn, binding)
@removeCleanRecords()
store = Ember.get(@, "store")
store.commit(commitDetails, callback)
module.exports = Tower.StoreBatch
|
[
{
"context": ", ->\n @upstream.setAuth({\n username: 'foo'\n password: 'bar'\n })\n\n @upstrea",
"end": 5199,
"score": 0.7480326294898987,
"start": 5196,
"tag": "USERNAME",
"value": "foo"
},
{
"context": "Auth({\n username: 'foo'\n password:... | packages/https-proxy/test/integration/proxy_spec.coffee | sebinsua/cypress | 3 | require("../spec_helper")
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
_ = require("lodash")
DebugProxy = require("@cypress/debugging-proxy")
net = require("net")
network = require("@packages/network")
path = require("path")
Promise = require("bluebird")
proxy = require("../helpers/proxy")
httpServer = require("../helpers/http_server")
httpsServer = require("../helpers/https_server")
describe "Proxy", ->
beforeEach ->
Promise.join(
httpServer.start()
httpsServer.start(8443)
httpsServer.start(8444)
proxy.start(3333)
.then (@proxy) =>
)
afterEach ->
Promise.join(
httpServer.stop()
httpsServer.stop()
proxy.stop()
)
it "can request the googles", ->
## give some padding to external
## network request
@timeout(10000)
Promise.all([
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://www.google.com"
})
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://mail.google.com"
})
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://google.com"
})
])
it "can call the httpsDirectly without a proxy", ->
request({
strictSSL: false
url: "https://localhost:8443"
})
it "can boot the httpsServer", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("https server")
it "yields the onRequest callback", ->
request({
strictSSL: false
url: "https://localhost:8443/replace"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("replaced content")
it "can pass directly through", ->
## this will fail due to dynamic cert
## generation when strict ssl is true
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("https server")
it "retries 5 times", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:12344"
proxy: "http://localhost:3333"
})
.then ->
throw new Error("should not reach")
.catch ->
expect(net.connect).to.have.callCount(5)
it "closes outgoing connections when client disconnects", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
})
.then (res) =>
## ensure client has disconnected
expect(res.socket.destroyed).to.be.true
## ensure the outgoing socket created for this connection was destroyed
socket = net.connect.getCalls()
.find (call) =>
call.args[0].port == "8444" && call.args[0].host == "localhost"
.returnValue
expect(socket.destroyed).to.be.true
it "can boot the httpServer", ->
request({
strictSSL: false
url: "http://localhost:8080/"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("http server")
context "generating certificates", ->
it "reuses existing certificates", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then =>
proxy.reset()
## force this to reject if its called
@sandbox.stub(@proxy, "_generateMissingCertificates").rejects(new Error("should not call"))
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
context "closing", ->
it "resets sslServers and can reopen", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then =>
proxy.stop()
.then =>
proxy.start(3333)
.then =>
## force this to reject if its called
@sandbox.stub(@proxy, "_generateMissingCertificates").rejects(new Error("should not call"))
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
context "with an upstream proxy", ->
beforeEach ->
process.env.NO_PROXY = ""
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = "http://localhost:9001"
@upstream = new DebugProxy({
keepRequests: true
})
@upstream.start(9001)
it "passes a request to an https server through the upstream", ->
@upstream._onConnect = (domain, port) ->
expect(domain).to.eq('localhost')
expect(port).to.eq('8444')
return true
request({
strictSSL: false
url: "https://localhost:8444/"
proxy: "http://localhost:3333"
}).then (res) =>
expect(res).to.contain("https server")
it "uses HTTP basic auth when provided", ->
@upstream.setAuth({
username: 'foo'
password: 'bar'
})
@upstream._onConnect = (domain, port) ->
expect(domain).to.eq('localhost')
expect(port).to.eq('8444')
return true
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = "http://foo:bar@localhost:9001"
request({
strictSSL: false
url: "https://localhost:8444/"
proxy: "http://localhost:3333"
}).then (res) =>
expect(res).to.contain("https server")
it "closes outgoing connections when client disconnects", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
forever: false
})
.then (res) =>
## ensure client has disconnected
expect(res.socket.destroyed).to.be.true
## ensure the outgoing socket created for this connection was destroyed
socket = net.connect.getCalls()
.find (call) =>
call.args[0].port == 9001 && call.args[0].host == "localhost"
.returnValue
new Promise (resolve) ->
socket.on 'close', =>
expect(socket.destroyed).to.be.true
resolve()
## https://github.com/cypress-io/cypress/issues/4257
it "passes through to SNI when it is intercepted and not through proxy", ->
createSocket = @sandbox.stub(network.connect, 'createRetryingSocket').callsArgWith(1, new Error('stub'))
createProxyConn = @sandbox.spy(network.agent.httpsAgent, 'createUpstreamProxyConnection')
request({
strictSSL: false
url: "https://localhost:8443"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
forever: false
})
.then =>
throw new Error('should not succeed')
.catch { message: 'Error: socket hang up' }, =>
expect(createProxyConn).to.not.be.called
expect(createSocket).to.be.calledWith({
port: @proxy._sniPort
host: 'localhost'
})
afterEach ->
@upstream.stop()
delete process.env.HTTP_PROXY
delete process.env.HTTPS_PROXY
delete process.env.NO_PROXY
| 128622 | require("../spec_helper")
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
_ = require("lodash")
DebugProxy = require("@cypress/debugging-proxy")
net = require("net")
network = require("@packages/network")
path = require("path")
Promise = require("bluebird")
proxy = require("../helpers/proxy")
httpServer = require("../helpers/http_server")
httpsServer = require("../helpers/https_server")
describe "Proxy", ->
beforeEach ->
Promise.join(
httpServer.start()
httpsServer.start(8443)
httpsServer.start(8444)
proxy.start(3333)
.then (@proxy) =>
)
afterEach ->
Promise.join(
httpServer.stop()
httpsServer.stop()
proxy.stop()
)
it "can request the googles", ->
## give some padding to external
## network request
@timeout(10000)
Promise.all([
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://www.google.com"
})
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://mail.google.com"
})
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://google.com"
})
])
it "can call the httpsDirectly without a proxy", ->
request({
strictSSL: false
url: "https://localhost:8443"
})
it "can boot the httpsServer", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("https server")
it "yields the onRequest callback", ->
request({
strictSSL: false
url: "https://localhost:8443/replace"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("replaced content")
it "can pass directly through", ->
## this will fail due to dynamic cert
## generation when strict ssl is true
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("https server")
it "retries 5 times", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:12344"
proxy: "http://localhost:3333"
})
.then ->
throw new Error("should not reach")
.catch ->
expect(net.connect).to.have.callCount(5)
it "closes outgoing connections when client disconnects", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
})
.then (res) =>
## ensure client has disconnected
expect(res.socket.destroyed).to.be.true
## ensure the outgoing socket created for this connection was destroyed
socket = net.connect.getCalls()
.find (call) =>
call.args[0].port == "8444" && call.args[0].host == "localhost"
.returnValue
expect(socket.destroyed).to.be.true
it "can boot the httpServer", ->
request({
strictSSL: false
url: "http://localhost:8080/"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("http server")
context "generating certificates", ->
it "reuses existing certificates", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then =>
proxy.reset()
## force this to reject if its called
@sandbox.stub(@proxy, "_generateMissingCertificates").rejects(new Error("should not call"))
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
context "closing", ->
it "resets sslServers and can reopen", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then =>
proxy.stop()
.then =>
proxy.start(3333)
.then =>
## force this to reject if its called
@sandbox.stub(@proxy, "_generateMissingCertificates").rejects(new Error("should not call"))
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
context "with an upstream proxy", ->
beforeEach ->
process.env.NO_PROXY = ""
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = "http://localhost:9001"
@upstream = new DebugProxy({
keepRequests: true
})
@upstream.start(9001)
it "passes a request to an https server through the upstream", ->
@upstream._onConnect = (domain, port) ->
expect(domain).to.eq('localhost')
expect(port).to.eq('8444')
return true
request({
strictSSL: false
url: "https://localhost:8444/"
proxy: "http://localhost:3333"
}).then (res) =>
expect(res).to.contain("https server")
it "uses HTTP basic auth when provided", ->
@upstream.setAuth({
username: 'foo'
password: '<PASSWORD>'
})
@upstream._onConnect = (domain, port) ->
expect(domain).to.eq('localhost')
expect(port).to.eq('8444')
return true
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = "http://foo:bar@localhost:9001"
request({
strictSSL: false
url: "https://localhost:8444/"
proxy: "http://localhost:3333"
}).then (res) =>
expect(res).to.contain("https server")
it "closes outgoing connections when client disconnects", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
forever: false
})
.then (res) =>
## ensure client has disconnected
expect(res.socket.destroyed).to.be.true
## ensure the outgoing socket created for this connection was destroyed
socket = net.connect.getCalls()
.find (call) =>
call.args[0].port == 9001 && call.args[0].host == "localhost"
.returnValue
new Promise (resolve) ->
socket.on 'close', =>
expect(socket.destroyed).to.be.true
resolve()
## https://github.com/cypress-io/cypress/issues/4257
it "passes through to SNI when it is intercepted and not through proxy", ->
createSocket = @sandbox.stub(network.connect, 'createRetryingSocket').callsArgWith(1, new Error('stub'))
createProxyConn = @sandbox.spy(network.agent.httpsAgent, 'createUpstreamProxyConnection')
request({
strictSSL: false
url: "https://localhost:8443"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
forever: false
})
.then =>
throw new Error('should not succeed')
.catch { message: 'Error: socket hang up' }, =>
expect(createProxyConn).to.not.be.called
expect(createSocket).to.be.calledWith({
port: @proxy._sniPort
host: 'localhost'
})
afterEach ->
@upstream.stop()
delete process.env.HTTP_PROXY
delete process.env.HTTPS_PROXY
delete process.env.NO_PROXY
| true | require("../spec_helper")
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
_ = require("lodash")
DebugProxy = require("@cypress/debugging-proxy")
net = require("net")
network = require("@packages/network")
path = require("path")
Promise = require("bluebird")
proxy = require("../helpers/proxy")
httpServer = require("../helpers/http_server")
httpsServer = require("../helpers/https_server")
describe "Proxy", ->
beforeEach ->
Promise.join(
httpServer.start()
httpsServer.start(8443)
httpsServer.start(8444)
proxy.start(3333)
.then (@proxy) =>
)
afterEach ->
Promise.join(
httpServer.stop()
httpsServer.stop()
proxy.stop()
)
it "can request the googles", ->
## give some padding to external
## network request
@timeout(10000)
Promise.all([
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://www.google.com"
})
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://mail.google.com"
})
request({
strictSSL: false
proxy: "http://localhost:3333"
url: "https://google.com"
})
])
it "can call the httpsDirectly without a proxy", ->
request({
strictSSL: false
url: "https://localhost:8443"
})
it "can boot the httpsServer", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("https server")
it "yields the onRequest callback", ->
request({
strictSSL: false
url: "https://localhost:8443/replace"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("replaced content")
it "can pass directly through", ->
## this will fail due to dynamic cert
## generation when strict ssl is true
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("https server")
it "retries 5 times", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:12344"
proxy: "http://localhost:3333"
})
.then ->
throw new Error("should not reach")
.catch ->
expect(net.connect).to.have.callCount(5)
it "closes outgoing connections when client disconnects", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
})
.then (res) =>
## ensure client has disconnected
expect(res.socket.destroyed).to.be.true
## ensure the outgoing socket created for this connection was destroyed
socket = net.connect.getCalls()
.find (call) =>
call.args[0].port == "8444" && call.args[0].host == "localhost"
.returnValue
expect(socket.destroyed).to.be.true
it "can boot the httpServer", ->
request({
strictSSL: false
url: "http://localhost:8080/"
proxy: "http://localhost:3333"
})
.then (html) ->
expect(html).to.include("http server")
context "generating certificates", ->
it "reuses existing certificates", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then =>
proxy.reset()
## force this to reject if its called
@sandbox.stub(@proxy, "_generateMissingCertificates").rejects(new Error("should not call"))
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
context "closing", ->
it "resets sslServers and can reopen", ->
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
.then =>
proxy.stop()
.then =>
proxy.start(3333)
.then =>
## force this to reject if its called
@sandbox.stub(@proxy, "_generateMissingCertificates").rejects(new Error("should not call"))
request({
strictSSL: false
url: "https://localhost:8443/"
proxy: "http://localhost:3333"
})
context "with an upstream proxy", ->
beforeEach ->
process.env.NO_PROXY = ""
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = "http://localhost:9001"
@upstream = new DebugProxy({
keepRequests: true
})
@upstream.start(9001)
it "passes a request to an https server through the upstream", ->
@upstream._onConnect = (domain, port) ->
expect(domain).to.eq('localhost')
expect(port).to.eq('8444')
return true
request({
strictSSL: false
url: "https://localhost:8444/"
proxy: "http://localhost:3333"
}).then (res) =>
expect(res).to.contain("https server")
it "uses HTTP basic auth when provided", ->
@upstream.setAuth({
username: 'foo'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
})
@upstream._onConnect = (domain, port) ->
expect(domain).to.eq('localhost')
expect(port).to.eq('8444')
return true
process.env.HTTP_PROXY = process.env.HTTPS_PROXY = "http://foo:bar@localhost:9001"
request({
strictSSL: false
url: "https://localhost:8444/"
proxy: "http://localhost:3333"
}).then (res) =>
expect(res).to.contain("https server")
it "closes outgoing connections when client disconnects", ->
@sandbox.spy(net, 'connect')
request({
strictSSL: false
url: "https://localhost:8444/replace"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
forever: false
})
.then (res) =>
## ensure client has disconnected
expect(res.socket.destroyed).to.be.true
## ensure the outgoing socket created for this connection was destroyed
socket = net.connect.getCalls()
.find (call) =>
call.args[0].port == 9001 && call.args[0].host == "localhost"
.returnValue
new Promise (resolve) ->
socket.on 'close', =>
expect(socket.destroyed).to.be.true
resolve()
## https://github.com/cypress-io/cypress/issues/4257
it "passes through to SNI when it is intercepted and not through proxy", ->
createSocket = @sandbox.stub(network.connect, 'createRetryingSocket').callsArgWith(1, new Error('stub'))
createProxyConn = @sandbox.spy(network.agent.httpsAgent, 'createUpstreamProxyConnection')
request({
strictSSL: false
url: "https://localhost:8443"
proxy: "http://localhost:3333"
resolveWithFullResponse: true
forever: false
})
.then =>
throw new Error('should not succeed')
.catch { message: 'Error: socket hang up' }, =>
expect(createProxyConn).to.not.be.called
expect(createSocket).to.be.calledWith({
port: @proxy._sniPort
host: 'localhost'
})
afterEach ->
@upstream.stop()
delete process.env.HTTP_PROXY
delete process.env.HTTPS_PROXY
delete process.env.NO_PROXY
|
[
{
"context": "ry the Sordid Dragon\n# Copyright Poll Everywhere\n# Paul Cortens, Mike Foley and Adam Heath\n# https://github.com/p",
"end": 69,
"score": 0.9998650550842285,
"start": 57,
"tag": "NAME",
"value": "Paul Cortens"
},
{
"context": "Dragon\n# Copyright Poll Everywhere\n# Pau... | src/sordid-dragon.jquery.coffee | polleverywhere/sordid-dragon | 2 | # jQuery the Sordid Dragon
# Copyright Poll Everywhere
# Paul Cortens, Mike Foley and Adam Heath
# https://github.com/polleverywhere/sordid-dragon
# Version 2.2.1
do ($=jQuery) ->
isTouchDevice = ->
'ontouchstart' of document.documentElement
$.fn.sordidDragon = (command="enable", options={}) ->
unless typeof command is "string"
options = command
$parent = this
$ghostContainer = $(options.ghostContainer) || $parent
isDragging = false
# Remove old instance if it exists
if $.isFunction $parent.data("removeSordidDragon")
$parent.data("removeSordidDragon")()
# Handle removing an old instance in case 'enable' is called multiple times
$parent.data "removeSordidDragon", ->
isDragging = false
hidePlaceholder()
hideGhost()
# Windows touch devices (such as the Microsoft Surface Pro 3) will end
# the drag event early (and not call dragend) if the element being
# dragged is moved in the DOM by JavaScript.
# To work around that problem we:
# 1) clone the element being moved
# 2) hide the element being moved
# 3) move the clone around in the DOM
# Then we clean it all up in the dragend event.
$placeholder = null
$activePlaceholderChild = null
showPlaceholder = ($child) ->
$activePlaceholderChild = $child
# Hide the element being moved and replace it with the clone.
$child.css opacity: 0
unless $placeholder.is(":visible")
$placeholder.addClass "sordidDragon-placeholder"
$child.after $placeholder
$placeholder.css opacity: 0.5
# The hiding must come after the clone is inserted. Otherwise when
# you are scrolled down to the bottom of the screen, the act of hiding
# $child will cause the screen to scroll up. This makes it feel like
# dragging has caused the list to jump around.
$child.hide()
$child.css opacity: 1
hidePlaceholder = ->
if $placeholder?.is(":visible")
$placeholder.after $activePlaceholderChild
$placeholder.off ".sordidDragon"
$placeholder.remove()
$activePlaceholderChild.show()
# The $ghost is a faded copy of the element that moves with the mouse or
# finger.
# In most (but not all) browsers that support drag events, the browser will
# create a ghost under the cursor for us. That doesn't happen with touch
# events, so we create one ourselves.
$ghost = null
showGhost = (pageY) ->
unless $ghost.is(":visible")
$ghost
.addClass "sordidDragon-ghost"
.css
position: "fixed"
opacity: 1
$ghostContainer.append $ghost
$ghost.css
left: $placeholder.offset().left
top: (pageY - ($placeholder.outerHeight() / 2)) - window.scrollY
width: $placeholder.outerWidth() - window.scrollX
hideGhost = ->
$ghost?.remove()
# Touch devices don't support dragenter or dragover events. Instead we
# keep track of the location of each child so we can know which child is
# currently under the user's finger.
positions = null
calculatePositions = ->
positions = []
$parent.children(options.childSelector).each (_, child) ->
$child = $(child)
positions.push [
$child.offset().top
$child.offset().top + $child.outerHeight()
]
positions
currentPosition = (pageY) ->
for i in [0...positions.length]
return i if pageY >= positions[i][0] && pageY < positions[i][1]
null
moveChild = ($besideChild) ->
$children = $parent.children("#{options.childSelector || ""}:visible")
newPosition = $children.index($besideChild)
oldPosition = $children.index($placeholder)
if newPosition > oldPosition
$besideChild.after $placeholder
else if newPosition < oldPosition
$besideChild.before $placeholder
# This allows the browser provided ghose to stay where it's dropped
# rather than returning home
attachDragOverHandler = ($el) ->
$el.on "dragover.sordidDragon", (e) ->
return unless isDragging
e.preventDefault()
e.originalEvent.dataTransfer?.dropEffect = "move"
$parent.children(options.childSelector).each (_, child) ->
$child = $(child)
$handle = if options.handle
$child.find(options.handle)
else
$child
# Careful here. This might be interfering with other code that sets the
# "draggable" attribute.
$handle.attr "draggable", String(command != "destroy")
# Clear out the existing events (so they aren't duplicated).
$handle.off ".sordidDragon"
$child.off ".sordidDragon"
# If we are destroying, then just move on to the next child rather
# than setting up any event listeners.
return if command is "destroy"
$handle.on "touchstart.sordidDragon dragstart.sordidDragon", (e) ->
if isTouchDevice()
# We must pre-cache the positions after they have been rendered, but
# before anything has changed. Otherwise the extra elements we create
# during the drag process will interfere.
calculatePositions()
$ghost = $child.clone()
e.preventDefault()
# Firefox needs this for drag events, and others to now animate the ghost home
e.originalEvent.dataTransfer?.effectAllowed = "move"
e.originalEvent.dataTransfer?.setData "text", ""
$placeholder = $child.clone()
attachDragOverHandler($placeholder)
isDragging = true
options.sortStart?(e, $child)
$handle.on "touchmove.sordidDragon drag.sordidDragon", (e) ->
return unless isDragging
showPlaceholder $child
if isTouchDevice()
pageY = e.originalEvent.targetTouches[0].pageY
showGhost pageY
# On touch devices, we don't have dragenter events, so we'll update
# the position of the element being dragged here instead.
newPosition = currentPosition(pageY)
if newPosition?
moveChild $parent.children("#{options.childSelector || ""}:visible").eq(newPosition)
e.preventDefault()
$child.on "dragenter.sordidDragon", (e) ->
return unless isDragging
moveChild $child
attachDragOverHandler($child)
$handle.on "touchend.sordidDragon dragend.sordidDragon", (e) ->
return unless isDragging
hidePlaceholder $child
if isTouchDevice()
hideGhost()
# We must recalculate the positions because in the case where items
# are not all the same height, we would get unexpected results from
# currentPosition.
calculatePositions()
e.preventDefault()
options.sortEnd?(e, $child)
isDragging = false
| 135176 | # jQuery the Sordid Dragon
# Copyright Poll Everywhere
# <NAME>, <NAME> and <NAME>
# https://github.com/polleverywhere/sordid-dragon
# Version 2.2.1
do ($=jQuery) ->
isTouchDevice = ->
'ontouchstart' of document.documentElement
$.fn.sordidDragon = (command="enable", options={}) ->
unless typeof command is "string"
options = command
$parent = this
$ghostContainer = $(options.ghostContainer) || $parent
isDragging = false
# Remove old instance if it exists
if $.isFunction $parent.data("removeSordidDragon")
$parent.data("removeSordidDragon")()
# Handle removing an old instance in case 'enable' is called multiple times
$parent.data "removeSordidDragon", ->
isDragging = false
hidePlaceholder()
hideGhost()
# Windows touch devices (such as the Microsoft Surface Pro 3) will end
# the drag event early (and not call dragend) if the element being
# dragged is moved in the DOM by JavaScript.
# To work around that problem we:
# 1) clone the element being moved
# 2) hide the element being moved
# 3) move the clone around in the DOM
# Then we clean it all up in the dragend event.
$placeholder = null
$activePlaceholderChild = null
showPlaceholder = ($child) ->
$activePlaceholderChild = $child
# Hide the element being moved and replace it with the clone.
$child.css opacity: 0
unless $placeholder.is(":visible")
$placeholder.addClass "sordidDragon-placeholder"
$child.after $placeholder
$placeholder.css opacity: 0.5
# The hiding must come after the clone is inserted. Otherwise when
# you are scrolled down to the bottom of the screen, the act of hiding
# $child will cause the screen to scroll up. This makes it feel like
# dragging has caused the list to jump around.
$child.hide()
$child.css opacity: 1
hidePlaceholder = ->
if $placeholder?.is(":visible")
$placeholder.after $activePlaceholderChild
$placeholder.off ".sordidDragon"
$placeholder.remove()
$activePlaceholderChild.show()
# The $ghost is a faded copy of the element that moves with the mouse or
# finger.
# In most (but not all) browsers that support drag events, the browser will
# create a ghost under the cursor for us. That doesn't happen with touch
# events, so we create one ourselves.
$ghost = null
showGhost = (pageY) ->
unless $ghost.is(":visible")
$ghost
.addClass "sordidDragon-ghost"
.css
position: "fixed"
opacity: 1
$ghostContainer.append $ghost
$ghost.css
left: $placeholder.offset().left
top: (pageY - ($placeholder.outerHeight() / 2)) - window.scrollY
width: $placeholder.outerWidth() - window.scrollX
hideGhost = ->
$ghost?.remove()
# Touch devices don't support dragenter or dragover events. Instead we
# keep track of the location of each child so we can know which child is
# currently under the user's finger.
positions = null
calculatePositions = ->
positions = []
$parent.children(options.childSelector).each (_, child) ->
$child = $(child)
positions.push [
$child.offset().top
$child.offset().top + $child.outerHeight()
]
positions
currentPosition = (pageY) ->
for i in [0...positions.length]
return i if pageY >= positions[i][0] && pageY < positions[i][1]
null
moveChild = ($besideChild) ->
$children = $parent.children("#{options.childSelector || ""}:visible")
newPosition = $children.index($besideChild)
oldPosition = $children.index($placeholder)
if newPosition > oldPosition
$besideChild.after $placeholder
else if newPosition < oldPosition
$besideChild.before $placeholder
# This allows the browser provided ghose to stay where it's dropped
# rather than returning home
attachDragOverHandler = ($el) ->
$el.on "dragover.sordidDragon", (e) ->
return unless isDragging
e.preventDefault()
e.originalEvent.dataTransfer?.dropEffect = "move"
$parent.children(options.childSelector).each (_, child) ->
$child = $(child)
$handle = if options.handle
$child.find(options.handle)
else
$child
# Careful here. This might be interfering with other code that sets the
# "draggable" attribute.
$handle.attr "draggable", String(command != "destroy")
# Clear out the existing events (so they aren't duplicated).
$handle.off ".sordidDragon"
$child.off ".sordidDragon"
# If we are destroying, then just move on to the next child rather
# than setting up any event listeners.
return if command is "destroy"
$handle.on "touchstart.sordidDragon dragstart.sordidDragon", (e) ->
if isTouchDevice()
# We must pre-cache the positions after they have been rendered, but
# before anything has changed. Otherwise the extra elements we create
# during the drag process will interfere.
calculatePositions()
$ghost = $child.clone()
e.preventDefault()
# Firefox needs this for drag events, and others to now animate the ghost home
e.originalEvent.dataTransfer?.effectAllowed = "move"
e.originalEvent.dataTransfer?.setData "text", ""
$placeholder = $child.clone()
attachDragOverHandler($placeholder)
isDragging = true
options.sortStart?(e, $child)
$handle.on "touchmove.sordidDragon drag.sordidDragon", (e) ->
return unless isDragging
showPlaceholder $child
if isTouchDevice()
pageY = e.originalEvent.targetTouches[0].pageY
showGhost pageY
# On touch devices, we don't have dragenter events, so we'll update
# the position of the element being dragged here instead.
newPosition = currentPosition(pageY)
if newPosition?
moveChild $parent.children("#{options.childSelector || ""}:visible").eq(newPosition)
e.preventDefault()
$child.on "dragenter.sordidDragon", (e) ->
return unless isDragging
moveChild $child
attachDragOverHandler($child)
$handle.on "touchend.sordidDragon dragend.sordidDragon", (e) ->
return unless isDragging
hidePlaceholder $child
if isTouchDevice()
hideGhost()
# We must recalculate the positions because in the case where items
# are not all the same height, we would get unexpected results from
# currentPosition.
calculatePositions()
e.preventDefault()
options.sortEnd?(e, $child)
isDragging = false
| true | # jQuery the Sordid Dragon
# Copyright Poll Everywhere
# PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
# https://github.com/polleverywhere/sordid-dragon
# Version 2.2.1
do ($=jQuery) ->
isTouchDevice = ->
'ontouchstart' of document.documentElement
$.fn.sordidDragon = (command="enable", options={}) ->
unless typeof command is "string"
options = command
$parent = this
$ghostContainer = $(options.ghostContainer) || $parent
isDragging = false
# Remove old instance if it exists
if $.isFunction $parent.data("removeSordidDragon")
$parent.data("removeSordidDragon")()
# Handle removing an old instance in case 'enable' is called multiple times
$parent.data "removeSordidDragon", ->
isDragging = false
hidePlaceholder()
hideGhost()
# Windows touch devices (such as the Microsoft Surface Pro 3) will end
# the drag event early (and not call dragend) if the element being
# dragged is moved in the DOM by JavaScript.
# To work around that problem we:
# 1) clone the element being moved
# 2) hide the element being moved
# 3) move the clone around in the DOM
# Then we clean it all up in the dragend event.
$placeholder = null
$activePlaceholderChild = null
showPlaceholder = ($child) ->
$activePlaceholderChild = $child
# Hide the element being moved and replace it with the clone.
$child.css opacity: 0
unless $placeholder.is(":visible")
$placeholder.addClass "sordidDragon-placeholder"
$child.after $placeholder
$placeholder.css opacity: 0.5
# The hiding must come after the clone is inserted. Otherwise when
# you are scrolled down to the bottom of the screen, the act of hiding
# $child will cause the screen to scroll up. This makes it feel like
# dragging has caused the list to jump around.
$child.hide()
$child.css opacity: 1
hidePlaceholder = ->
if $placeholder?.is(":visible")
$placeholder.after $activePlaceholderChild
$placeholder.off ".sordidDragon"
$placeholder.remove()
$activePlaceholderChild.show()
# The $ghost is a faded copy of the element that moves with the mouse or
# finger.
# In most (but not all) browsers that support drag events, the browser will
# create a ghost under the cursor for us. That doesn't happen with touch
# events, so we create one ourselves.
$ghost = null
showGhost = (pageY) ->
unless $ghost.is(":visible")
$ghost
.addClass "sordidDragon-ghost"
.css
position: "fixed"
opacity: 1
$ghostContainer.append $ghost
$ghost.css
left: $placeholder.offset().left
top: (pageY - ($placeholder.outerHeight() / 2)) - window.scrollY
width: $placeholder.outerWidth() - window.scrollX
hideGhost = ->
$ghost?.remove()
# Touch devices don't support dragenter or dragover events. Instead we
# keep track of the location of each child so we can know which child is
# currently under the user's finger.
positions = null
calculatePositions = ->
positions = []
$parent.children(options.childSelector).each (_, child) ->
$child = $(child)
positions.push [
$child.offset().top
$child.offset().top + $child.outerHeight()
]
positions
currentPosition = (pageY) ->
for i in [0...positions.length]
return i if pageY >= positions[i][0] && pageY < positions[i][1]
null
moveChild = ($besideChild) ->
$children = $parent.children("#{options.childSelector || ""}:visible")
newPosition = $children.index($besideChild)
oldPosition = $children.index($placeholder)
if newPosition > oldPosition
$besideChild.after $placeholder
else if newPosition < oldPosition
$besideChild.before $placeholder
# This allows the browser provided ghose to stay where it's dropped
# rather than returning home
attachDragOverHandler = ($el) ->
$el.on "dragover.sordidDragon", (e) ->
return unless isDragging
e.preventDefault()
e.originalEvent.dataTransfer?.dropEffect = "move"
$parent.children(options.childSelector).each (_, child) ->
$child = $(child)
$handle = if options.handle
$child.find(options.handle)
else
$child
# Careful here. This might be interfering with other code that sets the
# "draggable" attribute.
$handle.attr "draggable", String(command != "destroy")
# Clear out the existing events (so they aren't duplicated).
$handle.off ".sordidDragon"
$child.off ".sordidDragon"
# If we are destroying, then just move on to the next child rather
# than setting up any event listeners.
return if command is "destroy"
$handle.on "touchstart.sordidDragon dragstart.sordidDragon", (e) ->
if isTouchDevice()
# We must pre-cache the positions after they have been rendered, but
# before anything has changed. Otherwise the extra elements we create
# during the drag process will interfere.
calculatePositions()
$ghost = $child.clone()
e.preventDefault()
# Firefox needs this for drag events, and others to now animate the ghost home
e.originalEvent.dataTransfer?.effectAllowed = "move"
e.originalEvent.dataTransfer?.setData "text", ""
$placeholder = $child.clone()
attachDragOverHandler($placeholder)
isDragging = true
options.sortStart?(e, $child)
$handle.on "touchmove.sordidDragon drag.sordidDragon", (e) ->
return unless isDragging
showPlaceholder $child
if isTouchDevice()
pageY = e.originalEvent.targetTouches[0].pageY
showGhost pageY
# On touch devices, we don't have dragenter events, so we'll update
# the position of the element being dragged here instead.
newPosition = currentPosition(pageY)
if newPosition?
moveChild $parent.children("#{options.childSelector || ""}:visible").eq(newPosition)
e.preventDefault()
$child.on "dragenter.sordidDragon", (e) ->
return unless isDragging
moveChild $child
attachDragOverHandler($child)
$handle.on "touchend.sordidDragon dragend.sordidDragon", (e) ->
return unless isDragging
hidePlaceholder $child
if isTouchDevice()
hideGhost()
# We must recalculate the positions because in the case where items
# are not all the same height, we would get unexpected results from
# currentPosition.
calculatePositions()
e.preventDefault()
options.sortEnd?(e, $child)
isDragging = false
|
[
{
"context": ">\n us = new UserCredential\n secret: 'super secret key'\n userId: 'facebook'\n\n us.secret.shou",
"end": 455,
"score": 0.6739518046379089,
"start": 449,
"tag": "KEY",
"value": "secret"
}
] | test/models/user_credential.coffee | t3mpus/tempus-api | 3 | UserCredential = require "#{__dirname}/../../models/user_credential"
should = require 'should'
describe 'User Credential', ->
it 'should be able to construct a user credential', ->
uc = new UserCredential
userId: 5
uc.userId.should.be.equal 5
uc.should.have.property 'secret'
uc.should.have.property 'userId'
it 'should allow the generated properties to be passed in', ->
us = new UserCredential
secret: 'super secret key'
userId: 'facebook'
us.secret.should.be.equal 'super secret key'
us.userId.should.be.equal 'facebook'
| 46191 | UserCredential = require "#{__dirname}/../../models/user_credential"
should = require 'should'
describe 'User Credential', ->
it 'should be able to construct a user credential', ->
uc = new UserCredential
userId: 5
uc.userId.should.be.equal 5
uc.should.have.property 'secret'
uc.should.have.property 'userId'
it 'should allow the generated properties to be passed in', ->
us = new UserCredential
secret: 'super <KEY> key'
userId: 'facebook'
us.secret.should.be.equal 'super secret key'
us.userId.should.be.equal 'facebook'
| true | UserCredential = require "#{__dirname}/../../models/user_credential"
should = require 'should'
describe 'User Credential', ->
it 'should be able to construct a user credential', ->
uc = new UserCredential
userId: 5
uc.userId.should.be.equal 5
uc.should.have.property 'secret'
uc.should.have.property 'userId'
it 'should allow the generated properties to be passed in', ->
us = new UserCredential
secret: 'super PI:KEY:<KEY>END_PI key'
userId: 'facebook'
us.secret.should.be.equal 'super secret key'
us.userId.should.be.equal 'facebook'
|
[
{
"context": "# Heavily inspired by Matteo Spinelli's SpinningWheel\n\nSlotMachine =\n cellHeight: 44,\n ",
"end": 39,
"score": 0.9379143714904785,
"start": 22,
"tag": "NAME",
"value": "Matteo Spinelli's"
}
] | coffee/slotmachine.coffee | simoncozens/slotmachine | 0 | # Heavily inspired by Matteo Spinelli's SpinningWheel
SlotMachine =
cellHeight: 44,
friction: 0.003,
buttons:
cancel: { label: "Cancel", position: "left", style: "sw-cancel" },
done: { label: "Done", position: "right", style: "sw-done" }
scrolling: false,
onChangeAction: () ->
newSlotValue = SlotMachine.getValueForSlot(SlotMachine.activeSlot)
if newSlotValue != SlotMachine.oldSlotValue
SlotMachine.changeAction()
changeAction: () ->
assert: (test, label) ->
if !test
throw new Error("Assertion failed: "+label)
destroy: ->
SlotMachine.activeSlot = null
$("#sw-wrapper").remove()
init: (slots) ->
SlotMachine.destroy()
swheader = $('<div id="sw-header">')
for name, button of this.buttons
$("<div/>").attr("id", button.style) # Transitional
.append(button.label)
.on("pressed", button.action)
.on("touchstart mousedown", this.buttonTapDown)
.appendTo(swheader)
swwrapper = $('<div id="sw-wrapper"></div>').css(
top: window.innerHeight + window.pageYOffset + 'px',
webkitTransitionProperty: "-webkit-transform",
webkitTransitionDuration: "400ms",
).append(swheader)
swwrapper.append('<div id="sw-slots-wrapper"><div id="sw-slots"></div></div><div id="sw-frame"></div>')
$("body").append(swwrapper)
SlotMachine.createSlots(slots)
$("#sw-frame").on("touchstart mousedown", this.frameTouchstart)
open: () ->
$(document).on("touchstart touchmove mousedown mousemove", this.lockScreen)
$(window).on("orientationchange", this.orientationChangeHandler)
$(window).on("scroll", this.scrollHandler)
$("#sw-wrapper").css(
webkitTransitionTimingFunction: "ease-out"
webkitTransform: "translate3d(0, -260px, 0)"
)
close: () ->
$(document).off("touchstart touchmove mousedown mousemove", this.lockScreen)
$(window).off("orientationchange", this.orientationChangeHandler)
$(window).off("scroll", this.scrollHandler)
$("#sw-wrapper").css(
webkitTransitionTimingFunction: 'ease-in',
webkitTransform: 'translate3d(0, 0, 0)'
).one("webkitTransitionEnd", this.closedHandler)
slotByIndex: (index) ->
s = $("#sw-slots div:nth-child("+(1+index)+") ul")
if s[0] then return s
createSlots: (slots) ->
$("#sw-slots").empty()
this.createSlot(index, slots[index]) for index in [0..slots.length-1]
createSlot: (index, data) ->
# Do we have this already?
oldUl = $("#sw-slots div:nth-child("+(1+index)+")")
if oldUl[0]
ul = oldUl.children("ul")
ul.empty()
else
ul = $("<ul/>").css({webkitTransitionTimingFunction: 'cubic-bezier(0, 0, 0.2, 1)'})
ul.data(slotYPosition: 0)
@assert(typeof(data.entries) =="object", "data for slot "+index+" has entries")
for entry in data.entries
if typeof(entry) != "object" then entry = { label: entry }
this.assert(entry.label, "entry in slot "+index+" has a label")
if not entry.value then entry.value = entry.label
$("<li>"+entry.label+"</li>").data("value", entry.value).appendTo(ul)
if not oldUl[0]
div = $("<div/>").addClass(data.style).append(ul)
$("#sw-slots").append(div)
ul.data({ slotMaxScroll: $("#sw-slots-wrapper").innerHeight() - ul.innerHeight() - 86 }) # XXX clientHeight
defaultEntry = (entry for entry in data.entries when entry.default)
this.scrollToValue(ul, defaultEntry[0]) if defaultEntry[0]
scrollToValue: (slot, entry) ->
if typeof(slot) != "object" then slot = @slotByIndex(slot)
this.assert(entry.value, "entry has a value")
this.assert(slot[0], "slot exists in DOM")
count = 0
for v in slot.children()
if $(v).data("value") == entry.value
this.setPosition(slot, this.cellHeight * count)
break
count -= 1
setPosition: (slot, position) ->
this.assert(slot[0], "slot is a jQuery object")
slot.data("slotYPosition", position)
slot.css("webkitTransform", 'translate3d(0, ' + position + 'px, 0)')
getPosition: (slot) ->
slot.data("slotYPosition") || new WebKitCSSMatrix(slot.css("-webkit-transform")).m42
getValueForSlot: (slot) ->
this.assert(slot[0], "slot is a jQuery object")
slot.unbind("webkitTransitionEnd").css("webkitTransitionDuration", 0)
if slot.data("slotYPosition") > 0
this.setPosition(slot, 0)
else if slot.data("slotYPosition") < slot.data("slotMaxScroll")
this.setPosition(slot, slot.data("slotMaxScroll"))
index = -Math.round(SlotMachine.getPosition(slot) / this.cellHeight)
li = $(slot.children("li:nth-child("+(1+index)+")"))
return li.data("value")
getSelectedValues: ->
rv = []
for slot in $("#sw-slots div ul")
slot = $(slot)
rv.push this.getValueForSlot(slot)
rv
lockScreen: (e) ->
e.preventDefault()
e.stopPropagation()
orientationChangeHandler: () ->
window.scrollTo(0, 0)
$("sw-wrapper").css("top", window.innerHeight + window.pageYOffset + 'px')
scrollHandler: () ->
$("sw-wrapper").css("top", window.innerHeight + window.pageYOffset + 'px')
closedHandler: () ->
buttonTapDown: (e) ->
SlotMachine.lockScreen(e)
button = $(e.currentTarget)
button.on("touchmove mousemove", SlotMachine.buttonTapCancel)
button.on("touchend mouseup", SlotMachine.buttonTapUp)
button.addClass("sw-pressed")
buttonTapCancel: (e) ->
SlotMachine.lockScreen(e)
button = $(e.currentTarget)
button.off("touchmove mousemove", SlotMachine.buttonTapcancel)
button.off("touchend mouseup", SlotMachine.buttonTapUp)
button.removeClass("sw-pressed")
buttonTapUp: (e) ->
SlotMachine.lockScreen(e)
SlotMachine.buttonTapCancel(e)
button = $(e.currentTarget)
$("#sw-wrapper").one "webkitTransitionEnd", ->
button.trigger("pressed")
SlotMachine.close()
frameTouchstart: (e) ->
SlotMachine.lockScreen(e)
if e.originalEvent then e = e.originalEvent
yoffset = if e.targetTouches then e.targetTouches[0].clientY - e.target.getBoundingClientRect().top else e.offsetY
SlotMachine.whichPos = Math.floor(yoffset / SlotMachine.cellHeight) - 2
# You can only go up/down a max of two positions
SlotMachine.scrollStart(e)
SlotMachine.oldSlotValue = SlotMachine.getValueForSlot(SlotMachine.activeSlot)
frameTouchmove: (e) ->
SlotMachine.lockScreen(e)
SlotMachine.scrolling = true
SlotMachine.scrollMove(e)
frameTouchend: (e) ->
SlotMachine.scrollEnd(e)
if SlotMachine.scrolling
SlotMachine.activeSlot.one 'webkitTransitionEnd', (e) ->
if SlotMachine.backWithinBoundaries(e) then SlotMachine.onChangeAction(e)
SlotMachine.scrolling = false
else
scrollTo = SlotMachine.activeSlot.data("slotYPosition") - (SlotMachine.whichPos * SlotMachine.cellHeight)
if scrollTo <= 0 and scrollTo >= SlotMachine.activeSlot.data("slotMaxScroll")
SlotMachine.activeSlot.one 'webkitTransitionEnd', (e) ->
if SlotMachine.backWithinBoundaries(e) then SlotMachine.onChangeAction(e)
SlotMachine.scrollTo(SlotMachine.activeSlot, scrollTo)
scrollStart: (e) ->
this.lockScreen(e)
event = if e.targetTouches and e.targetTouches[0].clientX then e.targetTouches[0] else e
for slot in $("#sw-slots div ul")
slot = $(slot)
if event.clientX < slot.offset().left + slot.width()
this.activeSlot = slot
break
if this.activeSlot.hasClass("sw-readonly")
$("#sw-frame").off("touchmove touchend mousemove mouseup", this.frameMoved)
return
slot.unbind("webkitTransitionEnd").css("webkitTransitionDuration", 0)
theTransform = new WebKitCSSMatrix(slot.css("-webkit-transform")).m42
if theTransform != slot.data("slotYPosition")
this.setPosition(slot, theTransform)
this.startY = event.clientY;
this.scrollStartY = slot.data("slotYPosition")
this.scrollStartTime = e.timeStamp;
$("#sw-frame").on("touchmove mousemove", this.frameTouchmove)
$("#sw-frame").on("touchend mouseup", this.frameTouchend)
return true
scrollMove: (e) ->
if e.originalEvent then e = e.originalEvent
event = if e.targetTouches then e.targetTouches[0] else e
topDelta = event.clientY - this.startY
if this.activeSlot.data("slotYPosition") > 0 or this.activeSlot.data("slotYPosition") < this.activeSlot.data("slotMaxScroll")
topDelta /= 2
this.setPosition(this.activeSlot, this.activeSlot.data("slotYPosition") + topDelta)
this.startY = event.clientY
if e.timeStamp - this.scrollStartTime > 80
this.scrollStartY = this.activeSlot.data("slotYPosition")
this.scrollStartTime = e.timeStamp;
scrollEnd: (e) ->
$("#sw-frame").off("touchmove mousemove", this.frameTouchmove)
$("#sw-frame").off("touchend mouseup", this.frameTouchend)
ypos = this.activeSlot.data("slotYPosition")
maxScroll = this.activeSlot.data("slotMaxScroll")
if ypos > 0
this.scrollTo(this.activeSlot, 0)
return false
else if ypos < maxScroll
this.scrollTo(this.activeSlot, maxScroll)
return false
scrollDistance = ypos - this.scrollStartY
if scrollDistance < this.cellHeight / 1.5 and scrollDistance > -this.cellHeight / 1.5
if ypos % this.cellHeight
this.scrollTo(this.activeSlot, Math.round(ypos / this.cellHeight) * this.cellHeight, '250ms');
return false
scrollDuration = e.timeStamp - this.scrollStartTime
newDuration = (2 * scrollDistance / scrollDuration) / this.friction
newScrollDistance = (this.friction / 2) * (newDuration * newDuration)
if newDuration < 0
newDuration = -newDuration
newScrollDistance = -newScrollDistance
newPosition = ypos + newScrollDistance
if newPosition > 0
newPosition /= 2
newDuration /= 3
if newPosition > $("#sw-slots-wrapper").innerHeight() / 4
newPosition = $("#sw-slots-wrapper").innerHeight() / 4
else if newPosition < maxScroll
newPosition = (newPosition - maxScroll) / 2 + maxScroll
newDuration /= 3
if newPosition < maxScroll - $("#sw-slots-wrapper").innerHeight() / 4
newPosition = $("#sw-slots-wrapper").innerHeight() / 4
else
newPosition = Math.round(newPosition / this.cellHeight) * this.cellHeight
this.scrollTo(this.activeSlot, Math.round(newPosition), Math.round(newDuration) + 'ms');
return true
scrollTo: (slot, dest, runtime) ->
slot.css("webkitTransitionDuration", runtime || "250ms")
this.setPosition(slot, dest)
if slot.data("slotYPosition") > 0 or slot.data("slotYPosition") < slot.data("slotMaxScroll")
slot.one("webkitTransitionEnd", this.backWithinBoundaries)
backWithinBoundaries: (e) ->
slot = $(e.target)
if slot.data("slotYPosition") > 0
SlotMachine.scrollTo(slot, 0)
return false
else if slot.data("slotYPosition") < slot.data("slotMaxScroll")
SlotMachine.scrollTo(slot, slot.data("slotMaxScroll"))
return false
else
return true
| 86887 | # Heavily inspired by <NAME> SpinningWheel
SlotMachine =
cellHeight: 44,
friction: 0.003,
buttons:
cancel: { label: "Cancel", position: "left", style: "sw-cancel" },
done: { label: "Done", position: "right", style: "sw-done" }
scrolling: false,
onChangeAction: () ->
newSlotValue = SlotMachine.getValueForSlot(SlotMachine.activeSlot)
if newSlotValue != SlotMachine.oldSlotValue
SlotMachine.changeAction()
changeAction: () ->
assert: (test, label) ->
if !test
throw new Error("Assertion failed: "+label)
destroy: ->
SlotMachine.activeSlot = null
$("#sw-wrapper").remove()
init: (slots) ->
SlotMachine.destroy()
swheader = $('<div id="sw-header">')
for name, button of this.buttons
$("<div/>").attr("id", button.style) # Transitional
.append(button.label)
.on("pressed", button.action)
.on("touchstart mousedown", this.buttonTapDown)
.appendTo(swheader)
swwrapper = $('<div id="sw-wrapper"></div>').css(
top: window.innerHeight + window.pageYOffset + 'px',
webkitTransitionProperty: "-webkit-transform",
webkitTransitionDuration: "400ms",
).append(swheader)
swwrapper.append('<div id="sw-slots-wrapper"><div id="sw-slots"></div></div><div id="sw-frame"></div>')
$("body").append(swwrapper)
SlotMachine.createSlots(slots)
$("#sw-frame").on("touchstart mousedown", this.frameTouchstart)
open: () ->
$(document).on("touchstart touchmove mousedown mousemove", this.lockScreen)
$(window).on("orientationchange", this.orientationChangeHandler)
$(window).on("scroll", this.scrollHandler)
$("#sw-wrapper").css(
webkitTransitionTimingFunction: "ease-out"
webkitTransform: "translate3d(0, -260px, 0)"
)
close: () ->
$(document).off("touchstart touchmove mousedown mousemove", this.lockScreen)
$(window).off("orientationchange", this.orientationChangeHandler)
$(window).off("scroll", this.scrollHandler)
$("#sw-wrapper").css(
webkitTransitionTimingFunction: 'ease-in',
webkitTransform: 'translate3d(0, 0, 0)'
).one("webkitTransitionEnd", this.closedHandler)
slotByIndex: (index) ->
s = $("#sw-slots div:nth-child("+(1+index)+") ul")
if s[0] then return s
createSlots: (slots) ->
$("#sw-slots").empty()
this.createSlot(index, slots[index]) for index in [0..slots.length-1]
createSlot: (index, data) ->
# Do we have this already?
oldUl = $("#sw-slots div:nth-child("+(1+index)+")")
if oldUl[0]
ul = oldUl.children("ul")
ul.empty()
else
ul = $("<ul/>").css({webkitTransitionTimingFunction: 'cubic-bezier(0, 0, 0.2, 1)'})
ul.data(slotYPosition: 0)
@assert(typeof(data.entries) =="object", "data for slot "+index+" has entries")
for entry in data.entries
if typeof(entry) != "object" then entry = { label: entry }
this.assert(entry.label, "entry in slot "+index+" has a label")
if not entry.value then entry.value = entry.label
$("<li>"+entry.label+"</li>").data("value", entry.value).appendTo(ul)
if not oldUl[0]
div = $("<div/>").addClass(data.style).append(ul)
$("#sw-slots").append(div)
ul.data({ slotMaxScroll: $("#sw-slots-wrapper").innerHeight() - ul.innerHeight() - 86 }) # XXX clientHeight
defaultEntry = (entry for entry in data.entries when entry.default)
this.scrollToValue(ul, defaultEntry[0]) if defaultEntry[0]
scrollToValue: (slot, entry) ->
if typeof(slot) != "object" then slot = @slotByIndex(slot)
this.assert(entry.value, "entry has a value")
this.assert(slot[0], "slot exists in DOM")
count = 0
for v in slot.children()
if $(v).data("value") == entry.value
this.setPosition(slot, this.cellHeight * count)
break
count -= 1
setPosition: (slot, position) ->
this.assert(slot[0], "slot is a jQuery object")
slot.data("slotYPosition", position)
slot.css("webkitTransform", 'translate3d(0, ' + position + 'px, 0)')
getPosition: (slot) ->
slot.data("slotYPosition") || new WebKitCSSMatrix(slot.css("-webkit-transform")).m42
getValueForSlot: (slot) ->
this.assert(slot[0], "slot is a jQuery object")
slot.unbind("webkitTransitionEnd").css("webkitTransitionDuration", 0)
if slot.data("slotYPosition") > 0
this.setPosition(slot, 0)
else if slot.data("slotYPosition") < slot.data("slotMaxScroll")
this.setPosition(slot, slot.data("slotMaxScroll"))
index = -Math.round(SlotMachine.getPosition(slot) / this.cellHeight)
li = $(slot.children("li:nth-child("+(1+index)+")"))
return li.data("value")
getSelectedValues: ->
rv = []
for slot in $("#sw-slots div ul")
slot = $(slot)
rv.push this.getValueForSlot(slot)
rv
lockScreen: (e) ->
e.preventDefault()
e.stopPropagation()
orientationChangeHandler: () ->
window.scrollTo(0, 0)
$("sw-wrapper").css("top", window.innerHeight + window.pageYOffset + 'px')
scrollHandler: () ->
$("sw-wrapper").css("top", window.innerHeight + window.pageYOffset + 'px')
closedHandler: () ->
buttonTapDown: (e) ->
SlotMachine.lockScreen(e)
button = $(e.currentTarget)
button.on("touchmove mousemove", SlotMachine.buttonTapCancel)
button.on("touchend mouseup", SlotMachine.buttonTapUp)
button.addClass("sw-pressed")
buttonTapCancel: (e) ->
SlotMachine.lockScreen(e)
button = $(e.currentTarget)
button.off("touchmove mousemove", SlotMachine.buttonTapcancel)
button.off("touchend mouseup", SlotMachine.buttonTapUp)
button.removeClass("sw-pressed")
buttonTapUp: (e) ->
SlotMachine.lockScreen(e)
SlotMachine.buttonTapCancel(e)
button = $(e.currentTarget)
$("#sw-wrapper").one "webkitTransitionEnd", ->
button.trigger("pressed")
SlotMachine.close()
frameTouchstart: (e) ->
SlotMachine.lockScreen(e)
if e.originalEvent then e = e.originalEvent
yoffset = if e.targetTouches then e.targetTouches[0].clientY - e.target.getBoundingClientRect().top else e.offsetY
SlotMachine.whichPos = Math.floor(yoffset / SlotMachine.cellHeight) - 2
# You can only go up/down a max of two positions
SlotMachine.scrollStart(e)
SlotMachine.oldSlotValue = SlotMachine.getValueForSlot(SlotMachine.activeSlot)
frameTouchmove: (e) ->
SlotMachine.lockScreen(e)
SlotMachine.scrolling = true
SlotMachine.scrollMove(e)
frameTouchend: (e) ->
SlotMachine.scrollEnd(e)
if SlotMachine.scrolling
SlotMachine.activeSlot.one 'webkitTransitionEnd', (e) ->
if SlotMachine.backWithinBoundaries(e) then SlotMachine.onChangeAction(e)
SlotMachine.scrolling = false
else
scrollTo = SlotMachine.activeSlot.data("slotYPosition") - (SlotMachine.whichPos * SlotMachine.cellHeight)
if scrollTo <= 0 and scrollTo >= SlotMachine.activeSlot.data("slotMaxScroll")
SlotMachine.activeSlot.one 'webkitTransitionEnd', (e) ->
if SlotMachine.backWithinBoundaries(e) then SlotMachine.onChangeAction(e)
SlotMachine.scrollTo(SlotMachine.activeSlot, scrollTo)
scrollStart: (e) ->
this.lockScreen(e)
event = if e.targetTouches and e.targetTouches[0].clientX then e.targetTouches[0] else e
for slot in $("#sw-slots div ul")
slot = $(slot)
if event.clientX < slot.offset().left + slot.width()
this.activeSlot = slot
break
if this.activeSlot.hasClass("sw-readonly")
$("#sw-frame").off("touchmove touchend mousemove mouseup", this.frameMoved)
return
slot.unbind("webkitTransitionEnd").css("webkitTransitionDuration", 0)
theTransform = new WebKitCSSMatrix(slot.css("-webkit-transform")).m42
if theTransform != slot.data("slotYPosition")
this.setPosition(slot, theTransform)
this.startY = event.clientY;
this.scrollStartY = slot.data("slotYPosition")
this.scrollStartTime = e.timeStamp;
$("#sw-frame").on("touchmove mousemove", this.frameTouchmove)
$("#sw-frame").on("touchend mouseup", this.frameTouchend)
return true
scrollMove: (e) ->
if e.originalEvent then e = e.originalEvent
event = if e.targetTouches then e.targetTouches[0] else e
topDelta = event.clientY - this.startY
if this.activeSlot.data("slotYPosition") > 0 or this.activeSlot.data("slotYPosition") < this.activeSlot.data("slotMaxScroll")
topDelta /= 2
this.setPosition(this.activeSlot, this.activeSlot.data("slotYPosition") + topDelta)
this.startY = event.clientY
if e.timeStamp - this.scrollStartTime > 80
this.scrollStartY = this.activeSlot.data("slotYPosition")
this.scrollStartTime = e.timeStamp;
scrollEnd: (e) ->
$("#sw-frame").off("touchmove mousemove", this.frameTouchmove)
$("#sw-frame").off("touchend mouseup", this.frameTouchend)
ypos = this.activeSlot.data("slotYPosition")
maxScroll = this.activeSlot.data("slotMaxScroll")
if ypos > 0
this.scrollTo(this.activeSlot, 0)
return false
else if ypos < maxScroll
this.scrollTo(this.activeSlot, maxScroll)
return false
scrollDistance = ypos - this.scrollStartY
if scrollDistance < this.cellHeight / 1.5 and scrollDistance > -this.cellHeight / 1.5
if ypos % this.cellHeight
this.scrollTo(this.activeSlot, Math.round(ypos / this.cellHeight) * this.cellHeight, '250ms');
return false
scrollDuration = e.timeStamp - this.scrollStartTime
newDuration = (2 * scrollDistance / scrollDuration) / this.friction
newScrollDistance = (this.friction / 2) * (newDuration * newDuration)
if newDuration < 0
newDuration = -newDuration
newScrollDistance = -newScrollDistance
newPosition = ypos + newScrollDistance
if newPosition > 0
newPosition /= 2
newDuration /= 3
if newPosition > $("#sw-slots-wrapper").innerHeight() / 4
newPosition = $("#sw-slots-wrapper").innerHeight() / 4
else if newPosition < maxScroll
newPosition = (newPosition - maxScroll) / 2 + maxScroll
newDuration /= 3
if newPosition < maxScroll - $("#sw-slots-wrapper").innerHeight() / 4
newPosition = $("#sw-slots-wrapper").innerHeight() / 4
else
newPosition = Math.round(newPosition / this.cellHeight) * this.cellHeight
this.scrollTo(this.activeSlot, Math.round(newPosition), Math.round(newDuration) + 'ms');
return true
scrollTo: (slot, dest, runtime) ->
slot.css("webkitTransitionDuration", runtime || "250ms")
this.setPosition(slot, dest)
if slot.data("slotYPosition") > 0 or slot.data("slotYPosition") < slot.data("slotMaxScroll")
slot.one("webkitTransitionEnd", this.backWithinBoundaries)
backWithinBoundaries: (e) ->
slot = $(e.target)
if slot.data("slotYPosition") > 0
SlotMachine.scrollTo(slot, 0)
return false
else if slot.data("slotYPosition") < slot.data("slotMaxScroll")
SlotMachine.scrollTo(slot, slot.data("slotMaxScroll"))
return false
else
return true
| true | # Heavily inspired by PI:NAME:<NAME>END_PI SpinningWheel
SlotMachine =
cellHeight: 44,
friction: 0.003,
buttons:
cancel: { label: "Cancel", position: "left", style: "sw-cancel" },
done: { label: "Done", position: "right", style: "sw-done" }
scrolling: false,
onChangeAction: () ->
newSlotValue = SlotMachine.getValueForSlot(SlotMachine.activeSlot)
if newSlotValue != SlotMachine.oldSlotValue
SlotMachine.changeAction()
changeAction: () ->
assert: (test, label) ->
if !test
throw new Error("Assertion failed: "+label)
destroy: ->
SlotMachine.activeSlot = null
$("#sw-wrapper").remove()
init: (slots) ->
SlotMachine.destroy()
swheader = $('<div id="sw-header">')
for name, button of this.buttons
$("<div/>").attr("id", button.style) # Transitional
.append(button.label)
.on("pressed", button.action)
.on("touchstart mousedown", this.buttonTapDown)
.appendTo(swheader)
swwrapper = $('<div id="sw-wrapper"></div>').css(
top: window.innerHeight + window.pageYOffset + 'px',
webkitTransitionProperty: "-webkit-transform",
webkitTransitionDuration: "400ms",
).append(swheader)
swwrapper.append('<div id="sw-slots-wrapper"><div id="sw-slots"></div></div><div id="sw-frame"></div>')
$("body").append(swwrapper)
SlotMachine.createSlots(slots)
$("#sw-frame").on("touchstart mousedown", this.frameTouchstart)
open: () ->
$(document).on("touchstart touchmove mousedown mousemove", this.lockScreen)
$(window).on("orientationchange", this.orientationChangeHandler)
$(window).on("scroll", this.scrollHandler)
$("#sw-wrapper").css(
webkitTransitionTimingFunction: "ease-out"
webkitTransform: "translate3d(0, -260px, 0)"
)
close: () ->
$(document).off("touchstart touchmove mousedown mousemove", this.lockScreen)
$(window).off("orientationchange", this.orientationChangeHandler)
$(window).off("scroll", this.scrollHandler)
$("#sw-wrapper").css(
webkitTransitionTimingFunction: 'ease-in',
webkitTransform: 'translate3d(0, 0, 0)'
).one("webkitTransitionEnd", this.closedHandler)
slotByIndex: (index) ->
s = $("#sw-slots div:nth-child("+(1+index)+") ul")
if s[0] then return s
createSlots: (slots) ->
$("#sw-slots").empty()
this.createSlot(index, slots[index]) for index in [0..slots.length-1]
createSlot: (index, data) ->
# Do we have this already?
oldUl = $("#sw-slots div:nth-child("+(1+index)+")")
if oldUl[0]
ul = oldUl.children("ul")
ul.empty()
else
ul = $("<ul/>").css({webkitTransitionTimingFunction: 'cubic-bezier(0, 0, 0.2, 1)'})
ul.data(slotYPosition: 0)
@assert(typeof(data.entries) =="object", "data for slot "+index+" has entries")
for entry in data.entries
if typeof(entry) != "object" then entry = { label: entry }
this.assert(entry.label, "entry in slot "+index+" has a label")
if not entry.value then entry.value = entry.label
$("<li>"+entry.label+"</li>").data("value", entry.value).appendTo(ul)
if not oldUl[0]
div = $("<div/>").addClass(data.style).append(ul)
$("#sw-slots").append(div)
ul.data({ slotMaxScroll: $("#sw-slots-wrapper").innerHeight() - ul.innerHeight() - 86 }) # XXX clientHeight
defaultEntry = (entry for entry in data.entries when entry.default)
this.scrollToValue(ul, defaultEntry[0]) if defaultEntry[0]
scrollToValue: (slot, entry) ->
if typeof(slot) != "object" then slot = @slotByIndex(slot)
this.assert(entry.value, "entry has a value")
this.assert(slot[0], "slot exists in DOM")
count = 0
for v in slot.children()
if $(v).data("value") == entry.value
this.setPosition(slot, this.cellHeight * count)
break
count -= 1
setPosition: (slot, position) ->
this.assert(slot[0], "slot is a jQuery object")
slot.data("slotYPosition", position)
slot.css("webkitTransform", 'translate3d(0, ' + position + 'px, 0)')
getPosition: (slot) ->
slot.data("slotYPosition") || new WebKitCSSMatrix(slot.css("-webkit-transform")).m42
getValueForSlot: (slot) ->
this.assert(slot[0], "slot is a jQuery object")
slot.unbind("webkitTransitionEnd").css("webkitTransitionDuration", 0)
if slot.data("slotYPosition") > 0
this.setPosition(slot, 0)
else if slot.data("slotYPosition") < slot.data("slotMaxScroll")
this.setPosition(slot, slot.data("slotMaxScroll"))
index = -Math.round(SlotMachine.getPosition(slot) / this.cellHeight)
li = $(slot.children("li:nth-child("+(1+index)+")"))
return li.data("value")
getSelectedValues: ->
rv = []
for slot in $("#sw-slots div ul")
slot = $(slot)
rv.push this.getValueForSlot(slot)
rv
lockScreen: (e) ->
e.preventDefault()
e.stopPropagation()
orientationChangeHandler: () ->
window.scrollTo(0, 0)
$("sw-wrapper").css("top", window.innerHeight + window.pageYOffset + 'px')
scrollHandler: () ->
$("sw-wrapper").css("top", window.innerHeight + window.pageYOffset + 'px')
closedHandler: () ->
buttonTapDown: (e) ->
SlotMachine.lockScreen(e)
button = $(e.currentTarget)
button.on("touchmove mousemove", SlotMachine.buttonTapCancel)
button.on("touchend mouseup", SlotMachine.buttonTapUp)
button.addClass("sw-pressed")
buttonTapCancel: (e) ->
SlotMachine.lockScreen(e)
button = $(e.currentTarget)
button.off("touchmove mousemove", SlotMachine.buttonTapcancel)
button.off("touchend mouseup", SlotMachine.buttonTapUp)
button.removeClass("sw-pressed")
buttonTapUp: (e) ->
SlotMachine.lockScreen(e)
SlotMachine.buttonTapCancel(e)
button = $(e.currentTarget)
$("#sw-wrapper").one "webkitTransitionEnd", ->
button.trigger("pressed")
SlotMachine.close()
frameTouchstart: (e) ->
SlotMachine.lockScreen(e)
if e.originalEvent then e = e.originalEvent
yoffset = if e.targetTouches then e.targetTouches[0].clientY - e.target.getBoundingClientRect().top else e.offsetY
SlotMachine.whichPos = Math.floor(yoffset / SlotMachine.cellHeight) - 2
# You can only go up/down a max of two positions
SlotMachine.scrollStart(e)
SlotMachine.oldSlotValue = SlotMachine.getValueForSlot(SlotMachine.activeSlot)
frameTouchmove: (e) ->
SlotMachine.lockScreen(e)
SlotMachine.scrolling = true
SlotMachine.scrollMove(e)
frameTouchend: (e) ->
SlotMachine.scrollEnd(e)
if SlotMachine.scrolling
SlotMachine.activeSlot.one 'webkitTransitionEnd', (e) ->
if SlotMachine.backWithinBoundaries(e) then SlotMachine.onChangeAction(e)
SlotMachine.scrolling = false
else
scrollTo = SlotMachine.activeSlot.data("slotYPosition") - (SlotMachine.whichPos * SlotMachine.cellHeight)
if scrollTo <= 0 and scrollTo >= SlotMachine.activeSlot.data("slotMaxScroll")
SlotMachine.activeSlot.one 'webkitTransitionEnd', (e) ->
if SlotMachine.backWithinBoundaries(e) then SlotMachine.onChangeAction(e)
SlotMachine.scrollTo(SlotMachine.activeSlot, scrollTo)
scrollStart: (e) ->
this.lockScreen(e)
event = if e.targetTouches and e.targetTouches[0].clientX then e.targetTouches[0] else e
for slot in $("#sw-slots div ul")
slot = $(slot)
if event.clientX < slot.offset().left + slot.width()
this.activeSlot = slot
break
if this.activeSlot.hasClass("sw-readonly")
$("#sw-frame").off("touchmove touchend mousemove mouseup", this.frameMoved)
return
slot.unbind("webkitTransitionEnd").css("webkitTransitionDuration", 0)
theTransform = new WebKitCSSMatrix(slot.css("-webkit-transform")).m42
if theTransform != slot.data("slotYPosition")
this.setPosition(slot, theTransform)
this.startY = event.clientY;
this.scrollStartY = slot.data("slotYPosition")
this.scrollStartTime = e.timeStamp;
$("#sw-frame").on("touchmove mousemove", this.frameTouchmove)
$("#sw-frame").on("touchend mouseup", this.frameTouchend)
return true
scrollMove: (e) ->
if e.originalEvent then e = e.originalEvent
event = if e.targetTouches then e.targetTouches[0] else e
topDelta = event.clientY - this.startY
if this.activeSlot.data("slotYPosition") > 0 or this.activeSlot.data("slotYPosition") < this.activeSlot.data("slotMaxScroll")
topDelta /= 2
this.setPosition(this.activeSlot, this.activeSlot.data("slotYPosition") + topDelta)
this.startY = event.clientY
if e.timeStamp - this.scrollStartTime > 80
this.scrollStartY = this.activeSlot.data("slotYPosition")
this.scrollStartTime = e.timeStamp;
scrollEnd: (e) ->
$("#sw-frame").off("touchmove mousemove", this.frameTouchmove)
$("#sw-frame").off("touchend mouseup", this.frameTouchend)
ypos = this.activeSlot.data("slotYPosition")
maxScroll = this.activeSlot.data("slotMaxScroll")
if ypos > 0
this.scrollTo(this.activeSlot, 0)
return false
else if ypos < maxScroll
this.scrollTo(this.activeSlot, maxScroll)
return false
scrollDistance = ypos - this.scrollStartY
if scrollDistance < this.cellHeight / 1.5 and scrollDistance > -this.cellHeight / 1.5
if ypos % this.cellHeight
this.scrollTo(this.activeSlot, Math.round(ypos / this.cellHeight) * this.cellHeight, '250ms');
return false
scrollDuration = e.timeStamp - this.scrollStartTime
newDuration = (2 * scrollDistance / scrollDuration) / this.friction
newScrollDistance = (this.friction / 2) * (newDuration * newDuration)
if newDuration < 0
newDuration = -newDuration
newScrollDistance = -newScrollDistance
newPosition = ypos + newScrollDistance
if newPosition > 0
newPosition /= 2
newDuration /= 3
if newPosition > $("#sw-slots-wrapper").innerHeight() / 4
newPosition = $("#sw-slots-wrapper").innerHeight() / 4
else if newPosition < maxScroll
newPosition = (newPosition - maxScroll) / 2 + maxScroll
newDuration /= 3
if newPosition < maxScroll - $("#sw-slots-wrapper").innerHeight() / 4
newPosition = $("#sw-slots-wrapper").innerHeight() / 4
else
newPosition = Math.round(newPosition / this.cellHeight) * this.cellHeight
this.scrollTo(this.activeSlot, Math.round(newPosition), Math.round(newDuration) + 'ms');
return true
scrollTo: (slot, dest, runtime) ->
slot.css("webkitTransitionDuration", runtime || "250ms")
this.setPosition(slot, dest)
if slot.data("slotYPosition") > 0 or slot.data("slotYPosition") < slot.data("slotMaxScroll")
slot.one("webkitTransitionEnd", this.backWithinBoundaries)
backWithinBoundaries: (e) ->
slot = $(e.target)
if slot.data("slotYPosition") > 0
SlotMachine.scrollTo(slot, 0)
return false
else if slot.data("slotYPosition") < slot.data("slotMaxScroll")
SlotMachine.scrollTo(slot, slot.data("slotMaxScroll"))
return false
else
return true
|
[
{
"context": "ntents': '<div style=\"text-align: center;\">Author: Marc Bachmann</div>'\n\t'footer':\n\t\t'height': '28mm'\n\t\t'contents'",
"end": 542,
"score": 0.9995786547660828,
"start": 529,
"tag": "NAME",
"value": "Marc Bachmann"
}
] | app.coffee | SNP-team/SNP-pipeline-node | 0 | app = require('express')()
server = require('http').Server(app)
io = require('socket.io')(server)
cp = require('child_process')
path = require('path')
phantomjs = require('phantomjs')
pdf = require('node-html-pdf')
fs = require('fs')
config =
'directory': '/tmp'
'height': '10.5in'
'width': '8in'
'format': 'Letter'
'orientation': 'portrait'
'border': '0'
'border':
'top': '2in'
'right': '1in'
'bottom': '2in'
'left': '1.5in'
'header':
'height': '45mm'
'contents': '<div style="text-align: center;">Author: Marc Bachmann</div>'
'footer':
'height': '28mm'
'contents': '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>'
'type': 'pdf'
'quality': '75'
'phantomPath': './node_modules/phantomjs/bin/phantomjs'
'phantomArgs': []
'script': '/url'
'timeout': 30000
'httpHeaders': 'Authorization': 'Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B'
server.listen 8080
app.get '/', (req, res)->
res.sendfile __dirname + '/web/'+'/index.html'
app.get /(?:js|css|showdown)/, (req,res)->
res.sendfile __dirname + '/web/'+ req.path
app.get /data/, (req,res)->
res.sendfile(path.resolve(__dirname + '/../' + req.path))
runscript = (cmd,socket)->
run = cp.exec cmd,{}
socket.emit "log","CMD start #{cmd}"
run.stdout.on 'data', (data)->
socket.emit "log",data
run.stderr.on 'data', (data)->
socket.emit 'err',data
run.on 'exit',()->
socket.emit "log","CMD #{cmd} finish"
fs = require 'fs'
sendfile = (file)->
filepath = __dirname + '/../'+ file
str = fs.readFileSync(filepath, 'utf-8');
return str
io.on 'connection', (socket) ->
socket.emit 'log','successfully connect'
socket.on 'runscript',(data)->
runscript data,socket
socket.on 'needfile',(data)->
resp =
name : data['filename']
type : data['type']
container:data["container"]
content :sendfile data['filename']
socket.emit "file",resp
socket.on 'serverlog',(data)->
console.log data
socket.on 'convertpdf',(html)->
console.log html
console.log 'convertpdf called'
filename = __dirname + '/report.pdf'
pdf.create(html, config).toFile(filename, (err, res)->
console.log "filename: " + filename
if err
return console.log(err)
console.log(res)
socket.emit 'convertpdffinished', filename
)
| 121797 | app = require('express')()
server = require('http').Server(app)
io = require('socket.io')(server)
cp = require('child_process')
path = require('path')
phantomjs = require('phantomjs')
pdf = require('node-html-pdf')
fs = require('fs')
config =
'directory': '/tmp'
'height': '10.5in'
'width': '8in'
'format': 'Letter'
'orientation': 'portrait'
'border': '0'
'border':
'top': '2in'
'right': '1in'
'bottom': '2in'
'left': '1.5in'
'header':
'height': '45mm'
'contents': '<div style="text-align: center;">Author: <NAME></div>'
'footer':
'height': '28mm'
'contents': '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>'
'type': 'pdf'
'quality': '75'
'phantomPath': './node_modules/phantomjs/bin/phantomjs'
'phantomArgs': []
'script': '/url'
'timeout': 30000
'httpHeaders': 'Authorization': 'Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B'
server.listen 8080
app.get '/', (req, res)->
res.sendfile __dirname + '/web/'+'/index.html'
app.get /(?:js|css|showdown)/, (req,res)->
res.sendfile __dirname + '/web/'+ req.path
app.get /data/, (req,res)->
res.sendfile(path.resolve(__dirname + '/../' + req.path))
runscript = (cmd,socket)->
run = cp.exec cmd,{}
socket.emit "log","CMD start #{cmd}"
run.stdout.on 'data', (data)->
socket.emit "log",data
run.stderr.on 'data', (data)->
socket.emit 'err',data
run.on 'exit',()->
socket.emit "log","CMD #{cmd} finish"
fs = require 'fs'
sendfile = (file)->
filepath = __dirname + '/../'+ file
str = fs.readFileSync(filepath, 'utf-8');
return str
io.on 'connection', (socket) ->
socket.emit 'log','successfully connect'
socket.on 'runscript',(data)->
runscript data,socket
socket.on 'needfile',(data)->
resp =
name : data['filename']
type : data['type']
container:data["container"]
content :sendfile data['filename']
socket.emit "file",resp
socket.on 'serverlog',(data)->
console.log data
socket.on 'convertpdf',(html)->
console.log html
console.log 'convertpdf called'
filename = __dirname + '/report.pdf'
pdf.create(html, config).toFile(filename, (err, res)->
console.log "filename: " + filename
if err
return console.log(err)
console.log(res)
socket.emit 'convertpdffinished', filename
)
| true | app = require('express')()
server = require('http').Server(app)
io = require('socket.io')(server)
cp = require('child_process')
path = require('path')
phantomjs = require('phantomjs')
pdf = require('node-html-pdf')
fs = require('fs')
config =
'directory': '/tmp'
'height': '10.5in'
'width': '8in'
'format': 'Letter'
'orientation': 'portrait'
'border': '0'
'border':
'top': '2in'
'right': '1in'
'bottom': '2in'
'left': '1.5in'
'header':
'height': '45mm'
'contents': '<div style="text-align: center;">Author: PI:NAME:<NAME>END_PI</div>'
'footer':
'height': '28mm'
'contents': '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>'
'type': 'pdf'
'quality': '75'
'phantomPath': './node_modules/phantomjs/bin/phantomjs'
'phantomArgs': []
'script': '/url'
'timeout': 30000
'httpHeaders': 'Authorization': 'Bearer ACEFAD8C-4B4D-4042-AB30-6C735F5BAC8B'
server.listen 8080
app.get '/', (req, res)->
res.sendfile __dirname + '/web/'+'/index.html'
app.get /(?:js|css|showdown)/, (req,res)->
res.sendfile __dirname + '/web/'+ req.path
app.get /data/, (req,res)->
res.sendfile(path.resolve(__dirname + '/../' + req.path))
runscript = (cmd,socket)->
run = cp.exec cmd,{}
socket.emit "log","CMD start #{cmd}"
run.stdout.on 'data', (data)->
socket.emit "log",data
run.stderr.on 'data', (data)->
socket.emit 'err',data
run.on 'exit',()->
socket.emit "log","CMD #{cmd} finish"
fs = require 'fs'
sendfile = (file)->
filepath = __dirname + '/../'+ file
str = fs.readFileSync(filepath, 'utf-8');
return str
io.on 'connection', (socket) ->
socket.emit 'log','successfully connect'
socket.on 'runscript',(data)->
runscript data,socket
socket.on 'needfile',(data)->
resp =
name : data['filename']
type : data['type']
container:data["container"]
content :sendfile data['filename']
socket.emit "file",resp
socket.on 'serverlog',(data)->
console.log data
socket.on 'convertpdf',(html)->
console.log html
console.log 'convertpdf called'
filename = __dirname + '/report.pdf'
pdf.create(html, config).toFile(filename, (err, res)->
console.log "filename: " + filename
if err
return console.log(err)
console.log(res)
socket.emit 'convertpdffinished', filename
)
|
[
{
"context": "on\n connection.register.fields.username = \"juliet\"\n alert \"100\"\n connection.register.",
"end": 6913,
"score": 0.9996525049209595,
"start": 6907,
"tag": "USERNAME",
"value": "juliet"
},
{
"context": "0\"\n connection.register.fields.pas... | app/assets/javascripts/xmpp/scripts/xmpp.js.coffee | charlieanna/xmppify | 0 |
app = angular.module("idlecampus", ["ngResource", "$strap.directives"])
@xmpp = ["$scope",($scope) ->
group_name = undefined
group_code = undefined
$scope.$watch "spin", (newValue, oldValue) ->
$scope.connected = ->
iq = undefined
# $scope.XMPP.connection.pubsub.createNode $scope.XMPP.connection.jid.split("/")[0] + "/groups", "", (data) ->
# console.log data
iq = $iq(type: "get").c("query",
xmlns: "jabber:iq:roster"
)
$scope.XMPP.connection.sendIQ iq, $scope.XMPP.on_roster
$scope.XMPP.connection.addHandler $scope.XMPP.on_roster_changed, "jabber:iq:roster", "iq", "set"
$scope.XMPP.connection.addHandler $scope.XMPP.on_message, null, "message", "chat"
$scope.XMPP.connection.addHandler $scope.XMPP.on_message, null, "message", "headline"
$scope.spin = ""
$scope.disconnected = ->
unless localStorage.getItem("sid") is ""
bootbox.alert "Session Expired...Please login again", ->
window.location = "/signin"
eraseCookie("remember_token")
localStorage.clear()
XMPP.connection = null
$scope.XMPP =
NS_DATA_FORMS: "jabber:x:data"
NS_PUBSUB: "http://jabber.org/protocol/pubsub"
NS_PUBSUB_OWNER: "http://jabber.org/protocol/pubsub#owner"
NS_PUBSUB_ERRORS: "http://jabber.org/protocol/pubsub#errors"
NS_PUBSUB_NODE_CONFIG: "http://jabber.org/protocol/pubsub#node_config"
connection: null
start_time: null
jid_to_id: (jid) ->
Strophe.getBareJidFromJid(jid).replace(/@/g, "-").replace /\./g, "-"
on_roster: (iq) ->
$(iq).find("item").each ->
contact = undefined
jid = undefined
jid_id = undefined
name = undefined
jid = $(this).attr("jid")
name = $(this).attr("name") or jid
jid_id = $scope.XMPP.jid_to_id(jid)
contact = $("<li id='" + jid_id + "'>" + "<div class='roster-contact offline'>" + "<a href=#chat><img class='ui-li-icon ui-li-thumb' alt='' src=''><div class='roster-name'>" + name + "</div><div class='roster-jid'>" + jid + "</div></a></div></li>")
$scope.XMPP.insert_contact contact
$scope.XMPP.connection.addHandler $scope.XMPP.on_presence, null, "presence"
$scope.XMPP.connection.send $pres()
pending_subscriber: null
on_presence: (presence) ->
contact = undefined
from = undefined
jid_id = undefined
li = undefined
ptype = undefined
show = undefined
ptype = $(presence).attr("type")
from = $(presence).attr("from")
jid_id = $scope.XMPP.jid_to_id(from)
if ptype is "subscribe"
$scope.XMPP.pending_subscriber = from
$("#approve-jid").text Strophe.getBareJidFromJid(from)
$.mobile.changePage "#approve_dialog",
transition: "slideup"
else if ptype isnt "error"
contact = $("li#" + jid_id + " .roster-contact").removeClass("online").removeClass("away").removeClass("offline")
if ptype is "unavailable"
contact.addClass "offline"
else
show = $(presence).find("show").text()
if show is "" or show is "chat"
contact.addClass "online"
$("li#" + jid_id + " a img").attr "src", "green.jpg"
else
contact.addClass "away"
$("li#" + jid_id + " a img").attr "src", "red.png"
li = contact.parent().parent().parent()
li.remove()
$scope.XMPP.insert_contact li
jid_id = $scope.XMPP.jid_to_id(from)
$("#chat-" + jid_id).data "jid", Strophe.getBareJidFromJid(from)
true
on_roster_changed: (iq) ->
console.log "roster changed"
$(iq).find("item").each ->
contact = undefined
jid = undefined
jid_id = undefined
name = undefined
sub = undefined
sub = $(this).attr("subscription")
jid = $(this).attr("jid")
name = $(this).attr("name") or jid
jid_id = $scope.XMPP.jid_to_id(jid)
if sub is "remove"
$("#" + jid_id).remove()
else
contact = $("<li id='" + jid_id + "'>" + "<div class=" + ($("#" + jid_id).attr("class") or "roster-contact offline") + ">" + "<a href=#chat><img class='ui-li-icon ui-li-thumb' alt='' src=''><div class='roster-name'>" + name + "</div><div class='roster-jid'>" + jid + "</div></a></div></li>")
if $("#" + jid_id).length > 0
console.log 2
$("#" + jid_id).replaceWith contact
else
console.log "1"
$scope.XMPP.insert_contact contact
true
on_message: (message) ->
body = undefined
from = undefined
mess = undefined
messagetodisplay = undefined
type = undefined
console.log message
type = $(message).attr("type")
console.log type
if type is "chat"
body = $(message).children("body").text()
from = ""
console.log body
messagetodisplay = from + " : " + body
mess = "<li style='background-color:#ECEFF5; list-style:none;border:1px solid black;margin:5px'>" + messagetodisplay + "</li>"
$("ul#posts").append $(mess)
else if type = "headline"
if $(message).find("value").text()
body = $(message).find("value").text()
from = $(message).find("items").attr("node")
$scope.data.user = from
console.log body
messagetodisplay = body
$scope.data.groupMessages.push messagetodisplay
$scope.$digest()
true
scroll_chat: (jid_id) ->
div = undefined
div = $("#chat-" + jid_id + " .chat-messages").get(0)
div.scrollTop = div.scrollHeight
presence_value: (elem) ->
if elem.hasClass("online")
return 2
else
return 1 if elem.hasClass("away")
0
insert_contact: (elem) ->
contacts = undefined
inserted = undefined
jid = undefined
pres = undefined
jid = elem.find(".roster-jid").text()
pres = $scope.XMPP.presence_value(elem.find(".roster-contact"))
contacts = $("ul#myfriends li")
if contacts.length > 0
inserted = false
contacts.each ->
cmp_jid = undefined
cmp_pres = undefined
cmp_pres = $scope.XMPP.presence_value($(this).find(".roster-contact"))
cmp_jid = $(this).find(".roster-jid").text()
if pres > cmp_pres
$(this).before elem
inserted = true
false
else if pres is cmp_pres
if jid < cmp_jid
$(this).before elem
inserted = true
false
$("ul#myfriends").append elem unless inserted
else
$("ul#myfriends").append elem
callback: (status) ->
alert connection
if status is Strophe.Status.REGISTER
alert 10
alert connection
connection.register.fields.username = "juliet"
alert "100"
connection.register.fields.password = "R0m30"
lert "100"
alert "before"
connection.register.submit()
alert "after"
else if status is Strophe.Status.REGISTERED
alert 101
console.log "registered!"
connection.authenticate()
else if status is Strophe.Status.CONNECTED
alert 102
console.log "logged in!"
else
alert "con"
alert "con" + connection
$scope.getNodeSubscriptions = (group) ->
$scope.XMPP.connection.pubsub.getNodeSubscriptions group, (data) ->
console.log "Subscribers"
console.log data
$scope.connect = (user, password) ->
connection = undefined
connection = new Strophe.Connection("http://idlecampus.com/http-bind")
connection.connect user, password, (status) ->
$scope.XMPP.connection = connection
console.log status
connection.xmlInput = (body) ->
console.log body
connection.xmlOutput = (body) ->
console.log "XMPP OUTPUT"
console.log body
localStorage.setItem "rid", $(body).attr("rid")
localStorage.setItem "sid", $(body).attr("sid")
$scope.checkIfGroupsToCreate = ->
if (typeof gon isnt "undefined" and gon isnt null) and (gon.group?)
grouo_name = gon.group.group_name
group_code = gon.group.grup_code
$scope.XMPP.connection.pubsub.publish $scope.XMPP.connection.jid.split("/")[0] + "/groups", group_code, (data) ->
$scope.signout = ->
$scope.XMPP.connection.disconnect()
localStorage.clear()
$scope.attach = ->
conn = new Strophe.Connection(gon.global.xmpp_url)
conn.xmlInput = (body) ->
console.log body if gon.global.debug
conn.xmlOutput = (body) ->
console.log body if gon.global.debug
localStorage.setItem "rid", $(body).attr("rid")
localStorage.setItem "sid", $(body).attr("sid")
sid = localStorage.getItem("sid")
rid = localStorage.getItem("rid")
jid = localStorage.getItem("jid")
if typeof gon.attacher isnt "undefined" and gon.attacher isnt null
sid = gon.attacher.id
rid = gon.attacher.rid
jid = gon.attacher.jid
group = gon.attacher.group
localStorage.setItem "jid", jid
if jid and sid and rid
conn.attach jid, sid, rid, (status) ->
console.log status if gon.global.env != "test"
if status is Strophe.Status.CONNECTED or status is Strophe.Status.ATTACHED
$scope.XMPP.connection = conn
$scope.XMPP.connection.jid = jid
$scope.connected()
$scope.XMPP.connection.pubsub.subscribe group, "", ((data) ->
), ((data) ->
), ((data) ->
), true if group
else
$scope.disconnected() if status is Strophe.Status.DISCONNECTED]
| 44265 |
app = angular.module("idlecampus", ["ngResource", "$strap.directives"])
@xmpp = ["$scope",($scope) ->
group_name = undefined
group_code = undefined
$scope.$watch "spin", (newValue, oldValue) ->
$scope.connected = ->
iq = undefined
# $scope.XMPP.connection.pubsub.createNode $scope.XMPP.connection.jid.split("/")[0] + "/groups", "", (data) ->
# console.log data
iq = $iq(type: "get").c("query",
xmlns: "jabber:iq:roster"
)
$scope.XMPP.connection.sendIQ iq, $scope.XMPP.on_roster
$scope.XMPP.connection.addHandler $scope.XMPP.on_roster_changed, "jabber:iq:roster", "iq", "set"
$scope.XMPP.connection.addHandler $scope.XMPP.on_message, null, "message", "chat"
$scope.XMPP.connection.addHandler $scope.XMPP.on_message, null, "message", "headline"
$scope.spin = ""
$scope.disconnected = ->
unless localStorage.getItem("sid") is ""
bootbox.alert "Session Expired...Please login again", ->
window.location = "/signin"
eraseCookie("remember_token")
localStorage.clear()
XMPP.connection = null
$scope.XMPP =
NS_DATA_FORMS: "jabber:x:data"
NS_PUBSUB: "http://jabber.org/protocol/pubsub"
NS_PUBSUB_OWNER: "http://jabber.org/protocol/pubsub#owner"
NS_PUBSUB_ERRORS: "http://jabber.org/protocol/pubsub#errors"
NS_PUBSUB_NODE_CONFIG: "http://jabber.org/protocol/pubsub#node_config"
connection: null
start_time: null
jid_to_id: (jid) ->
Strophe.getBareJidFromJid(jid).replace(/@/g, "-").replace /\./g, "-"
on_roster: (iq) ->
$(iq).find("item").each ->
contact = undefined
jid = undefined
jid_id = undefined
name = undefined
jid = $(this).attr("jid")
name = $(this).attr("name") or jid
jid_id = $scope.XMPP.jid_to_id(jid)
contact = $("<li id='" + jid_id + "'>" + "<div class='roster-contact offline'>" + "<a href=#chat><img class='ui-li-icon ui-li-thumb' alt='' src=''><div class='roster-name'>" + name + "</div><div class='roster-jid'>" + jid + "</div></a></div></li>")
$scope.XMPP.insert_contact contact
$scope.XMPP.connection.addHandler $scope.XMPP.on_presence, null, "presence"
$scope.XMPP.connection.send $pres()
pending_subscriber: null
on_presence: (presence) ->
contact = undefined
from = undefined
jid_id = undefined
li = undefined
ptype = undefined
show = undefined
ptype = $(presence).attr("type")
from = $(presence).attr("from")
jid_id = $scope.XMPP.jid_to_id(from)
if ptype is "subscribe"
$scope.XMPP.pending_subscriber = from
$("#approve-jid").text Strophe.getBareJidFromJid(from)
$.mobile.changePage "#approve_dialog",
transition: "slideup"
else if ptype isnt "error"
contact = $("li#" + jid_id + " .roster-contact").removeClass("online").removeClass("away").removeClass("offline")
if ptype is "unavailable"
contact.addClass "offline"
else
show = $(presence).find("show").text()
if show is "" or show is "chat"
contact.addClass "online"
$("li#" + jid_id + " a img").attr "src", "green.jpg"
else
contact.addClass "away"
$("li#" + jid_id + " a img").attr "src", "red.png"
li = contact.parent().parent().parent()
li.remove()
$scope.XMPP.insert_contact li
jid_id = $scope.XMPP.jid_to_id(from)
$("#chat-" + jid_id).data "jid", Strophe.getBareJidFromJid(from)
true
on_roster_changed: (iq) ->
console.log "roster changed"
$(iq).find("item").each ->
contact = undefined
jid = undefined
jid_id = undefined
name = undefined
sub = undefined
sub = $(this).attr("subscription")
jid = $(this).attr("jid")
name = $(this).attr("name") or jid
jid_id = $scope.XMPP.jid_to_id(jid)
if sub is "remove"
$("#" + jid_id).remove()
else
contact = $("<li id='" + jid_id + "'>" + "<div class=" + ($("#" + jid_id).attr("class") or "roster-contact offline") + ">" + "<a href=#chat><img class='ui-li-icon ui-li-thumb' alt='' src=''><div class='roster-name'>" + name + "</div><div class='roster-jid'>" + jid + "</div></a></div></li>")
if $("#" + jid_id).length > 0
console.log 2
$("#" + jid_id).replaceWith contact
else
console.log "1"
$scope.XMPP.insert_contact contact
true
on_message: (message) ->
body = undefined
from = undefined
mess = undefined
messagetodisplay = undefined
type = undefined
console.log message
type = $(message).attr("type")
console.log type
if type is "chat"
body = $(message).children("body").text()
from = ""
console.log body
messagetodisplay = from + " : " + body
mess = "<li style='background-color:#ECEFF5; list-style:none;border:1px solid black;margin:5px'>" + messagetodisplay + "</li>"
$("ul#posts").append $(mess)
else if type = "headline"
if $(message).find("value").text()
body = $(message).find("value").text()
from = $(message).find("items").attr("node")
$scope.data.user = from
console.log body
messagetodisplay = body
$scope.data.groupMessages.push messagetodisplay
$scope.$digest()
true
scroll_chat: (jid_id) ->
div = undefined
div = $("#chat-" + jid_id + " .chat-messages").get(0)
div.scrollTop = div.scrollHeight
presence_value: (elem) ->
if elem.hasClass("online")
return 2
else
return 1 if elem.hasClass("away")
0
insert_contact: (elem) ->
contacts = undefined
inserted = undefined
jid = undefined
pres = undefined
jid = elem.find(".roster-jid").text()
pres = $scope.XMPP.presence_value(elem.find(".roster-contact"))
contacts = $("ul#myfriends li")
if contacts.length > 0
inserted = false
contacts.each ->
cmp_jid = undefined
cmp_pres = undefined
cmp_pres = $scope.XMPP.presence_value($(this).find(".roster-contact"))
cmp_jid = $(this).find(".roster-jid").text()
if pres > cmp_pres
$(this).before elem
inserted = true
false
else if pres is cmp_pres
if jid < cmp_jid
$(this).before elem
inserted = true
false
$("ul#myfriends").append elem unless inserted
else
$("ul#myfriends").append elem
callback: (status) ->
alert connection
if status is Strophe.Status.REGISTER
alert 10
alert connection
connection.register.fields.username = "juliet"
alert "100"
connection.register.fields.password = "<PASSWORD>"
lert "100"
alert "before"
connection.register.submit()
alert "after"
else if status is Strophe.Status.REGISTERED
alert 101
console.log "registered!"
connection.authenticate()
else if status is Strophe.Status.CONNECTED
alert 102
console.log "logged in!"
else
alert "con"
alert "con" + connection
$scope.getNodeSubscriptions = (group) ->
$scope.XMPP.connection.pubsub.getNodeSubscriptions group, (data) ->
console.log "Subscribers"
console.log data
$scope.connect = (user, password) ->
connection = undefined
connection = new Strophe.Connection("http://idlecampus.com/http-bind")
connection.connect user, password, (status) ->
$scope.XMPP.connection = connection
console.log status
connection.xmlInput = (body) ->
console.log body
connection.xmlOutput = (body) ->
console.log "XMPP OUTPUT"
console.log body
localStorage.setItem "rid", $(body).attr("rid")
localStorage.setItem "sid", $(body).attr("sid")
$scope.checkIfGroupsToCreate = ->
if (typeof gon isnt "undefined" and gon isnt null) and (gon.group?)
grouo_name = gon.group.group_name
group_code = gon.group.grup_code
$scope.XMPP.connection.pubsub.publish $scope.XMPP.connection.jid.split("/")[0] + "/groups", group_code, (data) ->
$scope.signout = ->
$scope.XMPP.connection.disconnect()
localStorage.clear()
$scope.attach = ->
conn = new Strophe.Connection(gon.global.xmpp_url)
conn.xmlInput = (body) ->
console.log body if gon.global.debug
conn.xmlOutput = (body) ->
console.log body if gon.global.debug
localStorage.setItem "rid", $(body).attr("rid")
localStorage.setItem "sid", $(body).attr("sid")
sid = localStorage.getItem("sid")
rid = localStorage.getItem("rid")
jid = localStorage.getItem("jid")
if typeof gon.attacher isnt "undefined" and gon.attacher isnt null
sid = gon.attacher.id
rid = gon.attacher.rid
jid = gon.attacher.jid
group = gon.attacher.group
localStorage.setItem "jid", jid
if jid and sid and rid
conn.attach jid, sid, rid, (status) ->
console.log status if gon.global.env != "test"
if status is Strophe.Status.CONNECTED or status is Strophe.Status.ATTACHED
$scope.XMPP.connection = conn
$scope.XMPP.connection.jid = jid
$scope.connected()
$scope.XMPP.connection.pubsub.subscribe group, "", ((data) ->
), ((data) ->
), ((data) ->
), true if group
else
$scope.disconnected() if status is Strophe.Status.DISCONNECTED]
| true |
app = angular.module("idlecampus", ["ngResource", "$strap.directives"])
@xmpp = ["$scope",($scope) ->
group_name = undefined
group_code = undefined
$scope.$watch "spin", (newValue, oldValue) ->
$scope.connected = ->
iq = undefined
# $scope.XMPP.connection.pubsub.createNode $scope.XMPP.connection.jid.split("/")[0] + "/groups", "", (data) ->
# console.log data
iq = $iq(type: "get").c("query",
xmlns: "jabber:iq:roster"
)
$scope.XMPP.connection.sendIQ iq, $scope.XMPP.on_roster
$scope.XMPP.connection.addHandler $scope.XMPP.on_roster_changed, "jabber:iq:roster", "iq", "set"
$scope.XMPP.connection.addHandler $scope.XMPP.on_message, null, "message", "chat"
$scope.XMPP.connection.addHandler $scope.XMPP.on_message, null, "message", "headline"
$scope.spin = ""
$scope.disconnected = ->
unless localStorage.getItem("sid") is ""
bootbox.alert "Session Expired...Please login again", ->
window.location = "/signin"
eraseCookie("remember_token")
localStorage.clear()
XMPP.connection = null
$scope.XMPP =
NS_DATA_FORMS: "jabber:x:data"
NS_PUBSUB: "http://jabber.org/protocol/pubsub"
NS_PUBSUB_OWNER: "http://jabber.org/protocol/pubsub#owner"
NS_PUBSUB_ERRORS: "http://jabber.org/protocol/pubsub#errors"
NS_PUBSUB_NODE_CONFIG: "http://jabber.org/protocol/pubsub#node_config"
connection: null
start_time: null
jid_to_id: (jid) ->
Strophe.getBareJidFromJid(jid).replace(/@/g, "-").replace /\./g, "-"
on_roster: (iq) ->
$(iq).find("item").each ->
contact = undefined
jid = undefined
jid_id = undefined
name = undefined
jid = $(this).attr("jid")
name = $(this).attr("name") or jid
jid_id = $scope.XMPP.jid_to_id(jid)
contact = $("<li id='" + jid_id + "'>" + "<div class='roster-contact offline'>" + "<a href=#chat><img class='ui-li-icon ui-li-thumb' alt='' src=''><div class='roster-name'>" + name + "</div><div class='roster-jid'>" + jid + "</div></a></div></li>")
$scope.XMPP.insert_contact contact
$scope.XMPP.connection.addHandler $scope.XMPP.on_presence, null, "presence"
$scope.XMPP.connection.send $pres()
pending_subscriber: null
on_presence: (presence) ->
contact = undefined
from = undefined
jid_id = undefined
li = undefined
ptype = undefined
show = undefined
ptype = $(presence).attr("type")
from = $(presence).attr("from")
jid_id = $scope.XMPP.jid_to_id(from)
if ptype is "subscribe"
$scope.XMPP.pending_subscriber = from
$("#approve-jid").text Strophe.getBareJidFromJid(from)
$.mobile.changePage "#approve_dialog",
transition: "slideup"
else if ptype isnt "error"
contact = $("li#" + jid_id + " .roster-contact").removeClass("online").removeClass("away").removeClass("offline")
if ptype is "unavailable"
contact.addClass "offline"
else
show = $(presence).find("show").text()
if show is "" or show is "chat"
contact.addClass "online"
$("li#" + jid_id + " a img").attr "src", "green.jpg"
else
contact.addClass "away"
$("li#" + jid_id + " a img").attr "src", "red.png"
li = contact.parent().parent().parent()
li.remove()
$scope.XMPP.insert_contact li
jid_id = $scope.XMPP.jid_to_id(from)
$("#chat-" + jid_id).data "jid", Strophe.getBareJidFromJid(from)
true
on_roster_changed: (iq) ->
console.log "roster changed"
$(iq).find("item").each ->
contact = undefined
jid = undefined
jid_id = undefined
name = undefined
sub = undefined
sub = $(this).attr("subscription")
jid = $(this).attr("jid")
name = $(this).attr("name") or jid
jid_id = $scope.XMPP.jid_to_id(jid)
if sub is "remove"
$("#" + jid_id).remove()
else
contact = $("<li id='" + jid_id + "'>" + "<div class=" + ($("#" + jid_id).attr("class") or "roster-contact offline") + ">" + "<a href=#chat><img class='ui-li-icon ui-li-thumb' alt='' src=''><div class='roster-name'>" + name + "</div><div class='roster-jid'>" + jid + "</div></a></div></li>")
if $("#" + jid_id).length > 0
console.log 2
$("#" + jid_id).replaceWith contact
else
console.log "1"
$scope.XMPP.insert_contact contact
true
on_message: (message) ->
body = undefined
from = undefined
mess = undefined
messagetodisplay = undefined
type = undefined
console.log message
type = $(message).attr("type")
console.log type
if type is "chat"
body = $(message).children("body").text()
from = ""
console.log body
messagetodisplay = from + " : " + body
mess = "<li style='background-color:#ECEFF5; list-style:none;border:1px solid black;margin:5px'>" + messagetodisplay + "</li>"
$("ul#posts").append $(mess)
else if type = "headline"
if $(message).find("value").text()
body = $(message).find("value").text()
from = $(message).find("items").attr("node")
$scope.data.user = from
console.log body
messagetodisplay = body
$scope.data.groupMessages.push messagetodisplay
$scope.$digest()
true
scroll_chat: (jid_id) ->
div = undefined
div = $("#chat-" + jid_id + " .chat-messages").get(0)
div.scrollTop = div.scrollHeight
presence_value: (elem) ->
if elem.hasClass("online")
return 2
else
return 1 if elem.hasClass("away")
0
insert_contact: (elem) ->
contacts = undefined
inserted = undefined
jid = undefined
pres = undefined
jid = elem.find(".roster-jid").text()
pres = $scope.XMPP.presence_value(elem.find(".roster-contact"))
contacts = $("ul#myfriends li")
if contacts.length > 0
inserted = false
contacts.each ->
cmp_jid = undefined
cmp_pres = undefined
cmp_pres = $scope.XMPP.presence_value($(this).find(".roster-contact"))
cmp_jid = $(this).find(".roster-jid").text()
if pres > cmp_pres
$(this).before elem
inserted = true
false
else if pres is cmp_pres
if jid < cmp_jid
$(this).before elem
inserted = true
false
$("ul#myfriends").append elem unless inserted
else
$("ul#myfriends").append elem
callback: (status) ->
alert connection
if status is Strophe.Status.REGISTER
alert 10
alert connection
connection.register.fields.username = "juliet"
alert "100"
connection.register.fields.password = "PI:PASSWORD:<PASSWORD>END_PI"
lert "100"
alert "before"
connection.register.submit()
alert "after"
else if status is Strophe.Status.REGISTERED
alert 101
console.log "registered!"
connection.authenticate()
else if status is Strophe.Status.CONNECTED
alert 102
console.log "logged in!"
else
alert "con"
alert "con" + connection
$scope.getNodeSubscriptions = (group) ->
$scope.XMPP.connection.pubsub.getNodeSubscriptions group, (data) ->
console.log "Subscribers"
console.log data
$scope.connect = (user, password) ->
connection = undefined
connection = new Strophe.Connection("http://idlecampus.com/http-bind")
connection.connect user, password, (status) ->
$scope.XMPP.connection = connection
console.log status
connection.xmlInput = (body) ->
console.log body
connection.xmlOutput = (body) ->
console.log "XMPP OUTPUT"
console.log body
localStorage.setItem "rid", $(body).attr("rid")
localStorage.setItem "sid", $(body).attr("sid")
$scope.checkIfGroupsToCreate = ->
if (typeof gon isnt "undefined" and gon isnt null) and (gon.group?)
grouo_name = gon.group.group_name
group_code = gon.group.grup_code
$scope.XMPP.connection.pubsub.publish $scope.XMPP.connection.jid.split("/")[0] + "/groups", group_code, (data) ->
$scope.signout = ->
$scope.XMPP.connection.disconnect()
localStorage.clear()
$scope.attach = ->
conn = new Strophe.Connection(gon.global.xmpp_url)
conn.xmlInput = (body) ->
console.log body if gon.global.debug
conn.xmlOutput = (body) ->
console.log body if gon.global.debug
localStorage.setItem "rid", $(body).attr("rid")
localStorage.setItem "sid", $(body).attr("sid")
sid = localStorage.getItem("sid")
rid = localStorage.getItem("rid")
jid = localStorage.getItem("jid")
if typeof gon.attacher isnt "undefined" and gon.attacher isnt null
sid = gon.attacher.id
rid = gon.attacher.rid
jid = gon.attacher.jid
group = gon.attacher.group
localStorage.setItem "jid", jid
if jid and sid and rid
conn.attach jid, sid, rid, (status) ->
console.log status if gon.global.env != "test"
if status is Strophe.Status.CONNECTED or status is Strophe.Status.ATTACHED
$scope.XMPP.connection = conn
$scope.XMPP.connection.jid = jid
$scope.connected()
$scope.XMPP.connection.pubsub.subscribe group, "", ((data) ->
), ((data) ->
), ((data) ->
), true if group
else
$scope.disconnected() if status is Strophe.Status.DISCONNECTED]
|
[
{
"context": "f user.remember() then user.name()\n password: @options.password #if settings.get('api_remember') then settings.ge",
"end": 542,
"score": 0.7395207285881042,
"start": 526,
"tag": "PASSWORD",
"value": "options.password"
}
] | Web.App/app/modules/common/views/signin-view.coffee | vip32/eventfeedback | 0 | application = require 'application'
vent = require 'vent'
settings = require 'settings'
user = require 'user'
module.exports = class SigninView extends Backbone.Marionette.ItemView
id: 'signin-view'
template: require './templates/signin'
events:
'click .js-signin': 'onSignin'
initialize: (options) ->
vent.trigger 'navigation:back:off'
serializeData: ->
resources: @resources?.toJSON()
username: if @options.username then @options.username else if user.remember() then user.name()
password: @options.password #if settings.get('api_remember') then settings.get('api_password')
remember: user.remember()
onSignin: (e) ->
e.preventDefault()
data = Backbone.Syphon.serialize(@)
data.returnroute = @options.returnroute
vent.trigger 'view:signin:do', data
onShow: ->
scrollTo(0,0)
# $('#make-switch').bootstrapSwitch('size', 'small')
onClose: ->
log 'signin view close'
| 70939 | application = require 'application'
vent = require 'vent'
settings = require 'settings'
user = require 'user'
module.exports = class SigninView extends Backbone.Marionette.ItemView
id: 'signin-view'
template: require './templates/signin'
events:
'click .js-signin': 'onSignin'
initialize: (options) ->
vent.trigger 'navigation:back:off'
serializeData: ->
resources: @resources?.toJSON()
username: if @options.username then @options.username else if user.remember() then user.name()
password: @<PASSWORD> #if settings.get('api_remember') then settings.get('api_password')
remember: user.remember()
onSignin: (e) ->
e.preventDefault()
data = Backbone.Syphon.serialize(@)
data.returnroute = @options.returnroute
vent.trigger 'view:signin:do', data
onShow: ->
scrollTo(0,0)
# $('#make-switch').bootstrapSwitch('size', 'small')
onClose: ->
log 'signin view close'
| true | application = require 'application'
vent = require 'vent'
settings = require 'settings'
user = require 'user'
module.exports = class SigninView extends Backbone.Marionette.ItemView
id: 'signin-view'
template: require './templates/signin'
events:
'click .js-signin': 'onSignin'
initialize: (options) ->
vent.trigger 'navigation:back:off'
serializeData: ->
resources: @resources?.toJSON()
username: if @options.username then @options.username else if user.remember() then user.name()
password: @PI:PASSWORD:<PASSWORD>END_PI #if settings.get('api_remember') then settings.get('api_password')
remember: user.remember()
onSignin: (e) ->
e.preventDefault()
data = Backbone.Syphon.serialize(@)
data.returnroute = @options.returnroute
vent.trigger 'view:signin:do', data
onShow: ->
scrollTo(0,0)
# $('#make-switch').bootstrapSwitch('size', 'small')
onClose: ->
log 'signin view close'
|
[
{
"context": "info.pl/mapserver/swinoujscie-vista\"\n name: \"obreby\"\n },\n {\n url: \"http://hubert.systherm-",
"end": 307,
"score": 0.7561743855476379,
"start": 301,
"tag": "NAME",
"value": "obreby"
},
{
"context": "info.pl/mapserver/swinoujscie-vista\"\n nam... | tests/dummy/app/controllers/application.coffee | huberts/ember-ol-map | 0 | `import Ember from 'ember'`
`import OpenlayersControlsScale from 'ember-ol-map/models/openlayers/controls/scale'`
Application = Ember.Controller.extend
extent: [174755, 664665, 208882, 685765]
layers: [
{
url: "http://hubert.systherm-info.pl/mapserver/swinoujscie-vista"
name: "obreby"
},
{
url: "http://hubert.systherm-info.pl/mapserver/swinoujscie-vista"
name: "dzialki"
}
]
scales: [
{scale: 250000, resolution: 88.19462083368612}
{scale: 100000, resolution: 35.277848333474445}
{scale: 50000, resolution: 17.638924166737223}
{scale: 25000, resolution: 8.819462083368611}
{scale: 10000, resolution: 3.5277848333474453}
{scale: 5000, resolution: 1.7638924166737227}
{scale: 2500, resolution: 0.8819462083368613}
{scale: 1000, resolution: 0.3527784833347445}
{scale: 500, resolution: 0.17638924166737224}
{scale: 250, resolution: 0.08819462083368612}
{scale: 100, resolution: 0.03527784833347444}
{scale: 50, resolution: 0.01763892416673722}
{scale: 25, resolution: 0.00881946208336861}
{scale: 10, resolution: 0.0035277848333474444}
]
controls: new ol.Collection [
new OpenlayersControlsScale()
new ol.control.MousePosition
className: "ol-map-coordinates-local"
projection: ol.proj.get("EPSG:2173")
coordinateFormat: (coordinates) -> "X: #{coordinates[1].toFixed(2)} Y: #{coordinates[0].toFixed(2)}"
undefinedHTML: "Współrzędne (X / Y)"
new ol.control.MousePosition
className: "ol-map-coordinates-lonlat"
projection: ol.proj.get("EPSG:4326")
coordinateFormat: ol.coordinate.toStringHDMS
undefinedHTML: "Współrzędne (szer./dł.)"
]
`export default Application`
| 179561 | `import Ember from 'ember'`
`import OpenlayersControlsScale from 'ember-ol-map/models/openlayers/controls/scale'`
Application = Ember.Controller.extend
extent: [174755, 664665, 208882, 685765]
layers: [
{
url: "http://hubert.systherm-info.pl/mapserver/swinoujscie-vista"
name: "<NAME>"
},
{
url: "http://hubert.systherm-info.pl/mapserver/swinoujscie-vista"
name: "<NAME>"
}
]
scales: [
{scale: 250000, resolution: 88.19462083368612}
{scale: 100000, resolution: 35.277848333474445}
{scale: 50000, resolution: 17.638924166737223}
{scale: 25000, resolution: 8.819462083368611}
{scale: 10000, resolution: 3.5277848333474453}
{scale: 5000, resolution: 1.7638924166737227}
{scale: 2500, resolution: 0.8819462083368613}
{scale: 1000, resolution: 0.3527784833347445}
{scale: 500, resolution: 0.17638924166737224}
{scale: 250, resolution: 0.08819462083368612}
{scale: 100, resolution: 0.03527784833347444}
{scale: 50, resolution: 0.01763892416673722}
{scale: 25, resolution: 0.00881946208336861}
{scale: 10, resolution: 0.0035277848333474444}
]
controls: new ol.Collection [
new OpenlayersControlsScale()
new ol.control.MousePosition
className: "ol-map-coordinates-local"
projection: ol.proj.get("EPSG:2173")
coordinateFormat: (coordinates) -> "X: #{coordinates[1].toFixed(2)} Y: #{coordinates[0].toFixed(2)}"
undefinedHTML: "Współrzędne (X / Y)"
new ol.control.MousePosition
className: "ol-map-coordinates-lonlat"
projection: ol.proj.get("EPSG:4326")
coordinateFormat: ol.coordinate.toStringHDMS
undefinedHTML: "Współrzędne (szer./dł.)"
]
`export default Application`
| true | `import Ember from 'ember'`
`import OpenlayersControlsScale from 'ember-ol-map/models/openlayers/controls/scale'`
Application = Ember.Controller.extend
extent: [174755, 664665, 208882, 685765]
layers: [
{
url: "http://hubert.systherm-info.pl/mapserver/swinoujscie-vista"
name: "PI:NAME:<NAME>END_PI"
},
{
url: "http://hubert.systherm-info.pl/mapserver/swinoujscie-vista"
name: "PI:NAME:<NAME>END_PI"
}
]
scales: [
{scale: 250000, resolution: 88.19462083368612}
{scale: 100000, resolution: 35.277848333474445}
{scale: 50000, resolution: 17.638924166737223}
{scale: 25000, resolution: 8.819462083368611}
{scale: 10000, resolution: 3.5277848333474453}
{scale: 5000, resolution: 1.7638924166737227}
{scale: 2500, resolution: 0.8819462083368613}
{scale: 1000, resolution: 0.3527784833347445}
{scale: 500, resolution: 0.17638924166737224}
{scale: 250, resolution: 0.08819462083368612}
{scale: 100, resolution: 0.03527784833347444}
{scale: 50, resolution: 0.01763892416673722}
{scale: 25, resolution: 0.00881946208336861}
{scale: 10, resolution: 0.0035277848333474444}
]
controls: new ol.Collection [
new OpenlayersControlsScale()
new ol.control.MousePosition
className: "ol-map-coordinates-local"
projection: ol.proj.get("EPSG:2173")
coordinateFormat: (coordinates) -> "X: #{coordinates[1].toFixed(2)} Y: #{coordinates[0].toFixed(2)}"
undefinedHTML: "Współrzędne (X / Y)"
new ol.control.MousePosition
className: "ol-map-coordinates-lonlat"
projection: ol.proj.get("EPSG:4326")
coordinateFormat: ol.coordinate.toStringHDMS
undefinedHTML: "Współrzędne (szer./dł.)"
]
`export default Application`
|
[
{
"context": "ss = _User_\n @sampleData =\n id: 24\n name: 'test user'\n email: 'test.user@guc.edu.eg'\n verif",
"end": 186,
"score": 0.5065292119979858,
"start": 182,
"tag": "NAME",
"value": "test"
},
{
"context": " _User_\n @sampleData =\n id: 24\n name: 'test u... | spec/models/user.coffee | ah450/guclink-auth-angular-modules | 0 |
describe 'User Model', ->
beforeEach module 'guclinkAuthModules'
@userClass = null
beforeEach inject (_User_) =>
@userClass = _User_
@sampleData =
id: 24
name: 'test user'
email: 'test.user@guc.edu.eg'
verified: true
student: false
super_user: false
full_name: 'Test User'
created_at: '2016-04-08T20:06:45.391Z'
updated_at: '2016-04-08T20:06:45.391Z'
beforeEach =>
@sampleUser = new @userClass @sampleData
it 'is verified', =>
expect(@sampleUser.verified).to.be.true
it 'is not a student', =>
expect(@sampleUser.student).to.be.false
it 'is a teacher', =>
expect(@sampleUser.teacher).to.be.true
it 'is not an admin', =>
expect(@sampleUser.admin).to.be.false
| 52457 |
describe 'User Model', ->
beforeEach module 'guclinkAuthModules'
@userClass = null
beforeEach inject (_User_) =>
@userClass = _User_
@sampleData =
id: 24
name: '<NAME> user'
email: '<EMAIL>'
verified: true
student: false
super_user: false
full_name: '<NAME>'
created_at: '2016-04-08T20:06:45.391Z'
updated_at: '2016-04-08T20:06:45.391Z'
beforeEach =>
@sampleUser = new @userClass @sampleData
it 'is verified', =>
expect(@sampleUser.verified).to.be.true
it 'is not a student', =>
expect(@sampleUser.student).to.be.false
it 'is a teacher', =>
expect(@sampleUser.teacher).to.be.true
it 'is not an admin', =>
expect(@sampleUser.admin).to.be.false
| true |
describe 'User Model', ->
beforeEach module 'guclinkAuthModules'
@userClass = null
beforeEach inject (_User_) =>
@userClass = _User_
@sampleData =
id: 24
name: 'PI:NAME:<NAME>END_PI user'
email: 'PI:EMAIL:<EMAIL>END_PI'
verified: true
student: false
super_user: false
full_name: 'PI:NAME:<NAME>END_PI'
created_at: '2016-04-08T20:06:45.391Z'
updated_at: '2016-04-08T20:06:45.391Z'
beforeEach =>
@sampleUser = new @userClass @sampleData
it 'is verified', =>
expect(@sampleUser.verified).to.be.true
it 'is not a student', =>
expect(@sampleUser.student).to.be.false
it 'is a teacher', =>
expect(@sampleUser.teacher).to.be.true
it 'is not an admin', =>
expect(@sampleUser.admin).to.be.false
|
[
{
"context": "#\r\n# ngQuickDate\r\n# by Adam Albrecht\r\n# http://adamalbrecht.com\r\n#\r\n# Source Code: htt",
"end": 36,
"score": 0.9998992681503296,
"start": 23,
"tag": "NAME",
"value": "Adam Albrecht"
},
{
"context": "lbrecht.com\r\n#\r\n# Source Code: https://github.com/adamalb... | src/ng-quick-date.coffee | moku-io/ngDatePicker | 0 | #
# ngQuickDate
# by Adam Albrecht
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngQuickDate
#
# Compatible with Angular 1.2.0+
#
app = angular.module("ngQuickDate", [])
app.provider "ngQuickDateDefaults", ->
{
options: {
dateFormat: 'M/d/yyyy'
timeFormat: 'h:mm a'
labelFormat: null
placeholder: 'Click to Set Date'
hoverText: null
buttonIconHtml: null
closeButtonHtml: '×'
nextLinkHtml: 'Next →'
prevLinkHtml: '← Prev'
clearButtonText: 'Clear'
dateLabelHtml: 'Date'
timeLabelHtml: 'Time'
disableTimepicker: false
disableDatepicker: false
disableClearButton: false
defaultTime: null
months: ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
dayAbbreviations: ["Su", "M", "Tu", "W", "Th", "F", "Sa"]
dateFilter: null
defaultCalendarDate: null
readOnly: false
parseDateFunction: (str) ->
seconds = Date.parse(str)
# Parse date helper function
# Author: Matt Kruse <matt@mattkruse.com>
# WWW: http://www.mattkruse.com/
getDateFromFormat = (val, format) ->
_isInteger = (val) ->
digits = "1234567890"
i = 0
while i < val.length
return false if digits.indexOf(val.charAt(i)) is -1
i++
true
_getInt = (str, i, minlength, maxlength) ->
x = maxlength
while x >= minlength
token = str.substring(i, i + x)
return null if token.length < minlength
return token if _isInteger(token)
x--
null
val = val + ""
format = format + ""
i_val = 0
i_format = 0
c = ""
token = ""
token2 = ""
x = undefined
y = undefined
now = new Date()
year = now.getYear()
month = now.getMonth() + 1
date = 1
hh = now.getHours()
mm = now.getMinutes()
ss = now.getSeconds()
ampm = ""
while i_format < format.length
# Get next token from format string
c = format.charAt(i_format)
token = ""
token += format.charAt(i_format++) while (format.charAt(i_format) is c) and (i_format < format.length)
# Extract contents of value based on format token
if token is "yyyy" or token is "yy" or token is "y"
if token is "yyyy"
x = 4
y = 4
if token is "yy"
x = 2
y = 2
if token is "y"
x = 2
y = 4
year = _getInt(val, i_val, x, y)
return 0 unless year?
i_val += year.length
if year.length is 2
if year > 70
year = 1900 + (year - 0)
else
year = 2000 + (year - 0)
else if token is "MMM" or token is "NNN"
month = 0
i = 0
while i < MONTH_NAMES.length
month_name = MONTH_NAMES[i]
if val.substring(i_val, i_val + month_name.length).toLowerCase() is month_name.toLowerCase()
if token is "MMM" or (token is "NNN" and i > 11)
month = i + 1
month -= 12 if month > 12
i_val += month_name.length
break
i++
return 0 if (month < 1) or (month > 12)
else if token is "EE" or token is "E"
i = 0
while i < DAY_NAMES.length
day_name = DAY_NAMES[i]
if val.substring(i_val, i_val + day_name.length).toLowerCase() is day_name.toLowerCase()
i_val += day_name.length
break
i++
else if token is "MM" or token is "M"
month = _getInt(val, i_val, token.length, 2)
return 0 if not month? or (month < 1) or (month > 12)
i_val += month.length
else if token is "dd" or token is "d"
date = _getInt(val, i_val, token.length, 2)
return 0 if not date? or (date < 1) or (date > 31)
i_val += date.length
else if token is "hh" or token is "h"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 1) or (hh > 12)
i_val += hh.length
else if token is "HH" or token is "H"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 0) or (hh > 23)
i_val += hh.length
else if token is "KK" or token is "K"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 0) or (hh > 11)
i_val += hh.length
else if token is "kk" or token is "k"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 1) or (hh > 24)
i_val += hh.length
hh--
else if token is "mm" or token is "m"
mm = _getInt(val, i_val, token.length, 2)
return 0 if not mm? or (mm < 0) or (mm > 59)
i_val += mm.length
else if token is "ss" or token is "s"
ss = _getInt(val, i_val, token.length, 2)
return 0 if not ss? or (ss < 0) or (ss > 59)
i_val += ss.length
else if token is "a"
if val.substring(i_val, i_val + 2).toLowerCase() is "am"
ampm = "AM"
else if val.substring(i_val, i_val + 2).toLowerCase() is "pm"
ampm = "PM"
else
return 0
i_val += 2
else
unless val.substring(i_val, i_val + token.length) is token
return 0
else
i_val += token.length
# If there are any trailing characters left in the value, it doesn't match
return 0 unless i_val is val.length
# Is date valid for month?
if month is 2
# Check for leap year
if ((year % 4 is 0) and (year % 100 isnt 0)) or (year % 400 is 0) # leap year
return 0 if date > 29
else
return 0 if date > 28
return 0 if date > 30 if (month is 4) or (month is 6) or (month is 9) or (month is 11)
# Correct hours value
if hh < 12 and ampm is "PM"
hh = hh - 0 + 12
else hh -= 12 if hh > 11 and ampm is "AM"
newdate = new Date(year, month - 1, date, hh, mm, ss)
newdate.getTime()
scope = this
seconds = getDateFromFormat(str, scope.labelFormat) || Date.parse(str)
if isNaN(seconds)
return null
else
new Date(seconds)
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
}
app.directive "quickDatepicker", ['ngQuickDateDefaults', '$filter', '$sce', (ngQuickDateDefaults, $filter, $sce) ->
restrict: "E"
require: "?ngModel"
scope:
dateFilter: '=?'
onChange: "&"
required: '@'
position: '@'
replace: true
link: (scope, element, attrs, ngModelCtrl) ->
# INITIALIZE VARIABLES AND CONFIGURATION
# ================================
initialize = ->
setConfigOptions() # Setup configuration variables
scope.toggleCalendar(false) # Make sure it is closed initially
scope.weeks = [] # Nested Array of visible weeks / days in the popup
scope.inputDate = null # Date inputted into the date text input field
scope.inputTime = null # Time inputted into the time text input field
scope.invalid = true
if typeof(attrs.initValue) == 'string'
ngModelCtrl.$setViewValue(parseDateString(attrs.initValue))
if !scope.defaultTime
templateDate = new Date()
scope.datePlaceholder = $filter('date')(templateDate, scope.dateFormat);
scope.timePlaceholder = $filter('date')(templateDate, scope.timeFormat);
setCalendarDate()
refreshView()
# Copy various configuration options from the default configuration to scope
setConfigOptions = ->
for key, value of ngQuickDateDefaults
if key.match(/[Hh]tml/)
scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "")
else if !scope[key] && attrs[key]
scope[key] = attrs[key]
else if !scope[key]
scope[key] = ngQuickDateDefaults[key]
if !scope.labelFormat
scope.labelFormat = scope.dateFormat
unless scope.disableTimepicker
scope.labelFormat += " " + scope.timeFormat
if attrs.iconClass && attrs.iconClass.length
scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='#{attrs.iconClass}'></i>")
# VIEW SETUP
# ================================
# This code listens for clicks both on the entire document and the popup.
# If a click on the document is received but not on the popup, the popup
# should be closed
datepickerClicked = false
window.document.addEventListener 'click', (event) ->
if scope.calendarShown && ! datepickerClicked
scope.toggleCalendar(false)
scope.$apply()
datepickerClicked = false
angular.element(element[0])[0].addEventListener 'click', (event) ->
datepickerClicked = true
scope.isTop = if scope.position == 'top' then true else false
# SCOPE MANIPULATION Methods
# ================================
# Refresh the calendar, the input dates, and the button date
refreshView = ->
date = if ngModelCtrl.$modelValue then parseDateString(ngModelCtrl.$modelValue) else null
setupCalendarView()
setInputFieldValues(date)
scope.mainButtonStr = if date then $filter('date')(date, scope.labelFormat) else scope.placeholder
scope.invalid = ngModelCtrl.$invalid
# Set the values used in the 2 input fields
setInputFieldValues = (val) ->
if val?
scope.inputDate = $filter('date')(val, scope.dateFormat)
scope.inputTime = $filter('date')(val, scope.timeFormat)
else
scope.inputDate = null
scope.inputTime = null
# Set the date that is used by the calendar to determine which month to show
# Defaults to the current month
setCalendarDate = (val=null) ->
d = if val?
new Date(val)
else
stringToDate(scope.defaultCalendarDate) ? new Date()
if (d.toString() == "Invalid Date")
d = new Date()
d.setDate(1)
scope.calendarDate = new Date(d)
# Setup the data needed by the table that makes up the calendar in the popup
# Uses scope.calendarDate to decide which month to show
setupCalendarView = ->
offset = scope.calendarDate.getDay()
daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth())
numRows = Math.ceil((offset + daysInMonth) / 7)
weeks = []
curDate = new Date(scope.calendarDate)
curDate.setDate(curDate.getDate() + (offset * -1))
for row in [0..(numRows-1)]
weeks.push([])
for day in [0..6]
d = new Date(curDate)
if scope.defaultTime
time = scope.defaultTime.split(':')
d.setHours(time[0] || 0)
d.setMinutes(time[1] || 0)
d.setSeconds(time[2] || 0)
selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue)
today = datesAreEqual(d, new Date())
weeks[row].push({
date: d
selected: selected
disabled: if (typeof(scope.dateFilter) == 'function') then !scope.dateFilter(d) else false
other: d.getMonth() != scope.calendarDate.getMonth()
today: today
})
curDate.setDate(curDate.getDate() + 1)
scope.weeks = weeks
# PARSERS AND FORMATTERS
# =================================
# When the model is set from within the datepicker, this will be run
# before passing it to the model.
ngModelCtrl.$parsers.push((viewVal) ->
if scope.required && !viewVal?
ngModelCtrl.$setValidity('required', false)
null
else if angular.isDate(viewVal)
ngModelCtrl.$setValidity('required', true)
viewVal
else if angular.isString(viewVal)
ngModelCtrl.$setValidity('required', true)
scope.parseDateFunction(viewVal)
else
null
)
# When the model is set from outside the datepicker, this will be run
# before passing it to the datepicker
ngModelCtrl.$formatters.push((modelVal) ->
if angular.isDate(modelVal)
modelVal
else if angular.isString(modelVal)
scope.parseDateFunction(modelVal)
else
undefined
)
# HELPER METHODS
# =================================
dateToString = (date, format) ->
$filter('date')(date, format)
stringToDate = (date) ->
if typeof date == 'string'
parseDateString(date)
else
date
parseDateString = () ->
ngQuickDateDefaults.parseDateFunction.apply(scope, arguments)
datesAreEqual = (d1, d2, compareTimes=false) ->
if compareTimes
(d1 - d2) == 0
else
d1 = stringToDate(d1)
d2 = stringToDate(d2)
d1 && d2 && (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDate() == d2.getDate())
datesAreEqualToMinute = (d1, d2) ->
return false unless d1 && d2
parseInt(d1.getTime() / 60000) == parseInt(d2.getTime() / 60000)
getDaysInMonth = (year, month) ->
[31, (if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) then 29 else 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
# DATA WATCHES
# ==================================
# Called when the model is updated from outside the datepicker
ngModelCtrl.$render = ->
setCalendarDate(ngModelCtrl.$viewValue)
refreshView()
# Called when the model is updated from inside the datepicker,
# either by clicking a calendar date, setting an input, etc
ngModelCtrl.$viewChangeListeners.unshift ->
setCalendarDate(ngModelCtrl.$viewValue)
refreshView()
if scope.onChange
scope.onChange()
# When the popup is toggled open, select the date input
scope.$watch 'calendarShown', (newVal, oldVal) ->
if newVal
dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0]
dateInput.select()
# VIEW ACTIONS
# ==================================
scope.toggleCalendar = (show) ->
if isFinite(show)
scope.calendarShown = show
else if scope.readOnly
scope.calendarShown = false
else
scope.calendarShown = not scope.calendarShown
# Select a new model date. This is called in 3 situations:
# * Clicking a day on the calendar or from the `selectDateFromInput`
# * Changing the date or time inputs, which call the `selectDateFromInput` method, which calls this method.
# * The clear button is clicked
scope.selectDate = (date, closeCalendar=true) ->
changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() != ngModelCtrl.$viewValue.getTime()))
if typeof(scope.dateFilter) == 'function' && !scope.dateFilter(date)
return false
ngModelCtrl.$setViewValue(date)
tmpDate = $filter('date')(date, scope.dateFormat)
date = parseDateString('' + tmpDate + ' ' + scope.inputTime)
if closeCalendar
scope.toggleCalendar(false)
true
# This is triggered when the date or time inputs have a blur or enter event.
scope.selectDateFromInput = (closeCalendar=false) ->
try
tmpDate = parseDateString(scope.inputDate)
if !tmpDate
throw 'Invalid Date'
if !scope.disableTimepicker && scope.inputTime and scope.inputTime.length and tmpDate
tmpTime = if scope.disableTimepicker then '00:00:00' else scope.inputTime
tmpDateAndTime = parseDateString("#{scope.inputDate} #{tmpTime}")
if !tmpDateAndTime
throw 'Invalid Time'
tmpDate = tmpDateAndTime
if !scope.selectDate(tmpDate, false)
throw 'Invalid Date'
if closeCalendar
scope.toggleCalendar(false)
scope.inputDateErr = false
scope.inputTimeErr = false
catch err
if err == 'Invalid Date'
scope.inputDateErr = true
else if err == 'Invalid Time'
scope.inputTimeErr = true
# When tab is pressed from the date input and the timepicker
# is disabled, close the popup
scope.onDateInputTab = ->
if scope.disableTimepicker
scope.toggleCalendar(false)
true
# When tab is pressed from the time input, close the popup
scope.onTimeInputTab = ->
scope.toggleCalendar(false)
true
# View the next and previous months in the calendar popup
scope.nextMonth = ->
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1)))
refreshView()
scope.prevMonth = ->
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1)))
refreshView()
# Set the date model to null
scope.clear = ->
scope.selectDate(null, true)
initialize()
# TEMPLATE
# ================================================================
templateUrl: 'ngQuickDate/template.html'
]
app.directive 'ngEnter', ->
(scope, element, attr) ->
element.bind 'keydown keypress', (e) ->
if (e.which == 13)
scope.$apply(attr.ngEnter)
e.preventDefault()
app.directive 'onTab', ->
restrict: 'A',
link: (scope, element, attr) ->
element.bind 'keydown keypress', (e) ->
if (e.which == 9) && !e.shiftKey
scope.$apply(attr.onTab)
app.filter 'replaceMonthWithAbbrev', ['ngQuickDateDefaults', '$filter', (ngQuickDateDefaults, $filter) ->
(date) ->
if ngQuickDateDefaults && date && ngQuickDateDefaults.months[date.getMonth()] then ngQuickDateDefaults.months[date.getMonth()] + ' ' + date.getFullYear() else $filter('date')(date)
]
app.run ['$templateCache', ($templateCache) ->
$templateCache.put(
'ngQuickDate/template.html'
"""
<div class='quickdate'>
<a href='' ng-click='toggleCalendar()' class='quickdate-button' title='{{hoverText}}'><div ng-hide='iconClass' ng-bind-html='buttonIconHtml'></div>{{mainButtonStr}}</a>
<div class='quickdate-popup' ng-class='{open: calendarShown, top: isTop}'>
<a href='' tabindex='-1' class='quickdate-close' ng-click='toggleCalendar()'><div ng-bind-html='closeButtonHtml'></div></a>
<div class='quickdate-text-inputs'>
<div class='quickdate-input-wrapper' ng-hide='disableDatepicker'>
<label ng-bind-html='dateLabelHtml'></label>
<input class='quickdate-date-input' ng-class="{'ng-invalid': inputDateErr}" name='inputDate' type='text' ng-model='inputDate' placeholder='{{ datePlaceholder }}' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onDateInputTab()' />
</div>
<div class='quickdate-input-wrapper' ng-hide='disableTimepicker'>
<label ng-bind-html='timeLabelHtml'></label>
<input class='quickdate-time-input' ng-class="{'ng-invalid': inputTimeErr}" name='inputTime' type='text' ng-model='inputTime' placeholder='{{ timePlaceholder }}' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onTimeInputTab()'>
</div>
</div>
<div class='quickdate-calendar-header'>
<a href='' class='quickdate-prev-month quickdate-action-link' tabindex='-1' ng-click='prevMonth()'><div ng-bind-html='prevLinkHtml'></div></a>
<span class='quickdate-month'>{{calendarDate | replaceMonthWithAbbrev }}</span>
<a href='' class='quickdate-next-month quickdate-action-link' ng-click='nextMonth()' tabindex='-1' ><div ng-bind-html='nextLinkHtml'></div></a>
</div>
<table class='quickdate-calendar'>
<thead>
<tr>
<th ng-repeat='day in dayAbbreviations track by $index'>{{day}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='week in weeks'>
<td ng-click='selectDate(day.date, true, true)' ng-class='{"other-month": day.other, "disabled-date": day.disabled, "selected": day.selected, "is-today": day.today}' ng-repeat='day in week'>{{day.date | date:'d'}}</td>
</tr>
</tbody>
</table>
<div class='quickdate-popup-footer'>
<a href='' class='quickdate-clear' tabindex='-1' ng-hide='disableClearButton' ng-click='clear()'>{{ clearButtonText }}</a>
</div>
</div>
</div>
"""
)
]
| 179887 | #
# ngQuickDate
# by <NAME>
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngQuickDate
#
# Compatible with Angular 1.2.0+
#
app = angular.module("ngQuickDate", [])
app.provider "ngQuickDateDefaults", ->
{
options: {
dateFormat: 'M/d/yyyy'
timeFormat: 'h:mm a'
labelFormat: null
placeholder: 'Click to Set Date'
hoverText: null
buttonIconHtml: null
closeButtonHtml: '×'
nextLinkHtml: 'Next →'
prevLinkHtml: '← Prev'
clearButtonText: 'Clear'
dateLabelHtml: 'Date'
timeLabelHtml: 'Time'
disableTimepicker: false
disableDatepicker: false
disableClearButton: false
defaultTime: null
months: ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
dayAbbreviations: ["Su", "M", "Tu", "W", "Th", "F", "Sa"]
dateFilter: null
defaultCalendarDate: null
readOnly: false
parseDateFunction: (str) ->
seconds = Date.parse(str)
# Parse date helper function
# Author: <NAME> <<EMAIL>>
# WWW: http://www.mattkruse.com/
getDateFromFormat = (val, format) ->
_isInteger = (val) ->
digits = "1234567890"
i = 0
while i < val.length
return false if digits.indexOf(val.charAt(i)) is -1
i++
true
_getInt = (str, i, minlength, maxlength) ->
x = maxlength
while x >= minlength
token = str.substring(i, i + x)
return null if token.length < minlength
return token if _isInteger(token)
x--
null
val = val + ""
format = format + ""
i_val = 0
i_format = 0
c = ""
token = ""
token2 = ""
x = undefined
y = undefined
now = new Date()
year = now.getYear()
month = now.getMonth() + 1
date = 1
hh = now.getHours()
mm = now.getMinutes()
ss = now.getSeconds()
ampm = ""
while i_format < format.length
# Get next token from format string
c = format.charAt(i_format)
token = ""
token += format.charAt(i_format++) while (format.charAt(i_format) is c) and (i_format < format.length)
# Extract contents of value based on format token
if token is "yyyy" or token is "yy" or token is "y"
if token is "yyyy"
x = 4
y = 4
if token is "yy"
x = 2
y = 2
if token is "y"
x = 2
y = 4
year = _getInt(val, i_val, x, y)
return 0 unless year?
i_val += year.length
if year.length is 2
if year > 70
year = 1900 + (year - 0)
else
year = 2000 + (year - 0)
else if token is "MMM" or token is "NN<KEY>"
month = 0
i = 0
while i < MONTH_NAMES.length
month_name = MONTH_NAMES[i]
if val.substring(i_val, i_val + month_name.length).toLowerCase() is month_name.toLowerCase()
if token is "MMM" or (token is "<KEY>" and i > 11)
month = i + 1
month -= 12 if month > 12
i_val += month_name.length
break
i++
return 0 if (month < 1) or (month > 12)
else if token is "EE" or token is "E"
i = 0
while i < DAY_NAMES.length
day_name = DAY_NAMES[i]
if val.substring(i_val, i_val + day_name.length).toLowerCase() is day_name.toLowerCase()
i_val += day_name.length
break
i++
else if token is "MM" or token is "M"
month = _getInt(val, i_val, token.length, 2)
return 0 if not month? or (month < 1) or (month > 12)
i_val += month.length
else if token is "dd" or token is "d"
date = _getInt(val, i_val, token.length, 2)
return 0 if not date? or (date < 1) or (date > 31)
i_val += date.length
else if token is "hh" or token is "h"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 1) or (hh > 12)
i_val += hh.length
else if token is "HH" or token is "H"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 0) or (hh > 23)
i_val += hh.length
else if token is "KK" or token is "K"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 0) or (hh > 11)
i_val += hh.length
else if token is "kk" or token is "k"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 1) or (hh > 24)
i_val += hh.length
hh--
else if token is "mm" or token is "m"
mm = _getInt(val, i_val, token.length, 2)
return 0 if not mm? or (mm < 0) or (mm > 59)
i_val += mm.length
else if token is "ss" or token is "s"
ss = _getInt(val, i_val, token.length, 2)
return 0 if not ss? or (ss < 0) or (ss > 59)
i_val += ss.length
else if token is "a"
if val.substring(i_val, i_val + 2).toLowerCase() is "am"
ampm = "AM"
else if val.substring(i_val, i_val + 2).toLowerCase() is "pm"
ampm = "PM"
else
return 0
i_val += 2
else
unless val.substring(i_val, i_val + token.length) is token
return 0
else
i_val += token.length
# If there are any trailing characters left in the value, it doesn't match
return 0 unless i_val is val.length
# Is date valid for month?
if month is 2
# Check for leap year
if ((year % 4 is 0) and (year % 100 isnt 0)) or (year % 400 is 0) # leap year
return 0 if date > 29
else
return 0 if date > 28
return 0 if date > 30 if (month is 4) or (month is 6) or (month is 9) or (month is 11)
# Correct hours value
if hh < 12 and ampm is "PM"
hh = hh - 0 + 12
else hh -= 12 if hh > 11 and ampm is "AM"
newdate = new Date(year, month - 1, date, hh, mm, ss)
newdate.getTime()
scope = this
seconds = getDateFromFormat(str, scope.labelFormat) || Date.parse(str)
if isNaN(seconds)
return null
else
new Date(seconds)
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
}
app.directive "quickDatepicker", ['ngQuickDateDefaults', '$filter', '$sce', (ngQuickDateDefaults, $filter, $sce) ->
restrict: "E"
require: "?ngModel"
scope:
dateFilter: '=?'
onChange: "&"
required: '@'
position: '@'
replace: true
link: (scope, element, attrs, ngModelCtrl) ->
# INITIALIZE VARIABLES AND CONFIGURATION
# ================================
initialize = ->
setConfigOptions() # Setup configuration variables
scope.toggleCalendar(false) # Make sure it is closed initially
scope.weeks = [] # Nested Array of visible weeks / days in the popup
scope.inputDate = null # Date inputted into the date text input field
scope.inputTime = null # Time inputted into the time text input field
scope.invalid = true
if typeof(attrs.initValue) == 'string'
ngModelCtrl.$setViewValue(parseDateString(attrs.initValue))
if !scope.defaultTime
templateDate = new Date()
scope.datePlaceholder = $filter('date')(templateDate, scope.dateFormat);
scope.timePlaceholder = $filter('date')(templateDate, scope.timeFormat);
setCalendarDate()
refreshView()
# Copy various configuration options from the default configuration to scope
setConfigOptions = ->
for key, value of ngQuickDateDefaults
if key.match(/[Hh]tml/)
scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "")
else if !scope[key] && attrs[key]
scope[key] = attrs[key]
else if !scope[key]
scope[key] = ngQuickDateDefaults[key]
if !scope.labelFormat
scope.labelFormat = scope.dateFormat
unless scope.disableTimepicker
scope.labelFormat += " " + scope.timeFormat
if attrs.iconClass && attrs.iconClass.length
scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='#{attrs.iconClass}'></i>")
# VIEW SETUP
# ================================
# This code listens for clicks both on the entire document and the popup.
# If a click on the document is received but not on the popup, the popup
# should be closed
datepickerClicked = false
window.document.addEventListener 'click', (event) ->
if scope.calendarShown && ! datepickerClicked
scope.toggleCalendar(false)
scope.$apply()
datepickerClicked = false
angular.element(element[0])[0].addEventListener 'click', (event) ->
datepickerClicked = true
scope.isTop = if scope.position == 'top' then true else false
# SCOPE MANIPULATION Methods
# ================================
# Refresh the calendar, the input dates, and the button date
refreshView = ->
date = if ngModelCtrl.$modelValue then parseDateString(ngModelCtrl.$modelValue) else null
setupCalendarView()
setInputFieldValues(date)
scope.mainButtonStr = if date then $filter('date')(date, scope.labelFormat) else scope.placeholder
scope.invalid = ngModelCtrl.$invalid
# Set the values used in the 2 input fields
setInputFieldValues = (val) ->
if val?
scope.inputDate = $filter('date')(val, scope.dateFormat)
scope.inputTime = $filter('date')(val, scope.timeFormat)
else
scope.inputDate = null
scope.inputTime = null
# Set the date that is used by the calendar to determine which month to show
# Defaults to the current month
setCalendarDate = (val=null) ->
d = if val?
new Date(val)
else
stringToDate(scope.defaultCalendarDate) ? new Date()
if (d.toString() == "Invalid Date")
d = new Date()
d.setDate(1)
scope.calendarDate = new Date(d)
# Setup the data needed by the table that makes up the calendar in the popup
# Uses scope.calendarDate to decide which month to show
setupCalendarView = ->
offset = scope.calendarDate.getDay()
daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth())
numRows = Math.ceil((offset + daysInMonth) / 7)
weeks = []
curDate = new Date(scope.calendarDate)
curDate.setDate(curDate.getDate() + (offset * -1))
for row in [0..(numRows-1)]
weeks.push([])
for day in [0..6]
d = new Date(curDate)
if scope.defaultTime
time = scope.defaultTime.split(':')
d.setHours(time[0] || 0)
d.setMinutes(time[1] || 0)
d.setSeconds(time[2] || 0)
selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue)
today = datesAreEqual(d, new Date())
weeks[row].push({
date: d
selected: selected
disabled: if (typeof(scope.dateFilter) == 'function') then !scope.dateFilter(d) else false
other: d.getMonth() != scope.calendarDate.getMonth()
today: today
})
curDate.setDate(curDate.getDate() + 1)
scope.weeks = weeks
# PARSERS AND FORMATTERS
# =================================
# When the model is set from within the datepicker, this will be run
# before passing it to the model.
ngModelCtrl.$parsers.push((viewVal) ->
if scope.required && !viewVal?
ngModelCtrl.$setValidity('required', false)
null
else if angular.isDate(viewVal)
ngModelCtrl.$setValidity('required', true)
viewVal
else if angular.isString(viewVal)
ngModelCtrl.$setValidity('required', true)
scope.parseDateFunction(viewVal)
else
null
)
# When the model is set from outside the datepicker, this will be run
# before passing it to the datepicker
ngModelCtrl.$formatters.push((modelVal) ->
if angular.isDate(modelVal)
modelVal
else if angular.isString(modelVal)
scope.parseDateFunction(modelVal)
else
undefined
)
# HELPER METHODS
# =================================
dateToString = (date, format) ->
$filter('date')(date, format)
stringToDate = (date) ->
if typeof date == 'string'
parseDateString(date)
else
date
parseDateString = () ->
ngQuickDateDefaults.parseDateFunction.apply(scope, arguments)
datesAreEqual = (d1, d2, compareTimes=false) ->
if compareTimes
(d1 - d2) == 0
else
d1 = stringToDate(d1)
d2 = stringToDate(d2)
d1 && d2 && (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDate() == d2.getDate())
datesAreEqualToMinute = (d1, d2) ->
return false unless d1 && d2
parseInt(d1.getTime() / 60000) == parseInt(d2.getTime() / 60000)
getDaysInMonth = (year, month) ->
[31, (if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) then 29 else 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
# DATA WATCHES
# ==================================
# Called when the model is updated from outside the datepicker
ngModelCtrl.$render = ->
setCalendarDate(ngModelCtrl.$viewValue)
refreshView()
# Called when the model is updated from inside the datepicker,
# either by clicking a calendar date, setting an input, etc
ngModelCtrl.$viewChangeListeners.unshift ->
setCalendarDate(ngModelCtrl.$viewValue)
refreshView()
if scope.onChange
scope.onChange()
# When the popup is toggled open, select the date input
scope.$watch 'calendarShown', (newVal, oldVal) ->
if newVal
dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0]
dateInput.select()
# VIEW ACTIONS
# ==================================
scope.toggleCalendar = (show) ->
if isFinite(show)
scope.calendarShown = show
else if scope.readOnly
scope.calendarShown = false
else
scope.calendarShown = not scope.calendarShown
# Select a new model date. This is called in 3 situations:
# * Clicking a day on the calendar or from the `selectDateFromInput`
# * Changing the date or time inputs, which call the `selectDateFromInput` method, which calls this method.
# * The clear button is clicked
scope.selectDate = (date, closeCalendar=true) ->
changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() != ngModelCtrl.$viewValue.getTime()))
if typeof(scope.dateFilter) == 'function' && !scope.dateFilter(date)
return false
ngModelCtrl.$setViewValue(date)
tmpDate = $filter('date')(date, scope.dateFormat)
date = parseDateString('' + tmpDate + ' ' + scope.inputTime)
if closeCalendar
scope.toggleCalendar(false)
true
# This is triggered when the date or time inputs have a blur or enter event.
scope.selectDateFromInput = (closeCalendar=false) ->
try
tmpDate = parseDateString(scope.inputDate)
if !tmpDate
throw 'Invalid Date'
if !scope.disableTimepicker && scope.inputTime and scope.inputTime.length and tmpDate
tmpTime = if scope.disableTimepicker then '00:00:00' else scope.inputTime
tmpDateAndTime = parseDateString("#{scope.inputDate} #{tmpTime}")
if !tmpDateAndTime
throw 'Invalid Time'
tmpDate = tmpDateAndTime
if !scope.selectDate(tmpDate, false)
throw 'Invalid Date'
if closeCalendar
scope.toggleCalendar(false)
scope.inputDateErr = false
scope.inputTimeErr = false
catch err
if err == 'Invalid Date'
scope.inputDateErr = true
else if err == 'Invalid Time'
scope.inputTimeErr = true
# When tab is pressed from the date input and the timepicker
# is disabled, close the popup
scope.onDateInputTab = ->
if scope.disableTimepicker
scope.toggleCalendar(false)
true
# When tab is pressed from the time input, close the popup
scope.onTimeInputTab = ->
scope.toggleCalendar(false)
true
# View the next and previous months in the calendar popup
scope.nextMonth = ->
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1)))
refreshView()
scope.prevMonth = ->
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1)))
refreshView()
# Set the date model to null
scope.clear = ->
scope.selectDate(null, true)
initialize()
# TEMPLATE
# ================================================================
templateUrl: 'ngQuickDate/template.html'
]
app.directive 'ngEnter', ->
(scope, element, attr) ->
element.bind 'keydown keypress', (e) ->
if (e.which == 13)
scope.$apply(attr.ngEnter)
e.preventDefault()
app.directive 'onTab', ->
restrict: 'A',
link: (scope, element, attr) ->
element.bind 'keydown keypress', (e) ->
if (e.which == 9) && !e.shiftKey
scope.$apply(attr.onTab)
app.filter 'replaceMonthWithAbbrev', ['ngQuickDateDefaults', '$filter', (ngQuickDateDefaults, $filter) ->
(date) ->
if ngQuickDateDefaults && date && ngQuickDateDefaults.months[date.getMonth()] then ngQuickDateDefaults.months[date.getMonth()] + ' ' + date.getFullYear() else $filter('date')(date)
]
app.run ['$templateCache', ($templateCache) ->
$templateCache.put(
'ngQuickDate/template.html'
"""
<div class='quickdate'>
<a href='' ng-click='toggleCalendar()' class='quickdate-button' title='{{hoverText}}'><div ng-hide='iconClass' ng-bind-html='buttonIconHtml'></div>{{mainButtonStr}}</a>
<div class='quickdate-popup' ng-class='{open: calendarShown, top: isTop}'>
<a href='' tabindex='-1' class='quickdate-close' ng-click='toggleCalendar()'><div ng-bind-html='closeButtonHtml'></div></a>
<div class='quickdate-text-inputs'>
<div class='quickdate-input-wrapper' ng-hide='disableDatepicker'>
<label ng-bind-html='dateLabelHtml'></label>
<input class='quickdate-date-input' ng-class="{'ng-invalid': inputDateErr}" name='inputDate' type='text' ng-model='inputDate' placeholder='{{ datePlaceholder }}' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onDateInputTab()' />
</div>
<div class='quickdate-input-wrapper' ng-hide='disableTimepicker'>
<label ng-bind-html='timeLabelHtml'></label>
<input class='quickdate-time-input' ng-class="{'ng-invalid': inputTimeErr}" name='inputTime' type='text' ng-model='inputTime' placeholder='{{ timePlaceholder }}' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onTimeInputTab()'>
</div>
</div>
<div class='quickdate-calendar-header'>
<a href='' class='quickdate-prev-month quickdate-action-link' tabindex='-1' ng-click='prevMonth()'><div ng-bind-html='prevLinkHtml'></div></a>
<span class='quickdate-month'>{{calendarDate | replaceMonthWithAbbrev }}</span>
<a href='' class='quickdate-next-month quickdate-action-link' ng-click='nextMonth()' tabindex='-1' ><div ng-bind-html='nextLinkHtml'></div></a>
</div>
<table class='quickdate-calendar'>
<thead>
<tr>
<th ng-repeat='day in dayAbbreviations track by $index'>{{day}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='week in weeks'>
<td ng-click='selectDate(day.date, true, true)' ng-class='{"other-month": day.other, "disabled-date": day.disabled, "selected": day.selected, "is-today": day.today}' ng-repeat='day in week'>{{day.date | date:'d'}}</td>
</tr>
</tbody>
</table>
<div class='quickdate-popup-footer'>
<a href='' class='quickdate-clear' tabindex='-1' ng-hide='disableClearButton' ng-click='clear()'>{{ clearButtonText }}</a>
</div>
</div>
</div>
"""
)
]
| true | #
# ngQuickDate
# by PI:NAME:<NAME>END_PI
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngQuickDate
#
# Compatible with Angular 1.2.0+
#
app = angular.module("ngQuickDate", [])
app.provider "ngQuickDateDefaults", ->
{
options: {
dateFormat: 'M/d/yyyy'
timeFormat: 'h:mm a'
labelFormat: null
placeholder: 'Click to Set Date'
hoverText: null
buttonIconHtml: null
closeButtonHtml: '×'
nextLinkHtml: 'Next →'
prevLinkHtml: '← Prev'
clearButtonText: 'Clear'
dateLabelHtml: 'Date'
timeLabelHtml: 'Time'
disableTimepicker: false
disableDatepicker: false
disableClearButton: false
defaultTime: null
months: ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
dayAbbreviations: ["Su", "M", "Tu", "W", "Th", "F", "Sa"]
dateFilter: null
defaultCalendarDate: null
readOnly: false
parseDateFunction: (str) ->
seconds = Date.parse(str)
# Parse date helper function
# Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# WWW: http://www.mattkruse.com/
getDateFromFormat = (val, format) ->
_isInteger = (val) ->
digits = "1234567890"
i = 0
while i < val.length
return false if digits.indexOf(val.charAt(i)) is -1
i++
true
_getInt = (str, i, minlength, maxlength) ->
x = maxlength
while x >= minlength
token = str.substring(i, i + x)
return null if token.length < minlength
return token if _isInteger(token)
x--
null
val = val + ""
format = format + ""
i_val = 0
i_format = 0
c = ""
token = ""
token2 = ""
x = undefined
y = undefined
now = new Date()
year = now.getYear()
month = now.getMonth() + 1
date = 1
hh = now.getHours()
mm = now.getMinutes()
ss = now.getSeconds()
ampm = ""
while i_format < format.length
# Get next token from format string
c = format.charAt(i_format)
token = ""
token += format.charAt(i_format++) while (format.charAt(i_format) is c) and (i_format < format.length)
# Extract contents of value based on format token
if token is "yyyy" or token is "yy" or token is "y"
if token is "yyyy"
x = 4
y = 4
if token is "yy"
x = 2
y = 2
if token is "y"
x = 2
y = 4
year = _getInt(val, i_val, x, y)
return 0 unless year?
i_val += year.length
if year.length is 2
if year > 70
year = 1900 + (year - 0)
else
year = 2000 + (year - 0)
else if token is "MMM" or token is "NNPI:KEY:<KEY>END_PI"
month = 0
i = 0
while i < MONTH_NAMES.length
month_name = MONTH_NAMES[i]
if val.substring(i_val, i_val + month_name.length).toLowerCase() is month_name.toLowerCase()
if token is "MMM" or (token is "PI:KEY:<KEY>END_PI" and i > 11)
month = i + 1
month -= 12 if month > 12
i_val += month_name.length
break
i++
return 0 if (month < 1) or (month > 12)
else if token is "EE" or token is "E"
i = 0
while i < DAY_NAMES.length
day_name = DAY_NAMES[i]
if val.substring(i_val, i_val + day_name.length).toLowerCase() is day_name.toLowerCase()
i_val += day_name.length
break
i++
else if token is "MM" or token is "M"
month = _getInt(val, i_val, token.length, 2)
return 0 if not month? or (month < 1) or (month > 12)
i_val += month.length
else if token is "dd" or token is "d"
date = _getInt(val, i_val, token.length, 2)
return 0 if not date? or (date < 1) or (date > 31)
i_val += date.length
else if token is "hh" or token is "h"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 1) or (hh > 12)
i_val += hh.length
else if token is "HH" or token is "H"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 0) or (hh > 23)
i_val += hh.length
else if token is "KK" or token is "K"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 0) or (hh > 11)
i_val += hh.length
else if token is "kk" or token is "k"
hh = _getInt(val, i_val, token.length, 2)
return 0 if not hh? or (hh < 1) or (hh > 24)
i_val += hh.length
hh--
else if token is "mm" or token is "m"
mm = _getInt(val, i_val, token.length, 2)
return 0 if not mm? or (mm < 0) or (mm > 59)
i_val += mm.length
else if token is "ss" or token is "s"
ss = _getInt(val, i_val, token.length, 2)
return 0 if not ss? or (ss < 0) or (ss > 59)
i_val += ss.length
else if token is "a"
if val.substring(i_val, i_val + 2).toLowerCase() is "am"
ampm = "AM"
else if val.substring(i_val, i_val + 2).toLowerCase() is "pm"
ampm = "PM"
else
return 0
i_val += 2
else
unless val.substring(i_val, i_val + token.length) is token
return 0
else
i_val += token.length
# If there are any trailing characters left in the value, it doesn't match
return 0 unless i_val is val.length
# Is date valid for month?
if month is 2
# Check for leap year
if ((year % 4 is 0) and (year % 100 isnt 0)) or (year % 400 is 0) # leap year
return 0 if date > 29
else
return 0 if date > 28
return 0 if date > 30 if (month is 4) or (month is 6) or (month is 9) or (month is 11)
# Correct hours value
if hh < 12 and ampm is "PM"
hh = hh - 0 + 12
else hh -= 12 if hh > 11 and ampm is "AM"
newdate = new Date(year, month - 1, date, hh, mm, ss)
newdate.getTime()
scope = this
seconds = getDateFromFormat(str, scope.labelFormat) || Date.parse(str)
if isNaN(seconds)
return null
else
new Date(seconds)
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
}
app.directive "quickDatepicker", ['ngQuickDateDefaults', '$filter', '$sce', (ngQuickDateDefaults, $filter, $sce) ->
restrict: "E"
require: "?ngModel"
scope:
dateFilter: '=?'
onChange: "&"
required: '@'
position: '@'
replace: true
link: (scope, element, attrs, ngModelCtrl) ->
# INITIALIZE VARIABLES AND CONFIGURATION
# ================================
initialize = ->
setConfigOptions() # Setup configuration variables
scope.toggleCalendar(false) # Make sure it is closed initially
scope.weeks = [] # Nested Array of visible weeks / days in the popup
scope.inputDate = null # Date inputted into the date text input field
scope.inputTime = null # Time inputted into the time text input field
scope.invalid = true
if typeof(attrs.initValue) == 'string'
ngModelCtrl.$setViewValue(parseDateString(attrs.initValue))
if !scope.defaultTime
templateDate = new Date()
scope.datePlaceholder = $filter('date')(templateDate, scope.dateFormat);
scope.timePlaceholder = $filter('date')(templateDate, scope.timeFormat);
setCalendarDate()
refreshView()
# Copy various configuration options from the default configuration to scope
setConfigOptions = ->
for key, value of ngQuickDateDefaults
if key.match(/[Hh]tml/)
scope[key] = $sce.trustAsHtml(ngQuickDateDefaults[key] || "")
else if !scope[key] && attrs[key]
scope[key] = attrs[key]
else if !scope[key]
scope[key] = ngQuickDateDefaults[key]
if !scope.labelFormat
scope.labelFormat = scope.dateFormat
unless scope.disableTimepicker
scope.labelFormat += " " + scope.timeFormat
if attrs.iconClass && attrs.iconClass.length
scope.buttonIconHtml = $sce.trustAsHtml("<i ng-show='iconClass' class='#{attrs.iconClass}'></i>")
# VIEW SETUP
# ================================
# This code listens for clicks both on the entire document and the popup.
# If a click on the document is received but not on the popup, the popup
# should be closed
datepickerClicked = false
window.document.addEventListener 'click', (event) ->
if scope.calendarShown && ! datepickerClicked
scope.toggleCalendar(false)
scope.$apply()
datepickerClicked = false
angular.element(element[0])[0].addEventListener 'click', (event) ->
datepickerClicked = true
scope.isTop = if scope.position == 'top' then true else false
# SCOPE MANIPULATION Methods
# ================================
# Refresh the calendar, the input dates, and the button date
refreshView = ->
date = if ngModelCtrl.$modelValue then parseDateString(ngModelCtrl.$modelValue) else null
setupCalendarView()
setInputFieldValues(date)
scope.mainButtonStr = if date then $filter('date')(date, scope.labelFormat) else scope.placeholder
scope.invalid = ngModelCtrl.$invalid
# Set the values used in the 2 input fields
setInputFieldValues = (val) ->
if val?
scope.inputDate = $filter('date')(val, scope.dateFormat)
scope.inputTime = $filter('date')(val, scope.timeFormat)
else
scope.inputDate = null
scope.inputTime = null
# Set the date that is used by the calendar to determine which month to show
# Defaults to the current month
setCalendarDate = (val=null) ->
d = if val?
new Date(val)
else
stringToDate(scope.defaultCalendarDate) ? new Date()
if (d.toString() == "Invalid Date")
d = new Date()
d.setDate(1)
scope.calendarDate = new Date(d)
# Setup the data needed by the table that makes up the calendar in the popup
# Uses scope.calendarDate to decide which month to show
setupCalendarView = ->
offset = scope.calendarDate.getDay()
daysInMonth = getDaysInMonth(scope.calendarDate.getFullYear(), scope.calendarDate.getMonth())
numRows = Math.ceil((offset + daysInMonth) / 7)
weeks = []
curDate = new Date(scope.calendarDate)
curDate.setDate(curDate.getDate() + (offset * -1))
for row in [0..(numRows-1)]
weeks.push([])
for day in [0..6]
d = new Date(curDate)
if scope.defaultTime
time = scope.defaultTime.split(':')
d.setHours(time[0] || 0)
d.setMinutes(time[1] || 0)
d.setSeconds(time[2] || 0)
selected = ngModelCtrl.$modelValue && d && datesAreEqual(d, ngModelCtrl.$modelValue)
today = datesAreEqual(d, new Date())
weeks[row].push({
date: d
selected: selected
disabled: if (typeof(scope.dateFilter) == 'function') then !scope.dateFilter(d) else false
other: d.getMonth() != scope.calendarDate.getMonth()
today: today
})
curDate.setDate(curDate.getDate() + 1)
scope.weeks = weeks
# PARSERS AND FORMATTERS
# =================================
# When the model is set from within the datepicker, this will be run
# before passing it to the model.
ngModelCtrl.$parsers.push((viewVal) ->
if scope.required && !viewVal?
ngModelCtrl.$setValidity('required', false)
null
else if angular.isDate(viewVal)
ngModelCtrl.$setValidity('required', true)
viewVal
else if angular.isString(viewVal)
ngModelCtrl.$setValidity('required', true)
scope.parseDateFunction(viewVal)
else
null
)
# When the model is set from outside the datepicker, this will be run
# before passing it to the datepicker
ngModelCtrl.$formatters.push((modelVal) ->
if angular.isDate(modelVal)
modelVal
else if angular.isString(modelVal)
scope.parseDateFunction(modelVal)
else
undefined
)
# HELPER METHODS
# =================================
dateToString = (date, format) ->
$filter('date')(date, format)
stringToDate = (date) ->
if typeof date == 'string'
parseDateString(date)
else
date
parseDateString = () ->
ngQuickDateDefaults.parseDateFunction.apply(scope, arguments)
datesAreEqual = (d1, d2, compareTimes=false) ->
if compareTimes
(d1 - d2) == 0
else
d1 = stringToDate(d1)
d2 = stringToDate(d2)
d1 && d2 && (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDate() == d2.getDate())
datesAreEqualToMinute = (d1, d2) ->
return false unless d1 && d2
parseInt(d1.getTime() / 60000) == parseInt(d2.getTime() / 60000)
getDaysInMonth = (year, month) ->
[31, (if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) then 29 else 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
# DATA WATCHES
# ==================================
# Called when the model is updated from outside the datepicker
ngModelCtrl.$render = ->
setCalendarDate(ngModelCtrl.$viewValue)
refreshView()
# Called when the model is updated from inside the datepicker,
# either by clicking a calendar date, setting an input, etc
ngModelCtrl.$viewChangeListeners.unshift ->
setCalendarDate(ngModelCtrl.$viewValue)
refreshView()
if scope.onChange
scope.onChange()
# When the popup is toggled open, select the date input
scope.$watch 'calendarShown', (newVal, oldVal) ->
if newVal
dateInput = angular.element(element[0].querySelector(".quickdate-date-input"))[0]
dateInput.select()
# VIEW ACTIONS
# ==================================
scope.toggleCalendar = (show) ->
if isFinite(show)
scope.calendarShown = show
else if scope.readOnly
scope.calendarShown = false
else
scope.calendarShown = not scope.calendarShown
# Select a new model date. This is called in 3 situations:
# * Clicking a day on the calendar or from the `selectDateFromInput`
# * Changing the date or time inputs, which call the `selectDateFromInput` method, which calls this method.
# * The clear button is clicked
scope.selectDate = (date, closeCalendar=true) ->
changed = (!ngModelCtrl.$viewValue && date) || (ngModelCtrl.$viewValue && !date) || ((date && ngModelCtrl.$viewValue) && (date.getTime() != ngModelCtrl.$viewValue.getTime()))
if typeof(scope.dateFilter) == 'function' && !scope.dateFilter(date)
return false
ngModelCtrl.$setViewValue(date)
tmpDate = $filter('date')(date, scope.dateFormat)
date = parseDateString('' + tmpDate + ' ' + scope.inputTime)
if closeCalendar
scope.toggleCalendar(false)
true
# This is triggered when the date or time inputs have a blur or enter event.
scope.selectDateFromInput = (closeCalendar=false) ->
try
tmpDate = parseDateString(scope.inputDate)
if !tmpDate
throw 'Invalid Date'
if !scope.disableTimepicker && scope.inputTime and scope.inputTime.length and tmpDate
tmpTime = if scope.disableTimepicker then '00:00:00' else scope.inputTime
tmpDateAndTime = parseDateString("#{scope.inputDate} #{tmpTime}")
if !tmpDateAndTime
throw 'Invalid Time'
tmpDate = tmpDateAndTime
if !scope.selectDate(tmpDate, false)
throw 'Invalid Date'
if closeCalendar
scope.toggleCalendar(false)
scope.inputDateErr = false
scope.inputTimeErr = false
catch err
if err == 'Invalid Date'
scope.inputDateErr = true
else if err == 'Invalid Time'
scope.inputTimeErr = true
# When tab is pressed from the date input and the timepicker
# is disabled, close the popup
scope.onDateInputTab = ->
if scope.disableTimepicker
scope.toggleCalendar(false)
true
# When tab is pressed from the time input, close the popup
scope.onTimeInputTab = ->
scope.toggleCalendar(false)
true
# View the next and previous months in the calendar popup
scope.nextMonth = ->
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() + 1)))
refreshView()
scope.prevMonth = ->
setCalendarDate(new Date(new Date(scope.calendarDate).setMonth(scope.calendarDate.getMonth() - 1)))
refreshView()
# Set the date model to null
scope.clear = ->
scope.selectDate(null, true)
initialize()
# TEMPLATE
# ================================================================
templateUrl: 'ngQuickDate/template.html'
]
app.directive 'ngEnter', ->
(scope, element, attr) ->
element.bind 'keydown keypress', (e) ->
if (e.which == 13)
scope.$apply(attr.ngEnter)
e.preventDefault()
app.directive 'onTab', ->
restrict: 'A',
link: (scope, element, attr) ->
element.bind 'keydown keypress', (e) ->
if (e.which == 9) && !e.shiftKey
scope.$apply(attr.onTab)
app.filter 'replaceMonthWithAbbrev', ['ngQuickDateDefaults', '$filter', (ngQuickDateDefaults, $filter) ->
(date) ->
if ngQuickDateDefaults && date && ngQuickDateDefaults.months[date.getMonth()] then ngQuickDateDefaults.months[date.getMonth()] + ' ' + date.getFullYear() else $filter('date')(date)
]
app.run ['$templateCache', ($templateCache) ->
$templateCache.put(
'ngQuickDate/template.html'
"""
<div class='quickdate'>
<a href='' ng-click='toggleCalendar()' class='quickdate-button' title='{{hoverText}}'><div ng-hide='iconClass' ng-bind-html='buttonIconHtml'></div>{{mainButtonStr}}</a>
<div class='quickdate-popup' ng-class='{open: calendarShown, top: isTop}'>
<a href='' tabindex='-1' class='quickdate-close' ng-click='toggleCalendar()'><div ng-bind-html='closeButtonHtml'></div></a>
<div class='quickdate-text-inputs'>
<div class='quickdate-input-wrapper' ng-hide='disableDatepicker'>
<label ng-bind-html='dateLabelHtml'></label>
<input class='quickdate-date-input' ng-class="{'ng-invalid': inputDateErr}" name='inputDate' type='text' ng-model='inputDate' placeholder='{{ datePlaceholder }}' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onDateInputTab()' />
</div>
<div class='quickdate-input-wrapper' ng-hide='disableTimepicker'>
<label ng-bind-html='timeLabelHtml'></label>
<input class='quickdate-time-input' ng-class="{'ng-invalid': inputTimeErr}" name='inputTime' type='text' ng-model='inputTime' placeholder='{{ timePlaceholder }}' ng-enter="selectDateFromInput(true)" ng-blur="selectDateFromInput(false)" on-tab='onTimeInputTab()'>
</div>
</div>
<div class='quickdate-calendar-header'>
<a href='' class='quickdate-prev-month quickdate-action-link' tabindex='-1' ng-click='prevMonth()'><div ng-bind-html='prevLinkHtml'></div></a>
<span class='quickdate-month'>{{calendarDate | replaceMonthWithAbbrev }}</span>
<a href='' class='quickdate-next-month quickdate-action-link' ng-click='nextMonth()' tabindex='-1' ><div ng-bind-html='nextLinkHtml'></div></a>
</div>
<table class='quickdate-calendar'>
<thead>
<tr>
<th ng-repeat='day in dayAbbreviations track by $index'>{{day}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='week in weeks'>
<td ng-click='selectDate(day.date, true, true)' ng-class='{"other-month": day.other, "disabled-date": day.disabled, "selected": day.selected, "is-today": day.today}' ng-repeat='day in week'>{{day.date | date:'d'}}</td>
</tr>
</tbody>
</table>
<div class='quickdate-popup-footer'>
<a href='' class='quickdate-clear' tabindex='-1' ng-hide='disableClearButton' ng-click='clear()'>{{ clearButtonText }}</a>
</div>
</div>
</div>
"""
)
]
|
[
{
"context": "pired by the original jQuery Email Autocomplete by Low Yong Zhen <cephyz@gmail.com>\n# http://yzlow.github.io/email",
"end": 175,
"score": 0.9998660087585449,
"start": 162,
"tag": "NAME",
"value": "Low Yong Zhen"
},
{
"context": "ginal jQuery Email Autocomplete by Low Y... | assets/javascripts/mice/email-autocomplete.coffee | miclle/mice | 7 | # Mice: Email Autocomplete
# A jQuery plugin that suggests and autocompletes the domain in email fields.
# Inspired by the original jQuery Email Autocomplete by Low Yong Zhen <cephyz@gmail.com>
# http://yzlow.github.io/email-autocomplete/demo/
# Copyright (c) 2014 Miclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
'use strict'
(($) ->
# EMAILAUTOCOMPLETE PUBLIC CLASS DEFINITION
# ===============================
class EmailAutoComplete
constructor: (element, options) ->
@$field = $(element);
@options = $.extend(true, {}, defaults, options); #we want deep extend
@_defaults = defaults;
@_domains = @options.domains;
@init();
init: ->
# shim indexOf
@doIndexOf() unless Array.prototype.indexOf
# bind handlers
@$field.on("keyup.eac", $.proxy(@displaySuggestion, @))
@$field.on("blur.eac", $.proxy(@autocomplete, @))
# get input padding,border and margin to offset text
@fieldLeftOffset = (@$field.outerWidth(true) - @$field.width()) / 2
# wrap our field
$wrap = $("<div class='eac-input-wrap' />").css({
display: @$field.css("display"),
position: "relative",
fontSize: @$field.css("fontSize")
})
@$field.wrap($wrap)
# create container to test width of current val
@$cval = $("<span class='eac-cval' />").css({
visibility: "hidden",
position: "absolute",
display: "inline-block",
fontFamily: @$field.css("fontFamily"),
fontWeight: @$field.css("fontWeight"),
letterSpacing: @$field.css("letterSpacing")
}).insertAfter(@$field)
# create the suggestion overlay
# touchstart jquery 1.7+
heightPad = (@$field.outerHeight(true) - @$field.height()) / 2 # padding+border
@$suggOverlay = $("<span class='"+@options.suggClass+"' />").css({
display: "block",
"box-sizing": "content-box", # standardize
lineHeight: @$field.css('lineHeight'),
paddingTop: heightPad + "px",
paddingBottom: heightPad + "px",
fontFamily: @$field.css("fontFamily"),
fontWeight: @$field.css("fontWeight"),
letterSpacing: @$field.css("letterSpacing"),
position: "absolute",
top: 0,
left: 0
}).insertAfter(@$field).on("mousedown.eac touchstart.eac", $.proxy(@autocomplete, this))
suggest: (str) ->
str_arr = str.split("@")
if str_arr.length > 1
str = str_arr.pop()
return "" if (!str.length)
else
return ""
match = @_domains.filter( (domain) -> return 0 == domain.indexOf(str) ).shift() || ""
return match.replace(str, "")
autocomplete: ->
return false if(typeof @suggestion == `undefined`)
@$field.val(@val + @suggestion)
@$suggOverlay.html("")
@$cval.html("")
# Displays the suggestion, handler for field keyup event
displaySuggestion: (e) ->
@val = @$field.val()
@suggestion = @suggest(@val)
if !@suggestion.length
@$suggOverlay.html("")
else
e.preventDefault()
# update with new suggestion
@$suggOverlay.html(@suggestion)
@$cval.html(@val)
# find width of current input val so we can offset the suggestion text
cvalWidth = @$cval.width()
# offset our suggestion container
@$suggOverlay.css('left', @fieldLeftOffset + cvalWidth + "px") if(@$field.outerWidth() > cvalWidth)
# indexof polyfill
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
doIndexOf: ->
Array.prototype.indexOf = (searchElement, fromIndex) ->
throw new TypeError( '"this" is null or not defined' ) if ( this == `undefined` || this == null )
length = @length >>> 0 # Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0
fromIndex = 0 if (Math.abs(fromIndex) == Infinity)
if (fromIndex < 0)
fromIndex += length
fromIndex = 0 if (fromIndex < 0)
for item in @
for fromIndex in length
return fromIndex if @[fromIndex] == searchElement
return -1
# EMAILAUTOCOMPLETE PLUGIN DEFINITION
# =========================
$.fn.emailautocomplete = (option) ->
@each ->
if (!$.data(this, "yz_" + pluginName)) {
$.data(this, "yz_" + pluginName, new EmailAutoComplete(@, options))
}
$.fn.emailautocomplete.Constructor = EmailAutoComplete
# EMAILAUTOCOMPLETE PLUGIN DEFAULT OPTIONS
# =========================
$.fn.emailautocomplete.defaults =
suggClass: "suggestion"
domains: ["yahoo.com" ,"google.com" ,"hotmail.com" ,"gmail.com" ,"me.com" ,"aol.com" ,"mac.com" ,"live.com" ,"comcast.net" ,"googlemail.com" ,"msn.com" ,"hotmail.co.uk" ,"yahoo.co.uk" ,"facebook.com" ,"verizon.net" ,"sbcglobal.net" ,"att.net" ,"gmx.com" ,"mail.com" ,"outlook.com" ,"icloud.com"]
# $ -> $("[data-toggle=emailautocomplete]").emailautocomplete()
return
) jQuery
| 166716 | # Mice: Email Autocomplete
# A jQuery plugin that suggests and autocompletes the domain in email fields.
# Inspired by the original jQuery Email Autocomplete by <NAME> <<EMAIL>>
# http://yzlow.github.io/email-autocomplete/demo/
# Copyright (c) 2014 Miclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
'use strict'
(($) ->
# EMAILAUTOCOMPLETE PUBLIC CLASS DEFINITION
# ===============================
class EmailAutoComplete
constructor: (element, options) ->
@$field = $(element);
@options = $.extend(true, {}, defaults, options); #we want deep extend
@_defaults = defaults;
@_domains = @options.domains;
@init();
init: ->
# shim indexOf
@doIndexOf() unless Array.prototype.indexOf
# bind handlers
@$field.on("keyup.eac", $.proxy(@displaySuggestion, @))
@$field.on("blur.eac", $.proxy(@autocomplete, @))
# get input padding,border and margin to offset text
@fieldLeftOffset = (@$field.outerWidth(true) - @$field.width()) / 2
# wrap our field
$wrap = $("<div class='eac-input-wrap' />").css({
display: @$field.css("display"),
position: "relative",
fontSize: @$field.css("fontSize")
})
@$field.wrap($wrap)
# create container to test width of current val
@$cval = $("<span class='eac-cval' />").css({
visibility: "hidden",
position: "absolute",
display: "inline-block",
fontFamily: @$field.css("fontFamily"),
fontWeight: @$field.css("fontWeight"),
letterSpacing: @$field.css("letterSpacing")
}).insertAfter(@$field)
# create the suggestion overlay
# touchstart jquery 1.7+
heightPad = (@$field.outerHeight(true) - @$field.height()) / 2 # padding+border
@$suggOverlay = $("<span class='"+@options.suggClass+"' />").css({
display: "block",
"box-sizing": "content-box", # standardize
lineHeight: @$field.css('lineHeight'),
paddingTop: heightPad + "px",
paddingBottom: heightPad + "px",
fontFamily: @$field.css("fontFamily"),
fontWeight: @$field.css("fontWeight"),
letterSpacing: @$field.css("letterSpacing"),
position: "absolute",
top: 0,
left: 0
}).insertAfter(@$field).on("mousedown.eac touchstart.eac", $.proxy(@autocomplete, this))
suggest: (str) ->
str_arr = str.split("@")
if str_arr.length > 1
str = str_arr.pop()
return "" if (!str.length)
else
return ""
match = @_domains.filter( (domain) -> return 0 == domain.indexOf(str) ).shift() || ""
return match.replace(str, "")
autocomplete: ->
return false if(typeof @suggestion == `undefined`)
@$field.val(@val + @suggestion)
@$suggOverlay.html("")
@$cval.html("")
# Displays the suggestion, handler for field keyup event
displaySuggestion: (e) ->
@val = @$field.val()
@suggestion = @suggest(@val)
if !@suggestion.length
@$suggOverlay.html("")
else
e.preventDefault()
# update with new suggestion
@$suggOverlay.html(@suggestion)
@$cval.html(@val)
# find width of current input val so we can offset the suggestion text
cvalWidth = @$cval.width()
# offset our suggestion container
@$suggOverlay.css('left', @fieldLeftOffset + cvalWidth + "px") if(@$field.outerWidth() > cvalWidth)
# indexof polyfill
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
doIndexOf: ->
Array.prototype.indexOf = (searchElement, fromIndex) ->
throw new TypeError( '"this" is null or not defined' ) if ( this == `undefined` || this == null )
length = @length >>> 0 # Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0
fromIndex = 0 if (Math.abs(fromIndex) == Infinity)
if (fromIndex < 0)
fromIndex += length
fromIndex = 0 if (fromIndex < 0)
for item in @
for fromIndex in length
return fromIndex if @[fromIndex] == searchElement
return -1
# EMAILAUTOCOMPLETE PLUGIN DEFINITION
# =========================
$.fn.emailautocomplete = (option) ->
@each ->
if (!$.data(this, "yz_" + pluginName)) {
$.data(this, "yz_" + pluginName, new EmailAutoComplete(@, options))
}
$.fn.emailautocomplete.Constructor = EmailAutoComplete
# EMAILAUTOCOMPLETE PLUGIN DEFAULT OPTIONS
# =========================
$.fn.emailautocomplete.defaults =
suggClass: "suggestion"
domains: ["yahoo.com" ,"google.com" ,"hotmail.com" ,"gmail.com" ,"me.com" ,"aol.com" ,"mac.com" ,"live.com" ,"comcast.net" ,"googlemail.com" ,"msn.com" ,"hotmail.co.uk" ,"yahoo.co.uk" ,"facebook.com" ,"verizon.net" ,"sbcglobal.net" ,"att.net" ,"gmx.com" ,"mail.com" ,"outlook.com" ,"icloud.com"]
# $ -> $("[data-toggle=emailautocomplete]").emailautocomplete()
return
) jQuery
| true | # Mice: Email Autocomplete
# A jQuery plugin that suggests and autocompletes the domain in email fields.
# Inspired by the original jQuery Email Autocomplete by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# http://yzlow.github.io/email-autocomplete/demo/
# Copyright (c) 2014 Miclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
'use strict'
(($) ->
# EMAILAUTOCOMPLETE PUBLIC CLASS DEFINITION
# ===============================
class EmailAutoComplete
constructor: (element, options) ->
@$field = $(element);
@options = $.extend(true, {}, defaults, options); #we want deep extend
@_defaults = defaults;
@_domains = @options.domains;
@init();
init: ->
# shim indexOf
@doIndexOf() unless Array.prototype.indexOf
# bind handlers
@$field.on("keyup.eac", $.proxy(@displaySuggestion, @))
@$field.on("blur.eac", $.proxy(@autocomplete, @))
# get input padding,border and margin to offset text
@fieldLeftOffset = (@$field.outerWidth(true) - @$field.width()) / 2
# wrap our field
$wrap = $("<div class='eac-input-wrap' />").css({
display: @$field.css("display"),
position: "relative",
fontSize: @$field.css("fontSize")
})
@$field.wrap($wrap)
# create container to test width of current val
@$cval = $("<span class='eac-cval' />").css({
visibility: "hidden",
position: "absolute",
display: "inline-block",
fontFamily: @$field.css("fontFamily"),
fontWeight: @$field.css("fontWeight"),
letterSpacing: @$field.css("letterSpacing")
}).insertAfter(@$field)
# create the suggestion overlay
# touchstart jquery 1.7+
heightPad = (@$field.outerHeight(true) - @$field.height()) / 2 # padding+border
@$suggOverlay = $("<span class='"+@options.suggClass+"' />").css({
display: "block",
"box-sizing": "content-box", # standardize
lineHeight: @$field.css('lineHeight'),
paddingTop: heightPad + "px",
paddingBottom: heightPad + "px",
fontFamily: @$field.css("fontFamily"),
fontWeight: @$field.css("fontWeight"),
letterSpacing: @$field.css("letterSpacing"),
position: "absolute",
top: 0,
left: 0
}).insertAfter(@$field).on("mousedown.eac touchstart.eac", $.proxy(@autocomplete, this))
suggest: (str) ->
str_arr = str.split("@")
if str_arr.length > 1
str = str_arr.pop()
return "" if (!str.length)
else
return ""
match = @_domains.filter( (domain) -> return 0 == domain.indexOf(str) ).shift() || ""
return match.replace(str, "")
autocomplete: ->
return false if(typeof @suggestion == `undefined`)
@$field.val(@val + @suggestion)
@$suggOverlay.html("")
@$cval.html("")
# Displays the suggestion, handler for field keyup event
displaySuggestion: (e) ->
@val = @$field.val()
@suggestion = @suggest(@val)
if !@suggestion.length
@$suggOverlay.html("")
else
e.preventDefault()
# update with new suggestion
@$suggOverlay.html(@suggestion)
@$cval.html(@val)
# find width of current input val so we can offset the suggestion text
cvalWidth = @$cval.width()
# offset our suggestion container
@$suggOverlay.css('left', @fieldLeftOffset + cvalWidth + "px") if(@$field.outerWidth() > cvalWidth)
# indexof polyfill
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
doIndexOf: ->
Array.prototype.indexOf = (searchElement, fromIndex) ->
throw new TypeError( '"this" is null or not defined' ) if ( this == `undefined` || this == null )
length = @length >>> 0 # Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0
fromIndex = 0 if (Math.abs(fromIndex) == Infinity)
if (fromIndex < 0)
fromIndex += length
fromIndex = 0 if (fromIndex < 0)
for item in @
for fromIndex in length
return fromIndex if @[fromIndex] == searchElement
return -1
# EMAILAUTOCOMPLETE PLUGIN DEFINITION
# =========================
$.fn.emailautocomplete = (option) ->
@each ->
if (!$.data(this, "yz_" + pluginName)) {
$.data(this, "yz_" + pluginName, new EmailAutoComplete(@, options))
}
$.fn.emailautocomplete.Constructor = EmailAutoComplete
# EMAILAUTOCOMPLETE PLUGIN DEFAULT OPTIONS
# =========================
$.fn.emailautocomplete.defaults =
suggClass: "suggestion"
domains: ["yahoo.com" ,"google.com" ,"hotmail.com" ,"gmail.com" ,"me.com" ,"aol.com" ,"mac.com" ,"live.com" ,"comcast.net" ,"googlemail.com" ,"msn.com" ,"hotmail.co.uk" ,"yahoo.co.uk" ,"facebook.com" ,"verizon.net" ,"sbcglobal.net" ,"att.net" ,"gmx.com" ,"mail.com" ,"outlook.com" ,"icloud.com"]
# $ -> $("[data-toggle=emailautocomplete]").emailautocomplete()
return
) jQuery
|
[
{
"context": " ' ' + 'email'.underline.blue + ' ' + '{\"email\": \"praj@infynyxx.com\"}\\n'.underline.magenta\n samplecCommandExpl",
"end": 2422,
"score": 0.9999262690544128,
"start": 2405,
"tag": "EMAIL",
"value": "praj@infynyxx.com"
}
] | src/sailthru-console.coffee | georgekliao/sailthru-cli | 0 | readline = require 'readline'
{createSailthruClient} = require 'sailthru-client'
colors = require 'colors'
{log} = require './util'
DEFAULT_URL = 'https://api.sailthru.com'
apiClient = (apiKey, apiSecret, apiUrl) ->
client = createSailthruClient(apiKey, apiSecret, apiUrl)
client.disableLogging()
client
class SailthruConsole
constructor: (options) ->
_apiKey = if options.apiKey then options.apiKey else ""
_apiSecret = if options.apiSecret then options.apiSecret else ""
_apiUrl = if options.apiUrl then options.apiUrl else DEFAULT_URL
@client = apiClient(_apiKey, _apiSecret, _apiUrl)
@welcomeMessage = "***Welcome to CLI for Sailthru API***".cyan
@prefix = if options.prefix then options.prefix else "SAILTHRU> "
initialize: ->
self = this
log @welcomeMessage
@readline = readline.createInterface process.stdin, process.stdout
@readline.on 'line', (cmd) ->
self.parseCommand cmd
@readline.on 'close', ->
process.stdout.write '\n'
process.exit 0
@prompt()
return
prompt: ->
length = @prefix.length
@readline.setPrompt @prefix, length
@readline.prompt()
return
parseCommand: (cmd, callback) ->
cmd = cmd.trim()
if cmd.length == 0
@prompt()
return
splits = cmd.split(" ")
verb = splits[0]
apiCall = if splits[1] then splits[1] else ""
payload = @extractPayload cmd
wait = true
switch cmd
when 'help'
@helpMessage()
wait = false
when 'quit', 'exit'
log 'Bye\n'
process.exit(0)
else
cb = ->
wait = false
return
@_apiRequest(verb, apiCall, payload, cb)
@prompt() if wait is false
return
extractPayload: (cmd) ->
splits = cmd.trim().split(" ")
payload = ''
if splits.length >= 3
payload += value + " " for value, index in splits when index >= 2
return payload.trim()
helpMessage: ->
sampleCommandText = 'Sample Command: '.grey
sampleCommandCmd = sampleCommandText + 'GET'.underline.green + ' ' + 'email'.underline.blue + ' ' + '{"email": "praj@infynyxx.com"}\n'.underline.magenta
samplecCommandExplanation = "The above command is divided into 3 parts: HTTP Verb, name of API call and JSON payload to make request. JSON payload requires valid JSON format as defined by http://www.json.org/ \n".cyan
otherCommands = "Other Commands: ".cyan + "help | exit | version | history (will be added soon)".blue
log sampleCommandCmd + samplecCommandExplanation + otherCommands
return
_apiRequest: (verb, action, payload, callback) ->
validVerbs = ["GET", "POST", "DELETE"]
verb = verb.toUpperCase()
verb = "GET" if validVerbs.indexOf(verb) is -1
self = this
action = action.toLowerCase()
error = false
try
json = JSON.parse(payload)
catch err
error = err
if error is false
cb = (response, err) ->
response = JSON.stringify(response, null, '\t')
#log payload.blue
if err then log response.red else log response.green
self.prompt()
switch verb
when 'GET'
@client.apiGet action, json, cb
when 'POST'
multipart = []
multipart.push 'file' if action is 'job' and json.file
@client.apiPost action, json, cb, multipart
when 'DELETE'
@client.apiDelete action, json, cb
else
log "Error: ".red + error.toString().red
log "Payload: ".red + payload.blue
self.prompt()
return
exports.createSailthruConsole = (options) ->
new SailthruConsole options
| 99543 | readline = require 'readline'
{createSailthruClient} = require 'sailthru-client'
colors = require 'colors'
{log} = require './util'
DEFAULT_URL = 'https://api.sailthru.com'
apiClient = (apiKey, apiSecret, apiUrl) ->
client = createSailthruClient(apiKey, apiSecret, apiUrl)
client.disableLogging()
client
class SailthruConsole
constructor: (options) ->
_apiKey = if options.apiKey then options.apiKey else ""
_apiSecret = if options.apiSecret then options.apiSecret else ""
_apiUrl = if options.apiUrl then options.apiUrl else DEFAULT_URL
@client = apiClient(_apiKey, _apiSecret, _apiUrl)
@welcomeMessage = "***Welcome to CLI for Sailthru API***".cyan
@prefix = if options.prefix then options.prefix else "SAILTHRU> "
initialize: ->
self = this
log @welcomeMessage
@readline = readline.createInterface process.stdin, process.stdout
@readline.on 'line', (cmd) ->
self.parseCommand cmd
@readline.on 'close', ->
process.stdout.write '\n'
process.exit 0
@prompt()
return
prompt: ->
length = @prefix.length
@readline.setPrompt @prefix, length
@readline.prompt()
return
parseCommand: (cmd, callback) ->
cmd = cmd.trim()
if cmd.length == 0
@prompt()
return
splits = cmd.split(" ")
verb = splits[0]
apiCall = if splits[1] then splits[1] else ""
payload = @extractPayload cmd
wait = true
switch cmd
when 'help'
@helpMessage()
wait = false
when 'quit', 'exit'
log 'Bye\n'
process.exit(0)
else
cb = ->
wait = false
return
@_apiRequest(verb, apiCall, payload, cb)
@prompt() if wait is false
return
extractPayload: (cmd) ->
splits = cmd.trim().split(" ")
payload = ''
if splits.length >= 3
payload += value + " " for value, index in splits when index >= 2
return payload.trim()
helpMessage: ->
sampleCommandText = 'Sample Command: '.grey
sampleCommandCmd = sampleCommandText + 'GET'.underline.green + ' ' + 'email'.underline.blue + ' ' + '{"email": "<EMAIL>"}\n'.underline.magenta
samplecCommandExplanation = "The above command is divided into 3 parts: HTTP Verb, name of API call and JSON payload to make request. JSON payload requires valid JSON format as defined by http://www.json.org/ \n".cyan
otherCommands = "Other Commands: ".cyan + "help | exit | version | history (will be added soon)".blue
log sampleCommandCmd + samplecCommandExplanation + otherCommands
return
_apiRequest: (verb, action, payload, callback) ->
validVerbs = ["GET", "POST", "DELETE"]
verb = verb.toUpperCase()
verb = "GET" if validVerbs.indexOf(verb) is -1
self = this
action = action.toLowerCase()
error = false
try
json = JSON.parse(payload)
catch err
error = err
if error is false
cb = (response, err) ->
response = JSON.stringify(response, null, '\t')
#log payload.blue
if err then log response.red else log response.green
self.prompt()
switch verb
when 'GET'
@client.apiGet action, json, cb
when 'POST'
multipart = []
multipart.push 'file' if action is 'job' and json.file
@client.apiPost action, json, cb, multipart
when 'DELETE'
@client.apiDelete action, json, cb
else
log "Error: ".red + error.toString().red
log "Payload: ".red + payload.blue
self.prompt()
return
exports.createSailthruConsole = (options) ->
new SailthruConsole options
| true | readline = require 'readline'
{createSailthruClient} = require 'sailthru-client'
colors = require 'colors'
{log} = require './util'
DEFAULT_URL = 'https://api.sailthru.com'
apiClient = (apiKey, apiSecret, apiUrl) ->
client = createSailthruClient(apiKey, apiSecret, apiUrl)
client.disableLogging()
client
class SailthruConsole
constructor: (options) ->
_apiKey = if options.apiKey then options.apiKey else ""
_apiSecret = if options.apiSecret then options.apiSecret else ""
_apiUrl = if options.apiUrl then options.apiUrl else DEFAULT_URL
@client = apiClient(_apiKey, _apiSecret, _apiUrl)
@welcomeMessage = "***Welcome to CLI for Sailthru API***".cyan
@prefix = if options.prefix then options.prefix else "SAILTHRU> "
initialize: ->
self = this
log @welcomeMessage
@readline = readline.createInterface process.stdin, process.stdout
@readline.on 'line', (cmd) ->
self.parseCommand cmd
@readline.on 'close', ->
process.stdout.write '\n'
process.exit 0
@prompt()
return
prompt: ->
length = @prefix.length
@readline.setPrompt @prefix, length
@readline.prompt()
return
parseCommand: (cmd, callback) ->
cmd = cmd.trim()
if cmd.length == 0
@prompt()
return
splits = cmd.split(" ")
verb = splits[0]
apiCall = if splits[1] then splits[1] else ""
payload = @extractPayload cmd
wait = true
switch cmd
when 'help'
@helpMessage()
wait = false
when 'quit', 'exit'
log 'Bye\n'
process.exit(0)
else
cb = ->
wait = false
return
@_apiRequest(verb, apiCall, payload, cb)
@prompt() if wait is false
return
extractPayload: (cmd) ->
splits = cmd.trim().split(" ")
payload = ''
if splits.length >= 3
payload += value + " " for value, index in splits when index >= 2
return payload.trim()
helpMessage: ->
sampleCommandText = 'Sample Command: '.grey
sampleCommandCmd = sampleCommandText + 'GET'.underline.green + ' ' + 'email'.underline.blue + ' ' + '{"email": "PI:EMAIL:<EMAIL>END_PI"}\n'.underline.magenta
samplecCommandExplanation = "The above command is divided into 3 parts: HTTP Verb, name of API call and JSON payload to make request. JSON payload requires valid JSON format as defined by http://www.json.org/ \n".cyan
otherCommands = "Other Commands: ".cyan + "help | exit | version | history (will be added soon)".blue
log sampleCommandCmd + samplecCommandExplanation + otherCommands
return
_apiRequest: (verb, action, payload, callback) ->
validVerbs = ["GET", "POST", "DELETE"]
verb = verb.toUpperCase()
verb = "GET" if validVerbs.indexOf(verb) is -1
self = this
action = action.toLowerCase()
error = false
try
json = JSON.parse(payload)
catch err
error = err
if error is false
cb = (response, err) ->
response = JSON.stringify(response, null, '\t')
#log payload.blue
if err then log response.red else log response.green
self.prompt()
switch verb
when 'GET'
@client.apiGet action, json, cb
when 'POST'
multipart = []
multipart.push 'file' if action is 'job' and json.file
@client.apiPost action, json, cb, multipart
when 'DELETE'
@client.apiDelete action, json, cb
else
log "Error: ".red + error.toString().red
log "Payload: ".red + payload.blue
self.prompt()
return
exports.createSailthruConsole = (options) ->
new SailthruConsole options
|
[
{
"context": "read source_selector )[ 'id' ]\n count_key = KEY.new_node 'µ', realm, type, 'count'\n registry.get co",
"end": 8686,
"score": 0.96821528673172,
"start": 8674,
"tag": "KEY",
"value": "KEY.new_node"
},
{
"context": "ector )[ 'id' ]\n count_key = KEY.n... | src/scratch/REGISTRY.coffee | loveencounterflow/hollerith1 | 0 |
############################################################################################################
njs_fs = require 'fs'
#...........................................................................................................
TYPES = require 'coffeenode-types'
TRM = require 'coffeenode-trm'
rpr = TRM.rpr.bind TRM
badge = 'TIMETABLE/REGISTRY'
log = TRM.get_logger 'plain', badge
info = TRM.get_logger 'info', badge
whisper = TRM.get_logger 'whisper', badge
alert = TRM.get_logger 'alert', badge
debug = TRM.get_logger 'debug', badge
warn = TRM.get_logger 'warn', badge
help = TRM.get_logger 'help', badge
urge = TRM.get_logger 'urge', badge
echo = TRM.echo.bind TRM
rainbow = TRM.rainbow.bind TRM
#...........................................................................................................
options = require '../options'
indexes = options[ 'data' ][ 'indexes' ]
new_db = require 'level'
#...........................................................................................................
ASYNC = require 'async'
#...........................................................................................................
P = require 'pipedreams'
# pimp_stream = P.create_readstream.pimp
$ = P.$.bind P
KEY = require './KEY'
#-----------------------------------------------------------------------------------------------------------
test_folder_exists = ( route ) ->
return false unless njs_fs.existsSync route
is_folder = ( njs_fs.statSync route ).isDirectory()
throw new Error "route exists but is not a folder: #{route}" unless is_folder
return true
#-----------------------------------------------------------------------------------------------------------
@new_registry = ( route ) ->
route ?= options[ 'levelup' ][ 'route' ]
return new_db route, options[ 'levelup' ][ 'new' ]
#-----------------------------------------------------------------------------------------------------------
@_new_registry = ( route ) ->
route ?= options[ 'levelup' ][ 'route' ]
folder_exists = test_folder_exists route
registry = @new_registry route
return [ folder_exists, registry, ]
#-----------------------------------------------------------------------------------------------------------
@close = ( registry, handler ) ->
registry.close ( error ) =>
help 'registry closed'
handler error
#-----------------------------------------------------------------------------------------------------------
@flush = ( registry, handler ) ->
registry.close ( error ) =>
return handler error if error?
registry.open ( error ) =>
help 'registry flushed'
handler error, registry
#-----------------------------------------------------------------------------------------------------------
@register = ( registry, record, handler ) ->
id = record[ 'id' ]
unless id?
throw new Error """
unable to register record without ID:
#{rpr record}"""
### Records whose only attribute is the ID field are replaced by `1`: ###
value = if ( Object.keys record ).length is 1 then 1 else record
registry.put id, value, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@$register = ( registry ) ->
return $ ( record, handler ) =>
@register registry, record, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@register_2 = ( registry, record, handler ) ->
### TAINT kludge, change to using strings as records ###
id = record[ 'id' ]
unless id?
throw new Error """
unable to register record without ID:
#{rpr record}"""
#.........................................................................................................
meta_value = '1'
entries = []
### TAINT kludge, must be changed in GTFS reader ###
[ realm, type, idn, ] = id.split '/'
route = KEY.new_route realm, type
key = KEY.new_node realm, type, idn
entries.push [ key, JSON.stringify record, ]
#.........................................................................................................
for name, value of record
### TAINT make configurable ###
continue if name is 'id'
continue if name is 'gtfs-id'
continue if name is 'gtfs-type'
facet_route = KEY.new_route realm, type, name
#.....................................................................................................
if ( has_index = indexes[ 'direct' ]?[ 'facet' ] )?
has_primary = has_index[ 'primary' ]?[ facet_route ] ? false
has_secondary = has_index[ 'secondary' ]?[ facet_route ] ? false
if has_primary or has_secondary
if has_primary
key = KEY.new_facet realm, type, idn, name, value
entries.push [ key, meta_value, ]
if has_secondary
key = KEY.new_secondary_facet realm, type, idn, name, value
entries.push [ key, meta_value, ]
#.....................................................................................................
if ( has_index = indexes[ 'direct' ]?[ 'link' ] )?
has_primary = has_index[ 'primary' ]?[ facet_route ] ? false
has_secondary = has_index[ 'secondary' ]?[ facet_route ] ? false
if has_primary or has_secondary
### TAINT inefficiently first splitting, then joining ###
id_1 = value
[ realm_1, type_1, idn_1, ] = KEY.split_id id_1
if has_primary
key = KEY.new_link realm, type, idn, realm_1, type_1, idn_1, 0
entries.push [ key, meta_value, ]
if has_secondary
key = KEY.new_secondary_link realm, type, idn, realm_1, type_1, idn_1, 0
entries.push [ key, meta_value, ]
#.........................................................................................................
tasks = ( { type: 'put', key: key, value: value } for [ key, value, ] in entries )
registry.batch tasks, ( error ) =>
handler if error? then error else null
#-----------------------------------------------------------------------------------------------------------
@$register_2 = ( registry ) ->
return $ ( record, handler ) =>
@register_2 registry, record, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@$count = ( registry, realm, type ) ->
count = 0
#.........................................................................................................
on_data = ( record ) ->
count += 1
@emit 'data', record
#.........................................................................................................
on_end = ( record ) ->
key = KEY.new_node 'µ', realm, type, 'count'
# emit = @emit.bind @
registry.put key, count, ( error ) =>
return @emit 'error', error if error?
@emit 'end'
#.........................................................................................................
return P.through on_data, on_end
#===========================================================================================================
# INFERRED PROPERTIES
#-----------------------------------------------------------------------------------------------------------
@register_inferred_properties = ( registry, handler ) ->
count = 0
for entry_type, type_index of indexes[ 'inferred' ]
for level, level_index of type_index
for compound_selector in level_index
[ source_selector
target_facet_names... ] = KEY.split_compound_selector compound_selector
unless target_facet_names.length is 1
warn "multiple target names are not yet implemented"
continue
target_facet_name = target_facet_names[ 0 ]
[ realm, type, ] = KEY.split_id ( KEY.read source_selector )[ 'id' ]
count_key = KEY.new_node 'µ', realm, type, 'count'
registry.get count_key, ( error, count ) =>
return handler error if error?
debug count_key, count
input = @_rdp_key_stream_from_prefix registry, source_selector
P.pimp_readstream input, count, "#{realm}/#{type}|"
.pipe @$_rdp_proxy_from_source()
.pipe @$_rdp_add_target_key level, entry_type, target_facet_name
.pipe P.$pick 'target-key'
.pipe $ ( target_key, handler ) -> handler null, key: target_key, value: '1'
.pipe P.duplex registry.createWriteStream(), input
# .pipe P.$sample 1 / 1e3
# .pipe P.$show()
.on 'end', -> return handler null
#-----------------------------------------------------------------------------------------------------------
### TAINT code duplication ###
### TAINT wrong place for method ###
@_rdp_read_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createReadStream query
#-----------------------------------------------------------------------------------------------------------
@_rdp_key_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createKeyStream query
#-----------------------------------------------------------------------------------------------------------
@_rdp_value_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createValueStream query
#-----------------------------------------------------------------------------------------------------------
@$_rdp_proxy_from_source = ->
return $ ( source_key, handler ) =>
### TAINT specific to links ###
Z =
'source-entry': source_entry = KEY.read source_key
'source-node-id': source_entry[ 'id' ]
'proxy-node-id': source_entry[ 'target' ]
### TAINT inefficiently splitting and joining key ###
[ Z[ 'source-realm' ]
Z[ 'source-type' ]
Z[ 'source-idn' ] ] = KEY.split_id Z[ 'source-node-id' ]
### TAINT inefficiently splitting and joining key ###
[ Z[ 'proxy-realm' ]
Z[ 'proxy-type' ]
Z[ 'proxy-idn' ] ] = KEY.split_id Z[ 'proxy-node-id' ]
Z[ 'proxy-node-key' ] = KEY.new_node Z[ 'proxy-realm' ], Z[ 'proxy-type' ], Z[ 'proxy-idn' ]
#.......................................................................................................
registry.get Z[ 'proxy-node-key' ], ( error, proxy_node ) =>
return handler error if error?
### TAINT why is this not done automatically? ###
Z[ 'proxy-node' ] = JSON.parse proxy_node
handler null, Z
#-----------------------------------------------------------------------------------------------------------
@$_rdp_add_target_key = ( level, entry_type, target_facet_name ) ->
return $ ( proxy_info, handler ) =>
proxy_node = proxy_info[ 'proxy-node' ]
target_value = proxy_node[ target_facet_name ]
### TAINT kludge ###
unless target_value?
return handler new Error "facet #{rpr target_facet_name} not defined in #{rpr target_node}"
# help rpr source_entry
# debug rpr proxy_node
# proxy_info target_facet_name, target_value
# proxy_info source_realm, source_type, source_idn
#.......................................................................................................
switch level
when 'secondary'
switch entry_type
when 'link'
### TAINT inefficiently splitting and joining key ###
[ target_realm
target_type
target_idn ] = KEY.split_id target_value
distance = proxy_info[ 'source-entry' ][ 'distance' ] + 1
target_key = KEY.new_secondary_link proxy_info[ 'source-realm' ],
proxy_info[ 'source-type' ],
proxy_info[ 'source-idn' ],
target_realm,
target_type,
target_idn,
distance
# registry.put key, '1', ( error ) =>
# return handler error if error?
# whisper count if count % 1000 is 0
# count += 1
else
return handler new Error "not implemented"
else
return handler new Error "not implemented"
#.......................................................................................................
proxy_info[ 'target-key' ] = target_key
handler null, proxy_info
# #-----------------------------------------------------------------------------------------------------------
# f = ->
# x
# .on 'data', ( source_key ) =>
# # [ target_realm, target_type, target_idn ] = KEY.split_id ( KEY.read source_key )[ 'target' ]
# # target_node_key = KEY.new_node target_realm, target_type, target_idn
# # registry.put
# .on 'error', ( error ) -> return handler error
# .on 'end', -> return handler null
############################################################################################################
unless module.parent?
registry = @new_registry()
@register_inferred_properties registry, ( error, data ) ->
throw error if error?
help data
| 208735 |
############################################################################################################
njs_fs = require 'fs'
#...........................................................................................................
TYPES = require 'coffeenode-types'
TRM = require 'coffeenode-trm'
rpr = TRM.rpr.bind TRM
badge = 'TIMETABLE/REGISTRY'
log = TRM.get_logger 'plain', badge
info = TRM.get_logger 'info', badge
whisper = TRM.get_logger 'whisper', badge
alert = TRM.get_logger 'alert', badge
debug = TRM.get_logger 'debug', badge
warn = TRM.get_logger 'warn', badge
help = TRM.get_logger 'help', badge
urge = TRM.get_logger 'urge', badge
echo = TRM.echo.bind TRM
rainbow = TRM.rainbow.bind TRM
#...........................................................................................................
options = require '../options'
indexes = options[ 'data' ][ 'indexes' ]
new_db = require 'level'
#...........................................................................................................
ASYNC = require 'async'
#...........................................................................................................
P = require 'pipedreams'
# pimp_stream = P.create_readstream.pimp
$ = P.$.bind P
KEY = require './KEY'
#-----------------------------------------------------------------------------------------------------------
test_folder_exists = ( route ) ->
return false unless njs_fs.existsSync route
is_folder = ( njs_fs.statSync route ).isDirectory()
throw new Error "route exists but is not a folder: #{route}" unless is_folder
return true
#-----------------------------------------------------------------------------------------------------------
@new_registry = ( route ) ->
route ?= options[ 'levelup' ][ 'route' ]
return new_db route, options[ 'levelup' ][ 'new' ]
#-----------------------------------------------------------------------------------------------------------
@_new_registry = ( route ) ->
route ?= options[ 'levelup' ][ 'route' ]
folder_exists = test_folder_exists route
registry = @new_registry route
return [ folder_exists, registry, ]
#-----------------------------------------------------------------------------------------------------------
@close = ( registry, handler ) ->
registry.close ( error ) =>
help 'registry closed'
handler error
#-----------------------------------------------------------------------------------------------------------
@flush = ( registry, handler ) ->
registry.close ( error ) =>
return handler error if error?
registry.open ( error ) =>
help 'registry flushed'
handler error, registry
#-----------------------------------------------------------------------------------------------------------
@register = ( registry, record, handler ) ->
id = record[ 'id' ]
unless id?
throw new Error """
unable to register record without ID:
#{rpr record}"""
### Records whose only attribute is the ID field are replaced by `1`: ###
value = if ( Object.keys record ).length is 1 then 1 else record
registry.put id, value, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@$register = ( registry ) ->
return $ ( record, handler ) =>
@register registry, record, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@register_2 = ( registry, record, handler ) ->
### TAINT kludge, change to using strings as records ###
id = record[ 'id' ]
unless id?
throw new Error """
unable to register record without ID:
#{rpr record}"""
#.........................................................................................................
meta_value = '1'
entries = []
### TAINT kludge, must be changed in GTFS reader ###
[ realm, type, idn, ] = id.split '/'
route = KEY.new_route realm, type
key = KEY.new_node realm, type, idn
entries.push [ key, JSON.stringify record, ]
#.........................................................................................................
for name, value of record
### TAINT make configurable ###
continue if name is 'id'
continue if name is 'gtfs-id'
continue if name is 'gtfs-type'
facet_route = KEY.new_route realm, type, name
#.....................................................................................................
if ( has_index = indexes[ 'direct' ]?[ 'facet' ] )?
has_primary = has_index[ 'primary' ]?[ facet_route ] ? false
has_secondary = has_index[ 'secondary' ]?[ facet_route ] ? false
if has_primary or has_secondary
if has_primary
key = KEY.new_facet realm, type, idn, name, value
entries.push [ key, meta_value, ]
if has_secondary
key = KEY.new_secondary_facet realm, type, idn, name, value
entries.push [ key, meta_value, ]
#.....................................................................................................
if ( has_index = indexes[ 'direct' ]?[ 'link' ] )?
has_primary = has_index[ 'primary' ]?[ facet_route ] ? false
has_secondary = has_index[ 'secondary' ]?[ facet_route ] ? false
if has_primary or has_secondary
### TAINT inefficiently first splitting, then joining ###
id_1 = value
[ realm_1, type_1, idn_1, ] = KEY.split_id id_1
if has_primary
key = KEY.new_link realm, type, idn, realm_1, type_1, idn_1, 0
entries.push [ key, meta_value, ]
if has_secondary
key = KEY.new_secondary_link realm, type, idn, realm_1, type_1, idn_1, 0
entries.push [ key, meta_value, ]
#.........................................................................................................
tasks = ( { type: 'put', key: key, value: value } for [ key, value, ] in entries )
registry.batch tasks, ( error ) =>
handler if error? then error else null
#-----------------------------------------------------------------------------------------------------------
@$register_2 = ( registry ) ->
return $ ( record, handler ) =>
@register_2 registry, record, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@$count = ( registry, realm, type ) ->
count = 0
#.........................................................................................................
on_data = ( record ) ->
count += 1
@emit 'data', record
#.........................................................................................................
on_end = ( record ) ->
key = KEY.new_node 'µ', realm, type, 'count'
# emit = @emit.bind @
registry.put key, count, ( error ) =>
return @emit 'error', error if error?
@emit 'end'
#.........................................................................................................
return P.through on_data, on_end
#===========================================================================================================
# INFERRED PROPERTIES
#-----------------------------------------------------------------------------------------------------------
@register_inferred_properties = ( registry, handler ) ->
count = 0
for entry_type, type_index of indexes[ 'inferred' ]
for level, level_index of type_index
for compound_selector in level_index
[ source_selector
target_facet_names... ] = KEY.split_compound_selector compound_selector
unless target_facet_names.length is 1
warn "multiple target names are not yet implemented"
continue
target_facet_name = target_facet_names[ 0 ]
[ realm, type, ] = KEY.split_id ( KEY.read source_selector )[ 'id' ]
count_key = <KEY> '<KEY>', realm, type, 'count'
registry.get count_key, ( error, count ) =>
return handler error if error?
debug count_key, count
input = @_rdp_key_stream_from_prefix registry, source_selector
P.pimp_readstream input, count, "#{realm}/#{type}|"
.pipe @$_rdp_proxy_from_source()
.pipe @$_rdp_add_target_key level, entry_type, target_facet_name
.pipe P.$pick 'target-key'
.pipe $ ( target_key, handler ) -> handler null, key: target_key, value: '1'
.pipe P.duplex registry.createWriteStream(), input
# .pipe P.$sample 1 / 1e3
# .pipe P.$show()
.on 'end', -> return handler null
#-----------------------------------------------------------------------------------------------------------
### TAINT code duplication ###
### TAINT wrong place for method ###
@_rdp_read_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createReadStream query
#-----------------------------------------------------------------------------------------------------------
@_rdp_key_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createKeyStream query
#-----------------------------------------------------------------------------------------------------------
@_rdp_value_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createValueStream query
#-----------------------------------------------------------------------------------------------------------
@$_rdp_proxy_from_source = ->
return $ ( source_key, handler ) =>
### TAINT specific to links ###
Z =
'source-entry': source_entry = KEY.read source_key
'source-node-id': source_entry[ 'id' ]
'proxy-node-id': source_entry[ 'target' ]
### TAINT inefficiently splitting and joining key ###
[ Z[ 'source-realm' ]
Z[ 'source-type' ]
Z[ 'source-idn' ] ] = KEY.split_id Z[ 'source-node-id' ]
### TAINT inefficiently splitting and joining key ###
[ Z[ 'proxy-realm' ]
Z[ 'proxy-type' ]
Z[ 'proxy-idn' ] ] = KEY.split_id Z[ 'proxy-node-id' ]
Z[ 'proxy-node-key' ] = KEY.new_node Z[ 'proxy-realm' ], Z[ 'proxy-type' ], Z[ 'proxy-idn' ]
#.......................................................................................................
registry.get Z[ 'proxy-node-key' ], ( error, proxy_node ) =>
return handler error if error?
### TAINT why is this not done automatically? ###
Z[ 'proxy-node' ] = JSON.parse proxy_node
handler null, Z
#-----------------------------------------------------------------------------------------------------------
@$_rdp_add_target_key = ( level, entry_type, target_facet_name ) ->
return $ ( proxy_info, handler ) =>
proxy_node = proxy_info[ 'proxy-node' ]
target_value = proxy_node[ target_facet_name ]
### TAINT kludge ###
unless target_value?
return handler new Error "facet #{rpr target_facet_name} not defined in #{rpr target_node}"
# help rpr source_entry
# debug rpr proxy_node
# proxy_info target_facet_name, target_value
# proxy_info source_realm, source_type, source_idn
#.......................................................................................................
switch level
when 'secondary'
switch entry_type
when 'link'
### TAINT inefficiently splitting and joining key ###
[ target_realm
target_type
target_idn ] = KEY.split_id target_value
distance = proxy_info[ 'source-entry' ][ 'distance' ] + 1
target_key = KEY.new_secondary_link proxy_info[ 'source-realm' ],
proxy_info[ 'source-type' ],
proxy_info[ 'source-idn' ],
target_realm,
target_type,
target_idn,
distance
# registry.put key, '1', ( error ) =>
# return handler error if error?
# whisper count if count % 1000 is 0
# count += 1
else
return handler new Error "not implemented"
else
return handler new Error "not implemented"
#.......................................................................................................
proxy_info[ 'target-key' ] = target_key
handler null, proxy_info
# #-----------------------------------------------------------------------------------------------------------
# f = ->
# x
# .on 'data', ( source_key ) =>
# # [ target_realm, target_type, target_idn ] = KEY.split_id ( KEY.read source_key )[ 'target' ]
# # target_node_key = KEY.new_node target_realm, target_type, target_idn
# # registry.put
# .on 'error', ( error ) -> return handler error
# .on 'end', -> return handler null
############################################################################################################
unless module.parent?
registry = @new_registry()
@register_inferred_properties registry, ( error, data ) ->
throw error if error?
help data
| true |
############################################################################################################
njs_fs = require 'fs'
#...........................................................................................................
TYPES = require 'coffeenode-types'
TRM = require 'coffeenode-trm'
rpr = TRM.rpr.bind TRM
badge = 'TIMETABLE/REGISTRY'
log = TRM.get_logger 'plain', badge
info = TRM.get_logger 'info', badge
whisper = TRM.get_logger 'whisper', badge
alert = TRM.get_logger 'alert', badge
debug = TRM.get_logger 'debug', badge
warn = TRM.get_logger 'warn', badge
help = TRM.get_logger 'help', badge
urge = TRM.get_logger 'urge', badge
echo = TRM.echo.bind TRM
rainbow = TRM.rainbow.bind TRM
#...........................................................................................................
options = require '../options'
indexes = options[ 'data' ][ 'indexes' ]
new_db = require 'level'
#...........................................................................................................
ASYNC = require 'async'
#...........................................................................................................
P = require 'pipedreams'
# pimp_stream = P.create_readstream.pimp
$ = P.$.bind P
KEY = require './KEY'
#-----------------------------------------------------------------------------------------------------------
test_folder_exists = ( route ) ->
return false unless njs_fs.existsSync route
is_folder = ( njs_fs.statSync route ).isDirectory()
throw new Error "route exists but is not a folder: #{route}" unless is_folder
return true
#-----------------------------------------------------------------------------------------------------------
@new_registry = ( route ) ->
route ?= options[ 'levelup' ][ 'route' ]
return new_db route, options[ 'levelup' ][ 'new' ]
#-----------------------------------------------------------------------------------------------------------
@_new_registry = ( route ) ->
route ?= options[ 'levelup' ][ 'route' ]
folder_exists = test_folder_exists route
registry = @new_registry route
return [ folder_exists, registry, ]
#-----------------------------------------------------------------------------------------------------------
@close = ( registry, handler ) ->
registry.close ( error ) =>
help 'registry closed'
handler error
#-----------------------------------------------------------------------------------------------------------
@flush = ( registry, handler ) ->
registry.close ( error ) =>
return handler error if error?
registry.open ( error ) =>
help 'registry flushed'
handler error, registry
#-----------------------------------------------------------------------------------------------------------
@register = ( registry, record, handler ) ->
id = record[ 'id' ]
unless id?
throw new Error """
unable to register record without ID:
#{rpr record}"""
### Records whose only attribute is the ID field are replaced by `1`: ###
value = if ( Object.keys record ).length is 1 then 1 else record
registry.put id, value, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@$register = ( registry ) ->
return $ ( record, handler ) =>
@register registry, record, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@register_2 = ( registry, record, handler ) ->
### TAINT kludge, change to using strings as records ###
id = record[ 'id' ]
unless id?
throw new Error """
unable to register record without ID:
#{rpr record}"""
#.........................................................................................................
meta_value = '1'
entries = []
### TAINT kludge, must be changed in GTFS reader ###
[ realm, type, idn, ] = id.split '/'
route = KEY.new_route realm, type
key = KEY.new_node realm, type, idn
entries.push [ key, JSON.stringify record, ]
#.........................................................................................................
for name, value of record
### TAINT make configurable ###
continue if name is 'id'
continue if name is 'gtfs-id'
continue if name is 'gtfs-type'
facet_route = KEY.new_route realm, type, name
#.....................................................................................................
if ( has_index = indexes[ 'direct' ]?[ 'facet' ] )?
has_primary = has_index[ 'primary' ]?[ facet_route ] ? false
has_secondary = has_index[ 'secondary' ]?[ facet_route ] ? false
if has_primary or has_secondary
if has_primary
key = KEY.new_facet realm, type, idn, name, value
entries.push [ key, meta_value, ]
if has_secondary
key = KEY.new_secondary_facet realm, type, idn, name, value
entries.push [ key, meta_value, ]
#.....................................................................................................
if ( has_index = indexes[ 'direct' ]?[ 'link' ] )?
has_primary = has_index[ 'primary' ]?[ facet_route ] ? false
has_secondary = has_index[ 'secondary' ]?[ facet_route ] ? false
if has_primary or has_secondary
### TAINT inefficiently first splitting, then joining ###
id_1 = value
[ realm_1, type_1, idn_1, ] = KEY.split_id id_1
if has_primary
key = KEY.new_link realm, type, idn, realm_1, type_1, idn_1, 0
entries.push [ key, meta_value, ]
if has_secondary
key = KEY.new_secondary_link realm, type, idn, realm_1, type_1, idn_1, 0
entries.push [ key, meta_value, ]
#.........................................................................................................
tasks = ( { type: 'put', key: key, value: value } for [ key, value, ] in entries )
registry.batch tasks, ( error ) =>
handler if error? then error else null
#-----------------------------------------------------------------------------------------------------------
@$register_2 = ( registry ) ->
return $ ( record, handler ) =>
@register_2 registry, record, ( error ) =>
return handler error if error?
handler null, record
#-----------------------------------------------------------------------------------------------------------
@$count = ( registry, realm, type ) ->
count = 0
#.........................................................................................................
on_data = ( record ) ->
count += 1
@emit 'data', record
#.........................................................................................................
on_end = ( record ) ->
key = KEY.new_node 'µ', realm, type, 'count'
# emit = @emit.bind @
registry.put key, count, ( error ) =>
return @emit 'error', error if error?
@emit 'end'
#.........................................................................................................
return P.through on_data, on_end
#===========================================================================================================
# INFERRED PROPERTIES
#-----------------------------------------------------------------------------------------------------------
@register_inferred_properties = ( registry, handler ) ->
count = 0
for entry_type, type_index of indexes[ 'inferred' ]
for level, level_index of type_index
for compound_selector in level_index
[ source_selector
target_facet_names... ] = KEY.split_compound_selector compound_selector
unless target_facet_names.length is 1
warn "multiple target names are not yet implemented"
continue
target_facet_name = target_facet_names[ 0 ]
[ realm, type, ] = KEY.split_id ( KEY.read source_selector )[ 'id' ]
count_key = PI:KEY:<KEY>END_PI 'PI:KEY:<KEY>END_PI', realm, type, 'count'
registry.get count_key, ( error, count ) =>
return handler error if error?
debug count_key, count
input = @_rdp_key_stream_from_prefix registry, source_selector
P.pimp_readstream input, count, "#{realm}/#{type}|"
.pipe @$_rdp_proxy_from_source()
.pipe @$_rdp_add_target_key level, entry_type, target_facet_name
.pipe P.$pick 'target-key'
.pipe $ ( target_key, handler ) -> handler null, key: target_key, value: '1'
.pipe P.duplex registry.createWriteStream(), input
# .pipe P.$sample 1 / 1e3
# .pipe P.$show()
.on 'end', -> return handler null
#-----------------------------------------------------------------------------------------------------------
### TAINT code duplication ###
### TAINT wrong place for method ###
@_rdp_read_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createReadStream query
#-----------------------------------------------------------------------------------------------------------
@_rdp_key_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createKeyStream query
#-----------------------------------------------------------------------------------------------------------
@_rdp_value_stream_from_prefix = ( registry, prefix ) ->
query =
gte: prefix
lte: KEY.lte_from_gte prefix
return registry.createValueStream query
#-----------------------------------------------------------------------------------------------------------
@$_rdp_proxy_from_source = ->
return $ ( source_key, handler ) =>
### TAINT specific to links ###
Z =
'source-entry': source_entry = KEY.read source_key
'source-node-id': source_entry[ 'id' ]
'proxy-node-id': source_entry[ 'target' ]
### TAINT inefficiently splitting and joining key ###
[ Z[ 'source-realm' ]
Z[ 'source-type' ]
Z[ 'source-idn' ] ] = KEY.split_id Z[ 'source-node-id' ]
### TAINT inefficiently splitting and joining key ###
[ Z[ 'proxy-realm' ]
Z[ 'proxy-type' ]
Z[ 'proxy-idn' ] ] = KEY.split_id Z[ 'proxy-node-id' ]
Z[ 'proxy-node-key' ] = KEY.new_node Z[ 'proxy-realm' ], Z[ 'proxy-type' ], Z[ 'proxy-idn' ]
#.......................................................................................................
registry.get Z[ 'proxy-node-key' ], ( error, proxy_node ) =>
return handler error if error?
### TAINT why is this not done automatically? ###
Z[ 'proxy-node' ] = JSON.parse proxy_node
handler null, Z
#-----------------------------------------------------------------------------------------------------------
@$_rdp_add_target_key = ( level, entry_type, target_facet_name ) ->
return $ ( proxy_info, handler ) =>
proxy_node = proxy_info[ 'proxy-node' ]
target_value = proxy_node[ target_facet_name ]
### TAINT kludge ###
unless target_value?
return handler new Error "facet #{rpr target_facet_name} not defined in #{rpr target_node}"
# help rpr source_entry
# debug rpr proxy_node
# proxy_info target_facet_name, target_value
# proxy_info source_realm, source_type, source_idn
#.......................................................................................................
switch level
when 'secondary'
switch entry_type
when 'link'
### TAINT inefficiently splitting and joining key ###
[ target_realm
target_type
target_idn ] = KEY.split_id target_value
distance = proxy_info[ 'source-entry' ][ 'distance' ] + 1
target_key = KEY.new_secondary_link proxy_info[ 'source-realm' ],
proxy_info[ 'source-type' ],
proxy_info[ 'source-idn' ],
target_realm,
target_type,
target_idn,
distance
# registry.put key, '1', ( error ) =>
# return handler error if error?
# whisper count if count % 1000 is 0
# count += 1
else
return handler new Error "not implemented"
else
return handler new Error "not implemented"
#.......................................................................................................
proxy_info[ 'target-key' ] = target_key
handler null, proxy_info
# #-----------------------------------------------------------------------------------------------------------
# f = ->
# x
# .on 'data', ( source_key ) =>
# # [ target_realm, target_type, target_idn ] = KEY.split_id ( KEY.read source_key )[ 'target' ]
# # target_node_key = KEY.new_node target_realm, target_type, target_idn
# # registry.put
# .on 'error', ( error ) -> return handler error
# .on 'end', -> return handler null
############################################################################################################
unless module.parent?
registry = @new_registry()
@register_inferred_properties registry, ( error, data ) ->
throw error if error?
help data
|
[
{
"context": " = require('../../config').config\n\nCHANNEL_KEY = 'OrderXmlFileExport'\nROLE_ORDER_EXPORT = 'OrderExport'\nROLE_INVENTORY",
"end": 231,
"score": 0.9988433718681335,
"start": 213,
"tag": "KEY",
"value": "OrderXmlFileExport"
},
{
"context": "ole and return it', (done) ->... | src/spec/integration/channels.spec.coffee | commercetools/sphere-node-sdk | 13 | debug = require('debug')('spec-integration:channels')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
{SphereClient} = require '../../lib/main'
Config = require('../../config').config
CHANNEL_KEY = 'OrderXmlFileExport'
ROLE_ORDER_EXPORT = 'OrderExport'
ROLE_INVENTORY_SUPPLY = 'InventorySupply'
ROLE_PRIMARY = 'Primary'
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
# 'InventorySupply' is provided by default
newChannel = ->
key: uniqueId 'c'
updateChannel = (version) ->
version: version
actions: [
{action: 'changeName', name: {en: 'A Channel'}}
{action: 'changeDescription', description: {en: 'This is a Channel'}}
{action: 'setRoles', roles: [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT]}
]
describe 'Integration Channels', ->
channels = []
beforeEach (done) ->
@client = new SphereClient
config: Config
stats:
includeHeaders: true
@client.channels.save(newChannel())
.then (result) =>
expect(result.statusCode).toBe 201
expect(result.http.response.headers['x-correlation-id']).toBeDefined()
@channelId = result.body.id
debug 'New channel created: %j', result.body
done()
.catch (error) -> done _.prettify(error)
afterEach (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.byId(@channelId).delete(result.body.version)
.then (result) =>
debug "Channel deleted: #{@channelId}"
expect(result.statusCode).toBe 200
done()
.catch (error) -> done _.prettify(error)
it 'should update a channel', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.byId(@channelId).update(updateChannel(result.body.version))
.then (result) ->
expect(result.statusCode).toBe 200
expect(result.body.name).toEqual {en: 'A Channel'}
expect(result.body.description).toEqual {en: 'This is a Channel'}
expect(result.body.roles).toEqual [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT]
done()
.catch (error) -> done _.prettify(error)
it 'should create a new channel with given role and return it', (done) ->
key = uniqueId "channel"
@client.channels.ensure(key, ROLE_ORDER_EXPORT)
.then (result) ->
expect(result.body).toBeDefined()
expect(result.body.key).toEqual key
expect(result.body.roles).toEqual [ROLE_ORDER_EXPORT]
done()
.catch (error) -> done _.prettify(error)
it 'should fetch an existing channel, add given role and return it', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.ensure(result.body.key, ROLE_ORDER_EXPORT)
.then (result) =>
@client.channels.ensure(result.body.key, ROLE_PRIMARY)
.then (result) ->
expect(result.body.roles).toEqual [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT, ROLE_PRIMARY]
done()
.catch (error) -> done _.prettify(error)
, 10000 # 10sec
it 'should fail if role value is not supported', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.ensure(result.body.key, 'undefined-role')
.then (result) ->
done 'Role value not supported.'
.catch (error) ->
expect(error).toBeDefined()
done()
it 'should have \'x-correlation-id\' header when request fails', (done) ->
@client.channels.save({})
.then (result) ->
done('Should have failed')
.catch (error) ->
expect(error.body.http.response.headers['x-correlation-id']).toBeDefined()
done()
| 129696 | debug = require('debug')('spec-integration:channels')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
{SphereClient} = require '../../lib/main'
Config = require('../../config').config
CHANNEL_KEY = '<KEY>'
ROLE_ORDER_EXPORT = 'OrderExport'
ROLE_INVENTORY_SUPPLY = 'InventorySupply'
ROLE_PRIMARY = 'Primary'
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
# 'InventorySupply' is provided by default
newChannel = ->
key: uniqueId 'c'
updateChannel = (version) ->
version: version
actions: [
{action: 'changeName', name: {en: 'A Channel'}}
{action: 'changeDescription', description: {en: 'This is a Channel'}}
{action: 'setRoles', roles: [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT]}
]
describe 'Integration Channels', ->
channels = []
beforeEach (done) ->
@client = new SphereClient
config: Config
stats:
includeHeaders: true
@client.channels.save(newChannel())
.then (result) =>
expect(result.statusCode).toBe 201
expect(result.http.response.headers['x-correlation-id']).toBeDefined()
@channelId = result.body.id
debug 'New channel created: %j', result.body
done()
.catch (error) -> done _.prettify(error)
afterEach (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.byId(@channelId).delete(result.body.version)
.then (result) =>
debug "Channel deleted: #{@channelId}"
expect(result.statusCode).toBe 200
done()
.catch (error) -> done _.prettify(error)
it 'should update a channel', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.byId(@channelId).update(updateChannel(result.body.version))
.then (result) ->
expect(result.statusCode).toBe 200
expect(result.body.name).toEqual {en: 'A Channel'}
expect(result.body.description).toEqual {en: 'This is a Channel'}
expect(result.body.roles).toEqual [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT]
done()
.catch (error) -> done _.prettify(error)
it 'should create a new channel with given role and return it', (done) ->
key = uniqueId "<KEY>"
@client.channels.ensure(key, ROLE_ORDER_EXPORT)
.then (result) ->
expect(result.body).toBeDefined()
expect(result.body.key).toEqual key
expect(result.body.roles).toEqual [ROLE_ORDER_EXPORT]
done()
.catch (error) -> done _.prettify(error)
it 'should fetch an existing channel, add given role and return it', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.ensure(result.body.key, ROLE_ORDER_EXPORT)
.then (result) =>
@client.channels.ensure(result.body.key, ROLE_PRIMARY)
.then (result) ->
expect(result.body.roles).toEqual [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT, ROLE_PRIMARY]
done()
.catch (error) -> done _.prettify(error)
, 10000 # 10sec
it 'should fail if role value is not supported', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.ensure(result.body.key, 'undefined-role')
.then (result) ->
done 'Role value not supported.'
.catch (error) ->
expect(error).toBeDefined()
done()
it 'should have \'x-correlation-id\' header when request fails', (done) ->
@client.channels.save({})
.then (result) ->
done('Should have failed')
.catch (error) ->
expect(error.body.http.response.headers['x-correlation-id']).toBeDefined()
done()
| true | debug = require('debug')('spec-integration:channels')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
{SphereClient} = require '../../lib/main'
Config = require('../../config').config
CHANNEL_KEY = 'PI:KEY:<KEY>END_PI'
ROLE_ORDER_EXPORT = 'OrderExport'
ROLE_INVENTORY_SUPPLY = 'InventorySupply'
ROLE_PRIMARY = 'Primary'
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
# 'InventorySupply' is provided by default
newChannel = ->
key: uniqueId 'c'
updateChannel = (version) ->
version: version
actions: [
{action: 'changeName', name: {en: 'A Channel'}}
{action: 'changeDescription', description: {en: 'This is a Channel'}}
{action: 'setRoles', roles: [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT]}
]
describe 'Integration Channels', ->
channels = []
beforeEach (done) ->
@client = new SphereClient
config: Config
stats:
includeHeaders: true
@client.channels.save(newChannel())
.then (result) =>
expect(result.statusCode).toBe 201
expect(result.http.response.headers['x-correlation-id']).toBeDefined()
@channelId = result.body.id
debug 'New channel created: %j', result.body
done()
.catch (error) -> done _.prettify(error)
afterEach (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.byId(@channelId).delete(result.body.version)
.then (result) =>
debug "Channel deleted: #{@channelId}"
expect(result.statusCode).toBe 200
done()
.catch (error) -> done _.prettify(error)
it 'should update a channel', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.byId(@channelId).update(updateChannel(result.body.version))
.then (result) ->
expect(result.statusCode).toBe 200
expect(result.body.name).toEqual {en: 'A Channel'}
expect(result.body.description).toEqual {en: 'This is a Channel'}
expect(result.body.roles).toEqual [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT]
done()
.catch (error) -> done _.prettify(error)
it 'should create a new channel with given role and return it', (done) ->
key = uniqueId "PI:KEY:<KEY>END_PI"
@client.channels.ensure(key, ROLE_ORDER_EXPORT)
.then (result) ->
expect(result.body).toBeDefined()
expect(result.body.key).toEqual key
expect(result.body.roles).toEqual [ROLE_ORDER_EXPORT]
done()
.catch (error) -> done _.prettify(error)
it 'should fetch an existing channel, add given role and return it', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.ensure(result.body.key, ROLE_ORDER_EXPORT)
.then (result) =>
@client.channels.ensure(result.body.key, ROLE_PRIMARY)
.then (result) ->
expect(result.body.roles).toEqual [ROLE_INVENTORY_SUPPLY, ROLE_ORDER_EXPORT, ROLE_PRIMARY]
done()
.catch (error) -> done _.prettify(error)
, 10000 # 10sec
it 'should fail if role value is not supported', (done) ->
@client.channels.byId(@channelId).fetch()
.then (result) =>
@client.channels.ensure(result.body.key, 'undefined-role')
.then (result) ->
done 'Role value not supported.'
.catch (error) ->
expect(error).toBeDefined()
done()
it 'should have \'x-correlation-id\' header when request fails', (done) ->
@client.channels.save({})
.then (result) ->
done('Should have failed')
.catch (error) ->
expect(error.body.http.response.headers['x-correlation-id']).toBeDefined()
done()
|
[
{
"context": "h: 620\n\theight: 34\n\tbackgroundColor: null\n\thtml: \"joeyqiang@gmail.com\"\n\tstyle:\n\t\ttextAlign: \"center\"\n\t\tfontFamily: \"Rob",
"end": 2775,
"score": 0.9999243021011353,
"start": 2756,
"tag": "EMAIL",
"value": "joeyqiang@gmail.com"
}
] | 10 Framer Animations/Form/Form.framer/app.coffee | JoeyQiang/Framer-Animations-for-10-Mobile-Interaction-Situations | 5 | InputModule = require "input"
# General settings
Utils.insertCSS("@import 'https://fonts.googleapis.com/css?family=Roboto:300,400,700';")
Canvas.backgroundColor = "#303030"
Screen.backgroundColor = "#303030"
Color.main = "#2196f3"
Boxshadow = "0 4px 4px 0 rgba(0, 0, 0, 0.24), 0 0 4px 0 rgba(0, 0, 0, 0.12)"
w = 344 * 2
h = 224 * 2
pageScroller = new PageComponent
point: Align.center
width: Screen.width
height: Screen.height
scrollVertical: false
clip: false
portrait = new Layer
x: Align.center
y: 126 * 2
borderRadius: "50%"
width: 96 * 2
height: 96 * 2
backgroundColor: "#757575"
style:
boxShadow: Boxshadow
portraitOverlay = new Layer
parent: portrait
borderRadius: "50%"
width: 96 * 2
height: 96 * 2
backgroundColor: "#E0E0E0"
portraitOverlay.states =
one:
opacity: 0
scale: 0
animationOptions:
curve: Bezier.easeIn
time: 0.15
two:
opacity: 1
scale: 1
animationOptions:
curve: Bezier.easeIn
time: 0.15
portraitOverlay.stateSwitch("one")
back = new Layer
x: 24 * 2
y: 36 * 2
width: 48
height: 48
image: "images/ic_arrow_back_black_24px.svg"
back.states =
hide:
opacity: 0
show:
opacity: 1
back.stateSwitch("hide")
slideContentOne = new Layer
parent: pageScroller.content
width: Screen.width
height: Screen.height
backgroundColor: null
slideContentTwo = new Layer
width: Screen.width
height: Screen.height
backgroundColor: null
inputEmail = new Layer
parent: slideContentOne
y: 246 * 2
x: Align.center
width: 328 * 2
height: 48 * 2
backgroundColor: null
style:
borderBottom:"solid 2px #2196f3"
inputPasscode = new Layer
parent: slideContentTwo
y: 254 * 2
x: Align.center
width: 328 * 2
height: 48 * 2
backgroundColor: null
style:
borderBottom:"solid 2px #2196f3"
buttonNext = new Layer
parent: slideContentOne
y: 319 * 2
x: Align.center
width: 329 * 2
height: 40 * 2
backgroundColor: Color.main
html: "NEXT"
borderRadius: 4
style:
textAlign: "center"
lineHeight: "80px"
fontSize: "28px"
fontFamily: "Roboto"
letterSpacing: "0.5px"
color: "rgba(255, 255, 255, 0.87)"
buttonNext.states =
up:
style:
backgroundColor: Color.main
down:
shadowY: 3
style:
backgroundColor: "#4fa1e2"
boxShadow: "0 16px 16px 0 rgba(0, 0, 0, 0.24), 0 0 16px 0 rgba(0, 0, 0, 0.12)"
buttonSignUp = new Layer
parent: slideContentTwo
y: 327 * 2
x: Align.center
width: 329 * 2
height: 40 * 2
backgroundColor: Color.main
html: "SIGN UP"
borderRadius: 4
style:
textAlign: "center"
lineHeight: "80px"
fontSize: "28px"
fontFamily: "Roboto"
letterSpacing: "0.5px"
color: "rgba(255, 255, 255, 0.87)"
account = new Layer
parent: slideContentTwo
y: 230 * 2
x: 65
width: 620
height: 34
backgroundColor: null
html: "joeyqiang@gmail.com"
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "28px"
color: "#fff"
pageScroller.addPage(slideContentTwo,"right")
buttonNext.on Events.MouseDown, () ->
buttonNext.stateSwitch("down")
buttonNext.on Events.MouseUp, () ->
buttonNext.stateSwitch("up")
pageScroller.snapToPage(slideContentTwo)
back.stateSwitch("show")
portraitOverlay.animate("two")
back.on Events.Click, () ->
pageScroller.snapToPage(slideContentOne)
back.stateSwitch("hide")
portraitOverlay.animate("one")
emailInput = new InputModule.Input
parent: slideContentOne
virtualKeyboard: false
x: 40
y: 514
width: 620
height: 40 * 2
placeholder: "Email"
placeholderColor: "rgba(255, 255, 255, 0.6)"
fontSize: 32
emailInput.style =
color: Color.main
textShadow: "0 0 0 rgba(255, 255, 255, 0.6)"
webkitTextFillColor: "transparent"
paswordInput = new InputModule.Input
parent: slideContentTwo
virtualKeyboard: false
x: 40
y: 530
width: 620
height: 40 * 2
placeholder: "Password"
placeholderColor: "rgba(255, 255, 255, 0.6)"
fontSize: 32
paswordInput.style =
color: Color.main
textShadow: "0 0 0 rgba(255, 255, 255, 0.6)"
webkitTextFillColor: "transparent"
Status_bar = new Layer
width: 750
height: 40
image: "images/Status_bar.png"
hint = new Layer
width: 312 * 2
x: Align.center
y: Screen.height - 182
backgroundColor: null
html: "THIS FORM ANIMATION PURPOSES ARE STATE, ATTENTION, FEEDBACK AND INDIVIDUALIZATION"
style:
fontFamily: "Roboto"
fontSize: "32px"
lineHeight: "48px"
letterSpacing: "0.5px"
textAlign: "center"
color: "rgba(255, 255, 255, 0.87)"
| 147470 | InputModule = require "input"
# General settings
Utils.insertCSS("@import 'https://fonts.googleapis.com/css?family=Roboto:300,400,700';")
Canvas.backgroundColor = "#303030"
Screen.backgroundColor = "#303030"
Color.main = "#2196f3"
Boxshadow = "0 4px 4px 0 rgba(0, 0, 0, 0.24), 0 0 4px 0 rgba(0, 0, 0, 0.12)"
w = 344 * 2
h = 224 * 2
pageScroller = new PageComponent
point: Align.center
width: Screen.width
height: Screen.height
scrollVertical: false
clip: false
portrait = new Layer
x: Align.center
y: 126 * 2
borderRadius: "50%"
width: 96 * 2
height: 96 * 2
backgroundColor: "#757575"
style:
boxShadow: Boxshadow
portraitOverlay = new Layer
parent: portrait
borderRadius: "50%"
width: 96 * 2
height: 96 * 2
backgroundColor: "#E0E0E0"
portraitOverlay.states =
one:
opacity: 0
scale: 0
animationOptions:
curve: Bezier.easeIn
time: 0.15
two:
opacity: 1
scale: 1
animationOptions:
curve: Bezier.easeIn
time: 0.15
portraitOverlay.stateSwitch("one")
back = new Layer
x: 24 * 2
y: 36 * 2
width: 48
height: 48
image: "images/ic_arrow_back_black_24px.svg"
back.states =
hide:
opacity: 0
show:
opacity: 1
back.stateSwitch("hide")
slideContentOne = new Layer
parent: pageScroller.content
width: Screen.width
height: Screen.height
backgroundColor: null
slideContentTwo = new Layer
width: Screen.width
height: Screen.height
backgroundColor: null
inputEmail = new Layer
parent: slideContentOne
y: 246 * 2
x: Align.center
width: 328 * 2
height: 48 * 2
backgroundColor: null
style:
borderBottom:"solid 2px #2196f3"
inputPasscode = new Layer
parent: slideContentTwo
y: 254 * 2
x: Align.center
width: 328 * 2
height: 48 * 2
backgroundColor: null
style:
borderBottom:"solid 2px #2196f3"
buttonNext = new Layer
parent: slideContentOne
y: 319 * 2
x: Align.center
width: 329 * 2
height: 40 * 2
backgroundColor: Color.main
html: "NEXT"
borderRadius: 4
style:
textAlign: "center"
lineHeight: "80px"
fontSize: "28px"
fontFamily: "Roboto"
letterSpacing: "0.5px"
color: "rgba(255, 255, 255, 0.87)"
buttonNext.states =
up:
style:
backgroundColor: Color.main
down:
shadowY: 3
style:
backgroundColor: "#4fa1e2"
boxShadow: "0 16px 16px 0 rgba(0, 0, 0, 0.24), 0 0 16px 0 rgba(0, 0, 0, 0.12)"
buttonSignUp = new Layer
parent: slideContentTwo
y: 327 * 2
x: Align.center
width: 329 * 2
height: 40 * 2
backgroundColor: Color.main
html: "SIGN UP"
borderRadius: 4
style:
textAlign: "center"
lineHeight: "80px"
fontSize: "28px"
fontFamily: "Roboto"
letterSpacing: "0.5px"
color: "rgba(255, 255, 255, 0.87)"
account = new Layer
parent: slideContentTwo
y: 230 * 2
x: 65
width: 620
height: 34
backgroundColor: null
html: "<EMAIL>"
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "28px"
color: "#fff"
pageScroller.addPage(slideContentTwo,"right")
buttonNext.on Events.MouseDown, () ->
buttonNext.stateSwitch("down")
buttonNext.on Events.MouseUp, () ->
buttonNext.stateSwitch("up")
pageScroller.snapToPage(slideContentTwo)
back.stateSwitch("show")
portraitOverlay.animate("two")
back.on Events.Click, () ->
pageScroller.snapToPage(slideContentOne)
back.stateSwitch("hide")
portraitOverlay.animate("one")
emailInput = new InputModule.Input
parent: slideContentOne
virtualKeyboard: false
x: 40
y: 514
width: 620
height: 40 * 2
placeholder: "Email"
placeholderColor: "rgba(255, 255, 255, 0.6)"
fontSize: 32
emailInput.style =
color: Color.main
textShadow: "0 0 0 rgba(255, 255, 255, 0.6)"
webkitTextFillColor: "transparent"
paswordInput = new InputModule.Input
parent: slideContentTwo
virtualKeyboard: false
x: 40
y: 530
width: 620
height: 40 * 2
placeholder: "Password"
placeholderColor: "rgba(255, 255, 255, 0.6)"
fontSize: 32
paswordInput.style =
color: Color.main
textShadow: "0 0 0 rgba(255, 255, 255, 0.6)"
webkitTextFillColor: "transparent"
Status_bar = new Layer
width: 750
height: 40
image: "images/Status_bar.png"
hint = new Layer
width: 312 * 2
x: Align.center
y: Screen.height - 182
backgroundColor: null
html: "THIS FORM ANIMATION PURPOSES ARE STATE, ATTENTION, FEEDBACK AND INDIVIDUALIZATION"
style:
fontFamily: "Roboto"
fontSize: "32px"
lineHeight: "48px"
letterSpacing: "0.5px"
textAlign: "center"
color: "rgba(255, 255, 255, 0.87)"
| true | InputModule = require "input"
# General settings
Utils.insertCSS("@import 'https://fonts.googleapis.com/css?family=Roboto:300,400,700';")
Canvas.backgroundColor = "#303030"
Screen.backgroundColor = "#303030"
Color.main = "#2196f3"
Boxshadow = "0 4px 4px 0 rgba(0, 0, 0, 0.24), 0 0 4px 0 rgba(0, 0, 0, 0.12)"
w = 344 * 2
h = 224 * 2
pageScroller = new PageComponent
point: Align.center
width: Screen.width
height: Screen.height
scrollVertical: false
clip: false
portrait = new Layer
x: Align.center
y: 126 * 2
borderRadius: "50%"
width: 96 * 2
height: 96 * 2
backgroundColor: "#757575"
style:
boxShadow: Boxshadow
portraitOverlay = new Layer
parent: portrait
borderRadius: "50%"
width: 96 * 2
height: 96 * 2
backgroundColor: "#E0E0E0"
portraitOverlay.states =
one:
opacity: 0
scale: 0
animationOptions:
curve: Bezier.easeIn
time: 0.15
two:
opacity: 1
scale: 1
animationOptions:
curve: Bezier.easeIn
time: 0.15
portraitOverlay.stateSwitch("one")
back = new Layer
x: 24 * 2
y: 36 * 2
width: 48
height: 48
image: "images/ic_arrow_back_black_24px.svg"
back.states =
hide:
opacity: 0
show:
opacity: 1
back.stateSwitch("hide")
slideContentOne = new Layer
parent: pageScroller.content
width: Screen.width
height: Screen.height
backgroundColor: null
slideContentTwo = new Layer
width: Screen.width
height: Screen.height
backgroundColor: null
inputEmail = new Layer
parent: slideContentOne
y: 246 * 2
x: Align.center
width: 328 * 2
height: 48 * 2
backgroundColor: null
style:
borderBottom:"solid 2px #2196f3"
inputPasscode = new Layer
parent: slideContentTwo
y: 254 * 2
x: Align.center
width: 328 * 2
height: 48 * 2
backgroundColor: null
style:
borderBottom:"solid 2px #2196f3"
buttonNext = new Layer
parent: slideContentOne
y: 319 * 2
x: Align.center
width: 329 * 2
height: 40 * 2
backgroundColor: Color.main
html: "NEXT"
borderRadius: 4
style:
textAlign: "center"
lineHeight: "80px"
fontSize: "28px"
fontFamily: "Roboto"
letterSpacing: "0.5px"
color: "rgba(255, 255, 255, 0.87)"
buttonNext.states =
up:
style:
backgroundColor: Color.main
down:
shadowY: 3
style:
backgroundColor: "#4fa1e2"
boxShadow: "0 16px 16px 0 rgba(0, 0, 0, 0.24), 0 0 16px 0 rgba(0, 0, 0, 0.12)"
buttonSignUp = new Layer
parent: slideContentTwo
y: 327 * 2
x: Align.center
width: 329 * 2
height: 40 * 2
backgroundColor: Color.main
html: "SIGN UP"
borderRadius: 4
style:
textAlign: "center"
lineHeight: "80px"
fontSize: "28px"
fontFamily: "Roboto"
letterSpacing: "0.5px"
color: "rgba(255, 255, 255, 0.87)"
account = new Layer
parent: slideContentTwo
y: 230 * 2
x: 65
width: 620
height: 34
backgroundColor: null
html: "PI:EMAIL:<EMAIL>END_PI"
style:
textAlign: "center"
fontFamily: "Roboto"
fontSize: "28px"
color: "#fff"
pageScroller.addPage(slideContentTwo,"right")
buttonNext.on Events.MouseDown, () ->
buttonNext.stateSwitch("down")
buttonNext.on Events.MouseUp, () ->
buttonNext.stateSwitch("up")
pageScroller.snapToPage(slideContentTwo)
back.stateSwitch("show")
portraitOverlay.animate("two")
back.on Events.Click, () ->
pageScroller.snapToPage(slideContentOne)
back.stateSwitch("hide")
portraitOverlay.animate("one")
emailInput = new InputModule.Input
parent: slideContentOne
virtualKeyboard: false
x: 40
y: 514
width: 620
height: 40 * 2
placeholder: "Email"
placeholderColor: "rgba(255, 255, 255, 0.6)"
fontSize: 32
emailInput.style =
color: Color.main
textShadow: "0 0 0 rgba(255, 255, 255, 0.6)"
webkitTextFillColor: "transparent"
paswordInput = new InputModule.Input
parent: slideContentTwo
virtualKeyboard: false
x: 40
y: 530
width: 620
height: 40 * 2
placeholder: "Password"
placeholderColor: "rgba(255, 255, 255, 0.6)"
fontSize: 32
paswordInput.style =
color: Color.main
textShadow: "0 0 0 rgba(255, 255, 255, 0.6)"
webkitTextFillColor: "transparent"
Status_bar = new Layer
width: 750
height: 40
image: "images/Status_bar.png"
hint = new Layer
width: 312 * 2
x: Align.center
y: Screen.height - 182
backgroundColor: null
html: "THIS FORM ANIMATION PURPOSES ARE STATE, ATTENTION, FEEDBACK AND INDIVIDUALIZATION"
style:
fontFamily: "Roboto"
fontSize: "32px"
lineHeight: "48px"
letterSpacing: "0.5px"
textAlign: "center"
color: "rgba(255, 255, 255, 0.87)"
|
[
{
"context": "xt.t(\"factions.faction_1_description\")\n\tdevName: \"lyonar\"\n\tisNeutral: false\n\tenabled: true\n\tisInDevelopmen",
"end": 8671,
"score": 0.9403063654899597,
"start": 8665,
"tag": "USERNAME",
"value": "lyonar"
},
{
"context": "xt.t(\"factions.faction_2_description\... | app/sdk/cards/factionFactory.coffee | willroberts/duelyst | 5 |
RSX = require('app/data/resources')
CONFIG = require('app/common/config')
UtilsGameSession = require('app/common/utils/utils_game_session')
Factions = require './factionsLookup'
Cards = require './cardsLookupComplete'
FactionProgression = require 'app/sdk/progression/factionProgression'
_ = require 'underscore'
i18next = require 'i18next'
class FactionFactory
@factionMap: {}
@factionForPlayer1: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getPlayer1())
@factionForPlayer2: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getPlayer2())
@factionForMyPlayer: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getMyPlayer())
@factionForOpponentPlayer: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getOpponentPlayer())
@factionForPlayer: (gameSession, player) ->
return @factionForPlayerId(gameSession, player.getPlayerId())
@factionForPlayerId: (gameSession, playerId) ->
playerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSession, playerId)
playerFactionId = playerSetupData.factionId
return @factionForIdentifier(playerFactionId)
@factionForIdentifier: (identifier) ->
faction = @factionMap[identifier]
if faction
return faction
else
# no faction found
console.error "FactionFactory.factionForIdentifier - Unknown faction identifier: #{identifier}".red
@_allFactions: null
@getAllFactions: () ->
if !@_allFactions?
@_allFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction
@_allFactions.push(faction)
return @_allFactions
@_playableFactions: null
@getAllPlayableFactions: () ->
if !@_playableFactions?
@_playableFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction and faction.enabled and not faction.isNeutral and not faction.isInDevelopment
@_playableFactions.push(faction)
return @_playableFactions
@_enabledFactions: null
@getAllEnabledFactions: () ->
if !@_enabledFactions?
@_enabledFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction and faction.enabled
@_enabledFactions.push(faction)
return @_enabledFactions
@starterDeckForFactionLevel: (factionId,factionLevel=0)->
starterDeck = @.factionForIdentifier(factionId).starterDeck.slice()
if factionLevel > 0
unlockedCardIds = FactionProgression.unlockedCardsUpToLevel(factionLevel, factionId)
for cardId in unlockedCardIds
if FactionFactory.unlockedCardIsValidForStarterDeck(cardId)
for i in [0...CONFIG.MAX_DECK_DUPLICATES]
starterDeck.push({id: cardId})
return starterDeck
@cardIdIsGeneral: (cardId) ->
return @factionForGeneralId(cardId)?
@unlockedCardIsValidForStarterDeck: (cardId) ->
# if card is not prismatic, it is valid for starter decks
if Cards.getIsPrismaticCardId(cardId) then return false
# search for faction for this card id
# if card id is a general, it will return a faction
# if card is not a general, it is valid for starter deck
# if card id is primary general, it is valid for starter deck
factionData = @factionForGeneralId(cardId)
return !factionData? or cardId == factionData.generalIdsByOrder[FactionFactory.GeneralOrder.Primary]
@generalIdForFactionByOrder: (factionId, order) ->
return @factionForIdentifier(factionId)?.generalIdsByOrder[order]
@generalOrderForFactionById: (factionId, generalId) ->
generalId = Cards.getBaseCardId(parseInt(generalId))
return @factionForIdentifier(factionId)?.generalOrderByIds[generalId]
@factionForGeneralId: (generalId) ->
generalId = Cards.getBaseCardId(parseInt(generalId))
factionIds = Object.keys(@factionMap)
for factionId in factionIds
faction = @factionMap[factionId]
if faction.generalIds? and _.contains(faction.generalIds, generalId)
return faction
@generalIdsForFaction: (factionId) ->
return @factionForIdentifier(factionId)?.generalIds or []
@factionIdForGeneralId: (generalId) ->
return @factionForGeneralId(generalId)?.id
@getCrestResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestResource
@getCrestShadowResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestShadowResource
@getCrestDeckSelectResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestDeckSelectResource
@getTauntCallout: (myGeneralId, opponentGeneralId) ->
callout = "Are you ready for this?"
myGeneralId = Cards.getBaseCardId(parseInt(myGeneralId))
myFaction = @factionForGeneralId(myGeneralId)
if myFaction?
opponentGeneralId = Cards.getBaseCardId(parseInt(opponentGeneralId))
# check if there is a callout map defined for my general
calloutDataForMyGeneral = myFaction.generalTauntCallouts[myGeneralId]
if _.isObject(calloutDataForMyGeneral)
# check if there is a callout defined for the opponent general
calloutDataForOpponentGeneral = calloutDataForMyGeneral[opponentGeneralId]
if _.isString(calloutDataForOpponentGeneral)
callout = calloutDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a callout defined for the opponent faction
calloutDataForOpponentFaction = calloutDataForMyGeneral[opponentFaction.id] || calloutDataForMyGeneral[Factions.Neutral]
if _.isString(calloutDataForOpponentFaction)
callout = calloutDataForOpponentFaction
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a callout defined for the opponent faction
calloutDataForOpponentFaction = myFaction.generalTauntCallouts[opponentFaction.id] || myFaction.generalTauntCallouts[Factions.Neutral]
if _.isString(calloutDataForOpponentFaction)
callout = calloutDataForOpponentFaction
else if _.isObject(calloutDataForOpponentFaction)
calloutDataForOpponentGeneral = calloutDataForOpponentFaction[opponentGeneralId]
if _.isString(calloutDataForOpponentGeneral)
callout = calloutDataForOpponentGeneral
return callout
@getTauntResponse: (myGeneralId, opponentGeneralId) ->
response = "Enough! To battle!"
myGeneralId = Cards.getBaseCardId(parseInt(myGeneralId))
myFaction = @factionForGeneralId(myGeneralId)
if myFaction?
opponentGeneralId = Cards.getBaseCardId(parseInt(opponentGeneralId))
# check if there is a response map defined for my general
responseDataForMyGeneral = myFaction.generalTauntResponses[myGeneralId]
if _.isObject(responseDataForMyGeneral)
# check if there is a response defined for the opponent general
responseDataForOpponentGeneral = responseDataForMyGeneral[opponentGeneralId]
if _.isString(responseDataForOpponentGeneral)
response = responseDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a response defined for the opponent faction
responseDataForOpponentFaction = responseDataForMyGeneral[opponentFaction.id] || responseDataForMyGeneral[Factions.Neutral]
if _.isString(responseDataForOpponentFaction)
response = responseDataForOpponentFaction
else
# check if there is a response defined for the opponent general
responseDataForOpponentGeneral = myFaction.generalTauntResponses[opponentGeneralId]
if _.isString(responseDataForOpponentGeneral)
response = responseDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a response defined for the opponent faction
responseDataForOpponentFaction = myFaction.generalTauntResponses[opponentFaction.id] || myFaction.generalTauntResponses[Factions.Neutral]
if _.isString(responseDataForOpponentFaction)
response = responseDataForOpponentFaction
return response
# setup map for general order
FactionFactory.GeneralOrder = {
Primary: 1
Secondary: 2
Tertiary: 3
}
# generate factions once in a map
fmap = FactionFactory.factionMap
# f1
fmap[Factions.Faction1] =
id: Factions.Faction1
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction1"]
name: i18next.t("factions.faction_1_name")
short_name: i18next.t("factions.faction_1_abbreviated_name")
description: i18next.t("factions.faction_1_description")
devName: "lyonar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction1.General, Cards.Faction1.AltGeneral, Cards.Faction1.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f1
crestShadowResource: RSX.crest_f1_shadow
crestDeckSelectResource: RSX.crest_f1_deck_select
gradientColorMapWhite: {r: 250, g: 200, b: 80, a: 255}
gradientColorMapBlack: {r: 40, g: 33, b: 4, a: 255}
starterDeck: [
{id: Cards.Faction1.General},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.WarSurge},
{id: Cards.Spell.WarSurge},
{id: Cards.Spell.WarSurge},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f1 general data
f1GO = fmap[Factions.Faction1].generalIdsByOrder
f1GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction1.General
f1GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction1.AltGeneral
f1GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction1.ThirdGeneral
f1OG = fmap[Factions.Faction1].generalOrderByIds
f1OG[Cards.Faction1.General] = FactionFactory.GeneralOrder.Primary
f1OG[Cards.Faction1.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f1OG[Cards.Faction1.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f1 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f1C = fmap[Factions.Faction1].generalTauntCallouts
f1C[Factions.Neutral] = i18next.t("factions.faction_1_taunt_neutral")
f1C[Factions.Faction1] = i18next.t("factions.faction_1_taunt_f1")
f1C[Factions.Faction2] = i18next.t("factions.faction_1_taunt_f2")
f1C[Factions.Faction3] = i18next.t("factions.faction_1_taunt_f3")
f1C[Factions.Faction4] = i18next.t("factions.faction_1_taunt_f4")
f1C[Factions.Faction5] = i18next.t("factions.faction_1_taunt_f5")
f1C[Factions.Faction6] = i18next.t("factions.faction_1_taunt_f6")
f1C[Factions.Boss] = i18next.t("factions.faction_1_taunt_boss")
#f1 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f1R = fmap[Factions.Faction1].generalTauntResponses
f1R[Factions.Neutral] = i18next.t("factions.faction_1_response_neutral")
f1R[Factions.Faction1] = i18next.t("factions.faction_1_response_f1")
f1R[Factions.Faction2] = i18next.t("factions.faction_1_response_f2")
f1R[Factions.Faction3] = i18next.t("factions.faction_1_response_f3")
f1R[Factions.Faction4] = i18next.t("factions.faction_1_response_f4")
f1R[Factions.Faction5] = i18next.t("factions.faction_1_response_f5")
f1R[Factions.Faction6] = i18next.t("factions.faction_1_response_f6")
f1R[Factions.Boss] = i18next.t("factions.faction_1_response_boss")
# f2
fmap[Factions.Faction2] =
id: Factions.Faction2
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction2"]
name: i18next.t("factions.faction_2_name")
short_name: i18next.t("factions.faction_2_abbreviated_name")
description: i18next.t("factions.faction_2_description")
devName: "songhai"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction2.General, Cards.Faction2.AltGeneral, Cards.Faction2.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f2
crestShadowResource: RSX.crest_f2_shadow
crestDeckSelectResource: RSX.crest_f2_deck_select
gradientColorMapWhite: {r: 254, g: 80, b: 100, a: 255}
gradientColorMapBlack: {r: 70, g: 5, b: 1, a: 255}
starterDeck: [
{id: Cards.Faction2.General},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Spell.KillingEdge},
{id: Cards.Spell.KillingEdge},
{id: Cards.Spell.KillingEdge},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f2 general data
f2GO = fmap[Factions.Faction2].generalIdsByOrder
f2GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction2.General
f2GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction2.AltGeneral
f2GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction2.ThirdGeneral
f2OG = fmap[Factions.Faction2].generalOrderByIds
f2OG[Cards.Faction2.General] = FactionFactory.GeneralOrder.Primary
f2OG[Cards.Faction2.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f2OG[Cards.Faction2.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f2 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f2C = fmap[Factions.Faction2].generalTauntCallouts
f2C[Factions.Neutral] = i18next.t("factions.faction_2_taunt_neutral")
f2C[Factions.Faction1] = i18next.t("factions.faction_2_taunt_f1")
f2C[Factions.Faction2] = i18next.t("factions.faction_2_taunt_f2")
f2C[Factions.Faction3] = i18next.t("factions.faction_2_taunt_f3")
f2C[Factions.Faction4] = i18next.t("factions.faction_2_taunt_f4")
f2C[Factions.Faction5] = i18next.t("factions.faction_2_taunt_f5")
f2C[Factions.Faction6] = i18next.t("factions.faction_2_taunt_f6")
f2C[Factions.Boss] = i18next.t("factions.faction_2_taunt_boss")
#f2 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f2R = fmap[Factions.Faction2].generalTauntResponses
f2R[Factions.Neutral] = i18next.t("factions.faction_2_response_neutral")
f2R[Factions.Faction1] = i18next.t("factions.faction_2_response_f1")
f2R[Factions.Faction2] = i18next.t("factions.faction_2_response_f2")
f2R[Factions.Faction3] = i18next.t("factions.faction_2_response_f3")
f2R[Factions.Faction4] = i18next.t("factions.faction_2_response_f4")
f2R[Factions.Faction5] = i18next.t("factions.faction_2_response_f5")
f2R[Factions.Faction6] = i18next.t("factions.faction_2_response_f6")
f2R[Factions.Boss] = i18next.t("factions.faction_2_response_boss")
# f3
fmap[Factions.Faction3] =
id: Factions.Faction3
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction3"]
name: i18next.t("factions.faction_3_name")
short_name: i18next.t("factions.faction_3_abbreviated_name")
description: i18next.t("factions.faction_3_description")
devName: "vetruvian"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction3.General, Cards.Faction3.AltGeneral, Cards.Faction3.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f3
crestShadowResource: RSX.crest_f3_shadow
crestDeckSelectResource: RSX.crest_f3_deck_select
gradientColorMapWhite: {r: 250, g: 160, b: 0, a: 255}
gradientColorMapBlack: {r: 39, g: 33, b: 21, a: 255}
starterDeck: [
{id: Cards.Faction3.General},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Faction3.WindShrike},
{id: Cards.Faction3.WindShrike},
{id: Cards.Faction3.WindShrike},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f3 general data
f3GO = fmap[Factions.Faction3].generalIdsByOrder
f3GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction3.General
f3GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction3.AltGeneral
f3GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction3.ThirdGeneral
f3OG = fmap[Factions.Faction3].generalOrderByIds
f3OG[Cards.Faction3.General] = FactionFactory.GeneralOrder.Primary
f3OG[Cards.Faction3.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f3OG[Cards.Faction3.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f3 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f3C = fmap[Factions.Faction3].generalTauntCallouts
f3C[Factions.Neutral] = i18next.t("factions.faction_3_taunt_neutral")
f3C[Factions.Faction1] = i18next.t("factions.faction_3_taunt_f1")
f3C[Factions.Faction2] = i18next.t("factions.faction_3_taunt_f2")
f3C[Factions.Faction3] = i18next.t("factions.faction_3_taunt_f3")
f3C[Factions.Faction4] = i18next.t("factions.faction_3_taunt_f4")
f3C[Factions.Faction5] = i18next.t("factions.faction_3_taunt_f5")
f3C[Factions.Faction6] = i18next.t("factions.faction_3_taunt_f6")
f3C[Factions.Boss] = i18next.t("factions.faction_3_taunt_boss")
#f3 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f3R = fmap[Factions.Faction3].generalTauntResponses
f3R[Factions.Neutral] = i18next.t("factions.faction_3_response_neutral")
f3R[Factions.Faction1] = i18next.t("factions.faction_3_response_f1")
f3R[Factions.Faction2] = i18next.t("factions.faction_3_response_f2")
f3R[Factions.Faction3] = i18next.t("factions.faction_3_response_f3")
f3R[Factions.Faction4] = i18next.t("factions.faction_3_response_f4")
f3R[Factions.Faction5] = i18next.t("factions.faction_3_response_f5")
f3R[Factions.Faction6] = i18next.t("factions.faction_3_response_f6")
f3R[Factions.Boss] = i18next.t("factions.faction_3_response_boss")
# f4
fmap[Factions.Faction4] =
id: Factions.Faction4
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction4"]
name: i18next.t("factions.faction_4_name")
short_name: i18next.t("factions.faction_4_abbreviated_name")
description: i18next.t("factions.faction_4_description")
devName: "abyssian"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction4.General, Cards.Faction4.AltGeneral, Cards.Faction4.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f4
crestShadowResource: RSX.crest_f4_shadow
crestDeckSelectResource: RSX.crest_f4_deck_select
gradientColorMapWhite: {r: 247, g: 151, b: 254, a: 255}
gradientColorMapBlack: {r: 45, g: 50, b: 167, a: 255}
starterDeck: [
{id: Cards.Faction4.General},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f4 general data
f4GO = fmap[Factions.Faction4].generalIdsByOrder
f4GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction4.General
f4GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction4.AltGeneral
f4GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction4.ThirdGeneral
f4OG = fmap[Factions.Faction4].generalOrderByIds
f4OG[Cards.Faction4.General] = FactionFactory.GeneralOrder.Primary
f4OG[Cards.Faction4.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f4OG[Cards.Faction4.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f4 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f4C = fmap[Factions.Faction4].generalTauntCallouts
f4C[Factions.Neutral] = i18next.t("factions.faction_4_taunt_neutral")
f4C[Factions.Faction1] = i18next.t("factions.faction_4_taunt_f1")
f4C[Factions.Faction2] = i18next.t("factions.faction_4_taunt_f2")
f4C[Factions.Faction3] = i18next.t("factions.faction_4_taunt_f3")
f4C[Factions.Faction4] = i18next.t("factions.faction_4_taunt_f4")
f4C[Factions.Faction5] = i18next.t("factions.faction_4_taunt_f5")
f4C[Factions.Faction6] = i18next.t("factions.faction_4_taunt_f6")
f4C[Factions.Boss] = i18next.t("factions.faction_4_taunt_boss")
#f4 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f4R = fmap[Factions.Faction4].generalTauntResponses
f4R[Factions.Neutral] = i18next.t("factions.faction_4_response_neutral")
f4R[Factions.Faction1] = i18next.t("factions.faction_4_response_f1")
f4R[Factions.Faction2] = i18next.t("factions.faction_4_response_f2")
f4R[Factions.Faction3] = i18next.t("factions.faction_4_response_f3")
f4R[Factions.Faction4] = i18next.t("factions.faction_4_response_f4")
f4R[Factions.Faction5] = i18next.t("factions.faction_4_response_f5")
f4R[Factions.Faction6] = i18next.t("factions.faction_4_response_f6")
f4R[Factions.Boss] = i18next.t("factions.faction_4_response_boss")
# f5
fmap[Factions.Faction5] =
id: Factions.Faction5
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction5"]
name: i18next.t("factions.faction_5_name")
short_name: i18next.t("factions.faction_5_abbreviated_name")
description: i18next.t("factions.faction_5_description")
devName: "magmar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction5.General, Cards.Faction5.AltGeneral, Cards.Faction5.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f5
crestShadowResource: RSX.crest_f5_shadow
crestDeckSelectResource: RSX.crest_f5_deck_select
gradientColorMapWhite: {r: 0, g: 252, b: 250, a: 255}
gradientColorMapBlack: {r: 0, g: 62, b: 66, a: 255}
starterDeck: [
{id: Cards.Faction5.General},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.BrightmossGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f5 general data
f5GO = fmap[Factions.Faction5].generalIdsByOrder
f5GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction5.General
f5GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction5.AltGeneral
f5GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction5.ThirdGeneral
f5OG = fmap[Factions.Faction5].generalOrderByIds
f5OG[Cards.Faction5.General] = FactionFactory.GeneralOrder.Primary
f5OG[Cards.Faction5.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f5OG[Cards.Faction5.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f5 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f5C = fmap[Factions.Faction5].generalTauntCallouts
f5C[Factions.Neutral] = i18next.t("factions.faction_5_taunt_neutral")
f5C[Factions.Faction1] = i18next.t("factions.faction_5_taunt_f1")
f5C[Factions.Faction2] = i18next.t("factions.faction_5_taunt_f2")
f5C[Factions.Faction3] = i18next.t("factions.faction_5_taunt_f3")
f5C[Factions.Faction4] = i18next.t("factions.faction_5_taunt_f4")
f5C[Factions.Faction5] = i18next.t("factions.faction_5_taunt_f5")
f5C[Factions.Faction6] = i18next.t("factions.faction_5_taunt_f6")
f5C[Factions.Boss] = i18next.t("factions.faction_5_taunt_boss")
#f5 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f5R = fmap[Factions.Faction5].generalTauntResponses
f5R[Factions.Neutral] = i18next.t("factions.faction_5_response_neutral")
f5R[Factions.Faction1] = i18next.t("factions.faction_5_response_f1")
f5R[Factions.Faction2] = i18next.t("factions.faction_5_response_f2")
f5R[Factions.Faction3] = i18next.t("factions.faction_5_response_f3")
f5R[Factions.Faction4] = i18next.t("factions.faction_5_response_f4")
f5R[Factions.Faction5] = i18next.t("factions.faction_5_response_f5")
f5R[Factions.Faction6] = i18next.t("factions.faction_5_response_f6")
f5R[Factions.Boss] = i18next.t("factions.faction_5_response_boss")
# f6
fmap[Factions.Faction6] =
id: Factions.Faction6
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction6"]
name: i18next.t("factions.faction_6_name")
short_name: i18next.t("factions.faction_6_abbreviated_name")
description: i18next.t("factions.faction_6_description")
devName: "vanar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction6.General, Cards.Faction6.AltGeneral, Cards.Faction6.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f6
crestShadowResource: RSX.crest_f6_shadow
crestDeckSelectResource: RSX.crest_f6_deck_select
gradientColorMapWhite: {r: 185, g: 208, b: 226, a: 255}
gradientColorMapBlack: {r: 9, g: 12, b: 55, a: 255}
starterDeck: [
{id: Cards.Faction6.General},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.FlameWing},
{id: Cards.Neutral.FlameWing},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f6 general data
f6GO = fmap[Factions.Faction6].generalIdsByOrder
f6GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction6.General
f6GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction6.AltGeneral
f6GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction6.ThirdGeneral
f6OG = fmap[Factions.Faction6].generalOrderByIds
f6OG[Cards.Faction6.General] = FactionFactory.GeneralOrder.Primary
f6OG[Cards.Faction6.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f6OG[Cards.Faction6.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f6 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f6C = fmap[Factions.Faction6].generalTauntCallouts
f6C[Factions.Neutral] = i18next.t("factions.faction_6_taunt_neutral")
f6C[Factions.Faction1] = i18next.t("factions.faction_6_taunt_f1")
f6C[Factions.Faction2] = i18next.t("factions.faction_6_taunt_f2")
f6C[Factions.Faction3] = i18next.t("factions.faction_6_taunt_f3")
f6C[Factions.Faction4] = i18next.t("factions.faction_6_taunt_f4")
f6C[Factions.Faction5] = i18next.t("factions.faction_6_taunt_f5")
f6C[Factions.Faction6] = i18next.t("factions.faction_6_taunt_f6")
f6C[Factions.Boss] = i18next.t("factions.faction_6_taunt_boss")
#f6 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f6R = fmap[Factions.Faction6].generalTauntResponses
f6R[Factions.Neutral] = i18next.t("factions.faction_6_response_neutral")
f6R[Factions.Faction1] = i18next.t("factions.faction_6_response_f1")
f6R[Factions.Faction2] = i18next.t("factions.faction_6_response_f2")
f6R[Factions.Faction3] = i18next.t("factions.faction_6_response_f3")
f6R[Factions.Faction4] = i18next.t("factions.faction_6_response_f4")
f6R[Factions.Faction5] = i18next.t("factions.faction_6_response_f5")
f6R[Factions.Faction6] = i18next.t("factions.faction_6_response_f6")
f6R[Factions.Boss] = i18next.t("factions.faction_6_response_boss")
# neutral
fmap[Factions.Neutral] =
id: Factions.Neutral
fxResource: ["FX.Factions.Neutral"]
name: i18next.t("factions.faction_neutral_name")
short_name: i18next.t("factions.faction_neutral_abbreviated_name")
devName: "neutral"
description: ""
isNeutral: true
enabled: true
isInDevelopment: false
# tutorial faction
fmap[Factions.Tutorial] =
id: Factions.Tutorial
fxResource: ["FX.Factions.Neutral", "FX.Factions.Tutorial"]
name: "Tutorial Teacher"
devName: "tutorial"
description: "The Teacher of Duelyst"
gameCountFlavorText: "N/A"
isNeutral: false
enabled: false
isInDevelopment: false
generalIds: [
Cards.Tutorial.TutorialGeneral,
Cards.Tutorial.TutorialSignatureGeneral,
Cards.Tutorial.TutorialOpponentGeneral1,
Cards.Tutorial.TutorialOpponentGeneral2,
Cards.Tutorial.TutorialOpponentGeneral4
]
announcerFirst: null # TODO: audio
announcerSecond: null # TODO: audio
gradientColorMapWhite: {r: 255, g: 255, b: 255, a: 255}
gradientColorMapBlack: {r: 0, g: 0, b: 0, a: 255}
# bosses faction
fmap[Factions.Boss] =
id: Factions.Boss
fxResource: ["FX.Factions.Neutral", "FX.Factions.Boss"]
name: "Boss"
devName: "bosses"
description: "Mysterious Challengers"
isNeutral: false
enabled: false
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [
Cards.Boss.Boss38,
Cards.Boss.Boss37,
Cards.Boss.Boss36,
Cards.Boss.Boss35,
Cards.Boss.Boss34,
Cards.Boss.Boss33,
Cards.Boss.Boss32,
Cards.Boss.Boss31,
Cards.Boss.Boss30,
Cards.Boss.Boss29,
Cards.Boss.Boss28,
Cards.Boss.Boss27,
Cards.Boss.Boss26,
Cards.Boss.Boss25,
Cards.Boss.Boss24,
Cards.Boss.Boss23,
Cards.Boss.Boss22,
Cards.Boss.Boss21,
Cards.Boss.Boss20,
Cards.Boss.Boss19,
Cards.Boss.Boss18,
Cards.Boss.Boss17,
Cards.Boss.Boss16,
Cards.Boss.Boss15,
Cards.Boss.Boss14,
Cards.Boss.Boss13,
Cards.Boss.Boss12,
Cards.Boss.Boss11,
Cards.Boss.Boss10,
Cards.Boss.Boss6,
Cards.Boss.Boss9,
Cards.Boss.Boss2,
Cards.Boss.Boss4,
Cards.Boss.Boss5,
Cards.Boss.Boss1,
Cards.Boss.Boss7,
Cards.Boss.Boss8,
Cards.Boss.Boss3
]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.generic_concede")
gameCountFlavorText: "N/A"
crestImg: null
crestShadowImg: null
crestDeckSelectImg: null
gradientColorMapWhite: {r: 255, g: 255, b: 255, a: 255}
gradientColorMapBlack: {r: 0, g: 0, b: 0, a: 255}
#boss callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
fbC = fmap[Factions.Boss].generalTauntCallouts
fbC[Factions.Neutral] = i18next.t("factions.boss_neutral_taunt")
# specific boss callouts
fbC1 = fbC[Cards.Boss.Boss1] = {}
fbC1[Factions.Neutral] = i18next.t("factions.boss_1_taunt")
fbC2 = fbC[Cards.Boss.Boss2] = {}
fbC2[Factions.Neutral] = i18next.t("factions.boss_2_taunt")
fbC3 = fbC[Cards.Boss.Boss3] = fbC[Cards.Boss.Boss7] = {}
fbC3[Factions.Neutral] = i18next.t("factions.boss_3_taunt")
fbC4 = fbC[Cards.Boss.Boss4] = {}
fbC4[Factions.Neutral] = i18next.t("factions.boss_4_taunt")
fbC5 = fbC[Cards.Boss.Boss5] = {}
fbC5[Factions.Neutral] = i18next.t("factions.boss_5_taunt")
fbC6 = fbC[Cards.Boss.Boss6] = {}
fbC6[Factions.Neutral] = i18next.t("factions.boss_6_taunt")
fbC8 = fbC[Cards.Boss.Boss8] = {}
fbC8[Factions.Neutral] = i18next.t("factions.boss_8_taunt")
fbC9 = fbC[Cards.Boss.Boss9] = {}
fbC9[Factions.Neutral] = i18next.t("factions.boss_9_taunt")
fbC10 = fbC[Cards.Boss.Boss10] = {}
fbC10[Factions.Neutral] = i18next.t("factions.boss_10_taunt")
fbC11 = fbC[Cards.Boss.Boss11] = {}
fbC11[Factions.Neutral] = i18next.t("factions.boss_11_taunt")
fbC12 = fbC[Cards.Boss.Boss12] = {}
fbC12[Factions.Neutral] = i18next.t("factions.boss_12_taunt")
fbC13 = fbC[Cards.Boss.Boss13] = {}
fbC13[Factions.Neutral] = i18next.t("factions.boss_13_taunt")
fbC14 = fbC[Cards.Boss.Boss14] = {}
fbC14[Factions.Neutral] = i18next.t("factions.boss_14_taunt")
fbC15 = fbC[Cards.Boss.Boss15] = {}
fbC15[Factions.Neutral] = i18next.t("factions.boss_15_taunt")
fbC16 = fbC[Cards.Boss.Boss16] = {}
fbC16[Factions.Neutral] = i18next.t("factions.boss_16_taunt")
fbC17 = fbC[Cards.Boss.Boss17] = {}
fbC17[Factions.Neutral] = i18next.t("factions.boss_17_taunt")
fbC18 = fbC[Cards.Boss.Boss18] = {}
fbC18[Factions.Neutral] = i18next.t("factions.boss_18_taunt")
fbC19 = fbC[Cards.Boss.Boss19] = {}
fbC19[Factions.Neutral] = i18next.t("factions.boss_19_taunt")
fbC20 = fbC[Cards.Boss.Boss20] = {}
fbC20[Factions.Neutral] = i18next.t("factions.boss_20_taunt")
fbC21 = fbC[Cards.Boss.Boss21] = {}
fbC21[Factions.Neutral] = i18next.t("factions.boss_21_taunt")
fbC22 = fbC[Cards.Boss.Boss22] = {}
fbC22[Factions.Neutral] = i18next.t("factions.boss_22_taunt")
fbC23 = fbC[Cards.Boss.Boss23] = {}
fbC23[Factions.Neutral] = i18next.t("factions.boss_23_taunt")
fbC24 = fbC[Cards.Boss.Boss24] = {}
fbC24[Factions.Neutral] = i18next.t("factions.boss_24_taunt")
fbC25 = fbC[Cards.Boss.Boss25] = {}
fbC25[Factions.Neutral] = i18next.t("factions.boss_25_taunt")
fbC26 = fbC[Cards.Boss.Boss26] = {}
fbC26[Factions.Neutral] = i18next.t("factions.boss_26_taunt")
fbC27 = fbC[Cards.Boss.Boss27] = {}
fbC27[Factions.Neutral] = i18next.t("factions.boss_27_taunt")
fbC28 = fbC[Cards.Boss.Boss28] = {}
fbC28[Factions.Neutral] = i18next.t("factions.boss_28_taunt")
fbC29 = fbC[Cards.Boss.Boss29] = {}
fbC29[Factions.Neutral] = i18next.t("factions.boss_29_taunt")
fbC30 = fbC[Cards.Boss.Boss30] = {}
fbC30[Factions.Neutral] = i18next.t("factions.boss_30_taunt")
fbC31 = fbC[Cards.Boss.Boss31] = {}
fbC31[Factions.Neutral] = i18next.t("factions.boss_31_taunt")
fbC32 = fbC[Cards.Boss.Boss32] = {}
fbC32[Factions.Neutral] = i18next.t("factions.boss_32_taunt")
fbC33 = fbC[Cards.Boss.Boss33] = {}
fbC33[Factions.Neutral] = i18next.t("factions.boss_33_taunt")
fbC34 = fbC[Cards.Boss.Boss34] = {}
fbC34[Factions.Neutral] = i18next.t("factions.boss_34_taunt")
fbC35 = fbC[Cards.Boss.Boss35] = {}
fbC35[Factions.Neutral] = i18next.t("factions.boss_35_taunt")
fbC36 = fbC[Cards.Boss.Boss36] = {}
fbC36[Factions.Neutral] = i18next.t("factions.boss_36_taunt")
fbC37 = fbC[Cards.Boss.Boss37] = {}
fbC37[Factions.Neutral] = i18next.t("factions.boss_37_taunt")
fbC38 = fbC[Cards.Boss.Boss38] = {}
fbC38[Factions.Neutral] = i18next.t("factions.boss_38_taunt")
#boss responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
fbR = fmap[Factions.Boss].generalTauntResponses
fbR[Factions.Neutral] = i18next.t("factions.boss_neutral_taunt")
# specific boss callouts
fbR1 = fbR[Cards.Boss.Boss1] = {}
fbR1[Factions.Neutral] = i18next.t("factions.boss_1_taunt")
fbR2 = fbR[Cards.Boss.Boss2] = {}
fbR2[Factions.Neutral] = i18next.t("factions.boss_2_taunt")
fbR3 = fbR[Cards.Boss.Boss3] = fbR[Cards.Boss.Boss7] = {}
fbR3[Factions.Neutral] = i18next.t("factions.boss_3_taunt")
fbR4 = fbR[Cards.Boss.Boss4] = {}
fbR4[Factions.Neutral] = i18next.t("factions.boss_4_taunt")
fbR5 = fbR[Cards.Boss.Boss5] = {}
fbR5[Factions.Neutral] = i18next.t("factions.boss_5_taunt")
fbR6 = fbR[Cards.Boss.Boss6] = {}
fbR6[Factions.Neutral] = i18next.t("factions.boss_6_taunt")
fbR8 = fbR[Cards.Boss.Boss8] = {}
fbR8[Factions.Neutral] = i18next.t("factions.boss_8_taunt")
fbR9 = fbR[Cards.Boss.Boss9] = {}
fbR9[Factions.Neutral] = i18next.t("factions.boss_9_taunt")
fbR10 = fbR[Cards.Boss.Boss10] = {}
fbR10[Factions.Neutral] = i18next.t("factions.boss_10_taunt")
fbR11 = fbR[Cards.Boss.Boss11] = {}
fbR11[Factions.Neutral] = i18next.t("factions.boss_11_taunt")
fbR12 = fbR[Cards.Boss.Boss12] = {}
fbR12[Factions.Neutral] = i18next.t("factions.boss_12_taunt")
fbR13 = fbR[Cards.Boss.Boss13] = {}
fbR13[Factions.Neutral] = i18next.t("factions.boss_13_taunt")
fbR14 = fbR[Cards.Boss.Boss14] = {}
fbR14[Factions.Neutral] = i18next.t("factions.boss_14_taunt")
fbR15 = fbR[Cards.Boss.Boss15] = {}
fbR15[Factions.Neutral] = i18next.t("factions.boss_15_taunt")
fbR16 = fbR[Cards.Boss.Boss16] = {}
fbR16[Factions.Neutral] = i18next.t("factions.boss_16_taunt")
fbR17 = fbR[Cards.Boss.Boss17] = {}
fbR17[Factions.Neutral] = i18next.t("factions.boss_17_taunt")
fbR18 = fbR[Cards.Boss.Boss18] = {}
fbR18[Factions.Neutral] = i18next.t("factions.boss_18_taunt")
fbR19 = fbR[Cards.Boss.Boss19] = {}
fbR19[Factions.Neutral] = i18next.t("factions.boss_19_taunt")
fbR20 = fbR[Cards.Boss.Boss20] = {}
fbR20[Factions.Neutral] = i18next.t("factions.boss_20_taunt")
fbR21 = fbR[Cards.Boss.Boss21] = {}
fbR21[Factions.Neutral] = i18next.t("factions.boss_21_taunt")
fbR22 = fbR[Cards.Boss.Boss22] = {}
fbR22[Factions.Neutral] = i18next.t("factions.boss_22_taunt")
fbR23 = fbR[Cards.Boss.Boss23] = {}
fbR23[Factions.Neutral] = i18next.t("factions.boss_23_taunt")
fbR24 = fbR[Cards.Boss.Boss24] = {}
fbR24[Factions.Neutral] = i18next.t("factions.boss_24_taunt")
fbR25 = fbR[Cards.Boss.Boss25] = {}
fbR25[Factions.Neutral] = i18next.t("factions.boss_25_taunt")
fbR26 = fbR[Cards.Boss.Boss26] = {}
fbR26[Factions.Neutral] = i18next.t("factions.boss_26_taunt")
fbR27 = fbR[Cards.Boss.Boss27] = {}
fbR27[Factions.Neutral] = i18next.t("factions.boss_27_taunt")
fbR28 = fbR[Cards.Boss.Boss28] = {}
fbR28[Factions.Neutral] = i18next.t("factions.boss_28_taunt")
fbR29 = fbR[Cards.Boss.Boss29] = {}
fbR29[Factions.Neutral] = i18next.t("factions.boss_29_taunt")
fbR30 = fbR[Cards.Boss.Boss30] = {}
fbR30[Factions.Neutral] = i18next.t("factions.boss_30_taunt")
fbR31 = fbR[Cards.Boss.Boss31] = {}
fbR31[Factions.Neutral] = i18next.t("factions.boss_31_taunt")
fbR32 = fbR[Cards.Boss.Boss32] = {}
fbR32[Factions.Neutral] = i18next.t("factions.boss_32_taunt")
fbR33 = fbR[Cards.Boss.Boss33] = {}
fbR33[Factions.Neutral] = i18next.t("factions.boss_33_taunt")
fbR34 = fbR[Cards.Boss.Boss34] = {}
fbR34[Factions.Neutral] = i18next.t("factions.boss_34_taunt")
fbR35 = fbR[Cards.Boss.Boss35] = {}
fbR35[Factions.Neutral] = i18next.t("factions.boss_35_taunt")
fbR36 = fbR[Cards.Boss.Boss36] = {}
fbR36[Factions.Neutral] = i18next.t("factions.boss_36_taunt")
fbR37 = fbR[Cards.Boss.Boss37] = {}
fbR37[Factions.Neutral] = i18next.t("factions.boss_37_taunt")
fbR38 = fbR[Cards.Boss.Boss38] = {}
fbR38[Factions.Neutral] = i18next.t("factions.boss_38_taunt")
module.exports = FactionFactory
| 199952 |
RSX = require('app/data/resources')
CONFIG = require('app/common/config')
UtilsGameSession = require('app/common/utils/utils_game_session')
Factions = require './factionsLookup'
Cards = require './cardsLookupComplete'
FactionProgression = require 'app/sdk/progression/factionProgression'
_ = require 'underscore'
i18next = require 'i18next'
class FactionFactory
@factionMap: {}
@factionForPlayer1: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getPlayer1())
@factionForPlayer2: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getPlayer2())
@factionForMyPlayer: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getMyPlayer())
@factionForOpponentPlayer: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getOpponentPlayer())
@factionForPlayer: (gameSession, player) ->
return @factionForPlayerId(gameSession, player.getPlayerId())
@factionForPlayerId: (gameSession, playerId) ->
playerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSession, playerId)
playerFactionId = playerSetupData.factionId
return @factionForIdentifier(playerFactionId)
@factionForIdentifier: (identifier) ->
faction = @factionMap[identifier]
if faction
return faction
else
# no faction found
console.error "FactionFactory.factionForIdentifier - Unknown faction identifier: #{identifier}".red
@_allFactions: null
@getAllFactions: () ->
if !@_allFactions?
@_allFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction
@_allFactions.push(faction)
return @_allFactions
@_playableFactions: null
@getAllPlayableFactions: () ->
if !@_playableFactions?
@_playableFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction and faction.enabled and not faction.isNeutral and not faction.isInDevelopment
@_playableFactions.push(faction)
return @_playableFactions
@_enabledFactions: null
@getAllEnabledFactions: () ->
if !@_enabledFactions?
@_enabledFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction and faction.enabled
@_enabledFactions.push(faction)
return @_enabledFactions
@starterDeckForFactionLevel: (factionId,factionLevel=0)->
starterDeck = @.factionForIdentifier(factionId).starterDeck.slice()
if factionLevel > 0
unlockedCardIds = FactionProgression.unlockedCardsUpToLevel(factionLevel, factionId)
for cardId in unlockedCardIds
if FactionFactory.unlockedCardIsValidForStarterDeck(cardId)
for i in [0...CONFIG.MAX_DECK_DUPLICATES]
starterDeck.push({id: cardId})
return starterDeck
@cardIdIsGeneral: (cardId) ->
return @factionForGeneralId(cardId)?
@unlockedCardIsValidForStarterDeck: (cardId) ->
# if card is not prismatic, it is valid for starter decks
if Cards.getIsPrismaticCardId(cardId) then return false
# search for faction for this card id
# if card id is a general, it will return a faction
# if card is not a general, it is valid for starter deck
# if card id is primary general, it is valid for starter deck
factionData = @factionForGeneralId(cardId)
return !factionData? or cardId == factionData.generalIdsByOrder[FactionFactory.GeneralOrder.Primary]
@generalIdForFactionByOrder: (factionId, order) ->
return @factionForIdentifier(factionId)?.generalIdsByOrder[order]
@generalOrderForFactionById: (factionId, generalId) ->
generalId = Cards.getBaseCardId(parseInt(generalId))
return @factionForIdentifier(factionId)?.generalOrderByIds[generalId]
@factionForGeneralId: (generalId) ->
generalId = Cards.getBaseCardId(parseInt(generalId))
factionIds = Object.keys(@factionMap)
for factionId in factionIds
faction = @factionMap[factionId]
if faction.generalIds? and _.contains(faction.generalIds, generalId)
return faction
@generalIdsForFaction: (factionId) ->
return @factionForIdentifier(factionId)?.generalIds or []
@factionIdForGeneralId: (generalId) ->
return @factionForGeneralId(generalId)?.id
@getCrestResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestResource
@getCrestShadowResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestShadowResource
@getCrestDeckSelectResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestDeckSelectResource
@getTauntCallout: (myGeneralId, opponentGeneralId) ->
callout = "Are you ready for this?"
myGeneralId = Cards.getBaseCardId(parseInt(myGeneralId))
myFaction = @factionForGeneralId(myGeneralId)
if myFaction?
opponentGeneralId = Cards.getBaseCardId(parseInt(opponentGeneralId))
# check if there is a callout map defined for my general
calloutDataForMyGeneral = myFaction.generalTauntCallouts[myGeneralId]
if _.isObject(calloutDataForMyGeneral)
# check if there is a callout defined for the opponent general
calloutDataForOpponentGeneral = calloutDataForMyGeneral[opponentGeneralId]
if _.isString(calloutDataForOpponentGeneral)
callout = calloutDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a callout defined for the opponent faction
calloutDataForOpponentFaction = calloutDataForMyGeneral[opponentFaction.id] || calloutDataForMyGeneral[Factions.Neutral]
if _.isString(calloutDataForOpponentFaction)
callout = calloutDataForOpponentFaction
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a callout defined for the opponent faction
calloutDataForOpponentFaction = myFaction.generalTauntCallouts[opponentFaction.id] || myFaction.generalTauntCallouts[Factions.Neutral]
if _.isString(calloutDataForOpponentFaction)
callout = calloutDataForOpponentFaction
else if _.isObject(calloutDataForOpponentFaction)
calloutDataForOpponentGeneral = calloutDataForOpponentFaction[opponentGeneralId]
if _.isString(calloutDataForOpponentGeneral)
callout = calloutDataForOpponentGeneral
return callout
@getTauntResponse: (myGeneralId, opponentGeneralId) ->
response = "Enough! To battle!"
myGeneralId = Cards.getBaseCardId(parseInt(myGeneralId))
myFaction = @factionForGeneralId(myGeneralId)
if myFaction?
opponentGeneralId = Cards.getBaseCardId(parseInt(opponentGeneralId))
# check if there is a response map defined for my general
responseDataForMyGeneral = myFaction.generalTauntResponses[myGeneralId]
if _.isObject(responseDataForMyGeneral)
# check if there is a response defined for the opponent general
responseDataForOpponentGeneral = responseDataForMyGeneral[opponentGeneralId]
if _.isString(responseDataForOpponentGeneral)
response = responseDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a response defined for the opponent faction
responseDataForOpponentFaction = responseDataForMyGeneral[opponentFaction.id] || responseDataForMyGeneral[Factions.Neutral]
if _.isString(responseDataForOpponentFaction)
response = responseDataForOpponentFaction
else
# check if there is a response defined for the opponent general
responseDataForOpponentGeneral = myFaction.generalTauntResponses[opponentGeneralId]
if _.isString(responseDataForOpponentGeneral)
response = responseDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a response defined for the opponent faction
responseDataForOpponentFaction = myFaction.generalTauntResponses[opponentFaction.id] || myFaction.generalTauntResponses[Factions.Neutral]
if _.isString(responseDataForOpponentFaction)
response = responseDataForOpponentFaction
return response
# setup map for general order
FactionFactory.GeneralOrder = {
Primary: 1
Secondary: 2
Tertiary: 3
}
# generate factions once in a map
fmap = FactionFactory.factionMap
# f1
fmap[Factions.Faction1] =
id: Factions.Faction1
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction1"]
name: i18next.t("factions.faction_1_name")
short_name: i18next.t("factions.faction_1_abbreviated_name")
description: i18next.t("factions.faction_1_description")
devName: "lyonar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction1.General, Cards.Faction1.AltGeneral, Cards.Faction1.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f1
crestShadowResource: RSX.crest_f1_shadow
crestDeckSelectResource: RSX.crest_f1_deck_select
gradientColorMapWhite: {r: 250, g: 200, b: 80, a: 255}
gradientColorMapBlack: {r: 40, g: 33, b: 4, a: 255}
starterDeck: [
{id: Cards.Faction1.General},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.WarSurge},
{id: Cards.Spell.WarSurge},
{id: Cards.Spell.WarSurge},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f1 general data
f1GO = fmap[Factions.Faction1].generalIdsByOrder
f1GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction1.General
f1GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction1.AltGeneral
f1GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction1.ThirdGeneral
f1OG = fmap[Factions.Faction1].generalOrderByIds
f1OG[Cards.Faction1.General] = FactionFactory.GeneralOrder.Primary
f1OG[Cards.Faction1.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f1OG[Cards.Faction1.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f1 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f1C = fmap[Factions.Faction1].generalTauntCallouts
f1C[Factions.Neutral] = i18next.t("factions.faction_1_taunt_neutral")
f1C[Factions.Faction1] = i18next.t("factions.faction_1_taunt_f1")
f1C[Factions.Faction2] = i18next.t("factions.faction_1_taunt_f2")
f1C[Factions.Faction3] = i18next.t("factions.faction_1_taunt_f3")
f1C[Factions.Faction4] = i18next.t("factions.faction_1_taunt_f4")
f1C[Factions.Faction5] = i18next.t("factions.faction_1_taunt_f5")
f1C[Factions.Faction6] = i18next.t("factions.faction_1_taunt_f6")
f1C[Factions.Boss] = i18next.t("factions.faction_1_taunt_boss")
#f1 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f1R = fmap[Factions.Faction1].generalTauntResponses
f1R[Factions.Neutral] = i18next.t("factions.faction_1_response_neutral")
f1R[Factions.Faction1] = i18next.t("factions.faction_1_response_f1")
f1R[Factions.Faction2] = i18next.t("factions.faction_1_response_f2")
f1R[Factions.Faction3] = i18next.t("factions.faction_1_response_f3")
f1R[Factions.Faction4] = i18next.t("factions.faction_1_response_f4")
f1R[Factions.Faction5] = i18next.t("factions.faction_1_response_f5")
f1R[Factions.Faction6] = i18next.t("factions.faction_1_response_f6")
f1R[Factions.Boss] = i18next.t("factions.faction_1_response_boss")
# f2
fmap[Factions.Faction2] =
id: Factions.Faction2
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction2"]
name: i18next.t("factions.faction_2_name")
short_name: i18next.t("factions.faction_2_abbreviated_name")
description: i18next.t("factions.faction_2_description")
devName: "songhai"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction2.General, Cards.Faction2.AltGeneral, Cards.Faction2.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f2
crestShadowResource: RSX.crest_f2_shadow
crestDeckSelectResource: RSX.crest_f2_deck_select
gradientColorMapWhite: {r: 254, g: 80, b: 100, a: 255}
gradientColorMapBlack: {r: 70, g: 5, b: 1, a: 255}
starterDeck: [
{id: Cards.Faction2.General},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Spell.KillingEdge},
{id: Cards.Spell.KillingEdge},
{id: Cards.Spell.KillingEdge},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f2 general data
f2GO = fmap[Factions.Faction2].generalIdsByOrder
f2GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction2.General
f2GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction2.AltGeneral
f2GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction2.ThirdGeneral
f2OG = fmap[Factions.Faction2].generalOrderByIds
f2OG[Cards.Faction2.General] = FactionFactory.GeneralOrder.Primary
f2OG[Cards.Faction2.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f2OG[Cards.Faction2.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f2 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f2C = fmap[Factions.Faction2].generalTauntCallouts
f2C[Factions.Neutral] = i18next.t("factions.faction_2_taunt_neutral")
f2C[Factions.Faction1] = i18next.t("factions.faction_2_taunt_f1")
f2C[Factions.Faction2] = i18next.t("factions.faction_2_taunt_f2")
f2C[Factions.Faction3] = i18next.t("factions.faction_2_taunt_f3")
f2C[Factions.Faction4] = i18next.t("factions.faction_2_taunt_f4")
f2C[Factions.Faction5] = i18next.t("factions.faction_2_taunt_f5")
f2C[Factions.Faction6] = i18next.t("factions.faction_2_taunt_f6")
f2C[Factions.Boss] = i18next.t("factions.faction_2_taunt_boss")
#f2 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f2R = fmap[Factions.Faction2].generalTauntResponses
f2R[Factions.Neutral] = i18next.t("factions.faction_2_response_neutral")
f2R[Factions.Faction1] = i18next.t("factions.faction_2_response_f1")
f2R[Factions.Faction2] = i18next.t("factions.faction_2_response_f2")
f2R[Factions.Faction3] = i18next.t("factions.faction_2_response_f3")
f2R[Factions.Faction4] = i18next.t("factions.faction_2_response_f4")
f2R[Factions.Faction5] = i18next.t("factions.faction_2_response_f5")
f2R[Factions.Faction6] = i18next.t("factions.faction_2_response_f6")
f2R[Factions.Boss] = i18next.t("factions.faction_2_response_boss")
# f3
fmap[Factions.Faction3] =
id: Factions.Faction3
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction3"]
name: i18next.t("factions.faction_3_name")
short_name: i18next.t("factions.faction_3_abbreviated_name")
description: i18next.t("factions.faction_3_description")
devName: "vetruvian"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction3.General, Cards.Faction3.AltGeneral, Cards.Faction3.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f3
crestShadowResource: RSX.crest_f3_shadow
crestDeckSelectResource: RSX.crest_f3_deck_select
gradientColorMapWhite: {r: 250, g: 160, b: 0, a: 255}
gradientColorMapBlack: {r: 39, g: 33, b: 21, a: 255}
starterDeck: [
{id: Cards.Faction3.General},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Faction3.WindShrike},
{id: Cards.Faction3.WindShrike},
{id: Cards.Faction3.WindShrike},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f3 general data
f3GO = fmap[Factions.Faction3].generalIdsByOrder
f3GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction3.General
f3GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction3.AltGeneral
f3GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction3.ThirdGeneral
f3OG = fmap[Factions.Faction3].generalOrderByIds
f3OG[Cards.Faction3.General] = FactionFactory.GeneralOrder.Primary
f3OG[Cards.Faction3.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f3OG[Cards.Faction3.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f3 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f3C = fmap[Factions.Faction3].generalTauntCallouts
f3C[Factions.Neutral] = i18next.t("factions.faction_3_taunt_neutral")
f3C[Factions.Faction1] = i18next.t("factions.faction_3_taunt_f1")
f3C[Factions.Faction2] = i18next.t("factions.faction_3_taunt_f2")
f3C[Factions.Faction3] = i18next.t("factions.faction_3_taunt_f3")
f3C[Factions.Faction4] = i18next.t("factions.faction_3_taunt_f4")
f3C[Factions.Faction5] = i18next.t("factions.faction_3_taunt_f5")
f3C[Factions.Faction6] = i18next.t("factions.faction_3_taunt_f6")
f3C[Factions.Boss] = i18next.t("factions.faction_3_taunt_boss")
#f3 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f3R = fmap[Factions.Faction3].generalTauntResponses
f3R[Factions.Neutral] = i18next.t("factions.faction_3_response_neutral")
f3R[Factions.Faction1] = i18next.t("factions.faction_3_response_f1")
f3R[Factions.Faction2] = i18next.t("factions.faction_3_response_f2")
f3R[Factions.Faction3] = i18next.t("factions.faction_3_response_f3")
f3R[Factions.Faction4] = i18next.t("factions.faction_3_response_f4")
f3R[Factions.Faction5] = i18next.t("factions.faction_3_response_f5")
f3R[Factions.Faction6] = i18next.t("factions.faction_3_response_f6")
f3R[Factions.Boss] = i18next.t("factions.faction_3_response_boss")
# f4
fmap[Factions.Faction4] =
id: Factions.Faction4
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction4"]
name: i18next.t("factions.faction_4_name")
short_name: i18next.t("factions.faction_4_abbreviated_name")
description: i18next.t("factions.faction_4_description")
devName: "abyssian"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction4.General, Cards.Faction4.AltGeneral, Cards.Faction4.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f4
crestShadowResource: RSX.crest_f4_shadow
crestDeckSelectResource: RSX.crest_f4_deck_select
gradientColorMapWhite: {r: 247, g: 151, b: 254, a: 255}
gradientColorMapBlack: {r: 45, g: 50, b: 167, a: 255}
starterDeck: [
{id: Cards.Faction4.General},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f4 general data
f4GO = fmap[Factions.Faction4].generalIdsByOrder
f4GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction4.General
f4GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction4.AltGeneral
f4GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction4.ThirdGeneral
f4OG = fmap[Factions.Faction4].generalOrderByIds
f4OG[Cards.Faction4.General] = FactionFactory.GeneralOrder.Primary
f4OG[Cards.Faction4.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f4OG[Cards.Faction4.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f4 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f4C = fmap[Factions.Faction4].generalTauntCallouts
f4C[Factions.Neutral] = i18next.t("factions.faction_4_taunt_neutral")
f4C[Factions.Faction1] = i18next.t("factions.faction_4_taunt_f1")
f4C[Factions.Faction2] = i18next.t("factions.faction_4_taunt_f2")
f4C[Factions.Faction3] = i18next.t("factions.faction_4_taunt_f3")
f4C[Factions.Faction4] = i18next.t("factions.faction_4_taunt_f4")
f4C[Factions.Faction5] = i18next.t("factions.faction_4_taunt_f5")
f4C[Factions.Faction6] = i18next.t("factions.faction_4_taunt_f6")
f4C[Factions.Boss] = i18next.t("factions.faction_4_taunt_boss")
#f4 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f4R = fmap[Factions.Faction4].generalTauntResponses
f4R[Factions.Neutral] = i18next.t("factions.faction_4_response_neutral")
f4R[Factions.Faction1] = i18next.t("factions.faction_4_response_f1")
f4R[Factions.Faction2] = i18next.t("factions.faction_4_response_f2")
f4R[Factions.Faction3] = i18next.t("factions.faction_4_response_f3")
f4R[Factions.Faction4] = i18next.t("factions.faction_4_response_f4")
f4R[Factions.Faction5] = i18next.t("factions.faction_4_response_f5")
f4R[Factions.Faction6] = i18next.t("factions.faction_4_response_f6")
f4R[Factions.Boss] = i18next.t("factions.faction_4_response_boss")
# f5
fmap[Factions.Faction5] =
id: Factions.Faction5
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction5"]
name: i18next.t("factions.faction_5_name")
short_name: i18next.t("factions.faction_5_abbreviated_name")
description: i18next.t("factions.faction_5_description")
devName: "magmar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction5.General, Cards.Faction5.AltGeneral, Cards.Faction5.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f5
crestShadowResource: RSX.crest_f5_shadow
crestDeckSelectResource: RSX.crest_f5_deck_select
gradientColorMapWhite: {r: 0, g: 252, b: 250, a: 255}
gradientColorMapBlack: {r: 0, g: 62, b: 66, a: 255}
starterDeck: [
{id: Cards.Faction5.General},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.BrightmossGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f5 general data
f5GO = fmap[Factions.Faction5].generalIdsByOrder
f5GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction5.General
f5GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction5.AltGeneral
f5GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction5.ThirdGeneral
f5OG = fmap[Factions.Faction5].generalOrderByIds
f5OG[Cards.Faction5.General] = FactionFactory.GeneralOrder.Primary
f5OG[Cards.Faction5.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f5OG[Cards.Faction5.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f5 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f5C = fmap[Factions.Faction5].generalTauntCallouts
f5C[Factions.Neutral] = i18next.t("factions.faction_5_taunt_neutral")
f5C[Factions.Faction1] = i18next.t("factions.faction_5_taunt_f1")
f5C[Factions.Faction2] = i18next.t("factions.faction_5_taunt_f2")
f5C[Factions.Faction3] = i18next.t("factions.faction_5_taunt_f3")
f5C[Factions.Faction4] = i18next.t("factions.faction_5_taunt_f4")
f5C[Factions.Faction5] = i18next.t("factions.faction_5_taunt_f5")
f5C[Factions.Faction6] = i18next.t("factions.faction_5_taunt_f6")
f5C[Factions.Boss] = i18next.t("factions.faction_5_taunt_boss")
#f5 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f5R = fmap[Factions.Faction5].generalTauntResponses
f5R[Factions.Neutral] = i18next.t("factions.faction_5_response_neutral")
f5R[Factions.Faction1] = i18next.t("factions.faction_5_response_f1")
f5R[Factions.Faction2] = i18next.t("factions.faction_5_response_f2")
f5R[Factions.Faction3] = i18next.t("factions.faction_5_response_f3")
f5R[Factions.Faction4] = i18next.t("factions.faction_5_response_f4")
f5R[Factions.Faction5] = i18next.t("factions.faction_5_response_f5")
f5R[Factions.Faction6] = i18next.t("factions.faction_5_response_f6")
f5R[Factions.Boss] = i18next.t("factions.faction_5_response_boss")
# f6
fmap[Factions.Faction6] =
id: Factions.Faction6
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction6"]
name: i18next.t("factions.faction_6_name")
short_name: i18next.t("factions.faction_6_abbreviated_name")
description: i18next.t("factions.faction_6_description")
devName: "<NAME>"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction6.General, Cards.Faction6.AltGeneral, Cards.Faction6.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f6
crestShadowResource: RSX.crest_f6_shadow
crestDeckSelectResource: RSX.crest_f6_deck_select
gradientColorMapWhite: {r: 185, g: 208, b: 226, a: 255}
gradientColorMapBlack: {r: 9, g: 12, b: 55, a: 255}
starterDeck: [
{id: Cards.Faction6.General},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.FlameWing},
{id: Cards.Neutral.FlameWing},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f6 general data
f6GO = fmap[Factions.Faction6].generalIdsByOrder
f6GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction6.General
f6GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction6.AltGeneral
f6GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction6.ThirdGeneral
f6OG = fmap[Factions.Faction6].generalOrderByIds
f6OG[Cards.Faction6.General] = FactionFactory.GeneralOrder.Primary
f6OG[Cards.Faction6.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f6OG[Cards.Faction6.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f6 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f6C = fmap[Factions.Faction6].generalTauntCallouts
f6C[Factions.Neutral] = i18next.t("factions.faction_6_taunt_neutral")
f6C[Factions.Faction1] = i18next.t("factions.faction_6_taunt_f1")
f6C[Factions.Faction2] = i18next.t("factions.faction_6_taunt_f2")
f6C[Factions.Faction3] = i18next.t("factions.faction_6_taunt_f3")
f6C[Factions.Faction4] = i18next.t("factions.faction_6_taunt_f4")
f6C[Factions.Faction5] = i18next.t("factions.faction_6_taunt_f5")
f6C[Factions.Faction6] = i18next.t("factions.faction_6_taunt_f6")
f6C[Factions.Boss] = i18next.t("factions.faction_6_taunt_boss")
#f6 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f6R = fmap[Factions.Faction6].generalTauntResponses
f6R[Factions.Neutral] = i18next.t("factions.faction_6_response_neutral")
f6R[Factions.Faction1] = i18next.t("factions.faction_6_response_f1")
f6R[Factions.Faction2] = i18next.t("factions.faction_6_response_f2")
f6R[Factions.Faction3] = i18next.t("factions.faction_6_response_f3")
f6R[Factions.Faction4] = i18next.t("factions.faction_6_response_f4")
f6R[Factions.Faction5] = i18next.t("factions.faction_6_response_f5")
f6R[Factions.Faction6] = i18next.t("factions.faction_6_response_f6")
f6R[Factions.Boss] = i18next.t("factions.faction_6_response_boss")
# neutral
fmap[Factions.Neutral] =
id: Factions.Neutral
fxResource: ["FX.Factions.Neutral"]
name: i18next.t("factions.faction_neutral_name")
short_name: i18next.t("factions.faction_neutral_abbreviated_name")
devName: "neutral"
description: ""
isNeutral: true
enabled: true
isInDevelopment: false
# tutorial faction
fmap[Factions.Tutorial] =
id: Factions.Tutorial
fxResource: ["FX.Factions.Neutral", "FX.Factions.Tutorial"]
name: "<NAME>"
devName: "<NAME>"
description: "The Teacher of Duelyst"
gameCountFlavorText: "N/A"
isNeutral: false
enabled: false
isInDevelopment: false
generalIds: [
Cards.Tutorial.TutorialGeneral,
Cards.Tutorial.TutorialSignatureGeneral,
Cards.Tutorial.TutorialOpponentGeneral1,
Cards.Tutorial.TutorialOpponentGeneral2,
Cards.Tutorial.TutorialOpponentGeneral4
]
announcerFirst: null # TODO: audio
announcerSecond: null # TODO: audio
gradientColorMapWhite: {r: 255, g: 255, b: 255, a: 255}
gradientColorMapBlack: {r: 0, g: 0, b: 0, a: 255}
# bosses faction
fmap[Factions.Boss] =
id: Factions.Boss
fxResource: ["FX.Factions.Neutral", "FX.Factions.Boss"]
name: "Boss"
devName: "bosses"
description: "Mysterious Challengers"
isNeutral: false
enabled: false
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [
Cards.Boss.Boss38,
Cards.Boss.Boss37,
Cards.Boss.Boss36,
Cards.Boss.Boss35,
Cards.Boss.Boss34,
Cards.Boss.Boss33,
Cards.Boss.Boss32,
Cards.Boss.Boss31,
Cards.Boss.Boss30,
Cards.Boss.Boss29,
Cards.Boss.Boss28,
Cards.Boss.Boss27,
Cards.Boss.Boss26,
Cards.Boss.Boss25,
Cards.Boss.Boss24,
Cards.Boss.Boss23,
Cards.Boss.Boss22,
Cards.Boss.Boss21,
Cards.Boss.Boss20,
Cards.Boss.Boss19,
Cards.Boss.Boss18,
Cards.Boss.Boss17,
Cards.Boss.Boss16,
Cards.Boss.Boss15,
Cards.Boss.Boss14,
Cards.Boss.Boss13,
Cards.Boss.Boss12,
Cards.Boss.Boss11,
Cards.Boss.Boss10,
Cards.Boss.Boss6,
Cards.Boss.Boss9,
Cards.Boss.Boss2,
Cards.Boss.Boss4,
Cards.Boss.Boss5,
Cards.Boss.Boss1,
Cards.Boss.Boss7,
Cards.Boss.Boss8,
Cards.Boss.Boss3
]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.generic_concede")
gameCountFlavorText: "N/A"
crestImg: null
crestShadowImg: null
crestDeckSelectImg: null
gradientColorMapWhite: {r: 255, g: 255, b: 255, a: 255}
gradientColorMapBlack: {r: 0, g: 0, b: 0, a: 255}
#boss callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
fbC = fmap[Factions.Boss].generalTauntCallouts
fbC[Factions.Neutral] = i18next.t("factions.boss_neutral_taunt")
# specific boss callouts
fbC1 = fbC[Cards.Boss.Boss1] = {}
fbC1[Factions.Neutral] = i18next.t("factions.boss_1_taunt")
fbC2 = fbC[Cards.Boss.Boss2] = {}
fbC2[Factions.Neutral] = i18next.t("factions.boss_2_taunt")
fbC3 = fbC[Cards.Boss.Boss3] = fbC[Cards.Boss.Boss7] = {}
fbC3[Factions.Neutral] = i18next.t("factions.boss_3_taunt")
fbC4 = fbC[Cards.Boss.Boss4] = {}
fbC4[Factions.Neutral] = i18next.t("factions.boss_4_taunt")
fbC5 = fbC[Cards.Boss.Boss5] = {}
fbC5[Factions.Neutral] = i18next.t("factions.boss_5_taunt")
fbC6 = fbC[Cards.Boss.Boss6] = {}
fbC6[Factions.Neutral] = i18next.t("factions.boss_6_taunt")
fbC8 = fbC[Cards.Boss.Boss8] = {}
fbC8[Factions.Neutral] = i18next.t("factions.boss_8_taunt")
fbC9 = fbC[Cards.Boss.Boss9] = {}
fbC9[Factions.Neutral] = i18next.t("factions.boss_9_taunt")
fbC10 = fbC[Cards.Boss.Boss10] = {}
fbC10[Factions.Neutral] = i18next.t("factions.boss_10_taunt")
fbC11 = fbC[Cards.Boss.Boss11] = {}
fbC11[Factions.Neutral] = i18next.t("factions.boss_11_taunt")
fbC12 = fbC[Cards.Boss.Boss12] = {}
fbC12[Factions.Neutral] = i18next.t("factions.boss_12_taunt")
fbC13 = fbC[Cards.Boss.Boss13] = {}
fbC13[Factions.Neutral] = i18next.t("factions.boss_13_taunt")
fbC14 = fbC[Cards.Boss.Boss14] = {}
fbC14[Factions.Neutral] = i18next.t("factions.boss_14_taunt")
fbC15 = fbC[Cards.Boss.Boss15] = {}
fbC15[Factions.Neutral] = i18next.t("factions.boss_15_taunt")
fbC16 = fbC[Cards.Boss.Boss16] = {}
fbC16[Factions.Neutral] = i18next.t("factions.boss_16_taunt")
fbC17 = fbC[Cards.Boss.Boss17] = {}
fbC17[Factions.Neutral] = i18next.t("factions.boss_17_taunt")
fbC18 = fbC[Cards.Boss.Boss18] = {}
fbC18[Factions.Neutral] = i18next.t("factions.boss_18_taunt")
fbC19 = fbC[Cards.Boss.Boss19] = {}
fbC19[Factions.Neutral] = i18next.t("factions.boss_19_taunt")
fbC20 = fbC[Cards.Boss.Boss20] = {}
fbC20[Factions.Neutral] = i18next.t("factions.boss_20_taunt")
fbC21 = fbC[Cards.Boss.Boss21] = {}
fbC21[Factions.Neutral] = i18next.t("factions.boss_21_taunt")
fbC22 = fbC[Cards.Boss.Boss22] = {}
fbC22[Factions.Neutral] = i18next.t("factions.boss_22_taunt")
fbC23 = fbC[Cards.Boss.Boss23] = {}
fbC23[Factions.Neutral] = i18next.t("factions.boss_23_taunt")
fbC24 = fbC[Cards.Boss.Boss24] = {}
fbC24[Factions.Neutral] = i18next.t("factions.boss_24_taunt")
fbC25 = fbC[Cards.Boss.Boss25] = {}
fbC25[Factions.Neutral] = i18next.t("factions.boss_25_taunt")
fbC26 = fbC[Cards.Boss.Boss26] = {}
fbC26[Factions.Neutral] = i18next.t("factions.boss_26_taunt")
fbC27 = fbC[Cards.Boss.Boss27] = {}
fbC27[Factions.Neutral] = i18next.t("factions.boss_27_taunt")
fbC28 = fbC[Cards.Boss.Boss28] = {}
fbC28[Factions.Neutral] = i18next.t("factions.boss_28_taunt")
fbC29 = fbC[Cards.Boss.Boss29] = {}
fbC29[Factions.Neutral] = i18next.t("factions.boss_29_taunt")
fbC30 = fbC[Cards.Boss.Boss30] = {}
fbC30[Factions.Neutral] = i18next.t("factions.boss_30_taunt")
fbC31 = fbC[Cards.Boss.Boss31] = {}
fbC31[Factions.Neutral] = i18next.t("factions.boss_31_taunt")
fbC32 = fbC[Cards.Boss.Boss32] = {}
fbC32[Factions.Neutral] = i18next.t("factions.boss_32_taunt")
fbC33 = fbC[Cards.Boss.Boss33] = {}
fbC33[Factions.Neutral] = i18next.t("factions.boss_33_taunt")
fbC34 = fbC[Cards.Boss.Boss34] = {}
fbC34[Factions.Neutral] = i18next.t("factions.boss_34_taunt")
fbC35 = fbC[Cards.Boss.Boss35] = {}
fbC35[Factions.Neutral] = i18next.t("factions.boss_35_taunt")
fbC36 = fbC[Cards.Boss.Boss36] = {}
fbC36[Factions.Neutral] = i18next.t("factions.boss_36_taunt")
fbC37 = fbC[Cards.Boss.Boss37] = {}
fbC37[Factions.Neutral] = i18next.t("factions.boss_37_taunt")
fbC38 = fbC[Cards.Boss.Boss38] = {}
fbC38[Factions.Neutral] = i18next.t("factions.boss_38_taunt")
#boss responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
fbR = fmap[Factions.Boss].generalTauntResponses
fbR[Factions.Neutral] = i18next.t("factions.boss_neutral_taunt")
# specific boss callouts
fbR1 = fbR[Cards.Boss.Boss1] = {}
fbR1[Factions.Neutral] = i18next.t("factions.boss_1_taunt")
fbR2 = fbR[Cards.Boss.Boss2] = {}
fbR2[Factions.Neutral] = i18next.t("factions.boss_2_taunt")
fbR3 = fbR[Cards.Boss.Boss3] = fbR[Cards.Boss.Boss7] = {}
fbR3[Factions.Neutral] = i18next.t("factions.boss_3_taunt")
fbR4 = fbR[Cards.Boss.Boss4] = {}
fbR4[Factions.Neutral] = i18next.t("factions.boss_4_taunt")
fbR5 = fbR[Cards.Boss.Boss5] = {}
fbR5[Factions.Neutral] = i18next.t("factions.boss_5_taunt")
fbR6 = fbR[Cards.Boss.Boss6] = {}
fbR6[Factions.Neutral] = i18next.t("factions.boss_6_taunt")
fbR8 = fbR[Cards.Boss.Boss8] = {}
fbR8[Factions.Neutral] = i18next.t("factions.boss_8_taunt")
fbR9 = fbR[Cards.Boss.Boss9] = {}
fbR9[Factions.Neutral] = i18next.t("factions.boss_9_taunt")
fbR10 = fbR[Cards.Boss.Boss10] = {}
fbR10[Factions.Neutral] = i18next.t("factions.boss_10_taunt")
fbR11 = fbR[Cards.Boss.Boss11] = {}
fbR11[Factions.Neutral] = i18next.t("factions.boss_11_taunt")
fbR12 = fbR[Cards.Boss.Boss12] = {}
fbR12[Factions.Neutral] = i18next.t("factions.boss_12_taunt")
fbR13 = fbR[Cards.Boss.Boss13] = {}
fbR13[Factions.Neutral] = i18next.t("factions.boss_13_taunt")
fbR14 = fbR[Cards.Boss.Boss14] = {}
fbR14[Factions.Neutral] = i18next.t("factions.boss_14_taunt")
fbR15 = fbR[Cards.Boss.Boss15] = {}
fbR15[Factions.Neutral] = i18next.t("factions.boss_15_taunt")
fbR16 = fbR[Cards.Boss.Boss16] = {}
fbR16[Factions.Neutral] = i18next.t("factions.boss_16_taunt")
fbR17 = fbR[Cards.Boss.Boss17] = {}
fbR17[Factions.Neutral] = i18next.t("factions.boss_17_taunt")
fbR18 = fbR[Cards.Boss.Boss18] = {}
fbR18[Factions.Neutral] = i18next.t("factions.boss_18_taunt")
fbR19 = fbR[Cards.Boss.Boss19] = {}
fbR19[Factions.Neutral] = i18next.t("factions.boss_19_taunt")
fbR20 = fbR[Cards.Boss.Boss20] = {}
fbR20[Factions.Neutral] = i18next.t("factions.boss_20_taunt")
fbR21 = fbR[Cards.Boss.Boss21] = {}
fbR21[Factions.Neutral] = i18next.t("factions.boss_21_taunt")
fbR22 = fbR[Cards.Boss.Boss22] = {}
fbR22[Factions.Neutral] = i18next.t("factions.boss_22_taunt")
fbR23 = fbR[Cards.Boss.Boss23] = {}
fbR23[Factions.Neutral] = i18next.t("factions.boss_23_taunt")
fbR24 = fbR[Cards.Boss.Boss24] = {}
fbR24[Factions.Neutral] = i18next.t("factions.boss_24_taunt")
fbR25 = fbR[Cards.Boss.Boss25] = {}
fbR25[Factions.Neutral] = i18next.t("factions.boss_25_taunt")
fbR26 = fbR[Cards.Boss.Boss26] = {}
fbR26[Factions.Neutral] = i18next.t("factions.boss_26_taunt")
fbR27 = fbR[Cards.Boss.Boss27] = {}
fbR27[Factions.Neutral] = i18next.t("factions.boss_27_taunt")
fbR28 = fbR[Cards.Boss.Boss28] = {}
fbR28[Factions.Neutral] = i18next.t("factions.boss_28_taunt")
fbR29 = fbR[Cards.Boss.Boss29] = {}
fbR29[Factions.Neutral] = i18next.t("factions.boss_29_taunt")
fbR30 = fbR[Cards.Boss.Boss30] = {}
fbR30[Factions.Neutral] = i18next.t("factions.boss_30_taunt")
fbR31 = fbR[Cards.Boss.Boss31] = {}
fbR31[Factions.Neutral] = i18next.t("factions.boss_31_taunt")
fbR32 = fbR[Cards.Boss.Boss32] = {}
fbR32[Factions.Neutral] = i18next.t("factions.boss_32_taunt")
fbR33 = fbR[Cards.Boss.Boss33] = {}
fbR33[Factions.Neutral] = i18next.t("factions.boss_33_taunt")
fbR34 = fbR[Cards.Boss.Boss34] = {}
fbR34[Factions.Neutral] = i18next.t("factions.boss_34_taunt")
fbR35 = fbR[Cards.Boss.Boss35] = {}
fbR35[Factions.Neutral] = i18next.t("factions.boss_35_taunt")
fbR36 = fbR[Cards.Boss.Boss36] = {}
fbR36[Factions.Neutral] = i18next.t("factions.boss_36_taunt")
fbR37 = fbR[Cards.Boss.Boss37] = {}
fbR37[Factions.Neutral] = i18next.t("factions.boss_37_taunt")
fbR38 = fbR[Cards.Boss.Boss38] = {}
fbR38[Factions.Neutral] = i18next.t("factions.boss_38_taunt")
module.exports = FactionFactory
| true |
RSX = require('app/data/resources')
CONFIG = require('app/common/config')
UtilsGameSession = require('app/common/utils/utils_game_session')
Factions = require './factionsLookup'
Cards = require './cardsLookupComplete'
FactionProgression = require 'app/sdk/progression/factionProgression'
_ = require 'underscore'
i18next = require 'i18next'
class FactionFactory
@factionMap: {}
@factionForPlayer1: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getPlayer1())
@factionForPlayer2: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getPlayer2())
@factionForMyPlayer: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getMyPlayer())
@factionForOpponentPlayer: (gameSession) ->
return @factionForPlayer(gameSession, gameSession.getOpponentPlayer())
@factionForPlayer: (gameSession, player) ->
return @factionForPlayerId(gameSession, player.getPlayerId())
@factionForPlayerId: (gameSession, playerId) ->
playerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSession, playerId)
playerFactionId = playerSetupData.factionId
return @factionForIdentifier(playerFactionId)
@factionForIdentifier: (identifier) ->
faction = @factionMap[identifier]
if faction
return faction
else
# no faction found
console.error "FactionFactory.factionForIdentifier - Unknown faction identifier: #{identifier}".red
@_allFactions: null
@getAllFactions: () ->
if !@_allFactions?
@_allFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction
@_allFactions.push(faction)
return @_allFactions
@_playableFactions: null
@getAllPlayableFactions: () ->
if !@_playableFactions?
@_playableFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction and faction.enabled and not faction.isNeutral and not faction.isInDevelopment
@_playableFactions.push(faction)
return @_playableFactions
@_enabledFactions: null
@getAllEnabledFactions: () ->
if !@_enabledFactions?
@_enabledFactions = []
for factionId in _.chain(Factions).values().uniq().value()
faction = FactionFactory.factionForIdentifier(factionId)
if faction and faction.enabled
@_enabledFactions.push(faction)
return @_enabledFactions
@starterDeckForFactionLevel: (factionId,factionLevel=0)->
starterDeck = @.factionForIdentifier(factionId).starterDeck.slice()
if factionLevel > 0
unlockedCardIds = FactionProgression.unlockedCardsUpToLevel(factionLevel, factionId)
for cardId in unlockedCardIds
if FactionFactory.unlockedCardIsValidForStarterDeck(cardId)
for i in [0...CONFIG.MAX_DECK_DUPLICATES]
starterDeck.push({id: cardId})
return starterDeck
@cardIdIsGeneral: (cardId) ->
return @factionForGeneralId(cardId)?
@unlockedCardIsValidForStarterDeck: (cardId) ->
# if card is not prismatic, it is valid for starter decks
if Cards.getIsPrismaticCardId(cardId) then return false
# search for faction for this card id
# if card id is a general, it will return a faction
# if card is not a general, it is valid for starter deck
# if card id is primary general, it is valid for starter deck
factionData = @factionForGeneralId(cardId)
return !factionData? or cardId == factionData.generalIdsByOrder[FactionFactory.GeneralOrder.Primary]
@generalIdForFactionByOrder: (factionId, order) ->
return @factionForIdentifier(factionId)?.generalIdsByOrder[order]
@generalOrderForFactionById: (factionId, generalId) ->
generalId = Cards.getBaseCardId(parseInt(generalId))
return @factionForIdentifier(factionId)?.generalOrderByIds[generalId]
@factionForGeneralId: (generalId) ->
generalId = Cards.getBaseCardId(parseInt(generalId))
factionIds = Object.keys(@factionMap)
for factionId in factionIds
faction = @factionMap[factionId]
if faction.generalIds? and _.contains(faction.generalIds, generalId)
return faction
@generalIdsForFaction: (factionId) ->
return @factionForIdentifier(factionId)?.generalIds or []
@factionIdForGeneralId: (generalId) ->
return @factionForGeneralId(generalId)?.id
@getCrestResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestResource
@getCrestShadowResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestShadowResource
@getCrestDeckSelectResourceForFactionId: (factionId) ->
faction = @factionForIdentifier(factionId)
return faction?.crestDeckSelectResource
@getTauntCallout: (myGeneralId, opponentGeneralId) ->
callout = "Are you ready for this?"
myGeneralId = Cards.getBaseCardId(parseInt(myGeneralId))
myFaction = @factionForGeneralId(myGeneralId)
if myFaction?
opponentGeneralId = Cards.getBaseCardId(parseInt(opponentGeneralId))
# check if there is a callout map defined for my general
calloutDataForMyGeneral = myFaction.generalTauntCallouts[myGeneralId]
if _.isObject(calloutDataForMyGeneral)
# check if there is a callout defined for the opponent general
calloutDataForOpponentGeneral = calloutDataForMyGeneral[opponentGeneralId]
if _.isString(calloutDataForOpponentGeneral)
callout = calloutDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a callout defined for the opponent faction
calloutDataForOpponentFaction = calloutDataForMyGeneral[opponentFaction.id] || calloutDataForMyGeneral[Factions.Neutral]
if _.isString(calloutDataForOpponentFaction)
callout = calloutDataForOpponentFaction
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a callout defined for the opponent faction
calloutDataForOpponentFaction = myFaction.generalTauntCallouts[opponentFaction.id] || myFaction.generalTauntCallouts[Factions.Neutral]
if _.isString(calloutDataForOpponentFaction)
callout = calloutDataForOpponentFaction
else if _.isObject(calloutDataForOpponentFaction)
calloutDataForOpponentGeneral = calloutDataForOpponentFaction[opponentGeneralId]
if _.isString(calloutDataForOpponentGeneral)
callout = calloutDataForOpponentGeneral
return callout
@getTauntResponse: (myGeneralId, opponentGeneralId) ->
response = "Enough! To battle!"
myGeneralId = Cards.getBaseCardId(parseInt(myGeneralId))
myFaction = @factionForGeneralId(myGeneralId)
if myFaction?
opponentGeneralId = Cards.getBaseCardId(parseInt(opponentGeneralId))
# check if there is a response map defined for my general
responseDataForMyGeneral = myFaction.generalTauntResponses[myGeneralId]
if _.isObject(responseDataForMyGeneral)
# check if there is a response defined for the opponent general
responseDataForOpponentGeneral = responseDataForMyGeneral[opponentGeneralId]
if _.isString(responseDataForOpponentGeneral)
response = responseDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a response defined for the opponent faction
responseDataForOpponentFaction = responseDataForMyGeneral[opponentFaction.id] || responseDataForMyGeneral[Factions.Neutral]
if _.isString(responseDataForOpponentFaction)
response = responseDataForOpponentFaction
else
# check if there is a response defined for the opponent general
responseDataForOpponentGeneral = myFaction.generalTauntResponses[opponentGeneralId]
if _.isString(responseDataForOpponentGeneral)
response = responseDataForOpponentGeneral
else
opponentFaction = @factionForGeneralId(opponentGeneralId)
if opponentFaction?
# check if there is a response defined for the opponent faction
responseDataForOpponentFaction = myFaction.generalTauntResponses[opponentFaction.id] || myFaction.generalTauntResponses[Factions.Neutral]
if _.isString(responseDataForOpponentFaction)
response = responseDataForOpponentFaction
return response
# setup map for general order
FactionFactory.GeneralOrder = {
Primary: 1
Secondary: 2
Tertiary: 3
}
# generate factions once in a map
fmap = FactionFactory.factionMap
# f1
fmap[Factions.Faction1] =
id: Factions.Faction1
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction1"]
name: i18next.t("factions.faction_1_name")
short_name: i18next.t("factions.faction_1_abbreviated_name")
description: i18next.t("factions.faction_1_description")
devName: "lyonar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction1.General, Cards.Faction1.AltGeneral, Cards.Faction1.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f1
crestShadowResource: RSX.crest_f1_shadow
crestDeckSelectResource: RSX.crest_f1_deck_select
gradientColorMapWhite: {r: 250, g: 200, b: 80, a: 255}
gradientColorMapBlack: {r: 40, g: 33, b: 4, a: 255}
starterDeck: [
{id: Cards.Faction1.General},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Artifact.SunstoneBracers},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.TrueStrike},
{id: Cards.Spell.WarSurge},
{id: Cards.Spell.WarSurge},
{id: Cards.Spell.WarSurge},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Faction1.WindbladeAdept},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Faction1.LysianBrawler},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f1 general data
f1GO = fmap[Factions.Faction1].generalIdsByOrder
f1GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction1.General
f1GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction1.AltGeneral
f1GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction1.ThirdGeneral
f1OG = fmap[Factions.Faction1].generalOrderByIds
f1OG[Cards.Faction1.General] = FactionFactory.GeneralOrder.Primary
f1OG[Cards.Faction1.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f1OG[Cards.Faction1.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f1 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f1C = fmap[Factions.Faction1].generalTauntCallouts
f1C[Factions.Neutral] = i18next.t("factions.faction_1_taunt_neutral")
f1C[Factions.Faction1] = i18next.t("factions.faction_1_taunt_f1")
f1C[Factions.Faction2] = i18next.t("factions.faction_1_taunt_f2")
f1C[Factions.Faction3] = i18next.t("factions.faction_1_taunt_f3")
f1C[Factions.Faction4] = i18next.t("factions.faction_1_taunt_f4")
f1C[Factions.Faction5] = i18next.t("factions.faction_1_taunt_f5")
f1C[Factions.Faction6] = i18next.t("factions.faction_1_taunt_f6")
f1C[Factions.Boss] = i18next.t("factions.faction_1_taunt_boss")
#f1 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f1R = fmap[Factions.Faction1].generalTauntResponses
f1R[Factions.Neutral] = i18next.t("factions.faction_1_response_neutral")
f1R[Factions.Faction1] = i18next.t("factions.faction_1_response_f1")
f1R[Factions.Faction2] = i18next.t("factions.faction_1_response_f2")
f1R[Factions.Faction3] = i18next.t("factions.faction_1_response_f3")
f1R[Factions.Faction4] = i18next.t("factions.faction_1_response_f4")
f1R[Factions.Faction5] = i18next.t("factions.faction_1_response_f5")
f1R[Factions.Faction6] = i18next.t("factions.faction_1_response_f6")
f1R[Factions.Boss] = i18next.t("factions.faction_1_response_boss")
# f2
fmap[Factions.Faction2] =
id: Factions.Faction2
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction2"]
name: i18next.t("factions.faction_2_name")
short_name: i18next.t("factions.faction_2_abbreviated_name")
description: i18next.t("factions.faction_2_description")
devName: "songhai"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction2.General, Cards.Faction2.AltGeneral, Cards.Faction2.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f2
crestShadowResource: RSX.crest_f2_shadow
crestDeckSelectResource: RSX.crest_f2_deck_select
gradientColorMapWhite: {r: 254, g: 80, b: 100, a: 255}
gradientColorMapBlack: {r: 70, g: 5, b: 1, a: 255}
starterDeck: [
{id: Cards.Faction2.General},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Artifact.MaskOfBloodLeech},
{id: Cards.Spell.KillingEdge},
{id: Cards.Spell.KillingEdge},
{id: Cards.Spell.KillingEdge},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Faction2.KaidoAssassin},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Spell.PhoenixFire},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Faction2.Widowmaker},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f2 general data
f2GO = fmap[Factions.Faction2].generalIdsByOrder
f2GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction2.General
f2GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction2.AltGeneral
f2GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction2.ThirdGeneral
f2OG = fmap[Factions.Faction2].generalOrderByIds
f2OG[Cards.Faction2.General] = FactionFactory.GeneralOrder.Primary
f2OG[Cards.Faction2.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f2OG[Cards.Faction2.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f2 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f2C = fmap[Factions.Faction2].generalTauntCallouts
f2C[Factions.Neutral] = i18next.t("factions.faction_2_taunt_neutral")
f2C[Factions.Faction1] = i18next.t("factions.faction_2_taunt_f1")
f2C[Factions.Faction2] = i18next.t("factions.faction_2_taunt_f2")
f2C[Factions.Faction3] = i18next.t("factions.faction_2_taunt_f3")
f2C[Factions.Faction4] = i18next.t("factions.faction_2_taunt_f4")
f2C[Factions.Faction5] = i18next.t("factions.faction_2_taunt_f5")
f2C[Factions.Faction6] = i18next.t("factions.faction_2_taunt_f6")
f2C[Factions.Boss] = i18next.t("factions.faction_2_taunt_boss")
#f2 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f2R = fmap[Factions.Faction2].generalTauntResponses
f2R[Factions.Neutral] = i18next.t("factions.faction_2_response_neutral")
f2R[Factions.Faction1] = i18next.t("factions.faction_2_response_f1")
f2R[Factions.Faction2] = i18next.t("factions.faction_2_response_f2")
f2R[Factions.Faction3] = i18next.t("factions.faction_2_response_f3")
f2R[Factions.Faction4] = i18next.t("factions.faction_2_response_f4")
f2R[Factions.Faction5] = i18next.t("factions.faction_2_response_f5")
f2R[Factions.Faction6] = i18next.t("factions.faction_2_response_f6")
f2R[Factions.Boss] = i18next.t("factions.faction_2_response_boss")
# f3
fmap[Factions.Faction3] =
id: Factions.Faction3
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction3"]
name: i18next.t("factions.faction_3_name")
short_name: i18next.t("factions.faction_3_abbreviated_name")
description: i18next.t("factions.faction_3_description")
devName: "vetruvian"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction3.General, Cards.Faction3.AltGeneral, Cards.Faction3.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f3
crestShadowResource: RSX.crest_f3_shadow
crestDeckSelectResource: RSX.crest_f3_deck_select
gradientColorMapWhite: {r: 250, g: 160, b: 0, a: 255}
gradientColorMapBlack: {r: 39, g: 33, b: 21, a: 255}
starterDeck: [
{id: Cards.Faction3.General},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Spell.ScionsFirstWish},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Faction3.Pyromancer},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Artifact.StaffOfYKir},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Spell.EntropicDecay},
{id: Cards.Faction3.WindShrike},
{id: Cards.Faction3.WindShrike},
{id: Cards.Faction3.WindShrike},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f3 general data
f3GO = fmap[Factions.Faction3].generalIdsByOrder
f3GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction3.General
f3GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction3.AltGeneral
f3GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction3.ThirdGeneral
f3OG = fmap[Factions.Faction3].generalOrderByIds
f3OG[Cards.Faction3.General] = FactionFactory.GeneralOrder.Primary
f3OG[Cards.Faction3.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f3OG[Cards.Faction3.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f3 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f3C = fmap[Factions.Faction3].generalTauntCallouts
f3C[Factions.Neutral] = i18next.t("factions.faction_3_taunt_neutral")
f3C[Factions.Faction1] = i18next.t("factions.faction_3_taunt_f1")
f3C[Factions.Faction2] = i18next.t("factions.faction_3_taunt_f2")
f3C[Factions.Faction3] = i18next.t("factions.faction_3_taunt_f3")
f3C[Factions.Faction4] = i18next.t("factions.faction_3_taunt_f4")
f3C[Factions.Faction5] = i18next.t("factions.faction_3_taunt_f5")
f3C[Factions.Faction6] = i18next.t("factions.faction_3_taunt_f6")
f3C[Factions.Boss] = i18next.t("factions.faction_3_taunt_boss")
#f3 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f3R = fmap[Factions.Faction3].generalTauntResponses
f3R[Factions.Neutral] = i18next.t("factions.faction_3_response_neutral")
f3R[Factions.Faction1] = i18next.t("factions.faction_3_response_f1")
f3R[Factions.Faction2] = i18next.t("factions.faction_3_response_f2")
f3R[Factions.Faction3] = i18next.t("factions.faction_3_response_f3")
f3R[Factions.Faction4] = i18next.t("factions.faction_3_response_f4")
f3R[Factions.Faction5] = i18next.t("factions.faction_3_response_f5")
f3R[Factions.Faction6] = i18next.t("factions.faction_3_response_f6")
f3R[Factions.Boss] = i18next.t("factions.faction_3_response_boss")
# f4
fmap[Factions.Faction4] =
id: Factions.Faction4
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction4"]
name: i18next.t("factions.faction_4_name")
short_name: i18next.t("factions.faction_4_abbreviated_name")
description: i18next.t("factions.faction_4_description")
devName: "abyssian"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction4.General, Cards.Faction4.AltGeneral, Cards.Faction4.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f4
crestShadowResource: RSX.crest_f4_shadow
crestDeckSelectResource: RSX.crest_f4_deck_select
gradientColorMapWhite: {r: 247, g: 151, b: 254, a: 255}
gradientColorMapBlack: {r: 45, g: 50, b: 167, a: 255}
starterDeck: [
{id: Cards.Faction4.General},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Artifact.HornOfTheForsaken},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.GloomChaser},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Faction4.ShadowWatcher},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Spell.WraithlingSwarm},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Neutral.ThornNeedler},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Spell.DarkTransformation},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f4 general data
f4GO = fmap[Factions.Faction4].generalIdsByOrder
f4GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction4.General
f4GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction4.AltGeneral
f4GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction4.ThirdGeneral
f4OG = fmap[Factions.Faction4].generalOrderByIds
f4OG[Cards.Faction4.General] = FactionFactory.GeneralOrder.Primary
f4OG[Cards.Faction4.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f4OG[Cards.Faction4.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f4 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f4C = fmap[Factions.Faction4].generalTauntCallouts
f4C[Factions.Neutral] = i18next.t("factions.faction_4_taunt_neutral")
f4C[Factions.Faction1] = i18next.t("factions.faction_4_taunt_f1")
f4C[Factions.Faction2] = i18next.t("factions.faction_4_taunt_f2")
f4C[Factions.Faction3] = i18next.t("factions.faction_4_taunt_f3")
f4C[Factions.Faction4] = i18next.t("factions.faction_4_taunt_f4")
f4C[Factions.Faction5] = i18next.t("factions.faction_4_taunt_f5")
f4C[Factions.Faction6] = i18next.t("factions.faction_4_taunt_f6")
f4C[Factions.Boss] = i18next.t("factions.faction_4_taunt_boss")
#f4 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f4R = fmap[Factions.Faction4].generalTauntResponses
f4R[Factions.Neutral] = i18next.t("factions.faction_4_response_neutral")
f4R[Factions.Faction1] = i18next.t("factions.faction_4_response_f1")
f4R[Factions.Faction2] = i18next.t("factions.faction_4_response_f2")
f4R[Factions.Faction3] = i18next.t("factions.faction_4_response_f3")
f4R[Factions.Faction4] = i18next.t("factions.faction_4_response_f4")
f4R[Factions.Faction5] = i18next.t("factions.faction_4_response_f5")
f4R[Factions.Faction6] = i18next.t("factions.faction_4_response_f6")
f4R[Factions.Boss] = i18next.t("factions.faction_4_response_boss")
# f5
fmap[Factions.Faction5] =
id: Factions.Faction5
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction5"]
name: i18next.t("factions.faction_5_name")
short_name: i18next.t("factions.faction_5_abbreviated_name")
description: i18next.t("factions.faction_5_description")
devName: "magmar"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction5.General, Cards.Faction5.AltGeneral, Cards.Faction5.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f5
crestShadowResource: RSX.crest_f5_shadow
crestDeckSelectResource: RSX.crest_f5_deck_select
gradientColorMapWhite: {r: 0, g: 252, b: 250, a: 255}
gradientColorMapBlack: {r: 0, g: 62, b: 66, a: 255}
starterDeck: [
{id: Cards.Faction5.General},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.GreaterFortitude},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Spell.NaturalSelection},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Faction5.Phalanxar},
{id: Cards.Neutral.BloodshardGolem},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Faction5.EarthWalker},
{id: Cards.Neutral.SaberspineTiger},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Artifact.AdamantineClaws},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.BrightmossGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f5 general data
f5GO = fmap[Factions.Faction5].generalIdsByOrder
f5GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction5.General
f5GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction5.AltGeneral
f5GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction5.ThirdGeneral
f5OG = fmap[Factions.Faction5].generalOrderByIds
f5OG[Cards.Faction5.General] = FactionFactory.GeneralOrder.Primary
f5OG[Cards.Faction5.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f5OG[Cards.Faction5.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f5 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f5C = fmap[Factions.Faction5].generalTauntCallouts
f5C[Factions.Neutral] = i18next.t("factions.faction_5_taunt_neutral")
f5C[Factions.Faction1] = i18next.t("factions.faction_5_taunt_f1")
f5C[Factions.Faction2] = i18next.t("factions.faction_5_taunt_f2")
f5C[Factions.Faction3] = i18next.t("factions.faction_5_taunt_f3")
f5C[Factions.Faction4] = i18next.t("factions.faction_5_taunt_f4")
f5C[Factions.Faction5] = i18next.t("factions.faction_5_taunt_f5")
f5C[Factions.Faction6] = i18next.t("factions.faction_5_taunt_f6")
f5C[Factions.Boss] = i18next.t("factions.faction_5_taunt_boss")
#f5 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f5R = fmap[Factions.Faction5].generalTauntResponses
f5R[Factions.Neutral] = i18next.t("factions.faction_5_response_neutral")
f5R[Factions.Faction1] = i18next.t("factions.faction_5_response_f1")
f5R[Factions.Faction2] = i18next.t("factions.faction_5_response_f2")
f5R[Factions.Faction3] = i18next.t("factions.faction_5_response_f3")
f5R[Factions.Faction4] = i18next.t("factions.faction_5_response_f4")
f5R[Factions.Faction5] = i18next.t("factions.faction_5_response_f5")
f5R[Factions.Faction6] = i18next.t("factions.faction_5_response_f6")
f5R[Factions.Boss] = i18next.t("factions.faction_5_response_boss")
# f6
fmap[Factions.Faction6] =
id: Factions.Faction6
fxResource: ["FX.Factions.Neutral", "FX.Factions.Faction6"]
name: i18next.t("factions.faction_6_name")
short_name: i18next.t("factions.faction_6_abbreviated_name")
description: i18next.t("factions.faction_6_description")
devName: "PI:NAME:<NAME>END_PI"
isNeutral: false
enabled: true
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [Cards.Faction6.General, Cards.Faction6.AltGeneral, Cards.Faction6.ThirdGeneral]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.faction_1_resign_statement")
crestResource: RSX.crest_f6
crestShadowResource: RSX.crest_f6_shadow
crestDeckSelectResource: RSX.crest_f6_deck_select
gradientColorMapWhite: {r: 185, g: 208, b: 226, a: 255}
gradientColorMapBlack: {r: 9, g: 12, b: 55, a: 255}
starterDeck: [
{id: Cards.Faction6.General},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Spell.FlashFreeze},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Faction6.CrystalCloaker},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Spell.PermafrostShield},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Artifact.Snowpiercer},
{id: Cards.Neutral.PutridMindflayer},
{id: Cards.Neutral.FlameWing},
{id: Cards.Neutral.FlameWing},
{id: Cards.Neutral.HailstoneGolem},
{id: Cards.Neutral.PrimusShieldmaster},
{id: Cards.Neutral.Necroseer},
{id: Cards.Neutral.Necroseer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Faction6.ArcticDisplacer},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.StormmetalGolem},
{id: Cards.Neutral.Bloodletter},
{id: Cards.Neutral.DragoneboneGolem},
{id: Cards.Neutral.DragoneboneGolem}
]
# f6 general data
f6GO = fmap[Factions.Faction6].generalIdsByOrder
f6GO[FactionFactory.GeneralOrder.Primary] = Cards.Faction6.General
f6GO[FactionFactory.GeneralOrder.Secondary] = Cards.Faction6.AltGeneral
f6GO[FactionFactory.GeneralOrder.Tertiary] = Cards.Faction6.ThirdGeneral
f6OG = fmap[Factions.Faction6].generalOrderByIds
f6OG[Cards.Faction6.General] = FactionFactory.GeneralOrder.Primary
f6OG[Cards.Faction6.AltGeneral] = FactionFactory.GeneralOrder.Secondary
f6OG[Cards.Faction6.ThirdGeneral] = FactionFactory.GeneralOrder.Tertiary
#f6 callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f6C = fmap[Factions.Faction6].generalTauntCallouts
f6C[Factions.Neutral] = i18next.t("factions.faction_6_taunt_neutral")
f6C[Factions.Faction1] = i18next.t("factions.faction_6_taunt_f1")
f6C[Factions.Faction2] = i18next.t("factions.faction_6_taunt_f2")
f6C[Factions.Faction3] = i18next.t("factions.faction_6_taunt_f3")
f6C[Factions.Faction4] = i18next.t("factions.faction_6_taunt_f4")
f6C[Factions.Faction5] = i18next.t("factions.faction_6_taunt_f5")
f6C[Factions.Faction6] = i18next.t("factions.faction_6_taunt_f6")
f6C[Factions.Boss] = i18next.t("factions.faction_6_taunt_boss")
#f6 responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
f6R = fmap[Factions.Faction6].generalTauntResponses
f6R[Factions.Neutral] = i18next.t("factions.faction_6_response_neutral")
f6R[Factions.Faction1] = i18next.t("factions.faction_6_response_f1")
f6R[Factions.Faction2] = i18next.t("factions.faction_6_response_f2")
f6R[Factions.Faction3] = i18next.t("factions.faction_6_response_f3")
f6R[Factions.Faction4] = i18next.t("factions.faction_6_response_f4")
f6R[Factions.Faction5] = i18next.t("factions.faction_6_response_f5")
f6R[Factions.Faction6] = i18next.t("factions.faction_6_response_f6")
f6R[Factions.Boss] = i18next.t("factions.faction_6_response_boss")
# neutral
fmap[Factions.Neutral] =
id: Factions.Neutral
fxResource: ["FX.Factions.Neutral"]
name: i18next.t("factions.faction_neutral_name")
short_name: i18next.t("factions.faction_neutral_abbreviated_name")
devName: "neutral"
description: ""
isNeutral: true
enabled: true
isInDevelopment: false
# tutorial faction
fmap[Factions.Tutorial] =
id: Factions.Tutorial
fxResource: ["FX.Factions.Neutral", "FX.Factions.Tutorial"]
name: "PI:NAME:<NAME>END_PI"
devName: "PI:NAME:<NAME>END_PI"
description: "The Teacher of Duelyst"
gameCountFlavorText: "N/A"
isNeutral: false
enabled: false
isInDevelopment: false
generalIds: [
Cards.Tutorial.TutorialGeneral,
Cards.Tutorial.TutorialSignatureGeneral,
Cards.Tutorial.TutorialOpponentGeneral1,
Cards.Tutorial.TutorialOpponentGeneral2,
Cards.Tutorial.TutorialOpponentGeneral4
]
announcerFirst: null # TODO: audio
announcerSecond: null # TODO: audio
gradientColorMapWhite: {r: 255, g: 255, b: 255, a: 255}
gradientColorMapBlack: {r: 0, g: 0, b: 0, a: 255}
# bosses faction
fmap[Factions.Boss] =
id: Factions.Boss
fxResource: ["FX.Factions.Neutral", "FX.Factions.Boss"]
name: "Boss"
devName: "bosses"
description: "Mysterious Challengers"
isNeutral: false
enabled: false
isInDevelopment: false
generalTauntCallouts: {}
generalTauntResponses: {}
generalIds: [
Cards.Boss.Boss38,
Cards.Boss.Boss37,
Cards.Boss.Boss36,
Cards.Boss.Boss35,
Cards.Boss.Boss34,
Cards.Boss.Boss33,
Cards.Boss.Boss32,
Cards.Boss.Boss31,
Cards.Boss.Boss30,
Cards.Boss.Boss29,
Cards.Boss.Boss28,
Cards.Boss.Boss27,
Cards.Boss.Boss26,
Cards.Boss.Boss25,
Cards.Boss.Boss24,
Cards.Boss.Boss23,
Cards.Boss.Boss22,
Cards.Boss.Boss21,
Cards.Boss.Boss20,
Cards.Boss.Boss19,
Cards.Boss.Boss18,
Cards.Boss.Boss17,
Cards.Boss.Boss16,
Cards.Boss.Boss15,
Cards.Boss.Boss14,
Cards.Boss.Boss13,
Cards.Boss.Boss12,
Cards.Boss.Boss11,
Cards.Boss.Boss10,
Cards.Boss.Boss6,
Cards.Boss.Boss9,
Cards.Boss.Boss2,
Cards.Boss.Boss4,
Cards.Boss.Boss5,
Cards.Boss.Boss1,
Cards.Boss.Boss7,
Cards.Boss.Boss8,
Cards.Boss.Boss3
]
generalIdsByOrder: {}
generalOrderByIds: {}
resignStatement: i18next.t("factions.generic_concede")
gameCountFlavorText: "N/A"
crestImg: null
crestShadowImg: null
crestDeckSelectImg: null
gradientColorMapWhite: {r: 255, g: 255, b: 255, a: 255}
gradientColorMapBlack: {r: 0, g: 0, b: 0, a: 255}
#boss callouts
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
fbC = fmap[Factions.Boss].generalTauntCallouts
fbC[Factions.Neutral] = i18next.t("factions.boss_neutral_taunt")
# specific boss callouts
fbC1 = fbC[Cards.Boss.Boss1] = {}
fbC1[Factions.Neutral] = i18next.t("factions.boss_1_taunt")
fbC2 = fbC[Cards.Boss.Boss2] = {}
fbC2[Factions.Neutral] = i18next.t("factions.boss_2_taunt")
fbC3 = fbC[Cards.Boss.Boss3] = fbC[Cards.Boss.Boss7] = {}
fbC3[Factions.Neutral] = i18next.t("factions.boss_3_taunt")
fbC4 = fbC[Cards.Boss.Boss4] = {}
fbC4[Factions.Neutral] = i18next.t("factions.boss_4_taunt")
fbC5 = fbC[Cards.Boss.Boss5] = {}
fbC5[Factions.Neutral] = i18next.t("factions.boss_5_taunt")
fbC6 = fbC[Cards.Boss.Boss6] = {}
fbC6[Factions.Neutral] = i18next.t("factions.boss_6_taunt")
fbC8 = fbC[Cards.Boss.Boss8] = {}
fbC8[Factions.Neutral] = i18next.t("factions.boss_8_taunt")
fbC9 = fbC[Cards.Boss.Boss9] = {}
fbC9[Factions.Neutral] = i18next.t("factions.boss_9_taunt")
fbC10 = fbC[Cards.Boss.Boss10] = {}
fbC10[Factions.Neutral] = i18next.t("factions.boss_10_taunt")
fbC11 = fbC[Cards.Boss.Boss11] = {}
fbC11[Factions.Neutral] = i18next.t("factions.boss_11_taunt")
fbC12 = fbC[Cards.Boss.Boss12] = {}
fbC12[Factions.Neutral] = i18next.t("factions.boss_12_taunt")
fbC13 = fbC[Cards.Boss.Boss13] = {}
fbC13[Factions.Neutral] = i18next.t("factions.boss_13_taunt")
fbC14 = fbC[Cards.Boss.Boss14] = {}
fbC14[Factions.Neutral] = i18next.t("factions.boss_14_taunt")
fbC15 = fbC[Cards.Boss.Boss15] = {}
fbC15[Factions.Neutral] = i18next.t("factions.boss_15_taunt")
fbC16 = fbC[Cards.Boss.Boss16] = {}
fbC16[Factions.Neutral] = i18next.t("factions.boss_16_taunt")
fbC17 = fbC[Cards.Boss.Boss17] = {}
fbC17[Factions.Neutral] = i18next.t("factions.boss_17_taunt")
fbC18 = fbC[Cards.Boss.Boss18] = {}
fbC18[Factions.Neutral] = i18next.t("factions.boss_18_taunt")
fbC19 = fbC[Cards.Boss.Boss19] = {}
fbC19[Factions.Neutral] = i18next.t("factions.boss_19_taunt")
fbC20 = fbC[Cards.Boss.Boss20] = {}
fbC20[Factions.Neutral] = i18next.t("factions.boss_20_taunt")
fbC21 = fbC[Cards.Boss.Boss21] = {}
fbC21[Factions.Neutral] = i18next.t("factions.boss_21_taunt")
fbC22 = fbC[Cards.Boss.Boss22] = {}
fbC22[Factions.Neutral] = i18next.t("factions.boss_22_taunt")
fbC23 = fbC[Cards.Boss.Boss23] = {}
fbC23[Factions.Neutral] = i18next.t("factions.boss_23_taunt")
fbC24 = fbC[Cards.Boss.Boss24] = {}
fbC24[Factions.Neutral] = i18next.t("factions.boss_24_taunt")
fbC25 = fbC[Cards.Boss.Boss25] = {}
fbC25[Factions.Neutral] = i18next.t("factions.boss_25_taunt")
fbC26 = fbC[Cards.Boss.Boss26] = {}
fbC26[Factions.Neutral] = i18next.t("factions.boss_26_taunt")
fbC27 = fbC[Cards.Boss.Boss27] = {}
fbC27[Factions.Neutral] = i18next.t("factions.boss_27_taunt")
fbC28 = fbC[Cards.Boss.Boss28] = {}
fbC28[Factions.Neutral] = i18next.t("factions.boss_28_taunt")
fbC29 = fbC[Cards.Boss.Boss29] = {}
fbC29[Factions.Neutral] = i18next.t("factions.boss_29_taunt")
fbC30 = fbC[Cards.Boss.Boss30] = {}
fbC30[Factions.Neutral] = i18next.t("factions.boss_30_taunt")
fbC31 = fbC[Cards.Boss.Boss31] = {}
fbC31[Factions.Neutral] = i18next.t("factions.boss_31_taunt")
fbC32 = fbC[Cards.Boss.Boss32] = {}
fbC32[Factions.Neutral] = i18next.t("factions.boss_32_taunt")
fbC33 = fbC[Cards.Boss.Boss33] = {}
fbC33[Factions.Neutral] = i18next.t("factions.boss_33_taunt")
fbC34 = fbC[Cards.Boss.Boss34] = {}
fbC34[Factions.Neutral] = i18next.t("factions.boss_34_taunt")
fbC35 = fbC[Cards.Boss.Boss35] = {}
fbC35[Factions.Neutral] = i18next.t("factions.boss_35_taunt")
fbC36 = fbC[Cards.Boss.Boss36] = {}
fbC36[Factions.Neutral] = i18next.t("factions.boss_36_taunt")
fbC37 = fbC[Cards.Boss.Boss37] = {}
fbC37[Factions.Neutral] = i18next.t("factions.boss_37_taunt")
fbC38 = fbC[Cards.Boss.Boss38] = {}
fbC38[Factions.Neutral] = i18next.t("factions.boss_38_taunt")
#boss responses
# adding a sub map keyed by general id to this map
# will use those instead when my general is that general
fbR = fmap[Factions.Boss].generalTauntResponses
fbR[Factions.Neutral] = i18next.t("factions.boss_neutral_taunt")
# specific boss callouts
fbR1 = fbR[Cards.Boss.Boss1] = {}
fbR1[Factions.Neutral] = i18next.t("factions.boss_1_taunt")
fbR2 = fbR[Cards.Boss.Boss2] = {}
fbR2[Factions.Neutral] = i18next.t("factions.boss_2_taunt")
fbR3 = fbR[Cards.Boss.Boss3] = fbR[Cards.Boss.Boss7] = {}
fbR3[Factions.Neutral] = i18next.t("factions.boss_3_taunt")
fbR4 = fbR[Cards.Boss.Boss4] = {}
fbR4[Factions.Neutral] = i18next.t("factions.boss_4_taunt")
fbR5 = fbR[Cards.Boss.Boss5] = {}
fbR5[Factions.Neutral] = i18next.t("factions.boss_5_taunt")
fbR6 = fbR[Cards.Boss.Boss6] = {}
fbR6[Factions.Neutral] = i18next.t("factions.boss_6_taunt")
fbR8 = fbR[Cards.Boss.Boss8] = {}
fbR8[Factions.Neutral] = i18next.t("factions.boss_8_taunt")
fbR9 = fbR[Cards.Boss.Boss9] = {}
fbR9[Factions.Neutral] = i18next.t("factions.boss_9_taunt")
fbR10 = fbR[Cards.Boss.Boss10] = {}
fbR10[Factions.Neutral] = i18next.t("factions.boss_10_taunt")
fbR11 = fbR[Cards.Boss.Boss11] = {}
fbR11[Factions.Neutral] = i18next.t("factions.boss_11_taunt")
fbR12 = fbR[Cards.Boss.Boss12] = {}
fbR12[Factions.Neutral] = i18next.t("factions.boss_12_taunt")
fbR13 = fbR[Cards.Boss.Boss13] = {}
fbR13[Factions.Neutral] = i18next.t("factions.boss_13_taunt")
fbR14 = fbR[Cards.Boss.Boss14] = {}
fbR14[Factions.Neutral] = i18next.t("factions.boss_14_taunt")
fbR15 = fbR[Cards.Boss.Boss15] = {}
fbR15[Factions.Neutral] = i18next.t("factions.boss_15_taunt")
fbR16 = fbR[Cards.Boss.Boss16] = {}
fbR16[Factions.Neutral] = i18next.t("factions.boss_16_taunt")
fbR17 = fbR[Cards.Boss.Boss17] = {}
fbR17[Factions.Neutral] = i18next.t("factions.boss_17_taunt")
fbR18 = fbR[Cards.Boss.Boss18] = {}
fbR18[Factions.Neutral] = i18next.t("factions.boss_18_taunt")
fbR19 = fbR[Cards.Boss.Boss19] = {}
fbR19[Factions.Neutral] = i18next.t("factions.boss_19_taunt")
fbR20 = fbR[Cards.Boss.Boss20] = {}
fbR20[Factions.Neutral] = i18next.t("factions.boss_20_taunt")
fbR21 = fbR[Cards.Boss.Boss21] = {}
fbR21[Factions.Neutral] = i18next.t("factions.boss_21_taunt")
fbR22 = fbR[Cards.Boss.Boss22] = {}
fbR22[Factions.Neutral] = i18next.t("factions.boss_22_taunt")
fbR23 = fbR[Cards.Boss.Boss23] = {}
fbR23[Factions.Neutral] = i18next.t("factions.boss_23_taunt")
fbR24 = fbR[Cards.Boss.Boss24] = {}
fbR24[Factions.Neutral] = i18next.t("factions.boss_24_taunt")
fbR25 = fbR[Cards.Boss.Boss25] = {}
fbR25[Factions.Neutral] = i18next.t("factions.boss_25_taunt")
fbR26 = fbR[Cards.Boss.Boss26] = {}
fbR26[Factions.Neutral] = i18next.t("factions.boss_26_taunt")
fbR27 = fbR[Cards.Boss.Boss27] = {}
fbR27[Factions.Neutral] = i18next.t("factions.boss_27_taunt")
fbR28 = fbR[Cards.Boss.Boss28] = {}
fbR28[Factions.Neutral] = i18next.t("factions.boss_28_taunt")
fbR29 = fbR[Cards.Boss.Boss29] = {}
fbR29[Factions.Neutral] = i18next.t("factions.boss_29_taunt")
fbR30 = fbR[Cards.Boss.Boss30] = {}
fbR30[Factions.Neutral] = i18next.t("factions.boss_30_taunt")
fbR31 = fbR[Cards.Boss.Boss31] = {}
fbR31[Factions.Neutral] = i18next.t("factions.boss_31_taunt")
fbR32 = fbR[Cards.Boss.Boss32] = {}
fbR32[Factions.Neutral] = i18next.t("factions.boss_32_taunt")
fbR33 = fbR[Cards.Boss.Boss33] = {}
fbR33[Factions.Neutral] = i18next.t("factions.boss_33_taunt")
fbR34 = fbR[Cards.Boss.Boss34] = {}
fbR34[Factions.Neutral] = i18next.t("factions.boss_34_taunt")
fbR35 = fbR[Cards.Boss.Boss35] = {}
fbR35[Factions.Neutral] = i18next.t("factions.boss_35_taunt")
fbR36 = fbR[Cards.Boss.Boss36] = {}
fbR36[Factions.Neutral] = i18next.t("factions.boss_36_taunt")
fbR37 = fbR[Cards.Boss.Boss37] = {}
fbR37[Factions.Neutral] = i18next.t("factions.boss_37_taunt")
fbR38 = fbR[Cards.Boss.Boss38] = {}
fbR38[Factions.Neutral] = i18next.t("factions.boss_38_taunt")
module.exports = FactionFactory
|
[
{
"context": "ew Enforce style prop value is an object\n# @author David Petersen\n###\n'use strict'\n\nvariableUtil = require '../util",
"end": 83,
"score": 0.9998289942741394,
"start": 69,
"tag": "NAME",
"value": "David Petersen"
}
] | src/rules/style-prop-object.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Enforce style prop value is an object
# @author David Petersen
###
'use strict'
variableUtil = require '../util/react/variable'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Enforce style prop value is an object'
category: ''
recommended: no
url: docsUrl 'style-prop-object'
schema: []
create: (context) ->
###*
# @param {object} node An Identifier node
###
isNonNullaryLiteral = (expression) ->
expression.type is 'Literal' and expression.value isnt null
###*
# @param {object} node A Identifier node
###
checkIdentifiers = (node) ->
variable =
variableUtil
.variablesInScope context
.find (item) -> item.name is node.name
if variable?.defs[0]?.node.init
if isNonNullaryLiteral variable.defs[0].node.init
context.report node, 'Style prop value must be an object'
if variable?.defs[0]?.node.parent.right
if isNonNullaryLiteral variable.defs[0].node.parent.right
context.report node, 'Style prop value must be an object'
CallExpression: (node) ->
if (
node.callee?.type is 'MemberExpression' and
node.callee.property.name is 'createElement' and
node.arguments.length > 1
)
if node.arguments[1].type is 'ObjectExpression'
style = node.arguments[1].properties.find (property) ->
property.key and
property.key.name is 'style' and
not property.computed
if style
if style.value.type is 'Identifier'
checkIdentifiers style.value
else if isNonNullaryLiteral style.value
context.report style.value, 'Style prop value must be an object'
JSXAttribute: (node) ->
return if not node.value or node.name.name isnt 'style'
if (
node.value.type isnt 'JSXExpressionContainer' or
isNonNullaryLiteral node.value.expression
)
context.report node, 'Style prop value must be an object'
else if node.value.expression.type is 'Identifier'
checkIdentifiers node.value.expression
| 224298 | ###*
# @fileoverview Enforce style prop value is an object
# @author <NAME>
###
'use strict'
variableUtil = require '../util/react/variable'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Enforce style prop value is an object'
category: ''
recommended: no
url: docsUrl 'style-prop-object'
schema: []
create: (context) ->
###*
# @param {object} node An Identifier node
###
isNonNullaryLiteral = (expression) ->
expression.type is 'Literal' and expression.value isnt null
###*
# @param {object} node A Identifier node
###
checkIdentifiers = (node) ->
variable =
variableUtil
.variablesInScope context
.find (item) -> item.name is node.name
if variable?.defs[0]?.node.init
if isNonNullaryLiteral variable.defs[0].node.init
context.report node, 'Style prop value must be an object'
if variable?.defs[0]?.node.parent.right
if isNonNullaryLiteral variable.defs[0].node.parent.right
context.report node, 'Style prop value must be an object'
CallExpression: (node) ->
if (
node.callee?.type is 'MemberExpression' and
node.callee.property.name is 'createElement' and
node.arguments.length > 1
)
if node.arguments[1].type is 'ObjectExpression'
style = node.arguments[1].properties.find (property) ->
property.key and
property.key.name is 'style' and
not property.computed
if style
if style.value.type is 'Identifier'
checkIdentifiers style.value
else if isNonNullaryLiteral style.value
context.report style.value, 'Style prop value must be an object'
JSXAttribute: (node) ->
return if not node.value or node.name.name isnt 'style'
if (
node.value.type isnt 'JSXExpressionContainer' or
isNonNullaryLiteral node.value.expression
)
context.report node, 'Style prop value must be an object'
else if node.value.expression.type is 'Identifier'
checkIdentifiers node.value.expression
| true | ###*
# @fileoverview Enforce style prop value is an object
# @author PI:NAME:<NAME>END_PI
###
'use strict'
variableUtil = require '../util/react/variable'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Enforce style prop value is an object'
category: ''
recommended: no
url: docsUrl 'style-prop-object'
schema: []
create: (context) ->
###*
# @param {object} node An Identifier node
###
isNonNullaryLiteral = (expression) ->
expression.type is 'Literal' and expression.value isnt null
###*
# @param {object} node A Identifier node
###
checkIdentifiers = (node) ->
variable =
variableUtil
.variablesInScope context
.find (item) -> item.name is node.name
if variable?.defs[0]?.node.init
if isNonNullaryLiteral variable.defs[0].node.init
context.report node, 'Style prop value must be an object'
if variable?.defs[0]?.node.parent.right
if isNonNullaryLiteral variable.defs[0].node.parent.right
context.report node, 'Style prop value must be an object'
CallExpression: (node) ->
if (
node.callee?.type is 'MemberExpression' and
node.callee.property.name is 'createElement' and
node.arguments.length > 1
)
if node.arguments[1].type is 'ObjectExpression'
style = node.arguments[1].properties.find (property) ->
property.key and
property.key.name is 'style' and
not property.computed
if style
if style.value.type is 'Identifier'
checkIdentifiers style.value
else if isNonNullaryLiteral style.value
context.report style.value, 'Style prop value must be an object'
JSXAttribute: (node) ->
return if not node.value or node.name.name isnt 'style'
if (
node.value.type isnt 'JSXExpressionContainer' or
isNonNullaryLiteral node.value.expression
)
context.report node, 'Style prop value must be an object'
else if node.value.expression.type is 'Identifier'
checkIdentifiers node.value.expression
|
[
{
"context": " .addPlugin('Permissions', {\n # user: 'Bill'\n # })\n #\n # Returns itself to allow chain",
"end": 17729,
"score": 0.9825305938720703,
"start": 17725,
"tag": "NAME",
"value": "Bill"
},
{
"context": "eate annotations?\n unless @canAnnotate\n #@... | h/lib/_annotator_mapsrc/src/annotator.coffee | gnott/h | 0 | # Selection and range creation reference for the following code:
# http://www.quirksmode.org/dom/range_intro.html
#
# I've removed any support for IE TextRange (see commit d7085bf2 for code)
# for the moment, having no means of testing it.
util =
uuid: (-> counter = 0; -> counter++)()
getGlobal: -> (-> this)()
# Return the maximum z-index of any element in $elements (a jQuery collection).
maxZIndex: ($elements) ->
all = for el in $elements
if $(el).css('position') == 'static'
-1
else
parseInt($(el).css('z-index'), 10) or -1
Math.max.apply(Math, all)
mousePosition: (e, offsetEl) ->
# If the offset element is not a positioning root use its offset parent
unless $(offsetEl).css('position') in ['absolute', 'fixed', 'relative']
offsetEl = $(offsetEl).offsetParent()[0]
offset = $(offsetEl).offset()
{
top: e.pageY - offset.top,
left: e.pageX - offset.left
}
# Checks to see if an event parameter is provided and contains the prevent
# default method. If it does it calls it.
#
# This is useful for methods that can be optionally used as callbacks
# where the existance of the parameter must be checked before calling.
preventEventDefault: (event) ->
event?.preventDefault?()
# Store a reference to the current Annotator object.
_Annotator = this.Annotator
# Fake two-phase / pagination support, used for HTML documents
class DummyDocumentAccess
@applicable: -> true
getPageIndex: -> 0
getPageCount: -> 1
getPageIndexForPos: -> 0
isPageMapped: -> true
scan: ->
class Annotator extends Delegator
# Events to be bound on Annotator#element.
events:
".annotator-adder button click": "onAdderClick"
".annotator-adder button mousedown": "onAdderMousedown"
html:
adder: '<div class="annotator-adder"><button>' + _t('Annotate') + '</button></div>'
wrapper: '<div class="annotator-wrapper"></div>'
options: # Configuration options
readOnly: false # Start Annotator in read-only mode. No controls will be shown.
plugins: {}
editor: null
viewer: null
selectedTargets: null
mouseIsDown: false
inAdderClick: false
canAnnotate: false
viewerHideTimer: null
# Public: Creates an instance of the Annotator. Requires a DOM Element in
# which to watch for annotations as well as any options.
#
# NOTE: If the Annotator is not supported by the current browser it will not
# perform any setup and simply return a basic object. This allows plugins
# to still be loaded but will not function as expected. It is reccomended
# to call Annotator.supported() before creating the instance or using the
# Unsupported plugin which will notify users that the Annotator will not work.
#
# element - A DOM Element in which to annotate.
# options - An options Object. NOTE: There are currently no user options.
#
# Examples
#
# annotator = new Annotator(document.body)
#
# # Example of checking for support.
# if Annotator.supported()
# annotator = new Annotator(document.body)
# else
# # Fallback for unsupported browsers.
#
# Returns a new instance of the Annotator.
constructor: (element, options) ->
super
@plugins = {}
@anchoringStrategies = []
# Return early if the annotator is not supported.
return this unless Annotator.supported()
this._setupDocumentEvents() unless @options.readOnly
this._setupAnchorEvents()
this._setupWrapper()
this._setupDocumentAccessStrategies()
this._setupViewer()._setupEditor()
this._setupDynamicStyle()
# Perform initial DOM scan, unless told not to.
this._scan() unless @options.noScan
# Create adder
this.adder = $(this.html.adder).appendTo(@wrapper).hide()
# Initializes the available document access strategies
_setupDocumentAccessStrategies: ->
@documentAccessStrategies = [
# Default dummy strategy for simple HTML documents.
# The generic fallback.
name: "Dummy"
mapper: DummyDocumentAccess
]
this
# Initializes the components used for analyzing the document
_chooseAccessPolicy: ->
if @domMapper? then return
# Go over the available strategies
for s in @documentAccessStrategies
# Can we use this strategy for this document?
if s.mapper.applicable()
@documentAccessStrategy = s
console.log "Selected document access strategy: " + s.name
@domMapper = new s.mapper()
@anchors = {}
addEventListener "docPageMapped", (evt) =>
@_realizePage evt.pageIndex
addEventListener "docPageUnmapped", (evt) =>
@_virtualizePage evt.pageIndex
s.init?()
return this
# Perform a scan of the DOM. Required for finding anchors.
_scan: ->
# If we haven't yet chosen a document access strategy, do so now.
this._chooseAccessPolicy() unless @domMapper
@pendingScan = @domMapper.scan()
if @pendingScan?
@pendingScan.then => @enableAnnotating()
else
@enableAnnotating()
# Wraps the children of @element in a @wrapper div. NOTE: This method will also
# remove any script elements inside @element to prevent them re-executing.
#
# Returns itself to allow chaining.
_setupWrapper: ->
@wrapper = $(@html.wrapper)
# We need to remove all scripts within the element before wrapping the
# contents within a div. Otherwise when scripts are reappended to the DOM
# they will re-execute. This is an issue for scripts that call
# document.write() - such as ads - as they will clear the page.
@element.find('script').remove()
@element.wrapInner(@wrapper)
@wrapper = @element.find('.annotator-wrapper')
this
# Creates an instance of Annotator.Viewer and assigns it to the @viewer
# property, appends it to the @wrapper and sets up event listeners.
#
# Returns itself to allow chaining.
_setupViewer: ->
@viewer = new Annotator.Viewer(readOnly: @options.readOnly)
@viewer.hide()
.on("edit", this.onEditAnnotation)
.on("delete", this.onDeleteAnnotation)
.addField({
load: (field, annotation) =>
if annotation.text
$(field).html(Util.escape(annotation.text))
else
$(field).html("<i>#{_t 'No Comment'}</i>")
this.publish('annotationViewerTextField', [field, annotation])
})
.element.appendTo(@wrapper).bind({
"mouseover": this.clearViewerHideTimer
"mouseout": this.startViewerHideTimer
})
this
# Creates an instance of the Annotator.Editor and assigns it to @editor.
# Appends this to the @wrapper and sets up event listeners.
#
# Returns itself for chaining.
_setupEditor: ->
@editor = new Annotator.Editor()
@editor.hide()
.on('hide', this.onEditorHide)
.on('save', this.onEditorSubmit)
.addField({
type: 'textarea',
label: _t('Comments') + '\u2026'
load: (field, annotation) ->
$(field).find('textarea').val(annotation.text || '')
submit: (field, annotation) ->
annotation.text = $(field).find('textarea').val()
})
@editor.element.appendTo(@wrapper)
this
# Sets up the selection event listeners to watch mouse actions on the document.
#
# Returns itself for chaining.
_setupDocumentEvents: ->
$(document).bind({
"mousedown": this.checkForStartSelection
})
this
# Sets up handlers to anchor-related events
_setupAnchorEvents: ->
# When annotations are updated
@on 'annotationUpdated', (annotation) =>
# Notify the anchors
for anchor in annotation.anchors or []
anchor.annotationUpdated()
# Sets up any dynamically calculated CSS for the Annotator.
#
# Returns itself for chaining.
_setupDynamicStyle: ->
style = $('#annotator-dynamic-style')
if (!style.length)
style = $('<style id="annotator-dynamic-style"></style>').appendTo(document.head)
sel = '*' + (":not(.annotator-#{x})" for x in ['adder', 'outer', 'notice', 'filter']).join('')
# use the maximum z-index in the page
max = util.maxZIndex($(document.body).find(sel))
# but don't go smaller than 1010, because this isn't bulletproof --
# dynamic elements in the page (notifications, dialogs, etc.) may well
# have high z-indices that we can't catch using the above method.
max = Math.max(max, 1000)
style.text [
".annotator-adder, .annotator-outer, .annotator-notice {"
" z-index: #{max + 20};"
"}"
".annotator-filter {"
" z-index: #{max + 10};"
"}"
].join("\n")
this
# Enables or disables the creation of annotations
#
# When it's set to false, nobody os supposed to call
# onSuccessfulSelection()
enableAnnotating: (value = true, local = true) ->
# If we already have this setting, do nothing
return if value is @canAnnotate
# Set the field
@canAnnotate = value
# Publish an event, so that others can react
this.publish "enableAnnotating", value
# If this call came from "outside" (whatever it means), and annotation
# is now disabled, then hide the adder.
@adder.hide() unless value or local
# Shortcut to disable annotating
disableAnnotating: (local = true) -> this.enableAnnotating false, local
# Utility function to get the decoded form of the document URI
getHref: =>
uri = decodeURIComponent document.location.href
if document.location.hash then uri = uri.slice 0, (-1 * location.hash.length)
$('meta[property^="og:url"]').each -> uri = decodeURIComponent this.content
$('link[rel^="canonical"]').each -> uri = decodeURIComponent this.href
return uri
# Public: Creates and returns a new annotation object. Publishes the
# 'beforeAnnotationCreated' event to allow the new annotation to be modified.
#
# Examples
#
# annotator.createAnnotation() # Returns {}
#
# annotator.on 'beforeAnnotationCreated', (annotation) ->
# annotation.myProperty = 'This is a custom property'
# annotator.createAnnotation() # Returns {myProperty: "This is a…"}
#
# Returns a newly created annotation Object.
createAnnotation: () ->
annotation = {}
this.publish('beforeAnnotationCreated', [annotation])
annotation
# Do some normalization to get a "canonical" form of a string.
# Used to even out some browser differences.
normalizeString: (string) -> string.replace /\s{2,}/g, " "
# Find the given type of selector from an array of selectors, if it exists.
# If it does not exist, null is returned.
findSelector: (selectors, type) ->
for selector in selectors
if selector.type is type then return selector
null
# Try to find the right anchoring point for a given target
#
# Returns an Anchor object if succeeded, null otherwise
createAnchor: (annotation, target) ->
unless target?
throw new Error "Trying to find anchor for null target!"
# console.log "Trying to find anchor for target: "
# console.log target
error = null
anchor = null
for s in @anchoringStrategies
try
a = s.code.call this, annotation, target
if a
# console.log "Strategy '" + s.name + "' yielded an anchor."
return result: a
# else
# console.log "Strategy '" + s.name + "' did NOT yield an anchor."
catch error
# console.log "Strategy '" + s.name + "' has thrown an error."
if error instanceof Range.RangeError
return error: error
else
throw error
return error: "No strategies worked."
# Public: Initialises an annotation either from an object representation or
# an annotation created with Annotator#createAnnotation(). It finds the
# selected range and higlights the selection in the DOM, extracts the
# quoted text and serializes the range.
#
# annotation - An annotation Object to initialise.
#
# Examples
#
# # Create a brand new annotation from the currently selected text.
# annotation = annotator.createAnnotation()
# annotation = annotator.setupAnnotation(annotation)
# # annotation has now been assigned the currently selected range
# # and a highlight appended to the DOM.
#
# # Add an existing annotation that has been stored elsewere to the DOM.
# annotation = getStoredAnnotationWithSerializedRanges()
# annotation = annotator.setupAnnotation(annotation)
#
# Returns the initialised annotation.
setupAnnotation: (annotation) ->
# If this is a new annotation, we might have to add the targets
annotation.target ?= @selectedTargets
@selectedTargets = []
unless annotation.target?
throw new Error "Can not run setupAnnotation(). No target or selection available."
annotation.quote = []
annotation.anchors = []
for t in annotation.target
try
# Create an anchor for this target
result = this.createAnchor annotation, t
anchor = result.result
if result.error? instanceof Range.RangeError
this.publish 'rangeNormalizeFail', [annotation, result.error.range, result.error]
if anchor?
annotation.quote.push t.quote = anchor.quote
t.diffHTML = anchor.diffHTML
t.diffCaseOnly = anchor.diffCaseOnly
# Store this anchor for the annotation
annotation.anchors.push anchor
# Store the anchor for all involved pages
for pageIndex in [anchor.startPage .. anchor.endPage]
@anchors[pageIndex] ?= []
@anchors[pageIndex].push anchor
# Realizing the anchor
anchor.realize()
else
console.log "Could not create anchor for annotation '",
annotation.id, "'."
catch exception
if exception.stack? then console.log exception.stack
console.log exception.message
console.log exception
# Join all the quotes into one string.
annotation.quote = annotation.quote.join(' / ')
annotation
# Public: Publishes the 'beforeAnnotationUpdated' and 'annotationUpdated'
# events. Listeners wishing to modify an updated annotation should subscribe
# to 'beforeAnnotationUpdated' while listeners storing annotations should
# subscribe to 'annotationUpdated'.
#
# annotation - An annotation Object to update.
#
# Examples
#
# annotation = {tags: 'apples oranges pears'}
# annotator.on 'beforeAnnotationUpdated', (annotation) ->
# # validate or modify a property.
# annotation.tags = annotation.tags.split(' ')
# annotator.updateAnnotation(annotation)
# # => Returns ["apples", "oranges", "pears"]
#
# Returns annotation Object.
updateAnnotation: (annotation) ->
this.publish('beforeAnnotationUpdated', [annotation])
this.publish('annotationUpdated', [annotation])
annotation
# Public: Deletes the annotation by removing the highlight from the DOM.
# Publishes the 'annotationDeleted' event on completion.
#
# annotation - An annotation Object to delete.
#
# Returns deleted annotation.
deleteAnnotation: (annotation) ->
if annotation.anchors?
for a in annotation.anchors
a.remove()
this.publish('annotationDeleted', [annotation])
annotation
# Public: Loads an Array of annotations into the @element. Breaks the task
# into chunks of 10 annotations.
#
# annotations - An Array of annotation Objects.
#
# Examples
#
# loadAnnotationsFromStore (annotations) ->
# annotator.loadAnnotations(annotations)
#
# Returns itself for chaining.
loadAnnotations: (annotations=[]) ->
loader = (annList=[]) =>
now = annList.splice(0,10)
for n in now
this.setupAnnotation(n)
# If there are more to do, do them after a 10ms break (for browser
# responsiveness).
if annList.length > 0
setTimeout((-> loader(annList)), 10)
else
this.publish 'annotationsLoaded', [clone]
clone = annotations.slice()
if annotations.length # Do we have to do something?
# Do we have a doc access strategy? If we don't have it yet, scan!
@_scan() unless @domMapper
if @pendingScan? # Is there a pending scan?
# Schedule the parsing the annotations for
# when scan has finished
@pendingScan.then =>
#console.log "Document scan finished. Can start anchoring."
setTimeout => loader annotations
else # no pending scan
# We can start parsing them right away
loader annotations
this
# Public: Calls the Store#dumpAnnotations() method.
#
# Returns dumped annotations Array or false if Store is not loaded.
dumpAnnotations: () ->
if @plugins['Store']
@plugins['Store'].dumpAnnotations()
else
console.warn(_t("Can't dump annotations without Store plugin."))
return false
# Public: Registers a plugin with the Annotator. A plugin can only be
# registered once. The plugin will be instantiated in the following order.
#
# 1. A new instance of the plugin will be created (providing the @element and
# options as params) then assigned to the @plugins registry.
# 2. The current Annotator instance will be attached to the plugin.
# 3. The Plugin#pluginInit() method will be called if it exists.
#
# name - Plugin to instantiate. Must be in the Annotator.Plugins namespace.
# options - Any options to be provided to the plugin constructor.
#
# Examples
#
# annotator
# .addPlugin('Tags')
# .addPlugin('Store', {
# prefix: '/store'
# })
# .addPlugin('Permissions', {
# user: 'Bill'
# })
#
# Returns itself to allow chaining.
addPlugin: (name, options) ->
if @plugins[name]
console.error _t("You cannot have more than one instance of any plugin.")
else
klass = Annotator.Plugin[name]
if typeof klass is 'function'
@plugins[name] = new klass(@element[0], options)
@plugins[name].annotator = this
@plugins[name].pluginInit?()
else
console.error _t("Could not load ") + name + _t(" plugin. Have you included the appropriate <script> tag?")
this # allow chaining
# Public: Loads the @editor with the provided annotation and updates its
# position in the window.
#
# annotation - An annotation to load into the editor.
# location - Position to set the Editor in the form {top: y, left: x}
#
# Examples
#
# annotator.showEditor({text: "my comment"}, {top: 34, left: 234})
#
# Returns itself to allow chaining.
showEditor: (annotation, location) =>
@editor.element.css(location)
@editor.load(annotation)
this.publish('annotationEditorShown', [@editor, annotation])
this
# Callback method called when the @editor fires the "hide" event. Itself
# publishes the 'annotationEditorHidden' event and sets the @canAnnotate
# property to allow the creation of new annotations
#
# Returns nothing.
onEditorHide: =>
this.publish('annotationEditorHidden', [@editor])
this.enableAnnotating()
# Callback method called when the @editor fires the "save" event. Itself
# publishes the 'annotationEditorSubmit' event and creates/updates the
# edited annotation.
#
# Returns nothing.
onEditorSubmit: (annotation) =>
this.publish('annotationEditorSubmit', [@editor, annotation])
# Public: Loads the @viewer with an Array of annotations and positions it
# at the location provided. Calls the 'annotationViewerShown' event.
#
# annotation - An Array of annotations to load into the viewer.
# location - Position to set the Viewer in the form {top: y, left: x}
#
# Examples
#
# annotator.showViewer(
# [{text: "my comment"}, {text: "my other comment"}],
# {top: 34, left: 234})
# )
#
# Returns itself to allow chaining.
showViewer: (annotations, location) =>
@viewer.element.css(location)
@viewer.load(annotations)
this.publish('annotationViewerShown', [@viewer, annotations])
# Annotator#element event callback. Allows 250ms for mouse pointer to get from
# annotation highlight to @viewer to manipulate annotations. If timer expires
# the @viewer is hidden.
#
# Returns nothing.
startViewerHideTimer: =>
# Don't do this if timer has already been set by another annotation.
if not @viewerHideTimer
@viewerHideTimer = setTimeout @viewer.hide, 250
# Viewer#element event callback. Clears the timer set by
# Annotator#startViewerHideTimer() when the @viewer is moused over.
#
# Returns nothing.
clearViewerHideTimer: () =>
clearTimeout(@viewerHideTimer)
@viewerHideTimer = false
# Annotator#element callback. Sets the @mouseIsDown property used to
# determine if a selection may have started to true. Also calls
# Annotator#startViewerHideTimer() to hide the Annotator#viewer.
#
# event - A mousedown Event object.
#
# Returns nothing.
checkForStartSelection: (event) =>
unless event and this.isAnnotator(event.target)
this.startViewerHideTimer()
@mouseIsDown = true
# This method is to be called by the mechanisms responsible for
# triggering annotation (and highlight) creation.
#
# event - any event which has triggered this.
# The following fields are used:
# targets: an array of targets, which should be used to anchor the
# newly created annotation
# pageX and pageY: if the adder button is shown, use there coordinates
#
# immadiate - should we show the adder button, or should be proceed
# to create the annotation/highlight immediately ?
#
# returns false if the creation of annotations is forbidden at the moment,
# true otherwise.
onSuccessfulSelection: (event, immediate = false) ->
# Check whether we got a proper event
unless event?
throw "Called onSuccessfulSelection without an event!"
unless event.targets?
throw "Called onSuccessulSelection with an event with missing targets!"
# Are we allowed to create annotations?
unless @canAnnotate
#@Annotator.showNotification "You are already editing an annotation!",
# @Annotator.Notification.INFO
return false
# Store the selected targets
@selectedTargets = event.targets
# Do we want immediate annotation?
if immediate
# Create an annotation
@onAdderClick event
else
# Show the adder button
@adder
.css(util.mousePosition(event, @wrapper[0]))
.show()
true
onFailedSelection: (event) ->
@adder.hide()
@selectedTargets = []
# Public: Determines if the provided element is part of the annotator plugin.
# Useful for ignoring mouse actions on the annotator elements.
# NOTE: The @wrapper is not included in this check.
#
# element - An Element or TextNode to check.
#
# Examples
#
# span = document.createElement('span')
# annotator.isAnnotator(span) # => Returns false
#
# annotator.isAnnotator(annotator.viewer.element) # => Returns true
#
# Returns true if the element is a child of an annotator element.
isAnnotator: (element) ->
!!$(element).parents().andSelf().filter('[class^=annotator-]').not(@wrapper).length
# Annotator#element callback. Sets the @canAnnotate to false to prevent
# the annotation selection events firing when the adder is clicked.
#
# event - A mousedown Event object
#
# Returns nothing.
onAdderMousedown: (event) =>
event?.preventDefault()
this.disableAnnotating()
@inAdderClick = true
# Annotator#element callback. Displays the @editor in place of the @adder and
# loads in a newly created annotation Object. The click event is used as well
# as the mousedown so that we get the :active state on the @adder when clicked
#
# event - A mousedown Event object
#
# Returns nothing.
onAdderClick: (event) =>
event?.preventDefault?()
# Hide the adder
position = @adder.position()
@adder.hide()
@inAdderClick = false
# Create a new annotation.
annotation = this.createAnnotation()
# Extract the quotation and serialize the ranges
annotation = this.setupAnnotation(annotation)
# Show a temporary highlight so the user can see what they selected
for anchor in annotation.anchors
for page, hl of anchor.highlight
hl.setTemporary true
# Make the highlights permanent if the annotation is saved
save = =>
do cleanup
for anchor in annotation.anchors
for page, hl of anchor.highlight
hl.setTemporary false
# Fire annotationCreated events so that plugins can react to them
this.publish('annotationCreated', [annotation])
# Remove the highlights if the edit is cancelled
cancel = =>
do cleanup
this.deleteAnnotation(annotation)
# Don't leak handlers at the end
cleanup = =>
this.unsubscribe('annotationEditorHidden', cancel)
this.unsubscribe('annotationEditorSubmit', save)
# Subscribe to the editor events
this.subscribe('annotationEditorHidden', cancel)
this.subscribe('annotationEditorSubmit', save)
# Display the editor.
this.showEditor(annotation, position)
# Annotator#viewer callback function. Displays the Annotator#editor in the
# positions of the Annotator#viewer and loads the passed annotation for
# editing.
#
# annotation - An annotation Object for editing.
#
# Returns nothing.
onEditAnnotation: (annotation) =>
offset = @viewer.element.position()
# Update the annotation when the editor is saved
update = =>
do cleanup
this.updateAnnotation(annotation)
# Remove handlers when finished
cleanup = =>
this.unsubscribe('annotationEditorHidden', cleanup)
this.unsubscribe('annotationEditorSubmit', update)
# Subscribe to the editor events
this.subscribe('annotationEditorHidden', cleanup)
this.subscribe('annotationEditorSubmit', update)
# Replace the viewer with the editor
@viewer.hide()
this.showEditor(annotation, offset)
# Annotator#viewer callback function. Deletes the annotation provided to the
# callback.
#
# annotation - An annotation Object for deletion.
#
# Returns nothing.
onDeleteAnnotation: (annotation) =>
@viewer.hide()
# Delete highlight elements.
this.deleteAnnotation annotation
# Collect all the highlights (optionally for a given set of annotations)
getHighlights: (annotations) ->
results = []
if annotations?
# Collect only the given set of annotations
for annotation in annotations
for anchor in annotation.anchors
for page, hl of anchor.highlight
results.push hl
else
# Collect from everywhere
for page, anchors of @anchors
$.merge results, (anchor.highlight[page] for anchor in anchors when anchor.highlight[page]?)
results
# Realize anchors on a given pages
_realizePage: (index) ->
# If the page is not mapped, give up
return unless @domMapper.isPageMapped index
# Go over all anchors related to this page
for anchor in @anchors[index] ? []
anchor.realize()
# Virtualize anchors on a given page
_virtualizePage: (index) ->
# Go over all anchors related to this page
for anchor in @anchors[index] ? []
anchor.virtualize index
onAnchorMouseover: (event) ->
#console.log "Mouse over annotations:", event.data.getAnnotations event
# Cancel any pending hiding of the viewer.
this.clearViewerHideTimer()
# Don't do anything if we're making a selection or
# already displaying the viewer
return false if @mouseIsDown or @viewer.isShown()
this.showViewer event.data.getAnnotations(event),
util.mousePosition(event, @wrapper[0])
onAnchorMouseout: (event) ->
#console.log "Mouse out on annotations:", event.data.getAnnotations event
this.startViewerHideTimer()
onAnchorMousedown: (event) ->
#console.log "Mouse down on annotations:", event.data.getAnnotations event
onAnchorClick: (event) ->
#console.log "Click on annotations:", event.data.getAnnotations event
# Create namespace for Annotator plugins
class Annotator.Plugin extends Delegator
constructor: (element, options) ->
super
pluginInit: ->
# Sniff the browser environment and attempt to add missing functionality.
g = util.getGlobal()
if not g.document?.evaluate?
$.getScript('http://assets.annotateit.org/vendor/xpath.min.js')
if not g.getSelection?
$.getScript('http://assets.annotateit.org/vendor/ierange.min.js')
if not g.JSON?
$.getScript('http://assets.annotateit.org/vendor/json2.min.js')
# Ensure the Node constants are defined
if not g.Node?
g.Node =
ELEMENT_NODE : 1
ATTRIBUTE_NODE : 2
TEXT_NODE : 3
CDATA_SECTION_NODE : 4
ENTITY_REFERENCE_NODE : 5
ENTITY_NODE : 6
PROCESSING_INSTRUCTION_NODE : 7
COMMENT_NODE : 8
DOCUMENT_NODE : 9
DOCUMENT_TYPE_NODE : 10
DOCUMENT_FRAGMENT_NODE : 11
NOTATION_NODE : 12
# Bind our local copy of jQuery so plugins can use the extensions.
Annotator.$ = $
# Export other modules for use in plugins.
Annotator.Delegator = Delegator
Annotator.Range = Range
Annotator.util = util
Annotator.Util = Util
Annotator.Highlight = Highlight
Annotator.Anchor = Anchor
# Bind gettext helper so plugins can use localisation.
Annotator._t = _t
# Returns true if the Annotator can be used in the current browser.
Annotator.supported = -> (-> !!this.getSelection)()
# Restores the Annotator property on the global object to it's
# previous value and returns the Annotator.
Annotator.noConflict = ->
util.getGlobal().Annotator = _Annotator
this
# Create global access for Annotator
$.fn.annotator = (options) ->
args = Array::slice.call(arguments, 1)
this.each ->
# check the data() cache, if it's there we'll call the method requested
instance = $.data(this, 'annotator')
if instance
options && instance[options].apply(instance, args)
else
instance = new Annotator(this, options)
$.data(this, 'annotator', instance)
# Export Annotator object.
this.Annotator = Annotator;
| 73296 | # Selection and range creation reference for the following code:
# http://www.quirksmode.org/dom/range_intro.html
#
# I've removed any support for IE TextRange (see commit d7085bf2 for code)
# for the moment, having no means of testing it.
util =
uuid: (-> counter = 0; -> counter++)()
getGlobal: -> (-> this)()
# Return the maximum z-index of any element in $elements (a jQuery collection).
maxZIndex: ($elements) ->
all = for el in $elements
if $(el).css('position') == 'static'
-1
else
parseInt($(el).css('z-index'), 10) or -1
Math.max.apply(Math, all)
mousePosition: (e, offsetEl) ->
# If the offset element is not a positioning root use its offset parent
unless $(offsetEl).css('position') in ['absolute', 'fixed', 'relative']
offsetEl = $(offsetEl).offsetParent()[0]
offset = $(offsetEl).offset()
{
top: e.pageY - offset.top,
left: e.pageX - offset.left
}
# Checks to see if an event parameter is provided and contains the prevent
# default method. If it does it calls it.
#
# This is useful for methods that can be optionally used as callbacks
# where the existance of the parameter must be checked before calling.
preventEventDefault: (event) ->
event?.preventDefault?()
# Store a reference to the current Annotator object.
_Annotator = this.Annotator
# Fake two-phase / pagination support, used for HTML documents
class DummyDocumentAccess
@applicable: -> true
getPageIndex: -> 0
getPageCount: -> 1
getPageIndexForPos: -> 0
isPageMapped: -> true
scan: ->
class Annotator extends Delegator
# Events to be bound on Annotator#element.
events:
".annotator-adder button click": "onAdderClick"
".annotator-adder button mousedown": "onAdderMousedown"
html:
adder: '<div class="annotator-adder"><button>' + _t('Annotate') + '</button></div>'
wrapper: '<div class="annotator-wrapper"></div>'
options: # Configuration options
readOnly: false # Start Annotator in read-only mode. No controls will be shown.
plugins: {}
editor: null
viewer: null
selectedTargets: null
mouseIsDown: false
inAdderClick: false
canAnnotate: false
viewerHideTimer: null
# Public: Creates an instance of the Annotator. Requires a DOM Element in
# which to watch for annotations as well as any options.
#
# NOTE: If the Annotator is not supported by the current browser it will not
# perform any setup and simply return a basic object. This allows plugins
# to still be loaded but will not function as expected. It is reccomended
# to call Annotator.supported() before creating the instance or using the
# Unsupported plugin which will notify users that the Annotator will not work.
#
# element - A DOM Element in which to annotate.
# options - An options Object. NOTE: There are currently no user options.
#
# Examples
#
# annotator = new Annotator(document.body)
#
# # Example of checking for support.
# if Annotator.supported()
# annotator = new Annotator(document.body)
# else
# # Fallback for unsupported browsers.
#
# Returns a new instance of the Annotator.
constructor: (element, options) ->
super
@plugins = {}
@anchoringStrategies = []
# Return early if the annotator is not supported.
return this unless Annotator.supported()
this._setupDocumentEvents() unless @options.readOnly
this._setupAnchorEvents()
this._setupWrapper()
this._setupDocumentAccessStrategies()
this._setupViewer()._setupEditor()
this._setupDynamicStyle()
# Perform initial DOM scan, unless told not to.
this._scan() unless @options.noScan
# Create adder
this.adder = $(this.html.adder).appendTo(@wrapper).hide()
# Initializes the available document access strategies
_setupDocumentAccessStrategies: ->
@documentAccessStrategies = [
# Default dummy strategy for simple HTML documents.
# The generic fallback.
name: "Dummy"
mapper: DummyDocumentAccess
]
this
# Initializes the components used for analyzing the document
_chooseAccessPolicy: ->
if @domMapper? then return
# Go over the available strategies
for s in @documentAccessStrategies
# Can we use this strategy for this document?
if s.mapper.applicable()
@documentAccessStrategy = s
console.log "Selected document access strategy: " + s.name
@domMapper = new s.mapper()
@anchors = {}
addEventListener "docPageMapped", (evt) =>
@_realizePage evt.pageIndex
addEventListener "docPageUnmapped", (evt) =>
@_virtualizePage evt.pageIndex
s.init?()
return this
# Perform a scan of the DOM. Required for finding anchors.
_scan: ->
# If we haven't yet chosen a document access strategy, do so now.
this._chooseAccessPolicy() unless @domMapper
@pendingScan = @domMapper.scan()
if @pendingScan?
@pendingScan.then => @enableAnnotating()
else
@enableAnnotating()
# Wraps the children of @element in a @wrapper div. NOTE: This method will also
# remove any script elements inside @element to prevent them re-executing.
#
# Returns itself to allow chaining.
_setupWrapper: ->
@wrapper = $(@html.wrapper)
# We need to remove all scripts within the element before wrapping the
# contents within a div. Otherwise when scripts are reappended to the DOM
# they will re-execute. This is an issue for scripts that call
# document.write() - such as ads - as they will clear the page.
@element.find('script').remove()
@element.wrapInner(@wrapper)
@wrapper = @element.find('.annotator-wrapper')
this
# Creates an instance of Annotator.Viewer and assigns it to the @viewer
# property, appends it to the @wrapper and sets up event listeners.
#
# Returns itself to allow chaining.
_setupViewer: ->
@viewer = new Annotator.Viewer(readOnly: @options.readOnly)
@viewer.hide()
.on("edit", this.onEditAnnotation)
.on("delete", this.onDeleteAnnotation)
.addField({
load: (field, annotation) =>
if annotation.text
$(field).html(Util.escape(annotation.text))
else
$(field).html("<i>#{_t 'No Comment'}</i>")
this.publish('annotationViewerTextField', [field, annotation])
})
.element.appendTo(@wrapper).bind({
"mouseover": this.clearViewerHideTimer
"mouseout": this.startViewerHideTimer
})
this
# Creates an instance of the Annotator.Editor and assigns it to @editor.
# Appends this to the @wrapper and sets up event listeners.
#
# Returns itself for chaining.
_setupEditor: ->
@editor = new Annotator.Editor()
@editor.hide()
.on('hide', this.onEditorHide)
.on('save', this.onEditorSubmit)
.addField({
type: 'textarea',
label: _t('Comments') + '\u2026'
load: (field, annotation) ->
$(field).find('textarea').val(annotation.text || '')
submit: (field, annotation) ->
annotation.text = $(field).find('textarea').val()
})
@editor.element.appendTo(@wrapper)
this
# Sets up the selection event listeners to watch mouse actions on the document.
#
# Returns itself for chaining.
_setupDocumentEvents: ->
$(document).bind({
"mousedown": this.checkForStartSelection
})
this
# Sets up handlers to anchor-related events
_setupAnchorEvents: ->
# When annotations are updated
@on 'annotationUpdated', (annotation) =>
# Notify the anchors
for anchor in annotation.anchors or []
anchor.annotationUpdated()
# Sets up any dynamically calculated CSS for the Annotator.
#
# Returns itself for chaining.
_setupDynamicStyle: ->
style = $('#annotator-dynamic-style')
if (!style.length)
style = $('<style id="annotator-dynamic-style"></style>').appendTo(document.head)
sel = '*' + (":not(.annotator-#{x})" for x in ['adder', 'outer', 'notice', 'filter']).join('')
# use the maximum z-index in the page
max = util.maxZIndex($(document.body).find(sel))
# but don't go smaller than 1010, because this isn't bulletproof --
# dynamic elements in the page (notifications, dialogs, etc.) may well
# have high z-indices that we can't catch using the above method.
max = Math.max(max, 1000)
style.text [
".annotator-adder, .annotator-outer, .annotator-notice {"
" z-index: #{max + 20};"
"}"
".annotator-filter {"
" z-index: #{max + 10};"
"}"
].join("\n")
this
# Enables or disables the creation of annotations
#
# When it's set to false, nobody os supposed to call
# onSuccessfulSelection()
enableAnnotating: (value = true, local = true) ->
# If we already have this setting, do nothing
return if value is @canAnnotate
# Set the field
@canAnnotate = value
# Publish an event, so that others can react
this.publish "enableAnnotating", value
# If this call came from "outside" (whatever it means), and annotation
# is now disabled, then hide the adder.
@adder.hide() unless value or local
# Shortcut to disable annotating
disableAnnotating: (local = true) -> this.enableAnnotating false, local
# Utility function to get the decoded form of the document URI
getHref: =>
uri = decodeURIComponent document.location.href
if document.location.hash then uri = uri.slice 0, (-1 * location.hash.length)
$('meta[property^="og:url"]').each -> uri = decodeURIComponent this.content
$('link[rel^="canonical"]').each -> uri = decodeURIComponent this.href
return uri
# Public: Creates and returns a new annotation object. Publishes the
# 'beforeAnnotationCreated' event to allow the new annotation to be modified.
#
# Examples
#
# annotator.createAnnotation() # Returns {}
#
# annotator.on 'beforeAnnotationCreated', (annotation) ->
# annotation.myProperty = 'This is a custom property'
# annotator.createAnnotation() # Returns {myProperty: "This is a…"}
#
# Returns a newly created annotation Object.
createAnnotation: () ->
annotation = {}
this.publish('beforeAnnotationCreated', [annotation])
annotation
# Do some normalization to get a "canonical" form of a string.
# Used to even out some browser differences.
normalizeString: (string) -> string.replace /\s{2,}/g, " "
# Find the given type of selector from an array of selectors, if it exists.
# If it does not exist, null is returned.
findSelector: (selectors, type) ->
for selector in selectors
if selector.type is type then return selector
null
# Try to find the right anchoring point for a given target
#
# Returns an Anchor object if succeeded, null otherwise
createAnchor: (annotation, target) ->
unless target?
throw new Error "Trying to find anchor for null target!"
# console.log "Trying to find anchor for target: "
# console.log target
error = null
anchor = null
for s in @anchoringStrategies
try
a = s.code.call this, annotation, target
if a
# console.log "Strategy '" + s.name + "' yielded an anchor."
return result: a
# else
# console.log "Strategy '" + s.name + "' did NOT yield an anchor."
catch error
# console.log "Strategy '" + s.name + "' has thrown an error."
if error instanceof Range.RangeError
return error: error
else
throw error
return error: "No strategies worked."
# Public: Initialises an annotation either from an object representation or
# an annotation created with Annotator#createAnnotation(). It finds the
# selected range and higlights the selection in the DOM, extracts the
# quoted text and serializes the range.
#
# annotation - An annotation Object to initialise.
#
# Examples
#
# # Create a brand new annotation from the currently selected text.
# annotation = annotator.createAnnotation()
# annotation = annotator.setupAnnotation(annotation)
# # annotation has now been assigned the currently selected range
# # and a highlight appended to the DOM.
#
# # Add an existing annotation that has been stored elsewere to the DOM.
# annotation = getStoredAnnotationWithSerializedRanges()
# annotation = annotator.setupAnnotation(annotation)
#
# Returns the initialised annotation.
setupAnnotation: (annotation) ->
# If this is a new annotation, we might have to add the targets
annotation.target ?= @selectedTargets
@selectedTargets = []
unless annotation.target?
throw new Error "Can not run setupAnnotation(). No target or selection available."
annotation.quote = []
annotation.anchors = []
for t in annotation.target
try
# Create an anchor for this target
result = this.createAnchor annotation, t
anchor = result.result
if result.error? instanceof Range.RangeError
this.publish 'rangeNormalizeFail', [annotation, result.error.range, result.error]
if anchor?
annotation.quote.push t.quote = anchor.quote
t.diffHTML = anchor.diffHTML
t.diffCaseOnly = anchor.diffCaseOnly
# Store this anchor for the annotation
annotation.anchors.push anchor
# Store the anchor for all involved pages
for pageIndex in [anchor.startPage .. anchor.endPage]
@anchors[pageIndex] ?= []
@anchors[pageIndex].push anchor
# Realizing the anchor
anchor.realize()
else
console.log "Could not create anchor for annotation '",
annotation.id, "'."
catch exception
if exception.stack? then console.log exception.stack
console.log exception.message
console.log exception
# Join all the quotes into one string.
annotation.quote = annotation.quote.join(' / ')
annotation
# Public: Publishes the 'beforeAnnotationUpdated' and 'annotationUpdated'
# events. Listeners wishing to modify an updated annotation should subscribe
# to 'beforeAnnotationUpdated' while listeners storing annotations should
# subscribe to 'annotationUpdated'.
#
# annotation - An annotation Object to update.
#
# Examples
#
# annotation = {tags: 'apples oranges pears'}
# annotator.on 'beforeAnnotationUpdated', (annotation) ->
# # validate or modify a property.
# annotation.tags = annotation.tags.split(' ')
# annotator.updateAnnotation(annotation)
# # => Returns ["apples", "oranges", "pears"]
#
# Returns annotation Object.
updateAnnotation: (annotation) ->
this.publish('beforeAnnotationUpdated', [annotation])
this.publish('annotationUpdated', [annotation])
annotation
# Public: Deletes the annotation by removing the highlight from the DOM.
# Publishes the 'annotationDeleted' event on completion.
#
# annotation - An annotation Object to delete.
#
# Returns deleted annotation.
deleteAnnotation: (annotation) ->
if annotation.anchors?
for a in annotation.anchors
a.remove()
this.publish('annotationDeleted', [annotation])
annotation
# Public: Loads an Array of annotations into the @element. Breaks the task
# into chunks of 10 annotations.
#
# annotations - An Array of annotation Objects.
#
# Examples
#
# loadAnnotationsFromStore (annotations) ->
# annotator.loadAnnotations(annotations)
#
# Returns itself for chaining.
loadAnnotations: (annotations=[]) ->
loader = (annList=[]) =>
now = annList.splice(0,10)
for n in now
this.setupAnnotation(n)
# If there are more to do, do them after a 10ms break (for browser
# responsiveness).
if annList.length > 0
setTimeout((-> loader(annList)), 10)
else
this.publish 'annotationsLoaded', [clone]
clone = annotations.slice()
if annotations.length # Do we have to do something?
# Do we have a doc access strategy? If we don't have it yet, scan!
@_scan() unless @domMapper
if @pendingScan? # Is there a pending scan?
# Schedule the parsing the annotations for
# when scan has finished
@pendingScan.then =>
#console.log "Document scan finished. Can start anchoring."
setTimeout => loader annotations
else # no pending scan
# We can start parsing them right away
loader annotations
this
# Public: Calls the Store#dumpAnnotations() method.
#
# Returns dumped annotations Array or false if Store is not loaded.
dumpAnnotations: () ->
if @plugins['Store']
@plugins['Store'].dumpAnnotations()
else
console.warn(_t("Can't dump annotations without Store plugin."))
return false
# Public: Registers a plugin with the Annotator. A plugin can only be
# registered once. The plugin will be instantiated in the following order.
#
# 1. A new instance of the plugin will be created (providing the @element and
# options as params) then assigned to the @plugins registry.
# 2. The current Annotator instance will be attached to the plugin.
# 3. The Plugin#pluginInit() method will be called if it exists.
#
# name - Plugin to instantiate. Must be in the Annotator.Plugins namespace.
# options - Any options to be provided to the plugin constructor.
#
# Examples
#
# annotator
# .addPlugin('Tags')
# .addPlugin('Store', {
# prefix: '/store'
# })
# .addPlugin('Permissions', {
# user: '<NAME>'
# })
#
# Returns itself to allow chaining.
addPlugin: (name, options) ->
if @plugins[name]
console.error _t("You cannot have more than one instance of any plugin.")
else
klass = Annotator.Plugin[name]
if typeof klass is 'function'
@plugins[name] = new klass(@element[0], options)
@plugins[name].annotator = this
@plugins[name].pluginInit?()
else
console.error _t("Could not load ") + name + _t(" plugin. Have you included the appropriate <script> tag?")
this # allow chaining
# Public: Loads the @editor with the provided annotation and updates its
# position in the window.
#
# annotation - An annotation to load into the editor.
# location - Position to set the Editor in the form {top: y, left: x}
#
# Examples
#
# annotator.showEditor({text: "my comment"}, {top: 34, left: 234})
#
# Returns itself to allow chaining.
showEditor: (annotation, location) =>
@editor.element.css(location)
@editor.load(annotation)
this.publish('annotationEditorShown', [@editor, annotation])
this
# Callback method called when the @editor fires the "hide" event. Itself
# publishes the 'annotationEditorHidden' event and sets the @canAnnotate
# property to allow the creation of new annotations
#
# Returns nothing.
onEditorHide: =>
this.publish('annotationEditorHidden', [@editor])
this.enableAnnotating()
# Callback method called when the @editor fires the "save" event. Itself
# publishes the 'annotationEditorSubmit' event and creates/updates the
# edited annotation.
#
# Returns nothing.
onEditorSubmit: (annotation) =>
this.publish('annotationEditorSubmit', [@editor, annotation])
# Public: Loads the @viewer with an Array of annotations and positions it
# at the location provided. Calls the 'annotationViewerShown' event.
#
# annotation - An Array of annotations to load into the viewer.
# location - Position to set the Viewer in the form {top: y, left: x}
#
# Examples
#
# annotator.showViewer(
# [{text: "my comment"}, {text: "my other comment"}],
# {top: 34, left: 234})
# )
#
# Returns itself to allow chaining.
showViewer: (annotations, location) =>
@viewer.element.css(location)
@viewer.load(annotations)
this.publish('annotationViewerShown', [@viewer, annotations])
# Annotator#element event callback. Allows 250ms for mouse pointer to get from
# annotation highlight to @viewer to manipulate annotations. If timer expires
# the @viewer is hidden.
#
# Returns nothing.
startViewerHideTimer: =>
# Don't do this if timer has already been set by another annotation.
if not @viewerHideTimer
@viewerHideTimer = setTimeout @viewer.hide, 250
# Viewer#element event callback. Clears the timer set by
# Annotator#startViewerHideTimer() when the @viewer is moused over.
#
# Returns nothing.
clearViewerHideTimer: () =>
clearTimeout(@viewerHideTimer)
@viewerHideTimer = false
# Annotator#element callback. Sets the @mouseIsDown property used to
# determine if a selection may have started to true. Also calls
# Annotator#startViewerHideTimer() to hide the Annotator#viewer.
#
# event - A mousedown Event object.
#
# Returns nothing.
checkForStartSelection: (event) =>
unless event and this.isAnnotator(event.target)
this.startViewerHideTimer()
@mouseIsDown = true
# This method is to be called by the mechanisms responsible for
# triggering annotation (and highlight) creation.
#
# event - any event which has triggered this.
# The following fields are used:
# targets: an array of targets, which should be used to anchor the
# newly created annotation
# pageX and pageY: if the adder button is shown, use there coordinates
#
# immadiate - should we show the adder button, or should be proceed
# to create the annotation/highlight immediately ?
#
# returns false if the creation of annotations is forbidden at the moment,
# true otherwise.
onSuccessfulSelection: (event, immediate = false) ->
# Check whether we got a proper event
unless event?
throw "Called onSuccessfulSelection without an event!"
unless event.targets?
throw "Called onSuccessulSelection with an event with missing targets!"
# Are we allowed to create annotations?
unless @canAnnotate
#@<EMAIL>.showNotification "You are already editing an annotation!",
# @Annotator.Notification.INFO
return false
# Store the selected targets
@selectedTargets = event.targets
# Do we want immediate annotation?
if immediate
# Create an annotation
@onAdderClick event
else
# Show the adder button
@adder
.css(util.mousePosition(event, @wrapper[0]))
.show()
true
onFailedSelection: (event) ->
@adder.hide()
@selectedTargets = []
# Public: Determines if the provided element is part of the annotator plugin.
# Useful for ignoring mouse actions on the annotator elements.
# NOTE: The @wrapper is not included in this check.
#
# element - An Element or TextNode to check.
#
# Examples
#
# span = document.createElement('span')
# annotator.isAnnotator(span) # => Returns false
#
# annotator.isAnnotator(annotator.viewer.element) # => Returns true
#
# Returns true if the element is a child of an annotator element.
isAnnotator: (element) ->
!!$(element).parents().andSelf().filter('[class^=annotator-]').not(@wrapper).length
# Annotator#element callback. Sets the @canAnnotate to false to prevent
# the annotation selection events firing when the adder is clicked.
#
# event - A mousedown Event object
#
# Returns nothing.
onAdderMousedown: (event) =>
event?.preventDefault()
this.disableAnnotating()
@inAdderClick = true
# Annotator#element callback. Displays the @editor in place of the @adder and
# loads in a newly created annotation Object. The click event is used as well
# as the mousedown so that we get the :active state on the @adder when clicked
#
# event - A mousedown Event object
#
# Returns nothing.
onAdderClick: (event) =>
event?.preventDefault?()
# Hide the adder
position = @adder.position()
@adder.hide()
@inAdderClick = false
# Create a new annotation.
annotation = this.createAnnotation()
# Extract the quotation and serialize the ranges
annotation = this.setupAnnotation(annotation)
# Show a temporary highlight so the user can see what they selected
for anchor in annotation.anchors
for page, hl of anchor.highlight
hl.setTemporary true
# Make the highlights permanent if the annotation is saved
save = =>
do cleanup
for anchor in annotation.anchors
for page, hl of anchor.highlight
hl.setTemporary false
# Fire annotationCreated events so that plugins can react to them
this.publish('annotationCreated', [annotation])
# Remove the highlights if the edit is cancelled
cancel = =>
do cleanup
this.deleteAnnotation(annotation)
# Don't leak handlers at the end
cleanup = =>
this.unsubscribe('annotationEditorHidden', cancel)
this.unsubscribe('annotationEditorSubmit', save)
# Subscribe to the editor events
this.subscribe('annotationEditorHidden', cancel)
this.subscribe('annotationEditorSubmit', save)
# Display the editor.
this.showEditor(annotation, position)
# Annotator#viewer callback function. Displays the Annotator#editor in the
# positions of the Annotator#viewer and loads the passed annotation for
# editing.
#
# annotation - An annotation Object for editing.
#
# Returns nothing.
onEditAnnotation: (annotation) =>
offset = @viewer.element.position()
# Update the annotation when the editor is saved
update = =>
do cleanup
this.updateAnnotation(annotation)
# Remove handlers when finished
cleanup = =>
this.unsubscribe('annotationEditorHidden', cleanup)
this.unsubscribe('annotationEditorSubmit', update)
# Subscribe to the editor events
this.subscribe('annotationEditorHidden', cleanup)
this.subscribe('annotationEditorSubmit', update)
# Replace the viewer with the editor
@viewer.hide()
this.showEditor(annotation, offset)
# Annotator#viewer callback function. Deletes the annotation provided to the
# callback.
#
# annotation - An annotation Object for deletion.
#
# Returns nothing.
onDeleteAnnotation: (annotation) =>
@viewer.hide()
# Delete highlight elements.
this.deleteAnnotation annotation
# Collect all the highlights (optionally for a given set of annotations)
getHighlights: (annotations) ->
results = []
if annotations?
# Collect only the given set of annotations
for annotation in annotations
for anchor in annotation.anchors
for page, hl of anchor.highlight
results.push hl
else
# Collect from everywhere
for page, anchors of @anchors
$.merge results, (anchor.highlight[page] for anchor in anchors when anchor.highlight[page]?)
results
# Realize anchors on a given pages
_realizePage: (index) ->
# If the page is not mapped, give up
return unless @domMapper.isPageMapped index
# Go over all anchors related to this page
for anchor in @anchors[index] ? []
anchor.realize()
# Virtualize anchors on a given page
_virtualizePage: (index) ->
# Go over all anchors related to this page
for anchor in @anchors[index] ? []
anchor.virtualize index
onAnchorMouseover: (event) ->
#console.log "Mouse over annotations:", event.data.getAnnotations event
# Cancel any pending hiding of the viewer.
this.clearViewerHideTimer()
# Don't do anything if we're making a selection or
# already displaying the viewer
return false if @mouseIsDown or @viewer.isShown()
this.showViewer event.data.getAnnotations(event),
util.mousePosition(event, @wrapper[0])
onAnchorMouseout: (event) ->
#console.log "Mouse out on annotations:", event.data.getAnnotations event
this.startViewerHideTimer()
onAnchorMousedown: (event) ->
#console.log "Mouse down on annotations:", event.data.getAnnotations event
onAnchorClick: (event) ->
#console.log "Click on annotations:", event.data.getAnnotations event
# Create namespace for Annotator plugins
class Annotator.Plugin extends Delegator
constructor: (element, options) ->
super
pluginInit: ->
# Sniff the browser environment and attempt to add missing functionality.
g = util.getGlobal()
if not g.document?.evaluate?
$.getScript('http://assets.annotateit.org/vendor/xpath.min.js')
if not g.getSelection?
$.getScript('http://assets.annotateit.org/vendor/ierange.min.js')
if not g.JSON?
$.getScript('http://assets.annotateit.org/vendor/json2.min.js')
# Ensure the Node constants are defined
if not g.Node?
g.Node =
ELEMENT_NODE : 1
ATTRIBUTE_NODE : 2
TEXT_NODE : 3
CDATA_SECTION_NODE : 4
ENTITY_REFERENCE_NODE : 5
ENTITY_NODE : 6
PROCESSING_INSTRUCTION_NODE : 7
COMMENT_NODE : 8
DOCUMENT_NODE : 9
DOCUMENT_TYPE_NODE : 10
DOCUMENT_FRAGMENT_NODE : 11
NOTATION_NODE : 12
# Bind our local copy of jQuery so plugins can use the extensions.
Annotator.$ = $
# Export other modules for use in plugins.
Annotator.Delegator = Delegator
Annotator.Range = Range
Annotator.util = util
Annotator.Util = Util
Annotator.Highlight = Highlight
Annotator.Anchor = Anchor
# Bind gettext helper so plugins can use localisation.
Annotator._t = _t
# Returns true if the Annotator can be used in the current browser.
Annotator.supported = -> (-> !!this.getSelection)()
# Restores the Annotator property on the global object to it's
# previous value and returns the Annotator.
Annotator.noConflict = ->
util.getGlobal().Annotator = _Annotator
this
# Create global access for Annotator
$.fn.annotator = (options) ->
args = Array::slice.call(arguments, 1)
this.each ->
# check the data() cache, if it's there we'll call the method requested
instance = $.data(this, 'annotator')
if instance
options && instance[options].apply(instance, args)
else
instance = new Annotator(this, options)
$.data(this, 'annotator', instance)
# Export Annotator object.
this.Annotator = Annotator;
| true | # Selection and range creation reference for the following code:
# http://www.quirksmode.org/dom/range_intro.html
#
# I've removed any support for IE TextRange (see commit d7085bf2 for code)
# for the moment, having no means of testing it.
util =
uuid: (-> counter = 0; -> counter++)()
getGlobal: -> (-> this)()
# Return the maximum z-index of any element in $elements (a jQuery collection).
maxZIndex: ($elements) ->
all = for el in $elements
if $(el).css('position') == 'static'
-1
else
parseInt($(el).css('z-index'), 10) or -1
Math.max.apply(Math, all)
mousePosition: (e, offsetEl) ->
# If the offset element is not a positioning root use its offset parent
unless $(offsetEl).css('position') in ['absolute', 'fixed', 'relative']
offsetEl = $(offsetEl).offsetParent()[0]
offset = $(offsetEl).offset()
{
top: e.pageY - offset.top,
left: e.pageX - offset.left
}
# Checks to see if an event parameter is provided and contains the prevent
# default method. If it does it calls it.
#
# This is useful for methods that can be optionally used as callbacks
# where the existance of the parameter must be checked before calling.
preventEventDefault: (event) ->
event?.preventDefault?()
# Store a reference to the current Annotator object.
_Annotator = this.Annotator
# Fake two-phase / pagination support, used for HTML documents
class DummyDocumentAccess
@applicable: -> true
getPageIndex: -> 0
getPageCount: -> 1
getPageIndexForPos: -> 0
isPageMapped: -> true
scan: ->
class Annotator extends Delegator
# Events to be bound on Annotator#element.
events:
".annotator-adder button click": "onAdderClick"
".annotator-adder button mousedown": "onAdderMousedown"
html:
adder: '<div class="annotator-adder"><button>' + _t('Annotate') + '</button></div>'
wrapper: '<div class="annotator-wrapper"></div>'
options: # Configuration options
readOnly: false # Start Annotator in read-only mode. No controls will be shown.
plugins: {}
editor: null
viewer: null
selectedTargets: null
mouseIsDown: false
inAdderClick: false
canAnnotate: false
viewerHideTimer: null
# Public: Creates an instance of the Annotator. Requires a DOM Element in
# which to watch for annotations as well as any options.
#
# NOTE: If the Annotator is not supported by the current browser it will not
# perform any setup and simply return a basic object. This allows plugins
# to still be loaded but will not function as expected. It is reccomended
# to call Annotator.supported() before creating the instance or using the
# Unsupported plugin which will notify users that the Annotator will not work.
#
# element - A DOM Element in which to annotate.
# options - An options Object. NOTE: There are currently no user options.
#
# Examples
#
# annotator = new Annotator(document.body)
#
# # Example of checking for support.
# if Annotator.supported()
# annotator = new Annotator(document.body)
# else
# # Fallback for unsupported browsers.
#
# Returns a new instance of the Annotator.
constructor: (element, options) ->
super
@plugins = {}
@anchoringStrategies = []
# Return early if the annotator is not supported.
return this unless Annotator.supported()
this._setupDocumentEvents() unless @options.readOnly
this._setupAnchorEvents()
this._setupWrapper()
this._setupDocumentAccessStrategies()
this._setupViewer()._setupEditor()
this._setupDynamicStyle()
# Perform initial DOM scan, unless told not to.
this._scan() unless @options.noScan
# Create adder
this.adder = $(this.html.adder).appendTo(@wrapper).hide()
# Initializes the available document access strategies
_setupDocumentAccessStrategies: ->
@documentAccessStrategies = [
# Default dummy strategy for simple HTML documents.
# The generic fallback.
name: "Dummy"
mapper: DummyDocumentAccess
]
this
# Initializes the components used for analyzing the document
_chooseAccessPolicy: ->
if @domMapper? then return
# Go over the available strategies
for s in @documentAccessStrategies
# Can we use this strategy for this document?
if s.mapper.applicable()
@documentAccessStrategy = s
console.log "Selected document access strategy: " + s.name
@domMapper = new s.mapper()
@anchors = {}
addEventListener "docPageMapped", (evt) =>
@_realizePage evt.pageIndex
addEventListener "docPageUnmapped", (evt) =>
@_virtualizePage evt.pageIndex
s.init?()
return this
# Perform a scan of the DOM. Required for finding anchors.
_scan: ->
# If we haven't yet chosen a document access strategy, do so now.
this._chooseAccessPolicy() unless @domMapper
@pendingScan = @domMapper.scan()
if @pendingScan?
@pendingScan.then => @enableAnnotating()
else
@enableAnnotating()
# Wraps the children of @element in a @wrapper div. NOTE: This method will also
# remove any script elements inside @element to prevent them re-executing.
#
# Returns itself to allow chaining.
_setupWrapper: ->
@wrapper = $(@html.wrapper)
# We need to remove all scripts within the element before wrapping the
# contents within a div. Otherwise when scripts are reappended to the DOM
# they will re-execute. This is an issue for scripts that call
# document.write() - such as ads - as they will clear the page.
@element.find('script').remove()
@element.wrapInner(@wrapper)
@wrapper = @element.find('.annotator-wrapper')
this
# Creates an instance of Annotator.Viewer and assigns it to the @viewer
# property, appends it to the @wrapper and sets up event listeners.
#
# Returns itself to allow chaining.
_setupViewer: ->
@viewer = new Annotator.Viewer(readOnly: @options.readOnly)
@viewer.hide()
.on("edit", this.onEditAnnotation)
.on("delete", this.onDeleteAnnotation)
.addField({
load: (field, annotation) =>
if annotation.text
$(field).html(Util.escape(annotation.text))
else
$(field).html("<i>#{_t 'No Comment'}</i>")
this.publish('annotationViewerTextField', [field, annotation])
})
.element.appendTo(@wrapper).bind({
"mouseover": this.clearViewerHideTimer
"mouseout": this.startViewerHideTimer
})
this
# Creates an instance of the Annotator.Editor and assigns it to @editor.
# Appends this to the @wrapper and sets up event listeners.
#
# Returns itself for chaining.
_setupEditor: ->
@editor = new Annotator.Editor()
@editor.hide()
.on('hide', this.onEditorHide)
.on('save', this.onEditorSubmit)
.addField({
type: 'textarea',
label: _t('Comments') + '\u2026'
load: (field, annotation) ->
$(field).find('textarea').val(annotation.text || '')
submit: (field, annotation) ->
annotation.text = $(field).find('textarea').val()
})
@editor.element.appendTo(@wrapper)
this
# Sets up the selection event listeners to watch mouse actions on the document.
#
# Returns itself for chaining.
_setupDocumentEvents: ->
$(document).bind({
"mousedown": this.checkForStartSelection
})
this
# Sets up handlers to anchor-related events
_setupAnchorEvents: ->
# When annotations are updated
@on 'annotationUpdated', (annotation) =>
# Notify the anchors
for anchor in annotation.anchors or []
anchor.annotationUpdated()
# Sets up any dynamically calculated CSS for the Annotator.
#
# Returns itself for chaining.
_setupDynamicStyle: ->
style = $('#annotator-dynamic-style')
if (!style.length)
style = $('<style id="annotator-dynamic-style"></style>').appendTo(document.head)
sel = '*' + (":not(.annotator-#{x})" for x in ['adder', 'outer', 'notice', 'filter']).join('')
# use the maximum z-index in the page
max = util.maxZIndex($(document.body).find(sel))
# but don't go smaller than 1010, because this isn't bulletproof --
# dynamic elements in the page (notifications, dialogs, etc.) may well
# have high z-indices that we can't catch using the above method.
max = Math.max(max, 1000)
style.text [
".annotator-adder, .annotator-outer, .annotator-notice {"
" z-index: #{max + 20};"
"}"
".annotator-filter {"
" z-index: #{max + 10};"
"}"
].join("\n")
this
# Enables or disables the creation of annotations
#
# When it's set to false, nobody os supposed to call
# onSuccessfulSelection()
enableAnnotating: (value = true, local = true) ->
# If we already have this setting, do nothing
return if value is @canAnnotate
# Set the field
@canAnnotate = value
# Publish an event, so that others can react
this.publish "enableAnnotating", value
# If this call came from "outside" (whatever it means), and annotation
# is now disabled, then hide the adder.
@adder.hide() unless value or local
# Shortcut to disable annotating
disableAnnotating: (local = true) -> this.enableAnnotating false, local
# Utility function to get the decoded form of the document URI
getHref: =>
uri = decodeURIComponent document.location.href
if document.location.hash then uri = uri.slice 0, (-1 * location.hash.length)
$('meta[property^="og:url"]').each -> uri = decodeURIComponent this.content
$('link[rel^="canonical"]').each -> uri = decodeURIComponent this.href
return uri
# Public: Creates and returns a new annotation object. Publishes the
# 'beforeAnnotationCreated' event to allow the new annotation to be modified.
#
# Examples
#
# annotator.createAnnotation() # Returns {}
#
# annotator.on 'beforeAnnotationCreated', (annotation) ->
# annotation.myProperty = 'This is a custom property'
# annotator.createAnnotation() # Returns {myProperty: "This is a…"}
#
# Returns a newly created annotation Object.
createAnnotation: () ->
annotation = {}
this.publish('beforeAnnotationCreated', [annotation])
annotation
# Do some normalization to get a "canonical" form of a string.
# Used to even out some browser differences.
normalizeString: (string) -> string.replace /\s{2,}/g, " "
# Find the given type of selector from an array of selectors, if it exists.
# If it does not exist, null is returned.
findSelector: (selectors, type) ->
for selector in selectors
if selector.type is type then return selector
null
# Try to find the right anchoring point for a given target
#
# Returns an Anchor object if succeeded, null otherwise
createAnchor: (annotation, target) ->
unless target?
throw new Error "Trying to find anchor for null target!"
# console.log "Trying to find anchor for target: "
# console.log target
error = null
anchor = null
for s in @anchoringStrategies
try
a = s.code.call this, annotation, target
if a
# console.log "Strategy '" + s.name + "' yielded an anchor."
return result: a
# else
# console.log "Strategy '" + s.name + "' did NOT yield an anchor."
catch error
# console.log "Strategy '" + s.name + "' has thrown an error."
if error instanceof Range.RangeError
return error: error
else
throw error
return error: "No strategies worked."
# Public: Initialises an annotation either from an object representation or
# an annotation created with Annotator#createAnnotation(). It finds the
# selected range and higlights the selection in the DOM, extracts the
# quoted text and serializes the range.
#
# annotation - An annotation Object to initialise.
#
# Examples
#
# # Create a brand new annotation from the currently selected text.
# annotation = annotator.createAnnotation()
# annotation = annotator.setupAnnotation(annotation)
# # annotation has now been assigned the currently selected range
# # and a highlight appended to the DOM.
#
# # Add an existing annotation that has been stored elsewere to the DOM.
# annotation = getStoredAnnotationWithSerializedRanges()
# annotation = annotator.setupAnnotation(annotation)
#
# Returns the initialised annotation.
setupAnnotation: (annotation) ->
# If this is a new annotation, we might have to add the targets
annotation.target ?= @selectedTargets
@selectedTargets = []
unless annotation.target?
throw new Error "Can not run setupAnnotation(). No target or selection available."
annotation.quote = []
annotation.anchors = []
for t in annotation.target
try
# Create an anchor for this target
result = this.createAnchor annotation, t
anchor = result.result
if result.error? instanceof Range.RangeError
this.publish 'rangeNormalizeFail', [annotation, result.error.range, result.error]
if anchor?
annotation.quote.push t.quote = anchor.quote
t.diffHTML = anchor.diffHTML
t.diffCaseOnly = anchor.diffCaseOnly
# Store this anchor for the annotation
annotation.anchors.push anchor
# Store the anchor for all involved pages
for pageIndex in [anchor.startPage .. anchor.endPage]
@anchors[pageIndex] ?= []
@anchors[pageIndex].push anchor
# Realizing the anchor
anchor.realize()
else
console.log "Could not create anchor for annotation '",
annotation.id, "'."
catch exception
if exception.stack? then console.log exception.stack
console.log exception.message
console.log exception
# Join all the quotes into one string.
annotation.quote = annotation.quote.join(' / ')
annotation
# Public: Publishes the 'beforeAnnotationUpdated' and 'annotationUpdated'
# events. Listeners wishing to modify an updated annotation should subscribe
# to 'beforeAnnotationUpdated' while listeners storing annotations should
# subscribe to 'annotationUpdated'.
#
# annotation - An annotation Object to update.
#
# Examples
#
# annotation = {tags: 'apples oranges pears'}
# annotator.on 'beforeAnnotationUpdated', (annotation) ->
# # validate or modify a property.
# annotation.tags = annotation.tags.split(' ')
# annotator.updateAnnotation(annotation)
# # => Returns ["apples", "oranges", "pears"]
#
# Returns annotation Object.
updateAnnotation: (annotation) ->
this.publish('beforeAnnotationUpdated', [annotation])
this.publish('annotationUpdated', [annotation])
annotation
# Public: Deletes the annotation by removing the highlight from the DOM.
# Publishes the 'annotationDeleted' event on completion.
#
# annotation - An annotation Object to delete.
#
# Returns deleted annotation.
deleteAnnotation: (annotation) ->
if annotation.anchors?
for a in annotation.anchors
a.remove()
this.publish('annotationDeleted', [annotation])
annotation
# Public: Loads an Array of annotations into the @element. Breaks the task
# into chunks of 10 annotations.
#
# annotations - An Array of annotation Objects.
#
# Examples
#
# loadAnnotationsFromStore (annotations) ->
# annotator.loadAnnotations(annotations)
#
# Returns itself for chaining.
loadAnnotations: (annotations=[]) ->
loader = (annList=[]) =>
now = annList.splice(0,10)
for n in now
this.setupAnnotation(n)
# If there are more to do, do them after a 10ms break (for browser
# responsiveness).
if annList.length > 0
setTimeout((-> loader(annList)), 10)
else
this.publish 'annotationsLoaded', [clone]
clone = annotations.slice()
if annotations.length # Do we have to do something?
# Do we have a doc access strategy? If we don't have it yet, scan!
@_scan() unless @domMapper
if @pendingScan? # Is there a pending scan?
# Schedule the parsing the annotations for
# when scan has finished
@pendingScan.then =>
#console.log "Document scan finished. Can start anchoring."
setTimeout => loader annotations
else # no pending scan
# We can start parsing them right away
loader annotations
this
# Public: Calls the Store#dumpAnnotations() method.
#
# Returns dumped annotations Array or false if Store is not loaded.
dumpAnnotations: () ->
if @plugins['Store']
@plugins['Store'].dumpAnnotations()
else
console.warn(_t("Can't dump annotations without Store plugin."))
return false
# Public: Registers a plugin with the Annotator. A plugin can only be
# registered once. The plugin will be instantiated in the following order.
#
# 1. A new instance of the plugin will be created (providing the @element and
# options as params) then assigned to the @plugins registry.
# 2. The current Annotator instance will be attached to the plugin.
# 3. The Plugin#pluginInit() method will be called if it exists.
#
# name - Plugin to instantiate. Must be in the Annotator.Plugins namespace.
# options - Any options to be provided to the plugin constructor.
#
# Examples
#
# annotator
# .addPlugin('Tags')
# .addPlugin('Store', {
# prefix: '/store'
# })
# .addPlugin('Permissions', {
# user: 'PI:NAME:<NAME>END_PI'
# })
#
# Returns itself to allow chaining.
addPlugin: (name, options) ->
if @plugins[name]
console.error _t("You cannot have more than one instance of any plugin.")
else
klass = Annotator.Plugin[name]
if typeof klass is 'function'
@plugins[name] = new klass(@element[0], options)
@plugins[name].annotator = this
@plugins[name].pluginInit?()
else
console.error _t("Could not load ") + name + _t(" plugin. Have you included the appropriate <script> tag?")
this # allow chaining
# Public: Loads the @editor with the provided annotation and updates its
# position in the window.
#
# annotation - An annotation to load into the editor.
# location - Position to set the Editor in the form {top: y, left: x}
#
# Examples
#
# annotator.showEditor({text: "my comment"}, {top: 34, left: 234})
#
# Returns itself to allow chaining.
showEditor: (annotation, location) =>
@editor.element.css(location)
@editor.load(annotation)
this.publish('annotationEditorShown', [@editor, annotation])
this
# Callback method called when the @editor fires the "hide" event. Itself
# publishes the 'annotationEditorHidden' event and sets the @canAnnotate
# property to allow the creation of new annotations
#
# Returns nothing.
onEditorHide: =>
this.publish('annotationEditorHidden', [@editor])
this.enableAnnotating()
# Callback method called when the @editor fires the "save" event. Itself
# publishes the 'annotationEditorSubmit' event and creates/updates the
# edited annotation.
#
# Returns nothing.
onEditorSubmit: (annotation) =>
this.publish('annotationEditorSubmit', [@editor, annotation])
# Public: Loads the @viewer with an Array of annotations and positions it
# at the location provided. Calls the 'annotationViewerShown' event.
#
# annotation - An Array of annotations to load into the viewer.
# location - Position to set the Viewer in the form {top: y, left: x}
#
# Examples
#
# annotator.showViewer(
# [{text: "my comment"}, {text: "my other comment"}],
# {top: 34, left: 234})
# )
#
# Returns itself to allow chaining.
showViewer: (annotations, location) =>
@viewer.element.css(location)
@viewer.load(annotations)
this.publish('annotationViewerShown', [@viewer, annotations])
# Annotator#element event callback. Allows 250ms for mouse pointer to get from
# annotation highlight to @viewer to manipulate annotations. If timer expires
# the @viewer is hidden.
#
# Returns nothing.
startViewerHideTimer: =>
# Don't do this if timer has already been set by another annotation.
if not @viewerHideTimer
@viewerHideTimer = setTimeout @viewer.hide, 250
# Viewer#element event callback. Clears the timer set by
# Annotator#startViewerHideTimer() when the @viewer is moused over.
#
# Returns nothing.
clearViewerHideTimer: () =>
clearTimeout(@viewerHideTimer)
@viewerHideTimer = false
# Annotator#element callback. Sets the @mouseIsDown property used to
# determine if a selection may have started to true. Also calls
# Annotator#startViewerHideTimer() to hide the Annotator#viewer.
#
# event - A mousedown Event object.
#
# Returns nothing.
checkForStartSelection: (event) =>
unless event and this.isAnnotator(event.target)
this.startViewerHideTimer()
@mouseIsDown = true
# This method is to be called by the mechanisms responsible for
# triggering annotation (and highlight) creation.
#
# event - any event which has triggered this.
# The following fields are used:
# targets: an array of targets, which should be used to anchor the
# newly created annotation
# pageX and pageY: if the adder button is shown, use there coordinates
#
# immadiate - should we show the adder button, or should be proceed
# to create the annotation/highlight immediately ?
#
# returns false if the creation of annotations is forbidden at the moment,
# true otherwise.
onSuccessfulSelection: (event, immediate = false) ->
# Check whether we got a proper event
unless event?
throw "Called onSuccessfulSelection without an event!"
unless event.targets?
throw "Called onSuccessulSelection with an event with missing targets!"
# Are we allowed to create annotations?
unless @canAnnotate
#@PI:EMAIL:<EMAIL>END_PI.showNotification "You are already editing an annotation!",
# @Annotator.Notification.INFO
return false
# Store the selected targets
@selectedTargets = event.targets
# Do we want immediate annotation?
if immediate
# Create an annotation
@onAdderClick event
else
# Show the adder button
@adder
.css(util.mousePosition(event, @wrapper[0]))
.show()
true
onFailedSelection: (event) ->
@adder.hide()
@selectedTargets = []
# Public: Determines if the provided element is part of the annotator plugin.
# Useful for ignoring mouse actions on the annotator elements.
# NOTE: The @wrapper is not included in this check.
#
# element - An Element or TextNode to check.
#
# Examples
#
# span = document.createElement('span')
# annotator.isAnnotator(span) # => Returns false
#
# annotator.isAnnotator(annotator.viewer.element) # => Returns true
#
# Returns true if the element is a child of an annotator element.
isAnnotator: (element) ->
!!$(element).parents().andSelf().filter('[class^=annotator-]').not(@wrapper).length
# Annotator#element callback. Sets the @canAnnotate to false to prevent
# the annotation selection events firing when the adder is clicked.
#
# event - A mousedown Event object
#
# Returns nothing.
onAdderMousedown: (event) =>
event?.preventDefault()
this.disableAnnotating()
@inAdderClick = true
# Annotator#element callback. Displays the @editor in place of the @adder and
# loads in a newly created annotation Object. The click event is used as well
# as the mousedown so that we get the :active state on the @adder when clicked
#
# event - A mousedown Event object
#
# Returns nothing.
onAdderClick: (event) =>
event?.preventDefault?()
# Hide the adder
position = @adder.position()
@adder.hide()
@inAdderClick = false
# Create a new annotation.
annotation = this.createAnnotation()
# Extract the quotation and serialize the ranges
annotation = this.setupAnnotation(annotation)
# Show a temporary highlight so the user can see what they selected
for anchor in annotation.anchors
for page, hl of anchor.highlight
hl.setTemporary true
# Make the highlights permanent if the annotation is saved
save = =>
do cleanup
for anchor in annotation.anchors
for page, hl of anchor.highlight
hl.setTemporary false
# Fire annotationCreated events so that plugins can react to them
this.publish('annotationCreated', [annotation])
# Remove the highlights if the edit is cancelled
cancel = =>
do cleanup
this.deleteAnnotation(annotation)
# Don't leak handlers at the end
cleanup = =>
this.unsubscribe('annotationEditorHidden', cancel)
this.unsubscribe('annotationEditorSubmit', save)
# Subscribe to the editor events
this.subscribe('annotationEditorHidden', cancel)
this.subscribe('annotationEditorSubmit', save)
# Display the editor.
this.showEditor(annotation, position)
# Annotator#viewer callback function. Displays the Annotator#editor in the
# positions of the Annotator#viewer and loads the passed annotation for
# editing.
#
# annotation - An annotation Object for editing.
#
# Returns nothing.
onEditAnnotation: (annotation) =>
offset = @viewer.element.position()
# Update the annotation when the editor is saved
update = =>
do cleanup
this.updateAnnotation(annotation)
# Remove handlers when finished
cleanup = =>
this.unsubscribe('annotationEditorHidden', cleanup)
this.unsubscribe('annotationEditorSubmit', update)
# Subscribe to the editor events
this.subscribe('annotationEditorHidden', cleanup)
this.subscribe('annotationEditorSubmit', update)
# Replace the viewer with the editor
@viewer.hide()
this.showEditor(annotation, offset)
# Annotator#viewer callback function. Deletes the annotation provided to the
# callback.
#
# annotation - An annotation Object for deletion.
#
# Returns nothing.
onDeleteAnnotation: (annotation) =>
@viewer.hide()
# Delete highlight elements.
this.deleteAnnotation annotation
# Collect all the highlights (optionally for a given set of annotations)
getHighlights: (annotations) ->
results = []
if annotations?
# Collect only the given set of annotations
for annotation in annotations
for anchor in annotation.anchors
for page, hl of anchor.highlight
results.push hl
else
# Collect from everywhere
for page, anchors of @anchors
$.merge results, (anchor.highlight[page] for anchor in anchors when anchor.highlight[page]?)
results
# Realize anchors on a given pages
_realizePage: (index) ->
# If the page is not mapped, give up
return unless @domMapper.isPageMapped index
# Go over all anchors related to this page
for anchor in @anchors[index] ? []
anchor.realize()
# Virtualize anchors on a given page
_virtualizePage: (index) ->
# Go over all anchors related to this page
for anchor in @anchors[index] ? []
anchor.virtualize index
onAnchorMouseover: (event) ->
#console.log "Mouse over annotations:", event.data.getAnnotations event
# Cancel any pending hiding of the viewer.
this.clearViewerHideTimer()
# Don't do anything if we're making a selection or
# already displaying the viewer
return false if @mouseIsDown or @viewer.isShown()
this.showViewer event.data.getAnnotations(event),
util.mousePosition(event, @wrapper[0])
onAnchorMouseout: (event) ->
#console.log "Mouse out on annotations:", event.data.getAnnotations event
this.startViewerHideTimer()
onAnchorMousedown: (event) ->
#console.log "Mouse down on annotations:", event.data.getAnnotations event
onAnchorClick: (event) ->
#console.log "Click on annotations:", event.data.getAnnotations event
# Create namespace for Annotator plugins
class Annotator.Plugin extends Delegator
constructor: (element, options) ->
super
pluginInit: ->
# Sniff the browser environment and attempt to add missing functionality.
g = util.getGlobal()
if not g.document?.evaluate?
$.getScript('http://assets.annotateit.org/vendor/xpath.min.js')
if not g.getSelection?
$.getScript('http://assets.annotateit.org/vendor/ierange.min.js')
if not g.JSON?
$.getScript('http://assets.annotateit.org/vendor/json2.min.js')
# Ensure the Node constants are defined
if not g.Node?
g.Node =
ELEMENT_NODE : 1
ATTRIBUTE_NODE : 2
TEXT_NODE : 3
CDATA_SECTION_NODE : 4
ENTITY_REFERENCE_NODE : 5
ENTITY_NODE : 6
PROCESSING_INSTRUCTION_NODE : 7
COMMENT_NODE : 8
DOCUMENT_NODE : 9
DOCUMENT_TYPE_NODE : 10
DOCUMENT_FRAGMENT_NODE : 11
NOTATION_NODE : 12
# Bind our local copy of jQuery so plugins can use the extensions.
Annotator.$ = $
# Export other modules for use in plugins.
Annotator.Delegator = Delegator
Annotator.Range = Range
Annotator.util = util
Annotator.Util = Util
Annotator.Highlight = Highlight
Annotator.Anchor = Anchor
# Bind gettext helper so plugins can use localisation.
Annotator._t = _t
# Returns true if the Annotator can be used in the current browser.
Annotator.supported = -> (-> !!this.getSelection)()
# Restores the Annotator property on the global object to it's
# previous value and returns the Annotator.
Annotator.noConflict = ->
util.getGlobal().Annotator = _Annotator
this
# Create global access for Annotator
$.fn.annotator = (options) ->
args = Array::slice.call(arguments, 1)
this.each ->
# check the data() cache, if it's there we'll call the method requested
instance = $.data(this, 'annotator')
if instance
options && instance[options].apply(instance, args)
else
instance = new Annotator(this, options)
$.data(this, 'annotator', instance)
# Export Annotator object.
this.Annotator = Annotator;
|
[
{
"context": "ploads_base\n \n instance = new model({name: 'testName', title: 'testTitle'})\n should.exist instanc",
"end": 2931,
"score": 0.8677068948745728,
"start": 2923,
"tag": "NAME",
"value": "testName"
},
{
"context": "true\n instance.should.have.property 'name... | node_modules/mongoose-thumbnail/test/test.coffee | brilliantyy/Pictopia | 9 | chai = require 'chai'
assert = chai.assert
expect = chai.expect
should = chai.should()
mongoose = require 'mongoose'
fs = require 'fs'
path = require 'path'
util = require 'util'
index = require '../src/index'
PLUGIN_TIMEOUT = 3000
rmDir = (dirPath) ->
try
files = fs.readdirSync(dirPath)
catch e
return
if files.length > 0
i = 0
while i < files.length
continue if files[i] in ['.', '..']
filePath = dirPath + "/" + files[i]
if fs.statSync(filePath).isFile()
fs.unlinkSync filePath
else
rmDir filePath
i++
fs.rmdirSync dirPath
filecopy = (src, dst, cb) ->
copy = (err) ->
is_ = undefined
os = undefined
return cb(new Error("File " + dst + " exists.")) unless err
fs.stat src, (err) ->
return cb(err) if err
is_ = fs.createReadStream(src)
os = fs.createWriteStream(dst)
util.pump is_, os, cb
fs.stat dst, copy
String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
db = mongoose.createConnection('localhost', 'mongoose_thumbnail_tests')
db.on('error', console.error.bind(console, 'connection error:'))
uploads_base = __dirname + "/uploads"
uploads = uploads_base + "/u"
origImagePath = path.join(__dirname, path.join('assets', 'lena.png'))
tmpFilePath = '/tmp/mongoose-thumbnail-test.png'
uploadedDate = new Date()
uploadedFile =
size: 476254
path: tmpFilePath
name: 'lena.png'
type: 'image/png',
hash: false,
lastModifiedDate: uploadedDate
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
schemaDef =
name: String
title: String
_schemas_and_models = {}
_next_schema_num = 0
getNewSchemaAndModel = (plug_cb) ->
num = _next_schema_num
_next_schema_num += 1
schema = new Schema(schemaDef)
if plug_cb
plug_cb.call(@, schema, num)
model = db.model("SimpleModel#{num}", schema)
data =
schema: schema
model: model
_schemas_and_models[num] = data
return data
getSchemaAndModel = (num) ->
if (num >= 0) and (num < _next_schema_num)
return _schemas_and_models[num]
describe 'WHEN working with the plugin', ->
before (done) ->
done()
after (done) ->
for num in [0..._next_schema_num]
{model, schema} = getSchemaAndModel num
model.remove {}, (err) ->
return done(err) if err
rmDir(uploads_base)
done()
describe 'library', ->
it 'should exist', (done) ->
should.exist index
done()
describe 'adding the plugin for non-inline thumbnail', ->
it 'should add correct properties', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', 'testName'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'thumb'
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.exist instance.photo.thumb
should.not.exist instance.photo.thumb.name
should.not.exist instance.photo.thumb.path
should.not.exist instance.photo.thumb.rel
done()
describe 'adding the plugin for inline thumbnail', ->
it 'should add correct properties', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: true
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', 'testName'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'thumb'
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.not.exist instance.photo.thumb
done()
describe 'assigning to the instance field for non-inline thumbnail', ->
it 'should properly populate subfields', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.exist instance.photo.thumb
should.equal instance.isModified(), true
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
should.exist instance.photo.thumb
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
instance.photo.thumb.should.have.property 'name'
instance.photo.thumb.should.have.property 'path'
instance.photo.thumb.should.have.property 'rel'
should.equal instance.photo.thumb.name, 't_lena.jpg'
should.equal instance.photo.thumb.rel, path.join(path.join("u", path.join("photos", instance.id)), 't_lena.jpg')
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field for inline thumbnail', ->
it 'should properly populate subfields', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: true
format: 'jpg'
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.equal instance.isModified(), true
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
should.exist instance.photo.thumb
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
instance.photo.thumb.should.be.a 'string'
should.equal instance.photo.thumb.beginsWith("data:image/jpg;base64,"), true
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should NOT mark as modified when save is set to true', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
save: true
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should mark as modified when save is set to false', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
save: false
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
| 149450 | chai = require 'chai'
assert = chai.assert
expect = chai.expect
should = chai.should()
mongoose = require 'mongoose'
fs = require 'fs'
path = require 'path'
util = require 'util'
index = require '../src/index'
PLUGIN_TIMEOUT = 3000
rmDir = (dirPath) ->
try
files = fs.readdirSync(dirPath)
catch e
return
if files.length > 0
i = 0
while i < files.length
continue if files[i] in ['.', '..']
filePath = dirPath + "/" + files[i]
if fs.statSync(filePath).isFile()
fs.unlinkSync filePath
else
rmDir filePath
i++
fs.rmdirSync dirPath
filecopy = (src, dst, cb) ->
copy = (err) ->
is_ = undefined
os = undefined
return cb(new Error("File " + dst + " exists.")) unless err
fs.stat src, (err) ->
return cb(err) if err
is_ = fs.createReadStream(src)
os = fs.createWriteStream(dst)
util.pump is_, os, cb
fs.stat dst, copy
String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
db = mongoose.createConnection('localhost', 'mongoose_thumbnail_tests')
db.on('error', console.error.bind(console, 'connection error:'))
uploads_base = __dirname + "/uploads"
uploads = uploads_base + "/u"
origImagePath = path.join(__dirname, path.join('assets', 'lena.png'))
tmpFilePath = '/tmp/mongoose-thumbnail-test.png'
uploadedDate = new Date()
uploadedFile =
size: 476254
path: tmpFilePath
name: 'lena.png'
type: 'image/png',
hash: false,
lastModifiedDate: uploadedDate
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
schemaDef =
name: String
title: String
_schemas_and_models = {}
_next_schema_num = 0
getNewSchemaAndModel = (plug_cb) ->
num = _next_schema_num
_next_schema_num += 1
schema = new Schema(schemaDef)
if plug_cb
plug_cb.call(@, schema, num)
model = db.model("SimpleModel#{num}", schema)
data =
schema: schema
model: model
_schemas_and_models[num] = data
return data
getSchemaAndModel = (num) ->
if (num >= 0) and (num < _next_schema_num)
return _schemas_and_models[num]
describe 'WHEN working with the plugin', ->
before (done) ->
done()
after (done) ->
for num in [0..._next_schema_num]
{model, schema} = getSchemaAndModel num
model.remove {}, (err) ->
return done(err) if err
rmDir(uploads_base)
done()
describe 'library', ->
it 'should exist', (done) ->
should.exist index
done()
describe 'adding the plugin for non-inline thumbnail', ->
it 'should add correct properties', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: '<NAME>', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', '<NAME>'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'thumb'
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.exist instance.photo.thumb
should.not.exist instance.photo.thumb.name
should.not.exist instance.photo.thumb.path
should.not.exist instance.photo.thumb.rel
done()
describe 'adding the plugin for inline thumbnail', ->
it 'should add correct properties', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: true
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: '<NAME>', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', '<NAME>'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'thumb'
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.not.exist instance.photo.thumb
done()
describe 'assigning to the instance field for non-inline thumbnail', ->
it 'should properly populate subfields', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: '<NAME>', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.exist instance.photo.thumb
should.equal instance.isModified(), true
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
should.exist instance.photo.thumb
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
instance.photo.thumb.should.have.property 'name'
instance.photo.thumb.should.have.property 'path'
instance.photo.thumb.should.have.property 'rel'
should.equal instance.photo.thumb.name, 't_lena.jpg'
should.equal instance.photo.thumb.rel, path.join(path.join("u", path.join("photos", instance.id)), 't_lena.jpg')
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field for inline thumbnail', ->
it 'should properly populate subfields', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: true
format: 'jpg'
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.equal instance.isModified(), true
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
should.exist instance.photo.thumb
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
instance.photo.thumb.should.be.a 'string'
should.equal instance.photo.thumb.beginsWith("data:image/jpg;base64,"), true
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should NOT mark as modified when save is set to true', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
save: true
instance = new model({name: '<NAME> <NAME>', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should mark as modified when save is set to false', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
save: false
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
| true | chai = require 'chai'
assert = chai.assert
expect = chai.expect
should = chai.should()
mongoose = require 'mongoose'
fs = require 'fs'
path = require 'path'
util = require 'util'
index = require '../src/index'
PLUGIN_TIMEOUT = 3000
rmDir = (dirPath) ->
try
files = fs.readdirSync(dirPath)
catch e
return
if files.length > 0
i = 0
while i < files.length
continue if files[i] in ['.', '..']
filePath = dirPath + "/" + files[i]
if fs.statSync(filePath).isFile()
fs.unlinkSync filePath
else
rmDir filePath
i++
fs.rmdirSync dirPath
filecopy = (src, dst, cb) ->
copy = (err) ->
is_ = undefined
os = undefined
return cb(new Error("File " + dst + " exists.")) unless err
fs.stat src, (err) ->
return cb(err) if err
is_ = fs.createReadStream(src)
os = fs.createWriteStream(dst)
util.pump is_, os, cb
fs.stat dst, copy
String::beginsWith = (str) -> if @match(new RegExp "^#{str}") then true else false
String::endsWith = (str) -> if @match(new RegExp "#{str}$") then true else false
db = mongoose.createConnection('localhost', 'mongoose_thumbnail_tests')
db.on('error', console.error.bind(console, 'connection error:'))
uploads_base = __dirname + "/uploads"
uploads = uploads_base + "/u"
origImagePath = path.join(__dirname, path.join('assets', 'lena.png'))
tmpFilePath = '/tmp/mongoose-thumbnail-test.png'
uploadedDate = new Date()
uploadedFile =
size: 476254
path: tmpFilePath
name: 'lena.png'
type: 'image/png',
hash: false,
lastModifiedDate: uploadedDate
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
schemaDef =
name: String
title: String
_schemas_and_models = {}
_next_schema_num = 0
getNewSchemaAndModel = (plug_cb) ->
num = _next_schema_num
_next_schema_num += 1
schema = new Schema(schemaDef)
if plug_cb
plug_cb.call(@, schema, num)
model = db.model("SimpleModel#{num}", schema)
data =
schema: schema
model: model
_schemas_and_models[num] = data
return data
getSchemaAndModel = (num) ->
if (num >= 0) and (num < _next_schema_num)
return _schemas_and_models[num]
describe 'WHEN working with the plugin', ->
before (done) ->
done()
after (done) ->
for num in [0..._next_schema_num]
{model, schema} = getSchemaAndModel num
model.remove {}, (err) ->
return done(err) if err
rmDir(uploads_base)
done()
describe 'library', ->
it 'should exist', (done) ->
should.exist index
done()
describe 'adding the plugin for non-inline thumbnail', ->
it 'should add correct properties', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'PI:NAME:<NAME>END_PI', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', 'PI:NAME:<NAME>END_PI'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'thumb'
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.exist instance.photo.thumb
should.not.exist instance.photo.thumb.name
should.not.exist instance.photo.thumb.path
should.not.exist instance.photo.thumb.rel
done()
describe 'adding the plugin for inline thumbnail', ->
it 'should add correct properties', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: true
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'PI:NAME:<NAME>END_PI', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', 'PI:NAME:<NAME>END_PI'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'thumb'
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.not.exist instance.photo.thumb
done()
describe 'assigning to the instance field for non-inline thumbnail', ->
it 'should properly populate subfields', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'PI:NAME:<NAME>END_PI', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.exist instance.photo.thumb
should.equal instance.isModified(), true
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
should.exist instance.photo.thumb
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
instance.photo.thumb.should.have.property 'name'
instance.photo.thumb.should.have.property 'path'
instance.photo.thumb.should.have.property 'rel'
should.equal instance.photo.thumb.name, 't_lena.jpg'
should.equal instance.photo.thumb.rel, path.join(path.join("u", path.join("photos", instance.id)), 't_lena.jpg')
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field for inline thumbnail', ->
it 'should properly populate subfields', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: true
format: 'jpg'
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.equal instance.isModified(), true
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
should.exist instance.photo.thumb
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
instance.photo.thumb.should.be.a 'string'
should.equal instance.photo.thumb.beginsWith("data:image/jpg;base64,"), true
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should NOT mark as modified when save is set to true', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
save: true
instance = new model({name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
# assigning to image field causes the instance to be saved
should.equal instance.isModified(), false
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should mark as modified when save is set to false', (done) ->
{model, schema} = getNewSchemaAndModel (schema) ->
schema.plugin index.thumbnailPlugin,
name: "photo"
inline: false
upload_to: index.make_upload_to_model(uploads, 'photos')
relative_to: uploads_base
save: false
instance = new model({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
filecopy origImagePath, tmpFilePath, (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
|
[
{
"context": " not rolled back on failure\n <https://github.com/fhirbase/fhirbase-plv8/issues/122>\n\n Hi!\n\n I retested th",
"end": 253,
"score": 0.9850954413414001,
"start": 245,
"tag": "USERNAME",
"value": "fhirbase"
},
{
"context": "\", \"resourceType\": \"Patient\",\"name\":... | test/integration/issues/122_transactions_are_not_rolled_back_on_failure_spec.coffee | micabe/fhirbase | 0 | plv8 = require('../../../plpl/src/plv8')
assert = require('assert')
describe 'Issues', ->
before ->
plv8.execute("SET plv8.start_proc = 'plv8_init'")
###
Issue #122
Transactions are not rolled back on failure
<https://github.com/fhirbase/fhirbase-plv8/issues/122>
Hi!
I retested the issue #112 on v1.3.0.15 and the problem still exists.
```
SELECT fhir_drop_storage('{"resourceType": "Patient"}');
SELECT fhir_create_storage('{"resourceType": "Patient"}');
SELECT fhir_create_resource('{"allowId": true, "resource": {"id": "id1", "resourceType": "Patient","name": [{"given": ["Jim"]}], "identifier": [{"use": "official", "value": "0987", "system": "test"}]}}');
```
Check what are patient names at this moment
```
SELECT resource ->> 'name' from patient;
-[ RECORD 1 ]------------------
?column? | [{"given": ["Jim"]}]
```
now the transaction:
```
SELECT fhir_transaction('{"resourceType":"Bundle","id":"bundle-transaction","type":"transaction","entry":[{"resource":{"resourceType":"Patient","name":[{"use":"official","family":["Chalmers"],"given":["Peter","James"]}],"gender":"male","birthDate":"1974-12-25","active":true},"request":{"method":"POST","url":"/Patient"}},{"resource":{"name":[{"use":"official","family":["Martin"],"given":["Bob"]}],"gender":"male","birthDate":"1955-05-05","active":true},"request":{"method":"PUT","url":"/Patient/1234"}},{"request":{"method":"DELETE","url":"/Patient/id1"}}]}');
```
and its response with a failure for an update:
```
fhir_transaction | {"resourceType":"Bundle","type":"transaction-response","entry":[{"resourceType":"Patient","name":[{"use":"official","family":["Chalmers"],"given":["Peter","James"]}],"gender":"male","birthDate":"1974-12-25","active":true,"id":"0cd5434d-e2a5-4019-a572-a05ee54d0da4","meta":{"versionId":"419e341f-6e8b-4f4a-b2f6-cb03d80868ee","lastUpdated":"2016-06-07T15:39:54.715Z","extension":[{"url":"fhir-request-method","valueString":"POST"},{"url":"fhir-request-uri","valueUri":"Patient"}]}},{"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"400","diagnostics":"Could not update resource without resourceType"}]},{"id":"id1","meta":{"extension":[{"url":"fhir-request-method","valueString":"DELETE"},{"url":"fhir-request-uri","valueUri":"Patient"}],"versionId":"9388401e-d04a-43a1-bd7e-5c3237f08f1a","lastUpdated":"2016-06-07T15:39:54.720Z"},"name":[{"given":["Jim"]}],"identifier":[{"use":"official","value":"0987","system":"test"}],"resourceType":"Patient"}]}
```
and again checks:
1) We don't have Patient with the name "Jim", he was deleted in a transaction
```
SELECT fhir_read_resource('{"resourceType": "Patient", "id": "id1"}');
-[ RECORD 1 ]------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
fhir_read_resource | {"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"not-found","details":{"coding":[{"code":"MSG_DELETED_ID","display":"The resource \"id1\" has been deleted"}]},"diagnostics":"Resource Id \"id1\" with versionId \"undefined\" has been deleted"}]}
```
2) but we have this one added in a transaction
```
SELECT resource ->> 'name' from patient; -[ RECORD 1 ]------------------------------------------------------------------------
?column? | [{"use": "official", "given": ["Peter", "James"], "family": ["Chalmers"]}]
```
###
it '#122 Transactions are not rolled back on failure', ->
plv8.execute('''
SELECT fhir_create_storage('{"resourceType": "Patient"}');
''')
plv8.execute('''
SELECT fhir_truncate_storage('{"resourceType": "Patient"}');
''')
plv8.execute('''
SELECT fhir_create_resource('
{"allowId": true,
"resource": {
"id": "id1",
"resourceType": "Patient",
"name": [{"given": ["Jim"]}],
"identifier": [
{"use": "official", "value": "0987", "system": "test"}
]
}
}
');
''')
transaction =
JSON.parse(
plv8.execute('''
SELECT fhir_transaction('
{
"resourceType":"Bundle",
"id":"bundle-transaction",
"type":"transaction",
"entry":[
{
"resource":{
"resourceType":"Patient",
"name":[
{
"use":"official",
"family":["Chalmers"],
"given":["Peter","James"]
}
],
"gender":"male",
"birthDate":"1974-12-25",
"active":true
},
"request":{"method":"POST","url":"/Patient"}
}, {
"resource":{
"name":[
{
"use":"official",
"family":["Martin"],
"given":["Bob"]
}
],
"gender":"male",
"birthDate":"1955-05-05",
"active":true
},
"request":{"method":"PUT","url":"/Patient/1234"}
}, {
"request":{"method":"DELETE","url":"/Patient/id1"}
}
]
}
');
''')[0].fhir_transaction
)
assert.equal(transaction.resourceType, 'OperationOutcome')
assert.equal(
transaction.issue[0].diagnostics,
'Could not update resource without resourceType'
)
patient =
JSON.parse(
plv8.execute('''
SELECT fhir_read_resource('
{"id": "id1", "resourceType": "Patient"}
');
''')[0].fhir_read_resource
)
assert.equal(patient.resourceType, 'Patient')
assert.equal(patient.id, 'id1')
assert.equal(patient.name[0].given, 'Jim')
search =
JSON.parse(
plv8.execute('''
SELECT fhir_search('
{"resourceType": "Patient", "queryString": "name=Peter,James,Chalmers"}
');
''')[0].fhir_search
)
assert.equal(search.total, 0)
| 171270 | plv8 = require('../../../plpl/src/plv8')
assert = require('assert')
describe 'Issues', ->
before ->
plv8.execute("SET plv8.start_proc = 'plv8_init'")
###
Issue #122
Transactions are not rolled back on failure
<https://github.com/fhirbase/fhirbase-plv8/issues/122>
Hi!
I retested the issue #112 on v1.3.0.15 and the problem still exists.
```
SELECT fhir_drop_storage('{"resourceType": "Patient"}');
SELECT fhir_create_storage('{"resourceType": "Patient"}');
SELECT fhir_create_resource('{"allowId": true, "resource": {"id": "id1", "resourceType": "Patient","name": [{"given": ["<NAME>"]}], "identifier": [{"use": "official", "value": "0987", "system": "test"}]}}');
```
Check what are patient names at this moment
```
SELECT resource ->> 'name' from patient;
-[ RECORD 1 ]------------------
?column? | [{"given": ["<NAME>"]}]
```
now the transaction:
```
SELECT fhir_transaction('{"resourceType":"Bundle","id":"bundle-transaction","type":"transaction","entry":[{"resource":{"resourceType":"Patient","name":[{"use":"official","family":["Chalmers"],"given":["<NAME>","<NAME>"]}],"gender":"male","birthDate":"1974-12-25","active":true},"request":{"method":"POST","url":"/Patient"}},{"resource":{"name":[{"use":"official","family":["<NAME>"],"given":["<NAME>"]}],"gender":"male","birthDate":"1955-05-05","active":true},"request":{"method":"PUT","url":"/Patient/1234"}},{"request":{"method":"DELETE","url":"/Patient/id1"}}]}');
```
and its response with a failure for an update:
```
fhir_transaction | {"resourceType":"Bundle","type":"transaction-response","entry":[{"resourceType":"Patient","name":[{"use":"official","family":["Chalmers"],"given":["<NAME>","<NAME>"]}],"gender":"male","birthDate":"1974-12-25","active":true,"id":"0cd5434d-e2a5-4019-a572-a05ee54d0da4","meta":{"versionId":"419e341f-6e8b-4f4a-b2f6-cb03d80868ee","lastUpdated":"2016-06-07T15:39:54.715Z","extension":[{"url":"fhir-request-method","valueString":"POST"},{"url":"fhir-request-uri","valueUri":"Patient"}]}},{"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"400","diagnostics":"Could not update resource without resourceType"}]},{"id":"id1","meta":{"extension":[{"url":"fhir-request-method","valueString":"DELETE"},{"url":"fhir-request-uri","valueUri":"Patient"}],"versionId":"9388401e-d04a-43a1-bd7e-5c3237f08f1a","lastUpdated":"2016-06-07T15:39:54.720Z"},"name":[{"given":["<NAME>"]}],"identifier":[{"use":"official","value":"0987","system":"test"}],"resourceType":"Patient"}]}
```
and again checks:
1) We don't have Patient with the name "<NAME>", he was deleted in a transaction
```
SELECT fhir_read_resource('{"resourceType": "Patient", "id": "id1"}');
-[ RECORD 1 ]------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
fhir_read_resource | {"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"not-found","details":{"coding":[{"code":"MSG_DELETED_ID","display":"The resource \"id1\" has been deleted"}]},"diagnostics":"Resource Id \"id1\" with versionId \"undefined\" has been deleted"}]}
```
2) but we have this one added in a transaction
```
SELECT resource ->> 'name' from patient; -[ RECORD 1 ]------------------------------------------------------------------------
?column? | [{"use": "official", "given": ["<NAME>", "<NAME>"], "family": ["Chalmers"]}]
```
###
it '#122 Transactions are not rolled back on failure', ->
plv8.execute('''
SELECT fhir_create_storage('{"resourceType": "Patient"}');
''')
plv8.execute('''
SELECT fhir_truncate_storage('{"resourceType": "Patient"}');
''')
plv8.execute('''
SELECT fhir_create_resource('
{"allowId": true,
"resource": {
"id": "id1",
"resourceType": "Patient",
"name": [{"given": ["<NAME>"]}],
"identifier": [
{"use": "official", "value": "0987", "system": "test"}
]
}
}
');
''')
transaction =
JSON.parse(
plv8.execute('''
SELECT fhir_transaction('
{
"resourceType":"Bundle",
"id":"bundle-transaction",
"type":"transaction",
"entry":[
{
"resource":{
"resourceType":"Patient",
"name":[
{
"use":"official",
"family":["Ch<NAME>"],
"given":["<NAME>","<NAME>"]
}
],
"gender":"male",
"birthDate":"1974-12-25",
"active":true
},
"request":{"method":"POST","url":"/Patient"}
}, {
"resource":{
"name":[
{
"use":"official",
"family":["<NAME>"],
"given":["<NAME>"]
}
],
"gender":"male",
"birthDate":"1955-05-05",
"active":true
},
"request":{"method":"PUT","url":"/Patient/1234"}
}, {
"request":{"method":"DELETE","url":"/Patient/id1"}
}
]
}
');
''')[0].fhir_transaction
)
assert.equal(transaction.resourceType, 'OperationOutcome')
assert.equal(
transaction.issue[0].diagnostics,
'Could not update resource without resourceType'
)
patient =
JSON.parse(
plv8.execute('''
SELECT fhir_read_resource('
{"id": "id1", "resourceType": "Patient"}
');
''')[0].fhir_read_resource
)
assert.equal(patient.resourceType, 'Patient')
assert.equal(patient.id, 'id1')
assert.equal(patient.name[0].given, '<NAME>')
search =
JSON.parse(
plv8.execute('''
SELECT fhir_search('
{"resourceType": "Patient", "queryString": "name=<NAME>,<NAME>,<NAME>"}
');
''')[0].fhir_search
)
assert.equal(search.total, 0)
| true | plv8 = require('../../../plpl/src/plv8')
assert = require('assert')
describe 'Issues', ->
before ->
plv8.execute("SET plv8.start_proc = 'plv8_init'")
###
Issue #122
Transactions are not rolled back on failure
<https://github.com/fhirbase/fhirbase-plv8/issues/122>
Hi!
I retested the issue #112 on v1.3.0.15 and the problem still exists.
```
SELECT fhir_drop_storage('{"resourceType": "Patient"}');
SELECT fhir_create_storage('{"resourceType": "Patient"}');
SELECT fhir_create_resource('{"allowId": true, "resource": {"id": "id1", "resourceType": "Patient","name": [{"given": ["PI:NAME:<NAME>END_PI"]}], "identifier": [{"use": "official", "value": "0987", "system": "test"}]}}');
```
Check what are patient names at this moment
```
SELECT resource ->> 'name' from patient;
-[ RECORD 1 ]------------------
?column? | [{"given": ["PI:NAME:<NAME>END_PI"]}]
```
now the transaction:
```
SELECT fhir_transaction('{"resourceType":"Bundle","id":"bundle-transaction","type":"transaction","entry":[{"resource":{"resourceType":"Patient","name":[{"use":"official","family":["Chalmers"],"given":["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]}],"gender":"male","birthDate":"1974-12-25","active":true},"request":{"method":"POST","url":"/Patient"}},{"resource":{"name":[{"use":"official","family":["PI:NAME:<NAME>END_PI"],"given":["PI:NAME:<NAME>END_PI"]}],"gender":"male","birthDate":"1955-05-05","active":true},"request":{"method":"PUT","url":"/Patient/1234"}},{"request":{"method":"DELETE","url":"/Patient/id1"}}]}');
```
and its response with a failure for an update:
```
fhir_transaction | {"resourceType":"Bundle","type":"transaction-response","entry":[{"resourceType":"Patient","name":[{"use":"official","family":["Chalmers"],"given":["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]}],"gender":"male","birthDate":"1974-12-25","active":true,"id":"0cd5434d-e2a5-4019-a572-a05ee54d0da4","meta":{"versionId":"419e341f-6e8b-4f4a-b2f6-cb03d80868ee","lastUpdated":"2016-06-07T15:39:54.715Z","extension":[{"url":"fhir-request-method","valueString":"POST"},{"url":"fhir-request-uri","valueUri":"Patient"}]}},{"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"400","diagnostics":"Could not update resource without resourceType"}]},{"id":"id1","meta":{"extension":[{"url":"fhir-request-method","valueString":"DELETE"},{"url":"fhir-request-uri","valueUri":"Patient"}],"versionId":"9388401e-d04a-43a1-bd7e-5c3237f08f1a","lastUpdated":"2016-06-07T15:39:54.720Z"},"name":[{"given":["PI:NAME:<NAME>END_PI"]}],"identifier":[{"use":"official","value":"0987","system":"test"}],"resourceType":"Patient"}]}
```
and again checks:
1) We don't have Patient with the name "PI:NAME:<NAME>END_PI", he was deleted in a transaction
```
SELECT fhir_read_resource('{"resourceType": "Patient", "id": "id1"}');
-[ RECORD 1 ]------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
fhir_read_resource | {"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"not-found","details":{"coding":[{"code":"MSG_DELETED_ID","display":"The resource \"id1\" has been deleted"}]},"diagnostics":"Resource Id \"id1\" with versionId \"undefined\" has been deleted"}]}
```
2) but we have this one added in a transaction
```
SELECT resource ->> 'name' from patient; -[ RECORD 1 ]------------------------------------------------------------------------
?column? | [{"use": "official", "given": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"], "family": ["Chalmers"]}]
```
###
it '#122 Transactions are not rolled back on failure', ->
plv8.execute('''
SELECT fhir_create_storage('{"resourceType": "Patient"}');
''')
plv8.execute('''
SELECT fhir_truncate_storage('{"resourceType": "Patient"}');
''')
plv8.execute('''
SELECT fhir_create_resource('
{"allowId": true,
"resource": {
"id": "id1",
"resourceType": "Patient",
"name": [{"given": ["PI:NAME:<NAME>END_PI"]}],
"identifier": [
{"use": "official", "value": "0987", "system": "test"}
]
}
}
');
''')
transaction =
JSON.parse(
plv8.execute('''
SELECT fhir_transaction('
{
"resourceType":"Bundle",
"id":"bundle-transaction",
"type":"transaction",
"entry":[
{
"resource":{
"resourceType":"Patient",
"name":[
{
"use":"official",
"family":["ChPI:NAME:<NAME>END_PI"],
"given":["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]
}
],
"gender":"male",
"birthDate":"1974-12-25",
"active":true
},
"request":{"method":"POST","url":"/Patient"}
}, {
"resource":{
"name":[
{
"use":"official",
"family":["PI:NAME:<NAME>END_PI"],
"given":["PI:NAME:<NAME>END_PI"]
}
],
"gender":"male",
"birthDate":"1955-05-05",
"active":true
},
"request":{"method":"PUT","url":"/Patient/1234"}
}, {
"request":{"method":"DELETE","url":"/Patient/id1"}
}
]
}
');
''')[0].fhir_transaction
)
assert.equal(transaction.resourceType, 'OperationOutcome')
assert.equal(
transaction.issue[0].diagnostics,
'Could not update resource without resourceType'
)
patient =
JSON.parse(
plv8.execute('''
SELECT fhir_read_resource('
{"id": "id1", "resourceType": "Patient"}
');
''')[0].fhir_read_resource
)
assert.equal(patient.resourceType, 'Patient')
assert.equal(patient.id, 'id1')
assert.equal(patient.name[0].given, 'PI:NAME:<NAME>END_PI')
search =
JSON.parse(
plv8.execute('''
SELECT fhir_search('
{"resourceType": "Patient", "queryString": "name=PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI"}
');
''')[0].fhir_search
)
assert.equal(search.total, 0)
|
[
{
"context": "t dimensions API tests\n#\n# Copyright (C) 2012-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\n\nTest.set \"/",
"end": 78,
"score": 0.9998854994773865,
"start": 61,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/dom/test/element/dimensions_test.coffee | lovely-io/lovely.io-stl | 2 | #
# Element dimensions API tests
#
# Copyright (C) 2012-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
Test.set "/dimensions.html", """
<html>
<head>
<script src="core.js"></script>
<script src="dom.js"></script>
</head>
<body>
<div id="absolute">
<div id="relative">
<div id="test">
Boobs
</div>
</div>
</div>
</body>
</html>
"""
describe "Element dimensions", ->
$ = window = document = element = abs_el = rel_el = null
before Test.load "/dimensions.html", (dom, win)->
$ = dom
window = win
document = win.document
element = $('#test')[0]
abs_el = $('#absolute')[0]
rel_el = $('#relative')[0]
# patching zombie.js while it doesn't support the stuff
document.documentElement.clientLeft or= 0
document.documentElement.clientTop or= 0
document.documentElement.getBoundingClientRect or= -> left: 0, top: 0
element._.getBoundingClientRect or= -> left: 0, top: 0
describe "#size()", ->
it "should return correct element's size in a hash", ->
element.size().should.eql x: 100, y: 100
it "should allow to set the element's size as a hash", ->
element.size(x: 200, y: 300)
element._.style.width.should.eql '300px' # coz it corrects the paddings
element._.style.height.should.eql '500px'
it "should allow to set the element's size as two numbers", ->
element.size(300, 400)
element._.style.width.should.eql '500px' # coz it corrects the paddings
element._.style.height.should.eql '700px'
it "should allow to specify one size only as a hash", ->
element.style(width: '100px', height: '100px')
element.size(x: 200)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '100px'
element.size(y: 300)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '500px'
it "should allow to specify the size with one value only", ->
element.style(width: '100px', height: '100px')
element.size(200)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '100px'
element.size(null, 300)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '500px'
it "should return the element itself when used as a setter", ->
element.size(x: 100).should.equal element
element.size(100).should.equal element
element.size(null, 100).should.equal element
describe "#scrolls()", ->
it "should return the element's scrolling positions", ->
element._.scrollLeft = 111
element._.scrollTop = 222
element.scrolls().should.eql x: 111, y: 222
it "should allow to set element's scrolling position as an x/y hash", ->
element.scrolls x: 222, y: 333
element._.scrollLeft.should.eql 222
element._.scrollTop.should.eql 333
it "should allow to set element's x scrolling only in as a hash", ->
element._.scrollLeft = element._.scrollTop = 100
element.scrolls x: 200
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 100
element.scrolls y: 300
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 300
it "should allow to set element's scrolling as a number only", ->
element._.scrollLeft = element._.scrollTop = 100
element.scrolls 200
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 100
element.scrolls(null, 300)
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 300
it "should return the element itself when used as a setter", ->
element.scrolls(x: 100).should.equal element
element.scrolls(100).should.equal element
element.scrolls(null, 100).should.equal element
describe "#position()", ->
it "should return correct element's position", ->
element.position().should.eql x: 0, y: 0
element._.getBoundingClientRect = -> left: 10, top: 20
element.position().should.eql x: 10, y: 20
it "should allow to set element's position as a hash", ->
element.position(x: 100, y: 200)
element._.style.left.should.equal '100px'
element._.style.top.should.equal '200px'
it "should allow to set the element's position with one entry hash", ->
element._.style.left = element._.style.top = '0px'
element.position x: 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.position y: 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should allow to set the position as a number only", ->
element._.style.left = element._.style.top = '0px'
element.position 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.position null, 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should return the element itself when used as a setter", ->
element.position(x: 100).should.equal element
element.position(100).should.equal element
element.position(null, 100).should.equal element
it "should correct the actual position for the nested positions space", ->
element._.style.left = element._.style.top = '0px'
abs_el._.style.position = 'absolute'
abs_el._.getBoundingClientRect or= -> left: 100, top: 200
element.position x: 500, y: 600
element._.style.left.should.equal '400px'
element._.style.top.should.equal '400px'
describe "#offset()", ->
it "should return element's offset against it's offsetParent correctly", ->
element._.getBoundingClientRect = -> left: 0, top: 0
abs_el._.style.position = 'static'
element.offset().should.eql x: 0, y: 0
abs_el._.style.position = 'absolute'
element._.getBoundingClientRect = -> left: 200, top: 400
abs_el._.getBoundingClientRect or= -> left: 100, top: 200
element.offset().should.eql x: 100, y: 200
it "should allow to set the offset as an x/y hash", ->
element._.style.left = element._.style.top = '0px'
element.offset(x: 55, y: 66)
element._.style.left.should.eql '55px'
element._.style.top.should.eql '66px'
it "should allow to set the offset as one entry hash", ->
element._.style.left = element._.style.top = '0px'
element.offset x: 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.offset y: 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should allow to set the offset in plain numbers", ->
element._.style.left = element._.style.top = '0px'
element.offset 500
element._.style.left.should.equal '500px'
element._.style.top.should.equal '0px'
element.offset null, 600
element._.style.left.should.equal '500px'
element._.style.top.should.equal '600px'
it "should return the element itself when used as a setter", ->
element.offset(x: 100).should.equal element
element.offset(100).should.equal element
element.offset(null, 100).should.equal element
describe "#offsetParent()", ->
before ->
abs_el._.style.position = 'absolute'
it "should return the correct offsetParent for an element inside of an absolutely positioned element", ->
element.offsetParent().should.equal abs_el
it "should return the HTML element as a fallback", ->
abs_el.offsetParent().should.equal $('html')[0]
describe "#overlaps()", ->
before ->
element.position = -> x: 100, y: 100
element.size = -> x: 100, y: 100
it "should return 'true' for positions inside of the element", ->
element.overlaps(x: 150, y: 150).should.be.true
element.overlaps(120, 120).should.be.true
it "should return 'false' for positions outside of the element", ->
element.overlaps(x: 50, y: 50).should.be.false
element.overlaps(x: 50, y: 150).should.be.false
element.overlaps(300, 300).should.be.false
element.overlaps(50, 300).should.be.false
element.overlaps(300, 50).should.be.false
describe "#index()", ->
e1 = e2 = e3 = null
before ->
element._.innerHTML = """
<div>one</div>
<div>two</div> boo hoo
<div>three</div>
"""
[e1, e2, e3] = element.find('div')
it "should return correct index for all the elements", ->
e1.index().should.eql 0
e2.index().should.eql 1
e3.index().should.eql 2
| 116627 | #
# Element dimensions API tests
#
# Copyright (C) 2012-2013 <NAME>
#
{Test,should} = require('lovely')
Test.set "/dimensions.html", """
<html>
<head>
<script src="core.js"></script>
<script src="dom.js"></script>
</head>
<body>
<div id="absolute">
<div id="relative">
<div id="test">
Boobs
</div>
</div>
</div>
</body>
</html>
"""
describe "Element dimensions", ->
$ = window = document = element = abs_el = rel_el = null
before Test.load "/dimensions.html", (dom, win)->
$ = dom
window = win
document = win.document
element = $('#test')[0]
abs_el = $('#absolute')[0]
rel_el = $('#relative')[0]
# patching zombie.js while it doesn't support the stuff
document.documentElement.clientLeft or= 0
document.documentElement.clientTop or= 0
document.documentElement.getBoundingClientRect or= -> left: 0, top: 0
element._.getBoundingClientRect or= -> left: 0, top: 0
describe "#size()", ->
it "should return correct element's size in a hash", ->
element.size().should.eql x: 100, y: 100
it "should allow to set the element's size as a hash", ->
element.size(x: 200, y: 300)
element._.style.width.should.eql '300px' # coz it corrects the paddings
element._.style.height.should.eql '500px'
it "should allow to set the element's size as two numbers", ->
element.size(300, 400)
element._.style.width.should.eql '500px' # coz it corrects the paddings
element._.style.height.should.eql '700px'
it "should allow to specify one size only as a hash", ->
element.style(width: '100px', height: '100px')
element.size(x: 200)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '100px'
element.size(y: 300)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '500px'
it "should allow to specify the size with one value only", ->
element.style(width: '100px', height: '100px')
element.size(200)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '100px'
element.size(null, 300)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '500px'
it "should return the element itself when used as a setter", ->
element.size(x: 100).should.equal element
element.size(100).should.equal element
element.size(null, 100).should.equal element
describe "#scrolls()", ->
it "should return the element's scrolling positions", ->
element._.scrollLeft = 111
element._.scrollTop = 222
element.scrolls().should.eql x: 111, y: 222
it "should allow to set element's scrolling position as an x/y hash", ->
element.scrolls x: 222, y: 333
element._.scrollLeft.should.eql 222
element._.scrollTop.should.eql 333
it "should allow to set element's x scrolling only in as a hash", ->
element._.scrollLeft = element._.scrollTop = 100
element.scrolls x: 200
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 100
element.scrolls y: 300
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 300
it "should allow to set element's scrolling as a number only", ->
element._.scrollLeft = element._.scrollTop = 100
element.scrolls 200
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 100
element.scrolls(null, 300)
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 300
it "should return the element itself when used as a setter", ->
element.scrolls(x: 100).should.equal element
element.scrolls(100).should.equal element
element.scrolls(null, 100).should.equal element
describe "#position()", ->
it "should return correct element's position", ->
element.position().should.eql x: 0, y: 0
element._.getBoundingClientRect = -> left: 10, top: 20
element.position().should.eql x: 10, y: 20
it "should allow to set element's position as a hash", ->
element.position(x: 100, y: 200)
element._.style.left.should.equal '100px'
element._.style.top.should.equal '200px'
it "should allow to set the element's position with one entry hash", ->
element._.style.left = element._.style.top = '0px'
element.position x: 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.position y: 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should allow to set the position as a number only", ->
element._.style.left = element._.style.top = '0px'
element.position 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.position null, 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should return the element itself when used as a setter", ->
element.position(x: 100).should.equal element
element.position(100).should.equal element
element.position(null, 100).should.equal element
it "should correct the actual position for the nested positions space", ->
element._.style.left = element._.style.top = '0px'
abs_el._.style.position = 'absolute'
abs_el._.getBoundingClientRect or= -> left: 100, top: 200
element.position x: 500, y: 600
element._.style.left.should.equal '400px'
element._.style.top.should.equal '400px'
describe "#offset()", ->
it "should return element's offset against it's offsetParent correctly", ->
element._.getBoundingClientRect = -> left: 0, top: 0
abs_el._.style.position = 'static'
element.offset().should.eql x: 0, y: 0
abs_el._.style.position = 'absolute'
element._.getBoundingClientRect = -> left: 200, top: 400
abs_el._.getBoundingClientRect or= -> left: 100, top: 200
element.offset().should.eql x: 100, y: 200
it "should allow to set the offset as an x/y hash", ->
element._.style.left = element._.style.top = '0px'
element.offset(x: 55, y: 66)
element._.style.left.should.eql '55px'
element._.style.top.should.eql '66px'
it "should allow to set the offset as one entry hash", ->
element._.style.left = element._.style.top = '0px'
element.offset x: 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.offset y: 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should allow to set the offset in plain numbers", ->
element._.style.left = element._.style.top = '0px'
element.offset 500
element._.style.left.should.equal '500px'
element._.style.top.should.equal '0px'
element.offset null, 600
element._.style.left.should.equal '500px'
element._.style.top.should.equal '600px'
it "should return the element itself when used as a setter", ->
element.offset(x: 100).should.equal element
element.offset(100).should.equal element
element.offset(null, 100).should.equal element
describe "#offsetParent()", ->
before ->
abs_el._.style.position = 'absolute'
it "should return the correct offsetParent for an element inside of an absolutely positioned element", ->
element.offsetParent().should.equal abs_el
it "should return the HTML element as a fallback", ->
abs_el.offsetParent().should.equal $('html')[0]
describe "#overlaps()", ->
before ->
element.position = -> x: 100, y: 100
element.size = -> x: 100, y: 100
it "should return 'true' for positions inside of the element", ->
element.overlaps(x: 150, y: 150).should.be.true
element.overlaps(120, 120).should.be.true
it "should return 'false' for positions outside of the element", ->
element.overlaps(x: 50, y: 50).should.be.false
element.overlaps(x: 50, y: 150).should.be.false
element.overlaps(300, 300).should.be.false
element.overlaps(50, 300).should.be.false
element.overlaps(300, 50).should.be.false
describe "#index()", ->
e1 = e2 = e3 = null
before ->
element._.innerHTML = """
<div>one</div>
<div>two</div> boo hoo
<div>three</div>
"""
[e1, e2, e3] = element.find('div')
it "should return correct index for all the elements", ->
e1.index().should.eql 0
e2.index().should.eql 1
e3.index().should.eql 2
| true | #
# Element dimensions API tests
#
# Copyright (C) 2012-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
Test.set "/dimensions.html", """
<html>
<head>
<script src="core.js"></script>
<script src="dom.js"></script>
</head>
<body>
<div id="absolute">
<div id="relative">
<div id="test">
Boobs
</div>
</div>
</div>
</body>
</html>
"""
describe "Element dimensions", ->
$ = window = document = element = abs_el = rel_el = null
before Test.load "/dimensions.html", (dom, win)->
$ = dom
window = win
document = win.document
element = $('#test')[0]
abs_el = $('#absolute')[0]
rel_el = $('#relative')[0]
# patching zombie.js while it doesn't support the stuff
document.documentElement.clientLeft or= 0
document.documentElement.clientTop or= 0
document.documentElement.getBoundingClientRect or= -> left: 0, top: 0
element._.getBoundingClientRect or= -> left: 0, top: 0
describe "#size()", ->
it "should return correct element's size in a hash", ->
element.size().should.eql x: 100, y: 100
it "should allow to set the element's size as a hash", ->
element.size(x: 200, y: 300)
element._.style.width.should.eql '300px' # coz it corrects the paddings
element._.style.height.should.eql '500px'
it "should allow to set the element's size as two numbers", ->
element.size(300, 400)
element._.style.width.should.eql '500px' # coz it corrects the paddings
element._.style.height.should.eql '700px'
it "should allow to specify one size only as a hash", ->
element.style(width: '100px', height: '100px')
element.size(x: 200)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '100px'
element.size(y: 300)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '500px'
it "should allow to specify the size with one value only", ->
element.style(width: '100px', height: '100px')
element.size(200)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '100px'
element.size(null, 300)
element._.style.width.should.eql '300px'
element._.style.height.should.eql '500px'
it "should return the element itself when used as a setter", ->
element.size(x: 100).should.equal element
element.size(100).should.equal element
element.size(null, 100).should.equal element
describe "#scrolls()", ->
it "should return the element's scrolling positions", ->
element._.scrollLeft = 111
element._.scrollTop = 222
element.scrolls().should.eql x: 111, y: 222
it "should allow to set element's scrolling position as an x/y hash", ->
element.scrolls x: 222, y: 333
element._.scrollLeft.should.eql 222
element._.scrollTop.should.eql 333
it "should allow to set element's x scrolling only in as a hash", ->
element._.scrollLeft = element._.scrollTop = 100
element.scrolls x: 200
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 100
element.scrolls y: 300
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 300
it "should allow to set element's scrolling as a number only", ->
element._.scrollLeft = element._.scrollTop = 100
element.scrolls 200
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 100
element.scrolls(null, 300)
element._.scrollLeft.should.eql 200
element._.scrollTop.should.eql 300
it "should return the element itself when used as a setter", ->
element.scrolls(x: 100).should.equal element
element.scrolls(100).should.equal element
element.scrolls(null, 100).should.equal element
describe "#position()", ->
it "should return correct element's position", ->
element.position().should.eql x: 0, y: 0
element._.getBoundingClientRect = -> left: 10, top: 20
element.position().should.eql x: 10, y: 20
it "should allow to set element's position as a hash", ->
element.position(x: 100, y: 200)
element._.style.left.should.equal '100px'
element._.style.top.should.equal '200px'
it "should allow to set the element's position with one entry hash", ->
element._.style.left = element._.style.top = '0px'
element.position x: 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.position y: 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should allow to set the position as a number only", ->
element._.style.left = element._.style.top = '0px'
element.position 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.position null, 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should return the element itself when used as a setter", ->
element.position(x: 100).should.equal element
element.position(100).should.equal element
element.position(null, 100).should.equal element
it "should correct the actual position for the nested positions space", ->
element._.style.left = element._.style.top = '0px'
abs_el._.style.position = 'absolute'
abs_el._.getBoundingClientRect or= -> left: 100, top: 200
element.position x: 500, y: 600
element._.style.left.should.equal '400px'
element._.style.top.should.equal '400px'
describe "#offset()", ->
it "should return element's offset against it's offsetParent correctly", ->
element._.getBoundingClientRect = -> left: 0, top: 0
abs_el._.style.position = 'static'
element.offset().should.eql x: 0, y: 0
abs_el._.style.position = 'absolute'
element._.getBoundingClientRect = -> left: 200, top: 400
abs_el._.getBoundingClientRect or= -> left: 100, top: 200
element.offset().should.eql x: 100, y: 200
it "should allow to set the offset as an x/y hash", ->
element._.style.left = element._.style.top = '0px'
element.offset(x: 55, y: 66)
element._.style.left.should.eql '55px'
element._.style.top.should.eql '66px'
it "should allow to set the offset as one entry hash", ->
element._.style.left = element._.style.top = '0px'
element.offset x: 300
element._.style.left.should.equal '300px'
element._.style.top.should.equal '0px'
element.offset y: 400
element._.style.left.should.equal '300px'
element._.style.top.should.equal '400px'
it "should allow to set the offset in plain numbers", ->
element._.style.left = element._.style.top = '0px'
element.offset 500
element._.style.left.should.equal '500px'
element._.style.top.should.equal '0px'
element.offset null, 600
element._.style.left.should.equal '500px'
element._.style.top.should.equal '600px'
it "should return the element itself when used as a setter", ->
element.offset(x: 100).should.equal element
element.offset(100).should.equal element
element.offset(null, 100).should.equal element
describe "#offsetParent()", ->
before ->
abs_el._.style.position = 'absolute'
it "should return the correct offsetParent for an element inside of an absolutely positioned element", ->
element.offsetParent().should.equal abs_el
it "should return the HTML element as a fallback", ->
abs_el.offsetParent().should.equal $('html')[0]
describe "#overlaps()", ->
before ->
element.position = -> x: 100, y: 100
element.size = -> x: 100, y: 100
it "should return 'true' for positions inside of the element", ->
element.overlaps(x: 150, y: 150).should.be.true
element.overlaps(120, 120).should.be.true
it "should return 'false' for positions outside of the element", ->
element.overlaps(x: 50, y: 50).should.be.false
element.overlaps(x: 50, y: 150).should.be.false
element.overlaps(300, 300).should.be.false
element.overlaps(50, 300).should.be.false
element.overlaps(300, 50).should.be.false
describe "#index()", ->
e1 = e2 = e3 = null
before ->
element._.innerHTML = """
<div>one</div>
<div>two</div> boo hoo
<div>three</div>
"""
[e1, e2, e3] = element.find('div')
it "should return correct index for all the elements", ->
e1.index().should.eql 0
e2.index().should.eql 1
e3.index().should.eql 2
|
[
{
"context": "ram request\n # @param response_cb\n key = JSON.stringify(chosen.get_search_request())\n data",
"end": 383,
"score": 0.8051333427429199,
"start": 379,
"tag": "KEY",
"value": "JSON"
},
{
"context": "quest\n # @param response_cb\n key = JSON.strin... | coffee/lib/callback-data-source.coffee | rohitcoupa/chosen | 0 | class CallbackDataSource extends DataSource
constructor: (form_field, source) ->
super(form_field, source)
@results = @select_parser.select_to_hash('value')
@cache = {}
search: (chosen, response_cb) ->
if chosen.results_data?
# Call @source function, setting this to the chosen object
# @param request
# @param response_cb
key = JSON.stringify(chosen.get_search_request())
data = @cache[key]
if not data?
chosen.loading(true)
@perform_search chosen, (data) =>
chosen.loading(false)
@cache[key] = data
response_cb (data)
else
response_cb(data)
else
this.did_search(chosen, response_cb, this.items_as_array())
perform_search: (chosen, response_cb) ->
@source.call chosen, chosen.get_search_request(), (data) =>
@did_search(chosen, response_cb, data)
did_search: (chosen, response_cb, data) ->
# Merge with new results
options = (this.add_option_from_data child for child in data)
response_cb options
add_option_from_data: (child) ->
item = @results[child.value] || child
item.text = item.label || item if not item.text?
item.html = this.escape_html(item.text) if not item.html?
item.value = item.text if not item.value
item.array_index = item.value
item.selected = item.selected || false
item.disabled = item.disabled || false
@results[item.value] = item
item
get_option_element: (array_index) ->
# array_index is set to item.value in this DataSource
this.get_option_element_by_value(array_index)
get_item: (array_index) ->
@results[array_index]
get_item_by_value: (value) ->
this.get_item value | 31970 | class CallbackDataSource extends DataSource
constructor: (form_field, source) ->
super(form_field, source)
@results = @select_parser.select_to_hash('value')
@cache = {}
search: (chosen, response_cb) ->
if chosen.results_data?
# Call @source function, setting this to the chosen object
# @param request
# @param response_cb
key = <KEY>.<KEY>(chosen.get_search_request())
data = @cache[key]
if not data?
chosen.loading(true)
@perform_search chosen, (data) =>
chosen.loading(false)
@cache[key] = data
response_cb (data)
else
response_cb(data)
else
this.did_search(chosen, response_cb, this.items_as_array())
perform_search: (chosen, response_cb) ->
@source.call chosen, chosen.get_search_request(), (data) =>
@did_search(chosen, response_cb, data)
did_search: (chosen, response_cb, data) ->
# Merge with new results
options = (this.add_option_from_data child for child in data)
response_cb options
add_option_from_data: (child) ->
item = @results[child.value] || child
item.text = item.label || item if not item.text?
item.html = this.escape_html(item.text) if not item.html?
item.value = item.text if not item.value
item.array_index = item.value
item.selected = item.selected || false
item.disabled = item.disabled || false
@results[item.value] = item
item
get_option_element: (array_index) ->
# array_index is set to item.value in this DataSource
this.get_option_element_by_value(array_index)
get_item: (array_index) ->
@results[array_index]
get_item_by_value: (value) ->
this.get_item value | true | class CallbackDataSource extends DataSource
constructor: (form_field, source) ->
super(form_field, source)
@results = @select_parser.select_to_hash('value')
@cache = {}
search: (chosen, response_cb) ->
if chosen.results_data?
# Call @source function, setting this to the chosen object
# @param request
# @param response_cb
key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI(chosen.get_search_request())
data = @cache[key]
if not data?
chosen.loading(true)
@perform_search chosen, (data) =>
chosen.loading(false)
@cache[key] = data
response_cb (data)
else
response_cb(data)
else
this.did_search(chosen, response_cb, this.items_as_array())
perform_search: (chosen, response_cb) ->
@source.call chosen, chosen.get_search_request(), (data) =>
@did_search(chosen, response_cb, data)
did_search: (chosen, response_cb, data) ->
# Merge with new results
options = (this.add_option_from_data child for child in data)
response_cb options
add_option_from_data: (child) ->
item = @results[child.value] || child
item.text = item.label || item if not item.text?
item.html = this.escape_html(item.text) if not item.html?
item.value = item.text if not item.value
item.array_index = item.value
item.selected = item.selected || false
item.disabled = item.disabled || false
@results[item.value] = item
item
get_option_element: (array_index) ->
# array_index is set to item.value in this DataSource
this.get_option_element_by_value(array_index)
get_item: (array_index) ->
@results[array_index]
get_item_by_value: (value) ->
this.get_item value |
[
{
"context": "t, $ window)\n chrome.storage.sync.set { nick: 'ournick' }\n init()\n\n afterEach ->\n mocks.dom.tearD",
"end": 1630,
"score": 0.9996836185455322,
"start": 1623,
"tag": "USERNAME",
"value": "ournick"
},
{
"context": "type '/names'\n type '/me is 1337'\n ... | test/chat_test.coffee | nornagon/ircv | 20 | describe 'An IRC client front end', ->
client = prompt = commandInput = undefined
room = (index) ->
return rooms().last() if index is -1
$ rooms()[index]
rooms = ->
$ '#rooms-container .rooms .room'
textOfRoom = (index) ->
$('.content-item', room(index)).text()
nick = (index) ->
return nicks().last() if index is -1
$ nicks()[index]
nicks = ->
$ '#nicks-container .nicks .nick'
textOfNick = (index) ->
$('.content-item', nick(index)).text()
device = (i) ->
mocks.RemoteDevice.devices[i]
irc = (name) ->
client.connections[name]?.irc
type = (text) ->
prompt.val(text)
commandInput._handleKeydown { which: 13, preventDefault: -> }
noticeIsVisible = ->
$("#notice")[0].style.top is "0px"
restart = ->
RemoteDevice.devices = []
mocks.dom.tearDown()
client.tearDown()
mocks.dom.setUp()
init()
init = ->
scriptHandler = new window.script.ScriptHandler
client = new window.chat.Chat
commandInput.setContext client
scriptHandler.addEventsFrom client
scriptHandler.addEventsFrom commandInput
scriptHandler.listenToScriptEvents client
client.listenToCommands scriptHandler
client.listenToScriptEvents scriptHandler
client.listenToIRCEvents scriptHandler
beforeEach ->
mocks.navigator.useMock()
mocks.ChromeSocket.useMock()
mocks.RemoteDevice.useMock()
mocks.NickMentionedNotification.useMock()
jasmine.Clock.useMock()
mocks.dom.setUp()
prompt = $('#input')
commandInput = new UserInputHandler(prompt, $ window)
chrome.storage.sync.set { nick: 'ournick' }
init()
afterEach ->
mocks.dom.tearDown()
chrome.storage.sync.clear()
client.tearDown()
it "displays the preferred nick in the status bar", ->
expect($ '#status').toHaveText 'ournick'
it "sets the document title to the version", ->
expect(document.title).toMatch /^CIRC \d{1,3}\.\d{1,3}\.\d{1,3}/
it "initially has one window", ->
expect(rooms().length).toBe 1
it "replaces the initial window with a server window on /connect", ->
type '/connect freenode'
expect(rooms().length).toBe 1
expect(textOfRoom 0).toBe 'freenode'
expect(client.currentWindow.conn.name).toBe 'freenode'
it "ignores commands that requicre a connection not connected", ->
type '/names'
type '/me is 1337'
type '/op bob'
type '/msg someguy'
type '/mode sally +o'
it "displays a prompt internet connectivity is lost", ->
expect(noticeIsVisible()).toBe false
mocks.navigator.goOffline()
expect(noticeIsVisible()).toBe true
describe "storage", ->
doActivity = ->
type '/nick newNick'
type '/server freenode 6667'
type '/join #bash'
type '/join #awesome'
type '/server dalnet 6697'
type '/win 4'
type '/join #hiphop'
beforeEach ->
doActivity()
it "chooses a new password when one doesn't currently exist", ->
expect(client.remoteConnection._password).toEqual jasmine.any(String)
it "keeps the old password when one exists", ->
chrome.storage.sync.set { password: 'bob' }
restart()
expect(client.remoteConnection._password).toBe 'bob'
it "restores the previously used nick", ->
restart()
expect($ '#status').toHaveText 'newNick'
it "generates random nick when no previously used nick is available", ->
chrome.storage.sync.set { nick: undefined }
restart()
type "/connect freenode"
expect(irc('freenode').preferredNick).toBeDefined()
it "restores the previously joined servers", ->
restart()
expect(client.connections['freenode']).toBeDefined()
expect(client.connections['dalnet']).toBeDefined()
it "restores the previously joined channels", ->
restart()
expect(client.connections['freenode'].windows['#bash']).toBeDefined()
expect(client.connections['freenode'].windows['#awesome']).toBeDefined()
expect(client.connections['dalnet'].windows['#hiphop']).toBeDefined()
expect(rooms().length).toBe 5
it "doesn't restore channels that were parted", ->
type '/part #hiphop'
restart()
expect(client.connections['dalnet'].windows['#hiphop']).not.toBeDefined()
expect(rooms().length).toBe 4
it "doesn't restore servers that were parted", ->
type '/win 1'
type '/quit'
restart()
expect(irc 'freenode').not.toBeDefined()
expect(rooms().length).toBe 2
it "displays restored private channels as connected", ->
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
irc('freenode').handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
restart()
expect(rooms().length).toBe 6
expect(textOfRoom 3).toBe 'someguy'
expect(room 3).not.toHaveClass 'disconnected'
describe "that is connecting", ->
beforeEach ->
type '/server freenode'
expect(irc('freenode').state).toBe 'connecting'
it 'can queue a disconnection request with /quit', ->
currentIRC = irc('freenode')
type '/quit'
currentIRC.handle '1', {}, 'ournick' # rpl_welcome
expect(currentIRC.state).toBe 'disconnected'
it 'allows channels to be joined while connecting', ->
type '/join #bash'
expect(rooms().length).toBe 2
expect(textOfRoom -1).toBe '#bash'
expect(room -1).toHaveClass 'selected'
expect(room -1).toHaveClass 'disconnected'
it 'automatically joins queued channels when connected', ->
type '/join #bash'
type '/part'
spyOn irc('freenode'), 'send'
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
expect(irc('freenode').send).not.toHaveBeenCalled()
it 'removes queued channels on /part', ->
type '/join #bash'
spyOn irc('freenode'), 'send'
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
expect(irc('freenode').send).toHaveBeenCalledWith 'JOIN', '#bash'
describe "that connects", ->
currentIRC = undefined
beforeEach ->
type '/server freenode'
currentIRC = irc('freenode')
currentIRC.handle '1', {}, 'ournick' # rpl_welcome
expect(currentIRC.state).toBe 'connected'
spyOn currentIRC, 'doCommand'
it "marks the server item in the window list as connected", ->
expect(room 0).not.toHaveClass 'disconnected'
it "updates the status bar on /away", ->
type '/away'
currentIRC.handle '306' # rpl_nowaway
expect($ '#status').toHaveText 'ournick' + 'away'
it "creates a new window when a direct private message is received", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
expect(rooms().length).toBe 2
expect(textOfRoom -1).toBe 'someguy'
expect(room -1).toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "displays /msg text in the current window if there is no existing conversation window", ->
spyOn(client.currentWindow, 'message').andCallThrough()
type '/msg someguy hey dude'
expect(rooms().length).toBe 1
expect(client.currentWindow.message).toHaveBeenCalled()
it "displays /msg text in the conversation window when it exists", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
spyOn(client.currentWindow, 'message').andCallThrough()
type '/msg someguy hey dude'
expect(client.currentWindow.message).not.toHaveBeenCalled()
it "/msg causes the conversation window to be marked with activity", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
type '/win 2'
type '/win 1'
expect(room -1).not.toHaveClass 'mention'
expect(room -1).not.toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
type '/msg someguy hey dude'
expect(room -1).not.toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "creates a notification when a direct private message is received", ->
chat.NickMentionedNotification.notificationCount = 0
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hey!'
expect(chat.NickMentionedNotification.notificationCount).toBe 1
it "can join a channel with /join", ->
type '/join #bash'
expect(currentIRC.doCommand).toHaveBeenCalledWith 'JOIN', '#bash'
expect(client.currentWindow.target).toBe '#bash'
describe "then is disconnected by a socket error", ->
beforeEach ->
currentIRC.onClose()
it 'shows all servers and channels as disconnected', ->
expect(room 0).toHaveClass 'disconnected'
it 'attempts to reconnect after a short amount of time', ->
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(2000)
expect(currentIRC.connect).toHaveBeenCalled()
it 'uses exponential backoff for reconnection attempts', ->
jasmine.Clock.tick(2000)
currentIRC.onError 'socket error!'
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(2000)
expect(currentIRC.connect).not.toHaveBeenCalled()
jasmine.Clock.tick(2000)
expect(currentIRC.connect).toHaveBeenCalled()
currentIRC.connect.reset() # reset the connect function spy
currentIRC.onError 'socket error!'
jasmine.Clock.tick(7999)
expect(currentIRC.connect).not.toHaveBeenCalled()
it 'closes the current window and stops reconnecting on /quit', ->
type "/quit"
expect(client.currentWindow.name).toBe 'none'
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(9000)
expect(currentIRC.connect).not.toHaveBeenCalled()
describe "then joins a channel", ->
beforeEach ->
type '/join #bash'
currentIRC.handle 'JOIN', {nick: 'ournick'}, '#bash'
it "adds another item to the room display", ->
expect(rooms().length).toBe 2
it "can switch windows with /win", ->
type "/win 1"
expect(client.currentWindow.target).toBe undefined
it "creates a notification when the users nick is mentioned", ->
type "/win 1"
chat.NickMentionedNotification.notificationCount = 0
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hey ournick!'
expect(chat.NickMentionedNotification.notificationCount).toBe 1
expect(room -1).toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "marks a window as active if a message is sent and it's not selected", ->
type '/server dalnet'
irc2 = client.currentWindow.conn.irc
irc2.handle '1', {}, 'ournick' # rpl_welcome
type '/win 3'
type '/join #bash'
currentIRC.handle 'JOIN', {nick: 'ournick'}, '#bash'
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hi'
expect(room 1).toHaveClass 'activity'
it "clears activity and mention style when switching to a window", ->
type "/win 1"
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hey!'
type "/win 2"
expect(room -1).not.toHaveClass 'mention'
expect(room -1).not.toHaveClass 'activity'
expect(room -1).toHaveClass 'selected'
it "clicking on a channel in the channel display switches to that channel", ->
client.channelDisplay.emit 'clicked', 'freenode', '#bash'
expect(client.currentWindow.target).toBe '#bash'
expect(room -1).toHaveClass 'selected'
describe "has a nick list which", ->
currentNicks = undefined
beforeEach ->
currentNicks = ['bart', 'bill', 'bob', 'charlie', 'derek', 'edward', 'jacob',
'megan', 'norman', 'sally', 'sue', 'Tereza',
'zabo1', 'ZABO2', 'zabo3', 'Zabo88']
addNicks = ->
currentIRC.emit 'names', '#bash', currentNicks.slice(0, 7)
currentIRC.emit 'names', '#bash', currentNicks.slice(7, 12)
currentIRC.emit 'names', '#bash', currentNicks.slice(12)
nameMap = {}
(nameMap[name] = name for name in currentNicks)
currentIRC.channels['#bash'].names = nameMap
it "displays the user's nick when first joining a channel", ->
expect(nicks().length).toBe 1
expect(textOfNick 0).toBe 'ournick'
it "displays all nicks in the channel when the nick list is sent", ->
addNicks()
expect(nicks().length).toBe currentNicks.length + 1
it "displays nicks in sorted order", ->
addNicks()
expect(textOfNick 9).toBe 'ournick'
it "displays newly joined nicks after they /join", ->
addNicks()
currentIRC.handle 'JOIN', {nick: 'alphy'}, '#bash'
expect(nicks().length).toBe currentNicks.length + 2
expect(textOfNick 0).toBe 'alphy'
it "doesn't display nicks after they have been kicked", ->
addNicks()
currentIRC.handle 'KICK', {nick: 'bob'}, '#bash', 'Zabo88'
expect(nicks().length).toBe currentNicks.length
expect(textOfNick 0).not.toBe 'Zabo88'
it "doesn't display nicks after they left with /parted", ->
addNicks()
currentIRC.handle 'PART', {nick: 'bob'}, '#bash'
expect(nicks().length).toBe currentNicks.length
expect(textOfNick 2).not.toBe 'bob'
it "doesn't display duplicate nicks", ->
currentNicks.push 'ournick'
addNicks()
expect(nicks().length).toBe currentNicks.length
it "stays visible when another non-selected window is closed", ->
type "/join #awesome"
event = new Event 'command', 'part'
event.setContext 'freenode', '#bash'
client.userCommands.handle 'part', event
expect($ '#rooms-and-nicks').not.toHaveClass 'no-nicks'
describe "with a remote connection", ->
state = onAuth = undefined
getChannels = ->
{ '#bash': { names: { sally: 'Sally', bob: 'bob', somenick: 'somenick' } } }
getState = ->
nick: 'preferredNick'
servers: [ { name: 'freenode', port: 6667 }, { name: 'dalnet', port: 6697 } ]
channels: [ { name: '#bash', server: 'freenode' }, { name: '#awesome', server: 'dalnet' } ]
ircStates: [ { server: 'freenode', state: 'connected', nick: 'somenick', away: true, channels: getChannels() } ]
findPort = ->
d = client.remoteConnection._thisDevice
d.port = 1
RemoteDevice.state = 'found_port'
d.emit 'found_port'
authenticate = (device) ->
authToken = client.remoteConnection._getAuthToken device.password
device.emit 'authenticate', device, authToken
receivePassword = (device, password) ->
device.emit 'authentication_offer', device, password
becomeClient = (opt_state) ->
state = opt_state if opt_state
(device 1).emit 'connection_message', device(1), 'irc_state', state
receiveChatHistory = (chatHistory) ->
device(1).emit 'connection_message', device(1), 'chat_log', chatHistory
beforeEach ->
state = getState()
spyOn(mocks.RemoteDevice, 'onConnect').andCallThrough()
it "connects to a server device with /join-server", ->
type "/join-server 1.1.1.2 1336"
expect(mocks.RemoteDevice.onConnect).toHaveBeenCalled()
it "emits 'server_found' when server sends a password", ->
type "/join-server 1.1.1.2 1336"
spyOn client.remoteConnection, 'emit'
receivePassword device(1), 'pw'
expect(client.remoteConnection.emit).toHaveBeenCalledWith 'server_found', device(1)
it "sends authentication after server sends a password and finalizeConnection() is called", ->
type "/join-server 1.1.1.2 1336"
receivePassword device(1), 'pw'
expect(device(1).sendType).toBe 'authenticate'
it "becomes a client after receiving IRC state", ->
type "/join-server 1.1.1.2 1336"
expect(client.remoteConnection.isClient()).toBe false
becomeClient []
expect(client.remoteConnection.isClient()).toBe true
it "doesn't add a client before authentication", ->
RemoteDevice.onNewDevice new RemoteDevice
expect(client.remoteConnection.devices[0]).not.toBeDefined()
it "add a client after it authenticates", ->
RemoteDevice.onNewDevice new RemoteDevice
expect(client.remoteConnection.devices[0]).not.toBeDefined()
authenticate device 1
expect(client.remoteConnection.devices[0]).toBeDefined()
it "disconnects from the current connection before using the server device's connection", ->
type "/join-server 1.1.1.2 1336"
becomeClient []
expect(rooms().length).toBe 1
expect(client.connections['freenode']).not.toBeDefined()
it "can load the IRC state from the server device", ->
type "/join-server 1.1.1.2 1336"
becomeClient()
expect(rooms().length).toBe 4
expect(irc('freenode').state).toBe 'connected'
expect(irc('dalnet').state).toBe 'disconnected'
expect(room 0).not.toHaveClass 'disconnected'
expect(room 1).not.toHaveClass 'disconnected'
expect(room 2).toHaveClass 'disconnected'
expect(room 3).toHaveClass 'disconnected'
type '/win 2'
for name, i in ['bob', 'Sally', 'somenick']
expect(textOfNick i).toBe name
expect($('#status').text()).toBe 'somenick' + 'away'
it "doesn't set the irc nick if the nick isn't saved", ->
type "/join-server 1.1.1.2 1336"
state.ircStates[0].nick = undefined
state.nick = undefined
becomeClient()
expect(irc('freenode').preferredNick).toBeDefined()
it "can listen to user input from the server device", ->
type "/join-server 1.1.1.2 1336"
becomeClient()
event = new Event 'command', 'nick', 'newnick'
event.setContext 'freenode'
spyOn client, 'setNick'
(device 1).emit 'user_input', device(1), event
expect(client.setNick).toHaveBeenCalledWith 'freenode', 'newnick'
it "can listen to socket data from the server device", ->
type "/join-server 1.1.1.2 1336"
becomeClient()
spyOn irc('freenode'), 'onDrain'
(device 1).emit 'socket_data', device(1), 'freenode', 'drain'
expect(irc('freenode').onDrain).toHaveBeenCalled()
it "uses own connection after connection to the server is lost", ->
type "/join-server 1.1.1.2 1336"
becomeClient []
spyOn client, 'closeAllConnections'
(device 1).emit 'closed', device(1)
expect(client.remoteConnection.isIdle()).toBe true
expect(client.closeAllConnections).toHaveBeenCalled()
it "on startup, when server exists, uses own connection after waiting a brief time", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
expect(rooms().length).toBe 1
jasmine.Clock.tick(2000)
expect(rooms().length).toBe 4
it "automatically connects if an existing server is present", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
restart()
expect(mocks.RemoteDevice.onConnect).toHaveBeenCalled()
it "becomes server if storage marks it as the server device", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.1', port: 1 } }
restart()
findPort()
expect(client.remoteConnection.isServer()).toBe true
it "updates stored server device info when the server device's port changes", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.1', port: 2 } }
restart()
findPort()
expect(client.remoteConnection.isServer()).toBe true
expect(chrome.storage.sync._storageMap.server_device.port).toBe 1
it "becomes idle if can't connect to server device", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
restart()
expect(client.remoteConnection.getState()).toBe 'connecting'
mocks.RemoteDevice.willConnect = false
restart()
expect(client.remoteConnection.isIdle()).toBe true
it "keeps trying to connect to the server device", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
restart()
mocks.RemoteDevice.willConnect = false
restart()
mocks.RemoteDevice.willConnect = true
jasmine.Clock.tick(1000)
expect(client.remoteConnection.getState()).toBe 'connecting'
it "forwards user input to connected clients when acting as the server device", ->
findPort()
type '/make-server'
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 1
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 2
expect(client.remoteConnection.devices.length).toBe 2
spyOn device(1), 'send'
spyOn device(2), 'send'
spyOn client.remoteConnection, 'emit'
device(1).emit 'user_input', device(1), {
type: 'command', name: 'say', args: ['hi guys'],
context: { server: 'freenode', channel: '#bash' } }
expect(device(1).send).not.toHaveBeenCalled()
expect(device(2).send.mostRecentCall.args[0]).toBe 'user_input'
expect(client.remoteConnection.emit).toHaveBeenCalledWith 'command',
jasmine.any(Event)
it "only sends IRC state to the connecting device, not all devices", ->
findPort()
type '/make-server'
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 1
RemoteDevice.onNewDevice new RemoteDevice
spyOn device(1), 'send'
spyOn device(2), 'send'
authenticate device 2
expect(device(2).send).toHaveBeenCalled()
expect(device(1).send).not.toHaveBeenCalled()
it "retains connections after /make-server", ->
findPort()
expect(rooms().length).toBe 2
type "/make-server"
expect(rooms().length).toBe 2
it "is able to connect to servers even if chrome.socket.listen isn't supported", ->
chrome.socket.listen = undefined
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
restart()
expect(client.remoteConnection.getState()).toBe 'connecting'
it "can't become a server if chrome.socket.listen isn't defined", ->
chrome.socket.listen = undefined
type "/make-server"
expect(client.remoteConnection.isIdle()).toBe true
it "sends chat history when a client connects", ->
findPort()
type "/make-server"
RemoteDevice.onNewDevice new RemoteDevice
spyOn device(1), 'send'
type 'hi there'
authenticate device 1
expect(device(1).send).toHaveBeenCalledWith 'connection_message',
['chat_log', jasmine.any(Object)]
it "replays received chat history after connecting to a server device", ->
type 'hi there'
type 'i am recording some chat history'
chatHistory = client.messageHandler.getChatLog()
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
restart()
becomeClient()
win = client.winList.get('freenode', '#bash')
spyOn win, 'rawMessage'
receiveChatHistory chatHistory
expect(client.remoteConnection.isClient()).toBe true
expect(win.rawMessage).toHaveBeenCalled()
it "connects to a server even when the server connection takes a long time", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
jasmine.Clock.tick(900) # now using own connection
spyOn(client.remoteConnection, 'finalizeConnection').andCallThrough()
receivePassword device(1), 'pw'
expect(client.remoteConnection.finalizeConnection).toHaveBeenCalled()
expect(client.remoteConnection.getState()).toBe 'connecting'
it "displays a prompt when connecting to the server device would be abrupt", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
client.remoteConnectionHandler._timer.elapsed = -> 5000
jasmine.Clock.tick(5000) # been using own connection for a while now
spyOn client.remoteConnection, 'finalizeConnection'
receivePassword device(1), 'pw'
expect(client.remoteConnection.finalizeConnection).not.toHaveBeenCalled()
expect(noticeIsVisible()).toBe true
it "closes sockets when internect connection is lost", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
becomeClient()
spyOn device(1), 'close'
mocks.navigator.goOffline()
expect(noticeIsVisible()).toBe true
expect(device(1).close).toHaveBeenCalled()
it "establishes connection when internet is renabled", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.2', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
becomeClient()
mocks.navigator.goOffline()
expect(client.remoteConnection.getState()).not.toBe 'connecting'
expect(noticeIsVisible()).toBe true
mocks.navigator.goOnline()
expect(client.remoteConnection.getState()).toBe 'connecting'
| 47157 | describe 'An IRC client front end', ->
client = prompt = commandInput = undefined
room = (index) ->
return rooms().last() if index is -1
$ rooms()[index]
rooms = ->
$ '#rooms-container .rooms .room'
textOfRoom = (index) ->
$('.content-item', room(index)).text()
nick = (index) ->
return nicks().last() if index is -1
$ nicks()[index]
nicks = ->
$ '#nicks-container .nicks .nick'
textOfNick = (index) ->
$('.content-item', nick(index)).text()
device = (i) ->
mocks.RemoteDevice.devices[i]
irc = (name) ->
client.connections[name]?.irc
type = (text) ->
prompt.val(text)
commandInput._handleKeydown { which: 13, preventDefault: -> }
noticeIsVisible = ->
$("#notice")[0].style.top is "0px"
restart = ->
RemoteDevice.devices = []
mocks.dom.tearDown()
client.tearDown()
mocks.dom.setUp()
init()
init = ->
scriptHandler = new window.script.ScriptHandler
client = new window.chat.Chat
commandInput.setContext client
scriptHandler.addEventsFrom client
scriptHandler.addEventsFrom commandInput
scriptHandler.listenToScriptEvents client
client.listenToCommands scriptHandler
client.listenToScriptEvents scriptHandler
client.listenToIRCEvents scriptHandler
beforeEach ->
mocks.navigator.useMock()
mocks.ChromeSocket.useMock()
mocks.RemoteDevice.useMock()
mocks.NickMentionedNotification.useMock()
jasmine.Clock.useMock()
mocks.dom.setUp()
prompt = $('#input')
commandInput = new UserInputHandler(prompt, $ window)
chrome.storage.sync.set { nick: 'ournick' }
init()
afterEach ->
mocks.dom.tearDown()
chrome.storage.sync.clear()
client.tearDown()
it "displays the preferred nick in the status bar", ->
expect($ '#status').toHaveText 'ournick'
it "sets the document title to the version", ->
expect(document.title).toMatch /^CIRC \d{1,3}\.\d{1,3}\.\d{1,3}/
it "initially has one window", ->
expect(rooms().length).toBe 1
it "replaces the initial window with a server window on /connect", ->
type '/connect freenode'
expect(rooms().length).toBe 1
expect(textOfRoom 0).toBe 'freenode'
expect(client.currentWindow.conn.name).toBe 'freenode'
it "ignores commands that requicre a connection not connected", ->
type '/names'
type '/me is 1337'
type '/op bob'
type '/msg someguy'
type '/mode sally +o'
it "displays a prompt internet connectivity is lost", ->
expect(noticeIsVisible()).toBe false
mocks.navigator.goOffline()
expect(noticeIsVisible()).toBe true
describe "storage", ->
doActivity = ->
type '/nick newNick'
type '/server freenode 6667'
type '/join #bash'
type '/join #awesome'
type '/server dalnet 6697'
type '/win 4'
type '/join #hiphop'
beforeEach ->
doActivity()
it "chooses a new password when one doesn't currently exist", ->
expect(client.remoteConnection._password).toEqual jasmine.any(String)
it "keeps the old password when one exists", ->
chrome.storage.sync.set { password: '<PASSWORD>' }
restart()
expect(client.remoteConnection._password).toBe '<PASSWORD>'
it "restores the previously used nick", ->
restart()
expect($ '#status').toHaveText 'newNick'
it "generates random nick when no previously used nick is available", ->
chrome.storage.sync.set { nick: undefined }
restart()
type "/connect freenode"
expect(irc('freenode').preferredNick).toBeDefined()
it "restores the previously joined servers", ->
restart()
expect(client.connections['freenode']).toBeDefined()
expect(client.connections['dalnet']).toBeDefined()
it "restores the previously joined channels", ->
restart()
expect(client.connections['freenode'].windows['#bash']).toBeDefined()
expect(client.connections['freenode'].windows['#awesome']).toBeDefined()
expect(client.connections['dalnet'].windows['#hiphop']).toBeDefined()
expect(rooms().length).toBe 5
it "doesn't restore channels that were parted", ->
type '/part #hiphop'
restart()
expect(client.connections['dalnet'].windows['#hiphop']).not.toBeDefined()
expect(rooms().length).toBe 4
it "doesn't restore servers that were parted", ->
type '/win 1'
type '/quit'
restart()
expect(irc 'freenode').not.toBeDefined()
expect(rooms().length).toBe 2
it "displays restored private channels as connected", ->
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
irc('freenode').handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
restart()
expect(rooms().length).toBe 6
expect(textOfRoom 3).toBe 'someguy'
expect(room 3).not.toHaveClass 'disconnected'
describe "that is connecting", ->
beforeEach ->
type '/server freenode'
expect(irc('freenode').state).toBe 'connecting'
it 'can queue a disconnection request with /quit', ->
currentIRC = irc('freenode')
type '/quit'
currentIRC.handle '1', {}, 'ournick' # rpl_welcome
expect(currentIRC.state).toBe 'disconnected'
it 'allows channels to be joined while connecting', ->
type '/join #bash'
expect(rooms().length).toBe 2
expect(textOfRoom -1).toBe '#bash'
expect(room -1).toHaveClass 'selected'
expect(room -1).toHaveClass 'disconnected'
it 'automatically joins queued channels when connected', ->
type '/join #bash'
type '/part'
spyOn irc('freenode'), 'send'
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
expect(irc('freenode').send).not.toHaveBeenCalled()
it 'removes queued channels on /part', ->
type '/join #bash'
spyOn irc('freenode'), 'send'
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
expect(irc('freenode').send).toHaveBeenCalledWith 'JOIN', '#bash'
describe "that connects", ->
currentIRC = undefined
beforeEach ->
type '/server freenode'
currentIRC = irc('freenode')
currentIRC.handle '1', {}, 'ournick' # rpl_welcome
expect(currentIRC.state).toBe 'connected'
spyOn currentIRC, 'doCommand'
it "marks the server item in the window list as connected", ->
expect(room 0).not.toHaveClass 'disconnected'
it "updates the status bar on /away", ->
type '/away'
currentIRC.handle '306' # rpl_nowaway
expect($ '#status').toHaveText 'ournick' + 'away'
it "creates a new window when a direct private message is received", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
expect(rooms().length).toBe 2
expect(textOfRoom -1).toBe 'someguy'
expect(room -1).toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "displays /msg text in the current window if there is no existing conversation window", ->
spyOn(client.currentWindow, 'message').andCallThrough()
type '/msg someguy hey dude'
expect(rooms().length).toBe 1
expect(client.currentWindow.message).toHaveBeenCalled()
it "displays /msg text in the conversation window when it exists", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
spyOn(client.currentWindow, 'message').andCallThrough()
type '/msg someguy hey dude'
expect(client.currentWindow.message).not.toHaveBeenCalled()
it "/msg causes the conversation window to be marked with activity", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ourn<NAME>', 'hi there'
type '/win 2'
type '/win 1'
expect(room -1).not.toHaveClass 'mention'
expect(room -1).not.toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
type '/msg someguy hey dude'
expect(room -1).not.toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "creates a notification when a direct private message is received", ->
chat.NickMentionedNotification.notificationCount = 0
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hey!'
expect(chat.NickMentionedNotification.notificationCount).toBe 1
it "can join a channel with /join", ->
type '/join #bash'
expect(currentIRC.doCommand).toHaveBeenCalledWith 'JOIN', '#bash'
expect(client.currentWindow.target).toBe '#bash'
describe "then is disconnected by a socket error", ->
beforeEach ->
currentIRC.onClose()
it 'shows all servers and channels as disconnected', ->
expect(room 0).toHaveClass 'disconnected'
it 'attempts to reconnect after a short amount of time', ->
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(2000)
expect(currentIRC.connect).toHaveBeenCalled()
it 'uses exponential backoff for reconnection attempts', ->
jasmine.Clock.tick(2000)
currentIRC.onError 'socket error!'
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(2000)
expect(currentIRC.connect).not.toHaveBeenCalled()
jasmine.Clock.tick(2000)
expect(currentIRC.connect).toHaveBeenCalled()
currentIRC.connect.reset() # reset the connect function spy
currentIRC.onError 'socket error!'
jasmine.Clock.tick(7999)
expect(currentIRC.connect).not.toHaveBeenCalled()
it 'closes the current window and stops reconnecting on /quit', ->
type "/quit"
expect(client.currentWindow.name).toBe 'none'
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(9000)
expect(currentIRC.connect).not.toHaveBeenCalled()
describe "then joins a channel", ->
beforeEach ->
type '/join #bash'
currentIRC.handle 'JOIN', {nick: 'ournick'}, '#bash'
it "adds another item to the room display", ->
expect(rooms().length).toBe 2
it "can switch windows with /win", ->
type "/win 1"
expect(client.currentWindow.target).toBe undefined
it "creates a notification when the users nick is mentioned", ->
type "/win 1"
chat.NickMentionedNotification.notificationCount = 0
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hey <NAME>!'
expect(chat.NickMentionedNotification.notificationCount).toBe 1
expect(room -1).toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "marks a window as active if a message is sent and it's not selected", ->
type '/server dalnet'
irc2 = client.currentWindow.conn.irc
irc2.handle '1', {}, 'ournick' # rpl_welcome
type '/win 3'
type '/join #bash'
currentIRC.handle 'JOIN', {nick: 'ournick'}, '#bash'
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hi'
expect(room 1).toHaveClass 'activity'
it "clears activity and mention style when switching to a window", ->
type "/win 1"
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hey!'
type "/win 2"
expect(room -1).not.toHaveClass 'mention'
expect(room -1).not.toHaveClass 'activity'
expect(room -1).toHaveClass 'selected'
it "clicking on a channel in the channel display switches to that channel", ->
client.channelDisplay.emit 'clicked', 'freenode', '#bash'
expect(client.currentWindow.target).toBe '#bash'
expect(room -1).toHaveClass 'selected'
describe "has a nick list which", ->
currentNicks = undefined
beforeEach ->
currentNicks = ['<NAME>', '<NAME>', '<PASSWORD>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',
'zabo1', 'ZABO2', 'zabo3', 'Zabo88']
addNicks = ->
currentIRC.emit 'names', '#bash', currentNicks.slice(0, 7)
currentIRC.emit 'names', '#bash', currentNicks.slice(7, 12)
currentIRC.emit 'names', '#bash', currentNicks.slice(12)
nameMap = {}
(nameMap[name] = name for name in currentNicks)
currentIRC.channels['#bash'].names = nameMap
it "displays the user's nick when first joining a channel", ->
expect(nicks().length).toBe 1
expect(textOfNick 0).toBe 'ournick'
it "displays all nicks in the channel when the nick list is sent", ->
addNicks()
expect(nicks().length).toBe currentNicks.length + 1
it "displays nicks in sorted order", ->
addNicks()
expect(textOfNick 9).toBe 'ournick'
it "displays newly joined nicks after they /join", ->
addNicks()
currentIRC.handle 'JOIN', {nick: 'alphy'}, '#bash'
expect(nicks().length).toBe currentNicks.length + 2
expect(textOfNick 0).toBe 'alphy'
it "doesn't display nicks after they have been kicked", ->
addNicks()
currentIRC.handle 'KICK', {nick: 'bob'}, '#bash', 'Zabo88'
expect(nicks().length).toBe currentNicks.length
expect(textOfNick 0).not.toBe 'Zabo88'
it "doesn't display nicks after they left with /parted", ->
addNicks()
currentIRC.handle 'PART', {nick: 'bob'}, '#bash'
expect(nicks().length).toBe currentNicks.length
expect(textOfNick 2).not.toBe 'bob'
it "doesn't display duplicate nicks", ->
currentNicks.push '<NAME>'
addNicks()
expect(nicks().length).toBe currentNicks.length
it "stays visible when another non-selected window is closed", ->
type "/join #awesome"
event = new Event 'command', 'part'
event.setContext 'freenode', '#bash'
client.userCommands.handle 'part', event
expect($ '#rooms-and-nicks').not.toHaveClass 'no-nicks'
describe "with a remote connection", ->
state = onAuth = undefined
getChannels = ->
{ '#bash': { names: { <NAME>ally: '<NAME>', bob: '<PASSWORD>', somenick: 'somenick' } } }
getState = ->
nick: 'preferredNick'
servers: [ { name: 'freenode', port: 6667 }, { name: 'dalnet', port: 6697 } ]
channels: [ { name: '#bash', server: 'freenode' }, { name: '#awesome', server: 'dalnet' } ]
ircStates: [ { server: 'freenode', state: 'connected', nick: 'somenick', away: true, channels: getChannels() } ]
findPort = ->
d = client.remoteConnection._thisDevice
d.port = 1
RemoteDevice.state = 'found_port'
d.emit 'found_port'
authenticate = (device) ->
authToken = client.remoteConnection._getAuthToken device.password
device.emit 'authenticate', device, authToken
receivePassword = (device, password) ->
device.emit 'authentication_offer', device, password
becomeClient = (opt_state) ->
state = opt_state if opt_state
(device 1).emit 'connection_message', device(1), 'irc_state', state
receiveChatHistory = (chatHistory) ->
device(1).emit 'connection_message', device(1), 'chat_log', chatHistory
beforeEach ->
state = getState()
spyOn(mocks.RemoteDevice, 'onConnect').andCallThrough()
it "connects to a server device with /join-server", ->
type "/join-server 192.168.3.11 1336"
expect(mocks.RemoteDevice.onConnect).toHaveBeenCalled()
it "emits 'server_found' when server sends a password", ->
type "/join-server 192.168.3.11 1336"
spyOn client.remoteConnection, 'emit'
receivePassword device(1), 'pw'
expect(client.remoteConnection.emit).toHaveBeenCalledWith 'server_found', device(1)
it "sends authentication after server sends a password and finalizeConnection() is called", ->
type "/join-server 192.168.3.11 1336"
receivePassword device(1), 'pw'
expect(device(1).sendType).toBe 'authenticate'
it "becomes a client after receiving IRC state", ->
type "/join-server 192.168.3.11 1336"
expect(client.remoteConnection.isClient()).toBe false
becomeClient []
expect(client.remoteConnection.isClient()).toBe true
it "doesn't add a client before authentication", ->
RemoteDevice.onNewDevice new RemoteDevice
expect(client.remoteConnection.devices[0]).not.toBeDefined()
it "add a client after it authenticates", ->
RemoteDevice.onNewDevice new RemoteDevice
expect(client.remoteConnection.devices[0]).not.toBeDefined()
authenticate device 1
expect(client.remoteConnection.devices[0]).toBeDefined()
it "disconnects from the current connection before using the server device's connection", ->
type "/join-server 192.168.3.11 1336"
becomeClient []
expect(rooms().length).toBe 1
expect(client.connections['freenode']).not.toBeDefined()
it "can load the IRC state from the server device", ->
type "/join-server 192.168.3.11 1336"
becomeClient()
expect(rooms().length).toBe 4
expect(irc('freenode').state).toBe 'connected'
expect(irc('dalnet').state).toBe 'disconnected'
expect(room 0).not.toHaveClass 'disconnected'
expect(room 1).not.toHaveClass 'disconnected'
expect(room 2).toHaveClass 'disconnected'
expect(room 3).toHaveClass 'disconnected'
type '/win 2'
for name, i in ['<PASSWORD>', '<NAME>', '<NAME>']
expect(textOfNick i).toBe name
expect($('#status').text()).toBe 'somenick' + 'away'
it "doesn't set the irc nick if the nick isn't saved", ->
type "/join-server 192.168.3.11 1336"
state.ircStates[0].nick = undefined
state.nick = undefined
becomeClient()
expect(irc('freenode').preferredNick).toBeDefined()
it "can listen to user input from the server device", ->
type "/join-server 192.168.3.11 1336"
becomeClient()
event = new Event 'command', 'nick', 'newnick'
event.setContext 'freenode'
spyOn client, 'setNick'
(device 1).emit 'user_input', device(1), event
expect(client.setNick).toHaveBeenCalledWith 'freenode', 'newnick'
it "can listen to socket data from the server device", ->
type "/join-server 192.168.3.11 1336"
becomeClient()
spyOn irc('freenode'), 'onDrain'
(device 1).emit 'socket_data', device(1), 'freenode', 'drain'
expect(irc('freenode').onDrain).toHaveBeenCalled()
it "uses own connection after connection to the server is lost", ->
type "/join-server 192.168.3.11 1336"
becomeClient []
spyOn client, 'closeAllConnections'
(device 1).emit 'closed', device(1)
expect(client.remoteConnection.isIdle()).toBe true
expect(client.closeAllConnections).toHaveBeenCalled()
it "on startup, when server exists, uses own connection after waiting a brief time", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
expect(rooms().length).toBe 1
jasmine.Clock.tick(2000)
expect(rooms().length).toBe 4
it "automatically connects if an existing server is present", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
restart()
expect(mocks.RemoteDevice.onConnect).toHaveBeenCalled()
it "becomes server if storage marks it as the server device", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.1', port: 1 } }
restart()
findPort()
expect(client.remoteConnection.isServer()).toBe true
it "updates stored server device info when the server device's port changes", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.1', port: 2 } }
restart()
findPort()
expect(client.remoteConnection.isServer()).toBe true
expect(chrome.storage.sync._storageMap.server_device.port).toBe 1
it "becomes idle if can't connect to server device", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
restart()
expect(client.remoteConnection.getState()).toBe 'connecting'
mocks.RemoteDevice.willConnect = false
restart()
expect(client.remoteConnection.isIdle()).toBe true
it "keeps trying to connect to the server device", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
restart()
mocks.RemoteDevice.willConnect = false
restart()
mocks.RemoteDevice.willConnect = true
jasmine.Clock.tick(1000)
expect(client.remoteConnection.getState()).toBe 'connecting'
it "forwards user input to connected clients when acting as the server device", ->
findPort()
type '/make-server'
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 1
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 2
expect(client.remoteConnection.devices.length).toBe 2
spyOn device(1), 'send'
spyOn device(2), 'send'
spyOn client.remoteConnection, 'emit'
device(1).emit 'user_input', device(1), {
type: 'command', name: 'say', args: ['<NAME> <NAME>'],
context: { server: 'freenode', channel: '#bash' } }
expect(device(1).send).not.toHaveBeenCalled()
expect(device(2).send.mostRecentCall.args[0]).toBe 'user_input'
expect(client.remoteConnection.emit).toHaveBeenCalledWith 'command',
jasmine.any(Event)
it "only sends IRC state to the connecting device, not all devices", ->
findPort()
type '/make-server'
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 1
RemoteDevice.onNewDevice new RemoteDevice
spyOn device(1), 'send'
spyOn device(2), 'send'
authenticate device 2
expect(device(2).send).toHaveBeenCalled()
expect(device(1).send).not.toHaveBeenCalled()
it "retains connections after /make-server", ->
findPort()
expect(rooms().length).toBe 2
type "/make-server"
expect(rooms().length).toBe 2
it "is able to connect to servers even if chrome.socket.listen isn't supported", ->
chrome.socket.listen = undefined
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
restart()
expect(client.remoteConnection.getState()).toBe 'connecting'
it "can't become a server if chrome.socket.listen isn't defined", ->
chrome.socket.listen = undefined
type "/make-server"
expect(client.remoteConnection.isIdle()).toBe true
it "sends chat history when a client connects", ->
findPort()
type "/make-server"
RemoteDevice.onNewDevice new RemoteDevice
spyOn device(1), 'send'
type 'hi there'
authenticate device 1
expect(device(1).send).toHaveBeenCalledWith 'connection_message',
['chat_log', jasmine.any(Object)]
it "replays received chat history after connecting to a server device", ->
type 'hi there'
type 'i am recording some chat history'
chatHistory = client.messageHandler.getChatLog()
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
restart()
becomeClient()
win = client.winList.get('freenode', '#bash')
spyOn win, 'rawMessage'
receiveChatHistory chatHistory
expect(client.remoteConnection.isClient()).toBe true
expect(win.rawMessage).toHaveBeenCalled()
it "connects to a server even when the server connection takes a long time", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
jasmine.Clock.tick(900) # now using own connection
spyOn(client.remoteConnection, 'finalizeConnection').andCallThrough()
receivePassword device(1), 'pw'
expect(client.remoteConnection.finalizeConnection).toHaveBeenCalled()
expect(client.remoteConnection.getState()).toBe 'connecting'
it "displays a prompt when connecting to the server device would be abrupt", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
client.remoteConnectionHandler._timer.elapsed = -> 5000
jasmine.Clock.tick(5000) # been using own connection for a while now
spyOn client.remoteConnection, 'finalizeConnection'
receivePassword device(1), 'pw'
expect(client.remoteConnection.finalizeConnection).not.toHaveBeenCalled()
expect(noticeIsVisible()).toBe true
it "closes sockets when internect connection is lost", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
becomeClient()
spyOn device(1), 'close'
mocks.navigator.goOffline()
expect(noticeIsVisible()).toBe true
expect(device(1).close).toHaveBeenCalled()
it "establishes connection when internet is renabled", ->
chrome.storage.sync.set { server_device: { addr: '192.168.3.11', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
becomeClient()
mocks.navigator.goOffline()
expect(client.remoteConnection.getState()).not.toBe 'connecting'
expect(noticeIsVisible()).toBe true
mocks.navigator.goOnline()
expect(client.remoteConnection.getState()).toBe 'connecting'
| true | describe 'An IRC client front end', ->
client = prompt = commandInput = undefined
room = (index) ->
return rooms().last() if index is -1
$ rooms()[index]
rooms = ->
$ '#rooms-container .rooms .room'
textOfRoom = (index) ->
$('.content-item', room(index)).text()
nick = (index) ->
return nicks().last() if index is -1
$ nicks()[index]
nicks = ->
$ '#nicks-container .nicks .nick'
textOfNick = (index) ->
$('.content-item', nick(index)).text()
device = (i) ->
mocks.RemoteDevice.devices[i]
irc = (name) ->
client.connections[name]?.irc
type = (text) ->
prompt.val(text)
commandInput._handleKeydown { which: 13, preventDefault: -> }
noticeIsVisible = ->
$("#notice")[0].style.top is "0px"
restart = ->
RemoteDevice.devices = []
mocks.dom.tearDown()
client.tearDown()
mocks.dom.setUp()
init()
init = ->
scriptHandler = new window.script.ScriptHandler
client = new window.chat.Chat
commandInput.setContext client
scriptHandler.addEventsFrom client
scriptHandler.addEventsFrom commandInput
scriptHandler.listenToScriptEvents client
client.listenToCommands scriptHandler
client.listenToScriptEvents scriptHandler
client.listenToIRCEvents scriptHandler
beforeEach ->
mocks.navigator.useMock()
mocks.ChromeSocket.useMock()
mocks.RemoteDevice.useMock()
mocks.NickMentionedNotification.useMock()
jasmine.Clock.useMock()
mocks.dom.setUp()
prompt = $('#input')
commandInput = new UserInputHandler(prompt, $ window)
chrome.storage.sync.set { nick: 'ournick' }
init()
afterEach ->
mocks.dom.tearDown()
chrome.storage.sync.clear()
client.tearDown()
it "displays the preferred nick in the status bar", ->
expect($ '#status').toHaveText 'ournick'
it "sets the document title to the version", ->
expect(document.title).toMatch /^CIRC \d{1,3}\.\d{1,3}\.\d{1,3}/
it "initially has one window", ->
expect(rooms().length).toBe 1
it "replaces the initial window with a server window on /connect", ->
type '/connect freenode'
expect(rooms().length).toBe 1
expect(textOfRoom 0).toBe 'freenode'
expect(client.currentWindow.conn.name).toBe 'freenode'
it "ignores commands that requicre a connection not connected", ->
type '/names'
type '/me is 1337'
type '/op bob'
type '/msg someguy'
type '/mode sally +o'
it "displays a prompt internet connectivity is lost", ->
expect(noticeIsVisible()).toBe false
mocks.navigator.goOffline()
expect(noticeIsVisible()).toBe true
describe "storage", ->
doActivity = ->
type '/nick newNick'
type '/server freenode 6667'
type '/join #bash'
type '/join #awesome'
type '/server dalnet 6697'
type '/win 4'
type '/join #hiphop'
beforeEach ->
doActivity()
it "chooses a new password when one doesn't currently exist", ->
expect(client.remoteConnection._password).toEqual jasmine.any(String)
it "keeps the old password when one exists", ->
chrome.storage.sync.set { password: 'PI:PASSWORD:<PASSWORD>END_PI' }
restart()
expect(client.remoteConnection._password).toBe 'PI:PASSWORD:<PASSWORD>END_PI'
it "restores the previously used nick", ->
restart()
expect($ '#status').toHaveText 'newNick'
it "generates random nick when no previously used nick is available", ->
chrome.storage.sync.set { nick: undefined }
restart()
type "/connect freenode"
expect(irc('freenode').preferredNick).toBeDefined()
it "restores the previously joined servers", ->
restart()
expect(client.connections['freenode']).toBeDefined()
expect(client.connections['dalnet']).toBeDefined()
it "restores the previously joined channels", ->
restart()
expect(client.connections['freenode'].windows['#bash']).toBeDefined()
expect(client.connections['freenode'].windows['#awesome']).toBeDefined()
expect(client.connections['dalnet'].windows['#hiphop']).toBeDefined()
expect(rooms().length).toBe 5
it "doesn't restore channels that were parted", ->
type '/part #hiphop'
restart()
expect(client.connections['dalnet'].windows['#hiphop']).not.toBeDefined()
expect(rooms().length).toBe 4
it "doesn't restore servers that were parted", ->
type '/win 1'
type '/quit'
restart()
expect(irc 'freenode').not.toBeDefined()
expect(rooms().length).toBe 2
it "displays restored private channels as connected", ->
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
irc('freenode').handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
restart()
expect(rooms().length).toBe 6
expect(textOfRoom 3).toBe 'someguy'
expect(room 3).not.toHaveClass 'disconnected'
describe "that is connecting", ->
beforeEach ->
type '/server freenode'
expect(irc('freenode').state).toBe 'connecting'
it 'can queue a disconnection request with /quit', ->
currentIRC = irc('freenode')
type '/quit'
currentIRC.handle '1', {}, 'ournick' # rpl_welcome
expect(currentIRC.state).toBe 'disconnected'
it 'allows channels to be joined while connecting', ->
type '/join #bash'
expect(rooms().length).toBe 2
expect(textOfRoom -1).toBe '#bash'
expect(room -1).toHaveClass 'selected'
expect(room -1).toHaveClass 'disconnected'
it 'automatically joins queued channels when connected', ->
type '/join #bash'
type '/part'
spyOn irc('freenode'), 'send'
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
expect(irc('freenode').send).not.toHaveBeenCalled()
it 'removes queued channels on /part', ->
type '/join #bash'
spyOn irc('freenode'), 'send'
irc('freenode').handle '1', {}, 'ournick' # rpl_welcome
expect(irc('freenode').send).toHaveBeenCalledWith 'JOIN', '#bash'
describe "that connects", ->
currentIRC = undefined
beforeEach ->
type '/server freenode'
currentIRC = irc('freenode')
currentIRC.handle '1', {}, 'ournick' # rpl_welcome
expect(currentIRC.state).toBe 'connected'
spyOn currentIRC, 'doCommand'
it "marks the server item in the window list as connected", ->
expect(room 0).not.toHaveClass 'disconnected'
it "updates the status bar on /away", ->
type '/away'
currentIRC.handle '306' # rpl_nowaway
expect($ '#status').toHaveText 'ournick' + 'away'
it "creates a new window when a direct private message is received", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
expect(rooms().length).toBe 2
expect(textOfRoom -1).toBe 'someguy'
expect(room -1).toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "displays /msg text in the current window if there is no existing conversation window", ->
spyOn(client.currentWindow, 'message').andCallThrough()
type '/msg someguy hey dude'
expect(rooms().length).toBe 1
expect(client.currentWindow.message).toHaveBeenCalled()
it "displays /msg text in the conversation window when it exists", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hi there'
spyOn(client.currentWindow, 'message').andCallThrough()
type '/msg someguy hey dude'
expect(client.currentWindow.message).not.toHaveBeenCalled()
it "/msg causes the conversation window to be marked with activity", ->
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournPI:NAME:<NAME>END_PI', 'hi there'
type '/win 2'
type '/win 1'
expect(room -1).not.toHaveClass 'mention'
expect(room -1).not.toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
type '/msg someguy hey dude'
expect(room -1).not.toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "creates a notification when a direct private message is received", ->
chat.NickMentionedNotification.notificationCount = 0
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, 'ournick', 'hey!'
expect(chat.NickMentionedNotification.notificationCount).toBe 1
it "can join a channel with /join", ->
type '/join #bash'
expect(currentIRC.doCommand).toHaveBeenCalledWith 'JOIN', '#bash'
expect(client.currentWindow.target).toBe '#bash'
describe "then is disconnected by a socket error", ->
beforeEach ->
currentIRC.onClose()
it 'shows all servers and channels as disconnected', ->
expect(room 0).toHaveClass 'disconnected'
it 'attempts to reconnect after a short amount of time', ->
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(2000)
expect(currentIRC.connect).toHaveBeenCalled()
it 'uses exponential backoff for reconnection attempts', ->
jasmine.Clock.tick(2000)
currentIRC.onError 'socket error!'
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(2000)
expect(currentIRC.connect).not.toHaveBeenCalled()
jasmine.Clock.tick(2000)
expect(currentIRC.connect).toHaveBeenCalled()
currentIRC.connect.reset() # reset the connect function spy
currentIRC.onError 'socket error!'
jasmine.Clock.tick(7999)
expect(currentIRC.connect).not.toHaveBeenCalled()
it 'closes the current window and stops reconnecting on /quit', ->
type "/quit"
expect(client.currentWindow.name).toBe 'none'
spyOn(currentIRC, 'connect')
jasmine.Clock.tick(9000)
expect(currentIRC.connect).not.toHaveBeenCalled()
describe "then joins a channel", ->
beforeEach ->
type '/join #bash'
currentIRC.handle 'JOIN', {nick: 'ournick'}, '#bash'
it "adds another item to the room display", ->
expect(rooms().length).toBe 2
it "can switch windows with /win", ->
type "/win 1"
expect(client.currentWindow.target).toBe undefined
it "creates a notification when the users nick is mentioned", ->
type "/win 1"
chat.NickMentionedNotification.notificationCount = 0
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hey PI:NAME:<NAME>END_PI!'
expect(chat.NickMentionedNotification.notificationCount).toBe 1
expect(room -1).toHaveClass 'mention'
expect(room -1).toHaveClass 'activity'
expect(room -1).not.toHaveClass 'selected'
it "marks a window as active if a message is sent and it's not selected", ->
type '/server dalnet'
irc2 = client.currentWindow.conn.irc
irc2.handle '1', {}, 'ournick' # rpl_welcome
type '/win 3'
type '/join #bash'
currentIRC.handle 'JOIN', {nick: 'ournick'}, '#bash'
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hi'
expect(room 1).toHaveClass 'activity'
it "clears activity and mention style when switching to a window", ->
type "/win 1"
currentIRC.handle 'PRIVMSG', {nick: 'someguy'}, '#bash', 'hey!'
type "/win 2"
expect(room -1).not.toHaveClass 'mention'
expect(room -1).not.toHaveClass 'activity'
expect(room -1).toHaveClass 'selected'
it "clicking on a channel in the channel display switches to that channel", ->
client.channelDisplay.emit 'clicked', 'freenode', '#bash'
expect(client.currentWindow.target).toBe '#bash'
expect(room -1).toHaveClass 'selected'
describe "has a nick list which", ->
currentNicks = undefined
beforeEach ->
currentNicks = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<PASSWORD>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI',
'zabo1', 'ZABO2', 'zabo3', 'Zabo88']
addNicks = ->
currentIRC.emit 'names', '#bash', currentNicks.slice(0, 7)
currentIRC.emit 'names', '#bash', currentNicks.slice(7, 12)
currentIRC.emit 'names', '#bash', currentNicks.slice(12)
nameMap = {}
(nameMap[name] = name for name in currentNicks)
currentIRC.channels['#bash'].names = nameMap
it "displays the user's nick when first joining a channel", ->
expect(nicks().length).toBe 1
expect(textOfNick 0).toBe 'ournick'
it "displays all nicks in the channel when the nick list is sent", ->
addNicks()
expect(nicks().length).toBe currentNicks.length + 1
it "displays nicks in sorted order", ->
addNicks()
expect(textOfNick 9).toBe 'ournick'
it "displays newly joined nicks after they /join", ->
addNicks()
currentIRC.handle 'JOIN', {nick: 'alphy'}, '#bash'
expect(nicks().length).toBe currentNicks.length + 2
expect(textOfNick 0).toBe 'alphy'
it "doesn't display nicks after they have been kicked", ->
addNicks()
currentIRC.handle 'KICK', {nick: 'bob'}, '#bash', 'Zabo88'
expect(nicks().length).toBe currentNicks.length
expect(textOfNick 0).not.toBe 'Zabo88'
it "doesn't display nicks after they left with /parted", ->
addNicks()
currentIRC.handle 'PART', {nick: 'bob'}, '#bash'
expect(nicks().length).toBe currentNicks.length
expect(textOfNick 2).not.toBe 'bob'
it "doesn't display duplicate nicks", ->
currentNicks.push 'PI:NAME:<NAME>END_PI'
addNicks()
expect(nicks().length).toBe currentNicks.length
it "stays visible when another non-selected window is closed", ->
type "/join #awesome"
event = new Event 'command', 'part'
event.setContext 'freenode', '#bash'
client.userCommands.handle 'part', event
expect($ '#rooms-and-nicks').not.toHaveClass 'no-nicks'
describe "with a remote connection", ->
state = onAuth = undefined
getChannels = ->
{ '#bash': { names: { PI:NAME:<NAME>END_PIally: 'PI:NAME:<NAME>END_PI', bob: 'PI:NAME:<PASSWORD>END_PI', somenick: 'somenick' } } }
getState = ->
nick: 'preferredNick'
servers: [ { name: 'freenode', port: 6667 }, { name: 'dalnet', port: 6697 } ]
channels: [ { name: '#bash', server: 'freenode' }, { name: '#awesome', server: 'dalnet' } ]
ircStates: [ { server: 'freenode', state: 'connected', nick: 'somenick', away: true, channels: getChannels() } ]
findPort = ->
d = client.remoteConnection._thisDevice
d.port = 1
RemoteDevice.state = 'found_port'
d.emit 'found_port'
authenticate = (device) ->
authToken = client.remoteConnection._getAuthToken device.password
device.emit 'authenticate', device, authToken
receivePassword = (device, password) ->
device.emit 'authentication_offer', device, password
becomeClient = (opt_state) ->
state = opt_state if opt_state
(device 1).emit 'connection_message', device(1), 'irc_state', state
receiveChatHistory = (chatHistory) ->
device(1).emit 'connection_message', device(1), 'chat_log', chatHistory
beforeEach ->
state = getState()
spyOn(mocks.RemoteDevice, 'onConnect').andCallThrough()
it "connects to a server device with /join-server", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
expect(mocks.RemoteDevice.onConnect).toHaveBeenCalled()
it "emits 'server_found' when server sends a password", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
spyOn client.remoteConnection, 'emit'
receivePassword device(1), 'pw'
expect(client.remoteConnection.emit).toHaveBeenCalledWith 'server_found', device(1)
it "sends authentication after server sends a password and finalizeConnection() is called", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
receivePassword device(1), 'pw'
expect(device(1).sendType).toBe 'authenticate'
it "becomes a client after receiving IRC state", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
expect(client.remoteConnection.isClient()).toBe false
becomeClient []
expect(client.remoteConnection.isClient()).toBe true
it "doesn't add a client before authentication", ->
RemoteDevice.onNewDevice new RemoteDevice
expect(client.remoteConnection.devices[0]).not.toBeDefined()
it "add a client after it authenticates", ->
RemoteDevice.onNewDevice new RemoteDevice
expect(client.remoteConnection.devices[0]).not.toBeDefined()
authenticate device 1
expect(client.remoteConnection.devices[0]).toBeDefined()
it "disconnects from the current connection before using the server device's connection", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
becomeClient []
expect(rooms().length).toBe 1
expect(client.connections['freenode']).not.toBeDefined()
it "can load the IRC state from the server device", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
becomeClient()
expect(rooms().length).toBe 4
expect(irc('freenode').state).toBe 'connected'
expect(irc('dalnet').state).toBe 'disconnected'
expect(room 0).not.toHaveClass 'disconnected'
expect(room 1).not.toHaveClass 'disconnected'
expect(room 2).toHaveClass 'disconnected'
expect(room 3).toHaveClass 'disconnected'
type '/win 2'
for name, i in ['PI:NAME:<PASSWORD>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
expect(textOfNick i).toBe name
expect($('#status').text()).toBe 'somenick' + 'away'
it "doesn't set the irc nick if the nick isn't saved", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
state.ircStates[0].nick = undefined
state.nick = undefined
becomeClient()
expect(irc('freenode').preferredNick).toBeDefined()
it "can listen to user input from the server device", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
becomeClient()
event = new Event 'command', 'nick', 'newnick'
event.setContext 'freenode'
spyOn client, 'setNick'
(device 1).emit 'user_input', device(1), event
expect(client.setNick).toHaveBeenCalledWith 'freenode', 'newnick'
it "can listen to socket data from the server device", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
becomeClient()
spyOn irc('freenode'), 'onDrain'
(device 1).emit 'socket_data', device(1), 'freenode', 'drain'
expect(irc('freenode').onDrain).toHaveBeenCalled()
it "uses own connection after connection to the server is lost", ->
type "/join-server PI:IP_ADDRESS:192.168.3.11END_PI 1336"
becomeClient []
spyOn client, 'closeAllConnections'
(device 1).emit 'closed', device(1)
expect(client.remoteConnection.isIdle()).toBe true
expect(client.closeAllConnections).toHaveBeenCalled()
it "on startup, when server exists, uses own connection after waiting a brief time", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
expect(rooms().length).toBe 1
jasmine.Clock.tick(2000)
expect(rooms().length).toBe 4
it "automatically connects if an existing server is present", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
restart()
expect(mocks.RemoteDevice.onConnect).toHaveBeenCalled()
it "becomes server if storage marks it as the server device", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.1', port: 1 } }
restart()
findPort()
expect(client.remoteConnection.isServer()).toBe true
it "updates stored server device info when the server device's port changes", ->
chrome.storage.sync.set { server_device: { addr: '1.1.1.1', port: 2 } }
restart()
findPort()
expect(client.remoteConnection.isServer()).toBe true
expect(chrome.storage.sync._storageMap.server_device.port).toBe 1
it "becomes idle if can't connect to server device", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
restart()
expect(client.remoteConnection.getState()).toBe 'connecting'
mocks.RemoteDevice.willConnect = false
restart()
expect(client.remoteConnection.isIdle()).toBe true
it "keeps trying to connect to the server device", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
restart()
mocks.RemoteDevice.willConnect = false
restart()
mocks.RemoteDevice.willConnect = true
jasmine.Clock.tick(1000)
expect(client.remoteConnection.getState()).toBe 'connecting'
it "forwards user input to connected clients when acting as the server device", ->
findPort()
type '/make-server'
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 1
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 2
expect(client.remoteConnection.devices.length).toBe 2
spyOn device(1), 'send'
spyOn device(2), 'send'
spyOn client.remoteConnection, 'emit'
device(1).emit 'user_input', device(1), {
type: 'command', name: 'say', args: ['PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'],
context: { server: 'freenode', channel: '#bash' } }
expect(device(1).send).not.toHaveBeenCalled()
expect(device(2).send.mostRecentCall.args[0]).toBe 'user_input'
expect(client.remoteConnection.emit).toHaveBeenCalledWith 'command',
jasmine.any(Event)
it "only sends IRC state to the connecting device, not all devices", ->
findPort()
type '/make-server'
RemoteDevice.onNewDevice new RemoteDevice
authenticate device 1
RemoteDevice.onNewDevice new RemoteDevice
spyOn device(1), 'send'
spyOn device(2), 'send'
authenticate device 2
expect(device(2).send).toHaveBeenCalled()
expect(device(1).send).not.toHaveBeenCalled()
it "retains connections after /make-server", ->
findPort()
expect(rooms().length).toBe 2
type "/make-server"
expect(rooms().length).toBe 2
it "is able to connect to servers even if chrome.socket.listen isn't supported", ->
chrome.socket.listen = undefined
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
restart()
expect(client.remoteConnection.getState()).toBe 'connecting'
it "can't become a server if chrome.socket.listen isn't defined", ->
chrome.socket.listen = undefined
type "/make-server"
expect(client.remoteConnection.isIdle()).toBe true
it "sends chat history when a client connects", ->
findPort()
type "/make-server"
RemoteDevice.onNewDevice new RemoteDevice
spyOn device(1), 'send'
type 'hi there'
authenticate device 1
expect(device(1).send).toHaveBeenCalledWith 'connection_message',
['chat_log', jasmine.any(Object)]
it "replays received chat history after connecting to a server device", ->
type 'hi there'
type 'i am recording some chat history'
chatHistory = client.messageHandler.getChatLog()
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
restart()
becomeClient()
win = client.winList.get('freenode', '#bash')
spyOn win, 'rawMessage'
receiveChatHistory chatHistory
expect(client.remoteConnection.isClient()).toBe true
expect(win.rawMessage).toHaveBeenCalled()
it "connects to a server even when the server connection takes a long time", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
jasmine.Clock.tick(900) # now using own connection
spyOn(client.remoteConnection, 'finalizeConnection').andCallThrough()
receivePassword device(1), 'pw'
expect(client.remoteConnection.finalizeConnection).toHaveBeenCalled()
expect(client.remoteConnection.getState()).toBe 'connecting'
it "displays a prompt when connecting to the server device would be abrupt", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
client.remoteConnectionHandler._timer.elapsed = -> 5000
jasmine.Clock.tick(5000) # been using own connection for a while now
spyOn client.remoteConnection, 'finalizeConnection'
receivePassword device(1), 'pw'
expect(client.remoteConnection.finalizeConnection).not.toHaveBeenCalled()
expect(noticeIsVisible()).toBe true
it "closes sockets when internect connection is lost", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
becomeClient()
spyOn device(1), 'close'
mocks.navigator.goOffline()
expect(noticeIsVisible()).toBe true
expect(device(1).close).toHaveBeenCalled()
it "establishes connection when internet is renabled", ->
chrome.storage.sync.set { server_device: { addr: 'PI:IP_ADDRESS:192.168.3.11END_PI', port: 1 } }
delete state.ircState
chrome.storage.sync.set state
restart()
becomeClient()
mocks.navigator.goOffline()
expect(client.remoteConnection.getState()).not.toBe 'connecting'
expect(noticeIsVisible()).toBe true
mocks.navigator.goOnline()
expect(client.remoteConnection.getState()).toBe 'connecting'
|
[
{
"context": "###*\n@author Mat Groves http://matgroves.com/\n###\ndefine 'Coffixi/extras/",
"end": 23,
"score": 0.9998767971992493,
"start": 13,
"tag": "NAME",
"value": "Mat Groves"
},
{
"context": "###*\n@author Mat Groves http://matgroves.com/\n###\ndefine 'Coffixi/extras/TilingSp... | src/Coffixi/extras/TilingSprite.coffee | namuol/Coffixi | 1 | ###*
@author Mat Groves http://matgroves.com/
###
define 'Coffixi/extras/TilingSprite', [
'Coffixi/core/Point'
'Coffixi/display/DisplayObjectContainer'
'Coffixi/display/Sprite'
'Coffixi/core/RenderTypes'
], (
Point
DisplayObjectContainer
Sprite
RenderTypes
) ->
###*
A tiling sprite is a fast way of rendering a tiling image
@class TilingSprite
@extends DisplayObjectContainer
@constructor
@param texture {Texture} the texture of the tiling sprite *NOTE*: Dimensions of the *baseTexture* must be a power-of-2! (eg. 32x64, 128x128, etc.)
@param width {Number} the width of the tiling sprite
@param height {Number} the height of the tiling sprite
###
class TilingSprite extends DisplayObjectContainer
__renderType: RenderTypes.TILINGSPRITE
constructor: (texture, width, height) ->
super
###*
The texture that the sprite is using
@property texture
@type Texture
###
@texture = texture
###*
The width of the tiling sprite
@property width
@type Number
###
@width = width
###*
The height of the tiling sprite
@property height
@type Number
###
@height = height
###*
The scaling of the image that is being tiled
@property tileScale
@type Point
###
@tileScale = new Point(1, 1)
###*
The offset position of the image that is being tiled
@property tilePosition
@type Point
###
@tilePosition = new Point(0, 0)
@renderable = true
@blendMode = Sprite.blendModes.NORMAL
###*
The texture used by this `TilingSprite`.
**NOTE**: Must be a power-of-two image.
@property texture
###
Object.defineProperty @::, 'texture',
get: -> @_texture
set: (texture) ->
#TODO SET THE TEXTURES
#TODO VISIBILITY
# stop current texture
@_texture = texture
@updateFrame = true
###*
When the texture is updated, this event will fire to update the frame
@method onTextureUpdate
@param event
@private
###
onTextureUpdate: (event) ->
@updateFrame = true
| 111923 | ###*
@author <NAME> http://matgroves.com/
###
define 'Coffixi/extras/TilingSprite', [
'Coffixi/core/Point'
'Coffixi/display/DisplayObjectContainer'
'Coffixi/display/Sprite'
'Coffixi/core/RenderTypes'
], (
Point
DisplayObjectContainer
Sprite
RenderTypes
) ->
###*
A tiling sprite is a fast way of rendering a tiling image
@class TilingSprite
@extends DisplayObjectContainer
@constructor
@param texture {Texture} the texture of the tiling sprite *NOTE*: Dimensions of the *baseTexture* must be a power-of-2! (eg. 32x64, 128x128, etc.)
@param width {Number} the width of the tiling sprite
@param height {Number} the height of the tiling sprite
###
class TilingSprite extends DisplayObjectContainer
__renderType: RenderTypes.TILINGSPRITE
constructor: (texture, width, height) ->
super
###*
The texture that the sprite is using
@property texture
@type Texture
###
@texture = texture
###*
The width of the tiling sprite
@property width
@type Number
###
@width = width
###*
The height of the tiling sprite
@property height
@type Number
###
@height = height
###*
The scaling of the image that is being tiled
@property tileScale
@type Point
###
@tileScale = new Point(1, 1)
###*
The offset position of the image that is being tiled
@property tilePosition
@type Point
###
@tilePosition = new Point(0, 0)
@renderable = true
@blendMode = Sprite.blendModes.NORMAL
###*
The texture used by this `TilingSprite`.
**NOTE**: Must be a power-of-two image.
@property texture
###
Object.defineProperty @::, 'texture',
get: -> @_texture
set: (texture) ->
#TODO SET THE TEXTURES
#TODO VISIBILITY
# stop current texture
@_texture = texture
@updateFrame = true
###*
When the texture is updated, this event will fire to update the frame
@method onTextureUpdate
@param event
@private
###
onTextureUpdate: (event) ->
@updateFrame = true
| true | ###*
@author PI:NAME:<NAME>END_PI http://matgroves.com/
###
define 'Coffixi/extras/TilingSprite', [
'Coffixi/core/Point'
'Coffixi/display/DisplayObjectContainer'
'Coffixi/display/Sprite'
'Coffixi/core/RenderTypes'
], (
Point
DisplayObjectContainer
Sprite
RenderTypes
) ->
###*
A tiling sprite is a fast way of rendering a tiling image
@class TilingSprite
@extends DisplayObjectContainer
@constructor
@param texture {Texture} the texture of the tiling sprite *NOTE*: Dimensions of the *baseTexture* must be a power-of-2! (eg. 32x64, 128x128, etc.)
@param width {Number} the width of the tiling sprite
@param height {Number} the height of the tiling sprite
###
class TilingSprite extends DisplayObjectContainer
__renderType: RenderTypes.TILINGSPRITE
constructor: (texture, width, height) ->
super
###*
The texture that the sprite is using
@property texture
@type Texture
###
@texture = texture
###*
The width of the tiling sprite
@property width
@type Number
###
@width = width
###*
The height of the tiling sprite
@property height
@type Number
###
@height = height
###*
The scaling of the image that is being tiled
@property tileScale
@type Point
###
@tileScale = new Point(1, 1)
###*
The offset position of the image that is being tiled
@property tilePosition
@type Point
###
@tilePosition = new Point(0, 0)
@renderable = true
@blendMode = Sprite.blendModes.NORMAL
###*
The texture used by this `TilingSprite`.
**NOTE**: Must be a power-of-two image.
@property texture
###
Object.defineProperty @::, 'texture',
get: -> @_texture
set: (texture) ->
#TODO SET THE TEXTURES
#TODO VISIBILITY
# stop current texture
@_texture = texture
@updateFrame = true
###*
When the texture is updated, this event will fire to update the frame
@method onTextureUpdate
@param event
@private
###
onTextureUpdate: (event) ->
@updateFrame = true
|
[
{
"context": "erview\n # @name Testing Module\n # @email test@test.com\n # @description\n # This is just a test\n",
"end": 4315,
"score": 0.9999221563339233,
"start": 4302,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "rse code, @lang, {}\n test.equ... | test/parse_test.coffee | adrianlee44/chalkboard | 1 | require "coffee-script/register"
chalkboard = require "../src/chalkboard"
exports.parseTest =
setUp: (callback) ->
@lang =
name: 'coffeescript'
symbol: '#'
block: '###'
commentRegex: /^\s*(?:#){1,2}\s*(?:@(\w+))?(?:\s*(.*))?/
lineRegex: /^\s*(?:#){1,2}\s+(.*)/
blockRegex: /###/
callback()
"chalk test": (test) ->
test.expect 2
code = """
#
# @name hello
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 0, "No section should be parsed"
code2 = """
#
# @chalk overview
# @name hello
#
"""
ret = chalkboard.parse code2, @lang, {}
test.equal ret.length, 1, "1 section should be parsed"
test.done()
"multiple chalk test": (test) ->
code = """
#
# @chalk overview
# @name hello
#
#
# @chalk function
# @function
# @name wah
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 2, "2 sections should be parsed"
test.done()
"name test": (test) ->
code = """
#
# @chalk overview
# @name hello
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "hello"
test.done()
"description test": (test) ->
code = """
#
# @chalk overview
# @description
# This is a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "This is a test \n"
test.done()
"multi-line description test": (test) ->
code = """
#
# @chalk overview
# @description
# This is a test
# Second line of the description
# - Point 1
# - Point 2
#
"""
output = "This is a test \n"
output += "Second line of the description \n"
output += "- Point 1 \n"
output += "- Point 2 \n"
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, output
test.done()
"param test": (test) ->
test.expect 4
code = """
#
# @chalk overview
# @param {String} test Another test name
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 1
param = ret[0].param[0]
test.equal param.name, "test"
test.equal param.type, "String"
test.equal param.description, "Another test name \n"
test.done()
"param multiple line description test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# This is the second line
# And then there is the third line
#
"""
ret = chalkboard.parse code, @lang, {}
param = ret[0].param[0]
output = "Another test name \nThis is the second line \nAnd then there is the third line \n"
test.equal param.description, output
test.done()
"multiple param test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# @param {Integer} random Just another random integer
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 2
test.done()
"multiple multi-line params description test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# Line 2 of the first param
# @param {Integer} random Just another random integer
# With just another random character
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 2
params = ret[0].param
test.equal params[0].description, "Another test name \nLine 2 of the first param \n"
test.equal params[1].description, "Just another random integer \nWith just another random character \n"
test.done()
"comment block": (test) ->
code = """
###
@chalk overview
@name Testing
@description
Hello World
###
"""
test.expect 2
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "Testing"
test.equal ret[0].description, "Hello World \n"
test.done()
"email test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @email test@test.com
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].email, "test@test.com"
test.done()
"copyright test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @copyright Test User c 2000
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].copyright, "Test User c 2000"
test.done()
"license test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @license MIT
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].license, "MIT"
test.done()
"url test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @url http://www.example.com
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].url, "http://www.example.com"
test.done()
"variable type identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @variable
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].type, "variable"
test.done()
"function type identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @function
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].type, "function"
test.done()
"private access identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @private
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "private"
test.done()
"public access identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @public
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "public"
test.done()
"using @access": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @access public
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "public"
test.done()
"since tag test": (test) ->
code = """
# @chalk overview
# @since Yesterday
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].since, "Yesterday"
test.done()
"version test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @version 9000+
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].version, "9000+"
test.done()
"maintain comment whitespaces": (test) ->
code = """
###
@chalk
@name Testing
@example
```
testObj =
hello: "123"
world: "321"
```
###
"""
ret = chalkboard.parse code, @lang, {}
expected = "``` \ntestObj = \n hello: \"123\" \n world: \"321\" \n``` \n"
test.equal ret[0].example, expected
test.done()
"maintain valid number of whitespaces": (test) ->
code = """
code
###
@chalk
@name Testing
@description
Hello
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "Hello \n"
test.done()
"preserve empty line between text bock": (test) ->
code = """
###
@chalk
@description
Testing
whitespaces
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "Testing \n \nwhitespaces \n"
test.done()
"Keep unsupported tag as normal text": (test) ->
code = """
###
@chalk
@description
This is some unsupported tags,
@static
@random
@text
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "This is some unsupported tags, \n@static \n@random \n@text \n"
test.done()
exports.jsParseTest =
setUp: (callback) ->
@lang =
name: 'javascript'
symbol: '//'
start: '/*'
end: '*/'
commentRegex: /^\s*(?:\/\/){1,2}\s*(?:@(\w+))?(?:\s*(.*))?/
lineRegex: /^\s*(?:\/\/){1,2}\s+(.*)/
startRegex: /\/\*/
endRegex: /\*\//
callback()
"js chalk test": (test) ->
test.expect 2
code = """
//
// @name hello
//
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 0, "No section should be parsed"
code2 = """
//
// @chalk overview
// @name hello
//
"""
ret = chalkboard.parse code2, @lang, {}
test.equal ret.length, 1, "1 section should be parsed"
test.done()
"js comment block": (test) ->
code = """
/*
@chalk overview
@name Testing
@description
Hello World
*/
"""
test.expect 2
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "Testing"
test.equal ret[0].description, "Hello World \n"
test.done()
| 17101 | require "coffee-script/register"
chalkboard = require "../src/chalkboard"
exports.parseTest =
setUp: (callback) ->
@lang =
name: 'coffeescript'
symbol: '#'
block: '###'
commentRegex: /^\s*(?:#){1,2}\s*(?:@(\w+))?(?:\s*(.*))?/
lineRegex: /^\s*(?:#){1,2}\s+(.*)/
blockRegex: /###/
callback()
"chalk test": (test) ->
test.expect 2
code = """
#
# @name hello
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 0, "No section should be parsed"
code2 = """
#
# @chalk overview
# @name hello
#
"""
ret = chalkboard.parse code2, @lang, {}
test.equal ret.length, 1, "1 section should be parsed"
test.done()
"multiple chalk test": (test) ->
code = """
#
# @chalk overview
# @name hello
#
#
# @chalk function
# @function
# @name wah
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 2, "2 sections should be parsed"
test.done()
"name test": (test) ->
code = """
#
# @chalk overview
# @name hello
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "hello"
test.done()
"description test": (test) ->
code = """
#
# @chalk overview
# @description
# This is a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "This is a test \n"
test.done()
"multi-line description test": (test) ->
code = """
#
# @chalk overview
# @description
# This is a test
# Second line of the description
# - Point 1
# - Point 2
#
"""
output = "This is a test \n"
output += "Second line of the description \n"
output += "- Point 1 \n"
output += "- Point 2 \n"
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, output
test.done()
"param test": (test) ->
test.expect 4
code = """
#
# @chalk overview
# @param {String} test Another test name
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 1
param = ret[0].param[0]
test.equal param.name, "test"
test.equal param.type, "String"
test.equal param.description, "Another test name \n"
test.done()
"param multiple line description test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# This is the second line
# And then there is the third line
#
"""
ret = chalkboard.parse code, @lang, {}
param = ret[0].param[0]
output = "Another test name \nThis is the second line \nAnd then there is the third line \n"
test.equal param.description, output
test.done()
"multiple param test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# @param {Integer} random Just another random integer
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 2
test.done()
"multiple multi-line params description test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# Line 2 of the first param
# @param {Integer} random Just another random integer
# With just another random character
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 2
params = ret[0].param
test.equal params[0].description, "Another test name \nLine 2 of the first param \n"
test.equal params[1].description, "Just another random integer \nWith just another random character \n"
test.done()
"comment block": (test) ->
code = """
###
@chalk overview
@name Testing
@description
Hello World
###
"""
test.expect 2
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "Testing"
test.equal ret[0].description, "Hello World \n"
test.done()
"email test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @email <EMAIL>
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].email, "<EMAIL>"
test.done()
"copyright test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @copyright Test User c 2000
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].copyright, "Test User c 2000"
test.done()
"license test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @license MIT
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].license, "MIT"
test.done()
"url test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @url http://www.example.com
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].url, "http://www.example.com"
test.done()
"variable type identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @variable
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].type, "variable"
test.done()
"function type identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @function
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].type, "function"
test.done()
"private access identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @private
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "private"
test.done()
"public access identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @public
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "public"
test.done()
"using @access": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @access public
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "public"
test.done()
"since tag test": (test) ->
code = """
# @chalk overview
# @since Yesterday
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].since, "Yesterday"
test.done()
"version test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @version 9000+
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].version, "9000+"
test.done()
"maintain comment whitespaces": (test) ->
code = """
###
@chalk
@name <NAME>
@example
```
testObj =
hello: "123"
world: "321"
```
###
"""
ret = chalkboard.parse code, @lang, {}
expected = "``` \ntestObj = \n hello: \"123\" \n world: \"321\" \n``` \n"
test.equal ret[0].example, expected
test.done()
"maintain valid number of whitespaces": (test) ->
code = """
code
###
@chalk
@name <NAME>
@description
Hello
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "Hello \n"
test.done()
"preserve empty line between text bock": (test) ->
code = """
###
@chalk
@description
Testing
whitespaces
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "Testing \n \nwhitespaces \n"
test.done()
"Keep unsupported tag as normal text": (test) ->
code = """
###
@chalk
@description
This is some unsupported tags,
@static
@random
@text
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "This is some unsupported tags, \n@static \n@random \n@text \n"
test.done()
exports.jsParseTest =
setUp: (callback) ->
@lang =
name: 'javascript'
symbol: '//'
start: '/*'
end: '*/'
commentRegex: /^\s*(?:\/\/){1,2}\s*(?:@(\w+))?(?:\s*(.*))?/
lineRegex: /^\s*(?:\/\/){1,2}\s+(.*)/
startRegex: /\/\*/
endRegex: /\*\//
callback()
"js chalk test": (test) ->
test.expect 2
code = """
//
// @name hello
//
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 0, "No section should be parsed"
code2 = """
//
// @chalk overview
// @name <NAME>
//
"""
ret = chalkboard.parse code2, @lang, {}
test.equal ret.length, 1, "1 section should be parsed"
test.done()
"js comment block": (test) ->
code = """
/*
@chalk overview
@name Testing
@description
Hello World
*/
"""
test.expect 2
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "Testing"
test.equal ret[0].description, "Hello World \n"
test.done()
| true | require "coffee-script/register"
chalkboard = require "../src/chalkboard"
exports.parseTest =
setUp: (callback) ->
@lang =
name: 'coffeescript'
symbol: '#'
block: '###'
commentRegex: /^\s*(?:#){1,2}\s*(?:@(\w+))?(?:\s*(.*))?/
lineRegex: /^\s*(?:#){1,2}\s+(.*)/
blockRegex: /###/
callback()
"chalk test": (test) ->
test.expect 2
code = """
#
# @name hello
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 0, "No section should be parsed"
code2 = """
#
# @chalk overview
# @name hello
#
"""
ret = chalkboard.parse code2, @lang, {}
test.equal ret.length, 1, "1 section should be parsed"
test.done()
"multiple chalk test": (test) ->
code = """
#
# @chalk overview
# @name hello
#
#
# @chalk function
# @function
# @name wah
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 2, "2 sections should be parsed"
test.done()
"name test": (test) ->
code = """
#
# @chalk overview
# @name hello
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "hello"
test.done()
"description test": (test) ->
code = """
#
# @chalk overview
# @description
# This is a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "This is a test \n"
test.done()
"multi-line description test": (test) ->
code = """
#
# @chalk overview
# @description
# This is a test
# Second line of the description
# - Point 1
# - Point 2
#
"""
output = "This is a test \n"
output += "Second line of the description \n"
output += "- Point 1 \n"
output += "- Point 2 \n"
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, output
test.done()
"param test": (test) ->
test.expect 4
code = """
#
# @chalk overview
# @param {String} test Another test name
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 1
param = ret[0].param[0]
test.equal param.name, "test"
test.equal param.type, "String"
test.equal param.description, "Another test name \n"
test.done()
"param multiple line description test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# This is the second line
# And then there is the third line
#
"""
ret = chalkboard.parse code, @lang, {}
param = ret[0].param[0]
output = "Another test name \nThis is the second line \nAnd then there is the third line \n"
test.equal param.description, output
test.done()
"multiple param test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# @param {Integer} random Just another random integer
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 2
test.done()
"multiple multi-line params description test": (test) ->
code = """
#
# @chalk overview
# @param {String} test Another test name
# Line 2 of the first param
# @param {Integer} random Just another random integer
# With just another random character
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].param.length, 2
params = ret[0].param
test.equal params[0].description, "Another test name \nLine 2 of the first param \n"
test.equal params[1].description, "Just another random integer \nWith just another random character \n"
test.done()
"comment block": (test) ->
code = """
###
@chalk overview
@name Testing
@description
Hello World
###
"""
test.expect 2
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "Testing"
test.equal ret[0].description, "Hello World \n"
test.done()
"email test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @email PI:EMAIL:<EMAIL>END_PI
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].email, "PI:EMAIL:<EMAIL>END_PI"
test.done()
"copyright test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @copyright Test User c 2000
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].copyright, "Test User c 2000"
test.done()
"license test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @license MIT
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].license, "MIT"
test.done()
"url test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @url http://www.example.com
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].url, "http://www.example.com"
test.done()
"variable type identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @variable
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].type, "variable"
test.done()
"function type identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @function
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].type, "function"
test.done()
"private access identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @private
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "private"
test.done()
"public access identifier test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @public
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "public"
test.done()
"using @access": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @access public
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].access, "public"
test.done()
"since tag test": (test) ->
code = """
# @chalk overview
# @since Yesterday
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].since, "Yesterday"
test.done()
"version test": (test) ->
code = """
#
# @chalk overview
# @name Testing Module
# @version 9000+
# @description
# This is just a test
#
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].version, "9000+"
test.done()
"maintain comment whitespaces": (test) ->
code = """
###
@chalk
@name PI:NAME:<NAME>END_PI
@example
```
testObj =
hello: "123"
world: "321"
```
###
"""
ret = chalkboard.parse code, @lang, {}
expected = "``` \ntestObj = \n hello: \"123\" \n world: \"321\" \n``` \n"
test.equal ret[0].example, expected
test.done()
"maintain valid number of whitespaces": (test) ->
code = """
code
###
@chalk
@name PI:NAME:<NAME>END_PI
@description
Hello
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "Hello \n"
test.done()
"preserve empty line between text bock": (test) ->
code = """
###
@chalk
@description
Testing
whitespaces
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "Testing \n \nwhitespaces \n"
test.done()
"Keep unsupported tag as normal text": (test) ->
code = """
###
@chalk
@description
This is some unsupported tags,
@static
@random
@text
###
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].description, "This is some unsupported tags, \n@static \n@random \n@text \n"
test.done()
exports.jsParseTest =
setUp: (callback) ->
@lang =
name: 'javascript'
symbol: '//'
start: '/*'
end: '*/'
commentRegex: /^\s*(?:\/\/){1,2}\s*(?:@(\w+))?(?:\s*(.*))?/
lineRegex: /^\s*(?:\/\/){1,2}\s+(.*)/
startRegex: /\/\*/
endRegex: /\*\//
callback()
"js chalk test": (test) ->
test.expect 2
code = """
//
// @name hello
//
"""
ret = chalkboard.parse code, @lang, {}
test.equal ret.length, 0, "No section should be parsed"
code2 = """
//
// @chalk overview
// @name PI:NAME:<NAME>END_PI
//
"""
ret = chalkboard.parse code2, @lang, {}
test.equal ret.length, 1, "1 section should be parsed"
test.done()
"js comment block": (test) ->
code = """
/*
@chalk overview
@name Testing
@description
Hello World
*/
"""
test.expect 2
ret = chalkboard.parse code, @lang, {}
test.equal ret[0].name, "Testing"
test.equal ret[0].description, "Hello World \n"
test.done()
|
[
{
"context": " req.set 'Authorization', \"Bearer #{@token or '53cr3t'}\"\n\n record = (done) -> (err, res) ->\n @err",
"end": 324,
"score": 0.5206142663955688,
"start": 321,
"tag": "PASSWORD",
"value": "3cr"
}
] | src/cuke-api.coffee | limadelic/cuke-api | 0 | http = require 'superagent'
async = require 'async'
require './support/globals'
table = require './support/table'
t = require './support/tokens'
{ shouldExp } = require './support/matchers'
steps = ->
url = (res) -> "http://#{config.api}/#{res}"
auth = (req) ->
req.set 'Authorization', "Bearer #{@token or '53cr3t'}"
record = (done) -> (err, res) ->
@error = err if err
@response = res
@results = res?.body
done?()
@When /^GET "([^"]*)"$/, (resource, done) ->
http.get url resource
.use auth
.end record done
@When /^DEL "([^"]*)"$/, (resource, done) ->
http.del url resource
.use auth
.end record done
post = (resource, payload, done) ->
http.post url resource
.use auth
.send payload
.end record done
@When /^POST "([^"]*)"$/, (resource, payload, done) ->
payload = JSON.parse payload
post resource, payload, done
@When /^POST "([^"]*)":$/, (resource, objects, done) ->
objects = table objects
objects = [objects] unless _.isArray objects
postit = (x, done) -> post resource, x, done
async.each objects, postit, done
@Then t.x("(#{t.text}) #{t.should} (#{t.arg})"), (actual, matcher, expected) ->
p shouldExp { actual, matcher, expected: 'expected' }
# @Then t.x("(#{t.text}) #{t.should}"), (actual, matcher) ->
# p shouldExp { actual, matcher }
# eval shouldExp { actual, matcher }
@Then t.x("(#{t.text}) #{t.should}:"), (actual, matcher, expected) ->
expected = table expected
eval shouldExp { actual, matcher, expected: 'expected' }
module.exports = (config={}) ->
_.merge global.config, config
steps
| 166090 | http = require 'superagent'
async = require 'async'
require './support/globals'
table = require './support/table'
t = require './support/tokens'
{ shouldExp } = require './support/matchers'
steps = ->
url = (res) -> "http://#{config.api}/#{res}"
auth = (req) ->
req.set 'Authorization', "Bearer #{@token or '5<PASSWORD>3t'}"
record = (done) -> (err, res) ->
@error = err if err
@response = res
@results = res?.body
done?()
@When /^GET "([^"]*)"$/, (resource, done) ->
http.get url resource
.use auth
.end record done
@When /^DEL "([^"]*)"$/, (resource, done) ->
http.del url resource
.use auth
.end record done
post = (resource, payload, done) ->
http.post url resource
.use auth
.send payload
.end record done
@When /^POST "([^"]*)"$/, (resource, payload, done) ->
payload = JSON.parse payload
post resource, payload, done
@When /^POST "([^"]*)":$/, (resource, objects, done) ->
objects = table objects
objects = [objects] unless _.isArray objects
postit = (x, done) -> post resource, x, done
async.each objects, postit, done
@Then t.x("(#{t.text}) #{t.should} (#{t.arg})"), (actual, matcher, expected) ->
p shouldExp { actual, matcher, expected: 'expected' }
# @Then t.x("(#{t.text}) #{t.should}"), (actual, matcher) ->
# p shouldExp { actual, matcher }
# eval shouldExp { actual, matcher }
@Then t.x("(#{t.text}) #{t.should}:"), (actual, matcher, expected) ->
expected = table expected
eval shouldExp { actual, matcher, expected: 'expected' }
module.exports = (config={}) ->
_.merge global.config, config
steps
| true | http = require 'superagent'
async = require 'async'
require './support/globals'
table = require './support/table'
t = require './support/tokens'
{ shouldExp } = require './support/matchers'
steps = ->
url = (res) -> "http://#{config.api}/#{res}"
auth = (req) ->
req.set 'Authorization', "Bearer #{@token or '5PI:PASSWORD:<PASSWORD>END_PI3t'}"
record = (done) -> (err, res) ->
@error = err if err
@response = res
@results = res?.body
done?()
@When /^GET "([^"]*)"$/, (resource, done) ->
http.get url resource
.use auth
.end record done
@When /^DEL "([^"]*)"$/, (resource, done) ->
http.del url resource
.use auth
.end record done
post = (resource, payload, done) ->
http.post url resource
.use auth
.send payload
.end record done
@When /^POST "([^"]*)"$/, (resource, payload, done) ->
payload = JSON.parse payload
post resource, payload, done
@When /^POST "([^"]*)":$/, (resource, objects, done) ->
objects = table objects
objects = [objects] unless _.isArray objects
postit = (x, done) -> post resource, x, done
async.each objects, postit, done
@Then t.x("(#{t.text}) #{t.should} (#{t.arg})"), (actual, matcher, expected) ->
p shouldExp { actual, matcher, expected: 'expected' }
# @Then t.x("(#{t.text}) #{t.should}"), (actual, matcher) ->
# p shouldExp { actual, matcher }
# eval shouldExp { actual, matcher }
@Then t.x("(#{t.text}) #{t.should}:"), (actual, matcher, expected) ->
expected = table expected
eval shouldExp { actual, matcher, expected: 'expected' }
module.exports = (config={}) ->
_.merge global.config, config
steps
|
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998915791511536,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/database/migrations/2021060500003-create-comments.coffee | AbdelhakimRafik/Project | 1 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date June 2021
###
###
Create comments table migration
###
module.exports =
up: (queryInterface, Sequelize) ->
queryInterface.createTable 'Comments',
id:
allowNull: false
autoIncrement: true
primaryKey: true
type: Sequelize.INTEGER
parent:
allowNull: true
type: Sequelize.INTEGER
references:
model: 'Comments'
key: 'id'
content:
allowNull: false
type: Sequelize.STRING
articleId:
allowNull: false
type: Sequelize.INTEGER
references:
model: 'Articles'
key: 'id'
userId:
allowNull: false
type: Sequelize.INTEGER
references:
model: 'Users'
key: 'id'
status:
allowNull: false
type: Sequelize.BOOLEAN
defaultValue: true
createdAt:
allowNull: false
type: Sequelize.DATE
updatedAt:
allowNull: false
type: Sequelize.DATE
down: (queryInterface, Sequelize) ->
queryInterface.dropTable 'Comments' | 179769 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date June 2021
###
###
Create comments table migration
###
module.exports =
up: (queryInterface, Sequelize) ->
queryInterface.createTable 'Comments',
id:
allowNull: false
autoIncrement: true
primaryKey: true
type: Sequelize.INTEGER
parent:
allowNull: true
type: Sequelize.INTEGER
references:
model: 'Comments'
key: 'id'
content:
allowNull: false
type: Sequelize.STRING
articleId:
allowNull: false
type: Sequelize.INTEGER
references:
model: 'Articles'
key: 'id'
userId:
allowNull: false
type: Sequelize.INTEGER
references:
model: 'Users'
key: 'id'
status:
allowNull: false
type: Sequelize.BOOLEAN
defaultValue: true
createdAt:
allowNull: false
type: Sequelize.DATE
updatedAt:
allowNull: false
type: Sequelize.DATE
down: (queryInterface, Sequelize) ->
queryInterface.dropTable 'Comments' | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date June 2021
###
###
Create comments table migration
###
module.exports =
up: (queryInterface, Sequelize) ->
queryInterface.createTable 'Comments',
id:
allowNull: false
autoIncrement: true
primaryKey: true
type: Sequelize.INTEGER
parent:
allowNull: true
type: Sequelize.INTEGER
references:
model: 'Comments'
key: 'id'
content:
allowNull: false
type: Sequelize.STRING
articleId:
allowNull: false
type: Sequelize.INTEGER
references:
model: 'Articles'
key: 'id'
userId:
allowNull: false
type: Sequelize.INTEGER
references:
model: 'Users'
key: 'id'
status:
allowNull: false
type: Sequelize.BOOLEAN
defaultValue: true
createdAt:
allowNull: false
type: Sequelize.DATE
updatedAt:
allowNull: false
type: Sequelize.DATE
down: (queryInterface, Sequelize) ->
queryInterface.dropTable 'Comments' |
[
{
"context": "hema\n\ngenid = (len = 16, prefix = \"\", keyspace = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") ->\n prefix += keyspace.charAt(Math.floor(Math.",
"end": 652,
"score": 0.9995771050453186,
"start": 590,
"tag": "KEY",
"value": "ABCDEFGHIJKLMNOPQRSTUVWXYZa... | servers/api/lib/database.coffee | sitedata/plunker | 340 | mongoose = require("mongoose")
nconf = require("nconf")
mime = require("mime")
url = require("url")
mime = require("mime")
mongoose.connect "mongodb:" + url.format(nconf.get("mongodb"))
connectTimeout = setTimeout(errorConnecting, 1000 * 30)
apiUrl = nconf.get('url:api')
wwwUrl = nconf.get('url:www')
runUrl = nconf.get('url:run')
errorConnecting = ->
console.error "Error connecting to mongodb"
process.exit(1)
mongoose.connection.on "open", -> clearTimeout(connectTimeout)
{Schema, Document, Query} = mongoose
{ObjectId} = Schema
genid = (len = 16, prefix = "", keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
# Change object _id to normal id
Document::toJSON = ->
json = @toObject(json: true, virtuals: true)
json.id = json._id if json._id
delete json._id
delete json.__v
json
Query::paginate = (page, limit, cb) ->
page = Math.max(1, parseInt(page, 10))
limit = Math.max(4, Math.min(12, parseInt(limit, 10))) # [4, 10]
query = @
model = @model
query.skip(page * limit - limit).limit(limit).exec (err, docs) ->
if err then return cb(err, null, null)
model.count query._conditions, (err, count) ->
if err then return cb(err, null, null)
cb(null, docs, count, Math.ceil(count / limit), page)
lastModified = (schema, options = {}) ->
schema.add updated_at: Date
schema.pre "save", (next) ->
@updated_at = new Date
next()
if options.index then schema.path("updated_at").index(options.index)
TokenSchema = new Schema
_id: String
token: String
SessionSchema = new Schema
user:
type: Schema.ObjectId
ref: "User"
last_access: { type: Date, index: true, 'default': Date.now }
public_id: { type: String, 'default': genid }
auth: {}
keychain: [TokenSchema]
SessionSchema.virtual("url").get -> apiUrl + "/sessions/#{@_id}"
SessionSchema.virtual("user_url").get -> apiUrl + "/sessions/#{@_id}/user"
SessionSchema.virtual("age").get -> Date.now() - @last_access
SessionSchema.plugin(lastModified)
SessionSchema.statics.prune = (max_age = 1000 * 60 * 60 * 24 * 7 * 2, cb = ->) ->
@find({}).where("last_access").lt(new Date(Date.now() - max_age)).remove()
mongoose.model "Session", SessionSchema
mongoose.model "User", UserSchema = new Schema
login: { type: String, index: true }
gravatar_id: String
service_id: { type: String, index: { unique: true } }
profile: {}
PlunkFileSchema = new Schema
filename: String
content: String
PlunkFileSchema.virtual("mime").get -> mime.lookup(@filename, "text/plain")
PlunkVoteSchema = new Schema
user: { type: Schema.ObjectId, ref: "User" }
created_at: { type: Date, 'default': Date.now }
PlunkSchema = new Schema
_id: { type: String, index: true }
description: String
score: { type: Number, 'default': Date.now }
thumbs: { type: Number, 'default': 0 }
created_at: { type: Date, 'default': Date.now }
updated_at: { type: Date, 'default': Date.now }
token: { type: String, 'default': genid.bind(null, 16) }
'private': { type: Boolean, 'default': false }
source: {}
files: [PlunkFileSchema]
user: { type: Schema.ObjectId, ref: "User", index: true }
comments: { type: Number, 'default': 0 }
fork_of: { type: String, ref: "Plunk", index: true }
forks: [{ type: String, ref: "Plunk", index: true }]
tags: [{ type: String, index: true}]
voters: [{ type: Schema.ObjectId, ref: "Users", index: true }]
PlunkSchema.index(score: -1, updated_at: -1)
PlunkSchema.index(thumbs: -1, updated_at: -1)
PlunkSchema.virtual("url").get -> apiUrl + "/plunks/#{@_id}"
PlunkSchema.virtual("raw_url").get -> runUrl + "/plunks/#{@_id}/"
PlunkSchema.virtual("comments_url").get -> wwwUrl + "/#{@_id}/comments"
mongoose.model "Plunk", PlunkSchema
PackageVersionSchema = new Schema
semver: String
scripts: [String]
styles: [String]
PackageSchema = new Schema
name: { type: String, match: /^[-_.a-z0-9]+$/i, index: true, unique: true }
description: { type: String }
homepage: String
keywords: [{type: String, index: true}]
versions: [PackageVersionSchema]
maintainers: [{ type: String, index: true }]
mongoose.model "Package", PackageSchema
module.exports = mongoose | 107991 | mongoose = require("mongoose")
nconf = require("nconf")
mime = require("mime")
url = require("url")
mime = require("mime")
mongoose.connect "mongodb:" + url.format(nconf.get("mongodb"))
connectTimeout = setTimeout(errorConnecting, 1000 * 30)
apiUrl = nconf.get('url:api')
wwwUrl = nconf.get('url:www')
runUrl = nconf.get('url:run')
errorConnecting = ->
console.error "Error connecting to mongodb"
process.exit(1)
mongoose.connection.on "open", -> clearTimeout(connectTimeout)
{Schema, Document, Query} = mongoose
{ObjectId} = Schema
genid = (len = 16, prefix = "", keyspace = "<KEY>") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
# Change object _id to normal id
Document::toJSON = ->
json = @toObject(json: true, virtuals: true)
json.id = json._id if json._id
delete json._id
delete json.__v
json
Query::paginate = (page, limit, cb) ->
page = Math.max(1, parseInt(page, 10))
limit = Math.max(4, Math.min(12, parseInt(limit, 10))) # [4, 10]
query = @
model = @model
query.skip(page * limit - limit).limit(limit).exec (err, docs) ->
if err then return cb(err, null, null)
model.count query._conditions, (err, count) ->
if err then return cb(err, null, null)
cb(null, docs, count, Math.ceil(count / limit), page)
lastModified = (schema, options = {}) ->
schema.add updated_at: Date
schema.pre "save", (next) ->
@updated_at = new Date
next()
if options.index then schema.path("updated_at").index(options.index)
TokenSchema = new Schema
_id: String
token: String
SessionSchema = new Schema
user:
type: Schema.ObjectId
ref: "User"
last_access: { type: Date, index: true, 'default': Date.now }
public_id: { type: String, 'default': genid }
auth: {}
keychain: [TokenSchema]
SessionSchema.virtual("url").get -> apiUrl + "/sessions/#{@_id}"
SessionSchema.virtual("user_url").get -> apiUrl + "/sessions/#{@_id}/user"
SessionSchema.virtual("age").get -> Date.now() - @last_access
SessionSchema.plugin(lastModified)
SessionSchema.statics.prune = (max_age = 1000 * 60 * 60 * 24 * 7 * 2, cb = ->) ->
@find({}).where("last_access").lt(new Date(Date.now() - max_age)).remove()
mongoose.model "Session", SessionSchema
mongoose.model "User", UserSchema = new Schema
login: { type: String, index: true }
gravatar_id: String
service_id: { type: String, index: { unique: true } }
profile: {}
PlunkFileSchema = new Schema
filename: String
content: String
PlunkFileSchema.virtual("mime").get -> mime.lookup(@filename, "text/plain")
PlunkVoteSchema = new Schema
user: { type: Schema.ObjectId, ref: "User" }
created_at: { type: Date, 'default': Date.now }
PlunkSchema = new Schema
_id: { type: String, index: true }
description: String
score: { type: Number, 'default': Date.now }
thumbs: { type: Number, 'default': 0 }
created_at: { type: Date, 'default': Date.now }
updated_at: { type: Date, 'default': Date.now }
token: { type: String, 'default': genid.bind(null, 16) }
'private': { type: Boolean, 'default': false }
source: {}
files: [PlunkFileSchema]
user: { type: Schema.ObjectId, ref: "User", index: true }
comments: { type: Number, 'default': 0 }
fork_of: { type: String, ref: "Plunk", index: true }
forks: [{ type: String, ref: "Plunk", index: true }]
tags: [{ type: String, index: true}]
voters: [{ type: Schema.ObjectId, ref: "Users", index: true }]
PlunkSchema.index(score: -1, updated_at: -1)
PlunkSchema.index(thumbs: -1, updated_at: -1)
PlunkSchema.virtual("url").get -> apiUrl + "/plunks/#{@_id}"
PlunkSchema.virtual("raw_url").get -> runUrl + "/plunks/#{@_id}/"
PlunkSchema.virtual("comments_url").get -> wwwUrl + "/#{@_id}/comments"
mongoose.model "Plunk", PlunkSchema
PackageVersionSchema = new Schema
semver: String
scripts: [String]
styles: [String]
PackageSchema = new Schema
name: { type: String, match: /^[-_.a-z0-9]+$/i, index: true, unique: true }
description: { type: String }
homepage: String
keywords: [{type: String, index: true}]
versions: [PackageVersionSchema]
maintainers: [{ type: String, index: true }]
mongoose.model "Package", PackageSchema
module.exports = mongoose | true | mongoose = require("mongoose")
nconf = require("nconf")
mime = require("mime")
url = require("url")
mime = require("mime")
mongoose.connect "mongodb:" + url.format(nconf.get("mongodb"))
connectTimeout = setTimeout(errorConnecting, 1000 * 30)
apiUrl = nconf.get('url:api')
wwwUrl = nconf.get('url:www')
runUrl = nconf.get('url:run')
errorConnecting = ->
console.error "Error connecting to mongodb"
process.exit(1)
mongoose.connection.on "open", -> clearTimeout(connectTimeout)
{Schema, Document, Query} = mongoose
{ObjectId} = Schema
genid = (len = 16, prefix = "", keyspace = "PI:KEY:<KEY>END_PI") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
# Change object _id to normal id
Document::toJSON = ->
json = @toObject(json: true, virtuals: true)
json.id = json._id if json._id
delete json._id
delete json.__v
json
Query::paginate = (page, limit, cb) ->
page = Math.max(1, parseInt(page, 10))
limit = Math.max(4, Math.min(12, parseInt(limit, 10))) # [4, 10]
query = @
model = @model
query.skip(page * limit - limit).limit(limit).exec (err, docs) ->
if err then return cb(err, null, null)
model.count query._conditions, (err, count) ->
if err then return cb(err, null, null)
cb(null, docs, count, Math.ceil(count / limit), page)
lastModified = (schema, options = {}) ->
schema.add updated_at: Date
schema.pre "save", (next) ->
@updated_at = new Date
next()
if options.index then schema.path("updated_at").index(options.index)
TokenSchema = new Schema
_id: String
token: String
SessionSchema = new Schema
user:
type: Schema.ObjectId
ref: "User"
last_access: { type: Date, index: true, 'default': Date.now }
public_id: { type: String, 'default': genid }
auth: {}
keychain: [TokenSchema]
SessionSchema.virtual("url").get -> apiUrl + "/sessions/#{@_id}"
SessionSchema.virtual("user_url").get -> apiUrl + "/sessions/#{@_id}/user"
SessionSchema.virtual("age").get -> Date.now() - @last_access
SessionSchema.plugin(lastModified)
SessionSchema.statics.prune = (max_age = 1000 * 60 * 60 * 24 * 7 * 2, cb = ->) ->
@find({}).where("last_access").lt(new Date(Date.now() - max_age)).remove()
mongoose.model "Session", SessionSchema
mongoose.model "User", UserSchema = new Schema
login: { type: String, index: true }
gravatar_id: String
service_id: { type: String, index: { unique: true } }
profile: {}
PlunkFileSchema = new Schema
filename: String
content: String
PlunkFileSchema.virtual("mime").get -> mime.lookup(@filename, "text/plain")
PlunkVoteSchema = new Schema
user: { type: Schema.ObjectId, ref: "User" }
created_at: { type: Date, 'default': Date.now }
PlunkSchema = new Schema
_id: { type: String, index: true }
description: String
score: { type: Number, 'default': Date.now }
thumbs: { type: Number, 'default': 0 }
created_at: { type: Date, 'default': Date.now }
updated_at: { type: Date, 'default': Date.now }
token: { type: String, 'default': genid.bind(null, 16) }
'private': { type: Boolean, 'default': false }
source: {}
files: [PlunkFileSchema]
user: { type: Schema.ObjectId, ref: "User", index: true }
comments: { type: Number, 'default': 0 }
fork_of: { type: String, ref: "Plunk", index: true }
forks: [{ type: String, ref: "Plunk", index: true }]
tags: [{ type: String, index: true}]
voters: [{ type: Schema.ObjectId, ref: "Users", index: true }]
PlunkSchema.index(score: -1, updated_at: -1)
PlunkSchema.index(thumbs: -1, updated_at: -1)
PlunkSchema.virtual("url").get -> apiUrl + "/plunks/#{@_id}"
PlunkSchema.virtual("raw_url").get -> runUrl + "/plunks/#{@_id}/"
PlunkSchema.virtual("comments_url").get -> wwwUrl + "/#{@_id}/comments"
mongoose.model "Plunk", PlunkSchema
PackageVersionSchema = new Schema
semver: String
scripts: [String]
styles: [String]
PackageSchema = new Schema
name: { type: String, match: /^[-_.a-z0-9]+$/i, index: true, unique: true }
description: { type: String }
homepage: String
keywords: [{type: String, index: true}]
versions: [PackageVersionSchema]
maintainers: [{ type: String, index: true }]
mongoose.model "Package", PackageSchema
module.exports = mongoose |
[
{
"context": "\nAWS_REGION: 'ap-southeast-2'\nAWS_ACCESS_KEY_ID: '1234'\nAWS_SECRET_ACCESS_KEY: '5678'\nAWS_ACCOUNT_ID: '0",
"end": 283,
"score": 0.9995342493057251,
"start": 279,
"tag": "KEY",
"value": "1234"
},
{
"context": "AWS_ACCESS_KEY_ID: '1234'\nAWS_SECRET_ACCESS_KEY: '5678'\... | server/config.cson | BoLaMN/node-client | 0 | serverName: 'server'
restApiRoot: "/api"
host: "localhost"
port: 3012
authHost: 'http://localhost:3010'
sdkHost: 'http://localhost:3012/api'
remoting:
rest:
normalizeHttpPath: false
xml: false
legacyExplorer: false
AWS_REGION: 'ap-southeast-2'
AWS_ACCESS_KEY_ID: '1234'
AWS_SECRET_ACCESS_KEY: '5678'
AWS_ACCOUNT_ID: '0000000' | 205052 | serverName: 'server'
restApiRoot: "/api"
host: "localhost"
port: 3012
authHost: 'http://localhost:3010'
sdkHost: 'http://localhost:3012/api'
remoting:
rest:
normalizeHttpPath: false
xml: false
legacyExplorer: false
AWS_REGION: 'ap-southeast-2'
AWS_ACCESS_KEY_ID: '<KEY>'
AWS_SECRET_ACCESS_KEY: '<KEY>'
AWS_ACCOUNT_ID: '<KEY>' | true | serverName: 'server'
restApiRoot: "/api"
host: "localhost"
port: 3012
authHost: 'http://localhost:3010'
sdkHost: 'http://localhost:3012/api'
remoting:
rest:
normalizeHttpPath: false
xml: false
legacyExplorer: false
AWS_REGION: 'ap-southeast-2'
AWS_ACCESS_KEY_ID: 'PI:KEY:<KEY>END_PI'
AWS_SECRET_ACCESS_KEY: 'PI:KEY:<KEY>END_PI'
AWS_ACCOUNT_ID: 'PI:KEY:<KEY>END_PI' |
[
{
"context": "* grunt-rails-asset-digest\n# * https://github.com/davemo/grunt-rails-asset-digest\n# *\n# * Copyright (c) 20",
"end": 60,
"score": 0.9997022747993469,
"start": 54,
"tag": "USERNAME",
"value": "davemo"
},
{
"context": "runt-rails-asset-digest\n# *\n# * Copyright (c) 201... | tasks/rails_asset_digest.coffee | davemo/grunt-rails-asset-digest | 9 | #
# * grunt-rails-asset-digest
# * https://github.com/davemo/grunt-rails-asset-digest
# *
# * Copyright (c) 2013 David Mosher
# * Licensed under the MIT license.
#
fs = require "fs"
path = require "path"
crypto = require "crypto"
"use strict"
module.exports = (grunt) ->
normalizeAssetPath = (path) ->
unless path.endsWith("/")
path += "/"
path
removeOldKeys = (filepath, obj) ->
keys = Object.keys(obj)
actualKeysToRemove = keys.filter (key) -> obj[key].logical_path == filepath
actualKeysToRemove.forEach (key) -> delete obj[key]
obj
grunt.registerMultiTask "rails_asset_digest", "Generates asset fingerprints and appends to a rails manifest", ->
assetPath = @options(assetPath: "public/assets/").assetPath
algorithm = @options(algorithm: "md5").algorithm
manifestName = @options(manifestName: "manifest.json").manifestName
assetPathRegex = ///^#{normalizeAssetPath(assetPath)}///
manifestPath = "#{normalizeAssetPath(assetPath)}#{manifestName}"
stripAssetPath = (path) ->
path.replace assetPathRegex, ''
if !grunt.file.exists manifestPath
grunt.log.warn "#{manifestPath} did not exist"
false
addedManifestFileEntries = {}
addedManifestAssetEntries = {}
existingManifestFilesData = JSON.parse(grunt.file.read(manifestPath))?.files
existingManifestAssetsData = JSON.parse(grunt.file.read(manifestPath))?.assets
@files.forEach (files) ->
src = files.src[0]
dest = files.dest
unless grunt.file.exists(src)
grunt.log.warn "Source file \"" + src + "\" not found."
return false
algorithmHash = crypto.createHash algorithm
extension = path.extname dest
if extension is ".map"
extension = "#{path.extname(path.basename(dest, extension))}#{extension}"
content = grunt.file.read(src)
digest = algorithmHash.update(content).digest("hex")
stats = fs.statSync(src)
undigestedFilename = "#{path.dirname(dest)}/#{path.basename(dest, extension)}#{extension}"
digestedFilename = "#{path.dirname(dest)}/#{path.basename(dest, extension)}-#{digest}#{extension}"
addedManifestFileEntries[stripAssetPath digestedFilename] = {
mtime: new Date(stats.mtime).toISOString()
digest: digest
size: stats.size
logical_path: stripAssetPath dest
}
addedManifestAssetEntries[stripAssetPath undigestedFilename] = stripAssetPath digestedFilename
if existingManifestFilesData
existingManifestFilesData = removeOldKeys(stripAssetPath(undigestedFilename), existingManifestFilesData)
if existingManifestAssetsData
existingManifestAssetsData = removeOldKeys(stripAssetPath(undigestedFilename), existingManifestAssetsData)
grunt.file.write digestedFilename, content
grunt.log.writeln "File #{digestedFilename} created."
addedCount = Object.keys(addedManifestFileEntries).length
fs.writeFileSync manifestPath, JSON.stringify({
files: { ...addedManifestFileEntries, ...existingManifestFilesData }
assets: { ...addedManifestAssetEntries, ...existingManifestAssetsData }
})
grunt.log.writeln "Added #{addedCount} keys to #{manifestPath} (in .files and .assets), total #{Object.keys(addedManifestFileEntries).length}"
| 95921 | #
# * grunt-rails-asset-digest
# * https://github.com/davemo/grunt-rails-asset-digest
# *
# * Copyright (c) 2013 <NAME>
# * Licensed under the MIT license.
#
fs = require "fs"
path = require "path"
crypto = require "crypto"
"use strict"
module.exports = (grunt) ->
normalizeAssetPath = (path) ->
unless path.endsWith("/")
path += "/"
path
removeOldKeys = (filepath, obj) ->
keys = Object.keys(obj)
actualKeysToRemove = keys.filter (key) -> obj[key].logical_path == filepath
actualKeysToRemove.forEach (key) -> delete obj[key]
obj
grunt.registerMultiTask "rails_asset_digest", "Generates asset fingerprints and appends to a rails manifest", ->
assetPath = @options(assetPath: "public/assets/").assetPath
algorithm = @options(algorithm: "md5").algorithm
manifestName = @options(manifestName: "manifest.json").manifestName
assetPathRegex = ///^#{normalizeAssetPath(assetPath)}///
manifestPath = "#{normalizeAssetPath(assetPath)}#{manifestName}"
stripAssetPath = (path) ->
path.replace assetPathRegex, ''
if !grunt.file.exists manifestPath
grunt.log.warn "#{manifestPath} did not exist"
false
addedManifestFileEntries = {}
addedManifestAssetEntries = {}
existingManifestFilesData = JSON.parse(grunt.file.read(manifestPath))?.files
existingManifestAssetsData = JSON.parse(grunt.file.read(manifestPath))?.assets
@files.forEach (files) ->
src = files.src[0]
dest = files.dest
unless grunt.file.exists(src)
grunt.log.warn "Source file \"" + src + "\" not found."
return false
algorithmHash = crypto.createHash algorithm
extension = path.extname dest
if extension is ".map"
extension = "#{path.extname(path.basename(dest, extension))}#{extension}"
content = grunt.file.read(src)
digest = algorithmHash.update(content).digest("hex")
stats = fs.statSync(src)
undigestedFilename = "#{path.dirname(dest)}/#{path.basename(dest, extension)}#{extension}"
digestedFilename = "#{path.dirname(dest)}/#{path.basename(dest, extension)}-#{digest}#{extension}"
addedManifestFileEntries[stripAssetPath digestedFilename] = {
mtime: new Date(stats.mtime).toISOString()
digest: digest
size: stats.size
logical_path: stripAssetPath dest
}
addedManifestAssetEntries[stripAssetPath undigestedFilename] = stripAssetPath digestedFilename
if existingManifestFilesData
existingManifestFilesData = removeOldKeys(stripAssetPath(undigestedFilename), existingManifestFilesData)
if existingManifestAssetsData
existingManifestAssetsData = removeOldKeys(stripAssetPath(undigestedFilename), existingManifestAssetsData)
grunt.file.write digestedFilename, content
grunt.log.writeln "File #{digestedFilename} created."
addedCount = Object.keys(addedManifestFileEntries).length
fs.writeFileSync manifestPath, JSON.stringify({
files: { ...addedManifestFileEntries, ...existingManifestFilesData }
assets: { ...addedManifestAssetEntries, ...existingManifestAssetsData }
})
grunt.log.writeln "Added #{addedCount} keys to #{manifestPath} (in .files and .assets), total #{Object.keys(addedManifestFileEntries).length}"
| true | #
# * grunt-rails-asset-digest
# * https://github.com/davemo/grunt-rails-asset-digest
# *
# * Copyright (c) 2013 PI:NAME:<NAME>END_PI
# * Licensed under the MIT license.
#
fs = require "fs"
path = require "path"
crypto = require "crypto"
"use strict"
module.exports = (grunt) ->
normalizeAssetPath = (path) ->
unless path.endsWith("/")
path += "/"
path
removeOldKeys = (filepath, obj) ->
keys = Object.keys(obj)
actualKeysToRemove = keys.filter (key) -> obj[key].logical_path == filepath
actualKeysToRemove.forEach (key) -> delete obj[key]
obj
grunt.registerMultiTask "rails_asset_digest", "Generates asset fingerprints and appends to a rails manifest", ->
assetPath = @options(assetPath: "public/assets/").assetPath
algorithm = @options(algorithm: "md5").algorithm
manifestName = @options(manifestName: "manifest.json").manifestName
assetPathRegex = ///^#{normalizeAssetPath(assetPath)}///
manifestPath = "#{normalizeAssetPath(assetPath)}#{manifestName}"
stripAssetPath = (path) ->
path.replace assetPathRegex, ''
if !grunt.file.exists manifestPath
grunt.log.warn "#{manifestPath} did not exist"
false
addedManifestFileEntries = {}
addedManifestAssetEntries = {}
existingManifestFilesData = JSON.parse(grunt.file.read(manifestPath))?.files
existingManifestAssetsData = JSON.parse(grunt.file.read(manifestPath))?.assets
@files.forEach (files) ->
src = files.src[0]
dest = files.dest
unless grunt.file.exists(src)
grunt.log.warn "Source file \"" + src + "\" not found."
return false
algorithmHash = crypto.createHash algorithm
extension = path.extname dest
if extension is ".map"
extension = "#{path.extname(path.basename(dest, extension))}#{extension}"
content = grunt.file.read(src)
digest = algorithmHash.update(content).digest("hex")
stats = fs.statSync(src)
undigestedFilename = "#{path.dirname(dest)}/#{path.basename(dest, extension)}#{extension}"
digestedFilename = "#{path.dirname(dest)}/#{path.basename(dest, extension)}-#{digest}#{extension}"
addedManifestFileEntries[stripAssetPath digestedFilename] = {
mtime: new Date(stats.mtime).toISOString()
digest: digest
size: stats.size
logical_path: stripAssetPath dest
}
addedManifestAssetEntries[stripAssetPath undigestedFilename] = stripAssetPath digestedFilename
if existingManifestFilesData
existingManifestFilesData = removeOldKeys(stripAssetPath(undigestedFilename), existingManifestFilesData)
if existingManifestAssetsData
existingManifestAssetsData = removeOldKeys(stripAssetPath(undigestedFilename), existingManifestAssetsData)
grunt.file.write digestedFilename, content
grunt.log.writeln "File #{digestedFilename} created."
addedCount = Object.keys(addedManifestFileEntries).length
fs.writeFileSync manifestPath, JSON.stringify({
files: { ...addedManifestFileEntries, ...existingManifestFilesData }
assets: { ...addedManifestAssetEntries, ...existingManifestAssetsData }
})
grunt.log.writeln "Added #{addedCount} keys to #{manifestPath} (in .files and .assets), total #{Object.keys(addedManifestFileEntries).length}"
|
[
{
"context": "on : @props.setCurrentFunction\n key : \"invocation-\" + invocation.id\n )\n )\n )\n\n ",
"end": 2085,
"score": 0.6336867809295654,
"start": 2073,
"tag": "KEY",
"value": "invocation-\""
}
] | app/scripts/views/callhistory_view.coffee | philippotto/analyze.js | 2 | ### define
react : React
react-bootstrap : ReactBootstrap
with_react : withReact
./object_viewer : ObjectViewer
./invocation_view : InvocationView
###
R = withReact.R
classSet = React.addons.classSet
pageHeight = 1000
invocationHeight = 32
invocationsPerPage = pageHeight / invocationHeight
CallHistoryView = React.createClass
componentWillMount: ->
@visiblePages = [ 0 ]
componentDidMount: ->
@onScroll()
onScroll: (e) ->
container = @getDOMNode()
bellowFold = Math.ceil(container.scrollTop / pageHeight) or 1
aboveFold = Math.ceil((container.scrollTop + 100 + container.clientHeight) / pageHeight)
visiblePages = _.uniq([ bellowFold, aboveFold ])
if _.isEqual(visiblePages, @visiblePages)
return
@visiblePages = visiblePages
@forceUpdate()
render : ->
callGraph = @props.callGraph
lowest = _.max([ _.first(@visiblePages) - 1, 0 ])
highest = callGraph.getSize() / invocationsPerPage - _.last(@visiblePages)
spacer =
top :
R.div({
style: {height: lowest * pageHeight + "px"}
className: "spacer top-spacer"
}, null)
bottom :
R.div({
style: {height: highest * pageHeight + "px"}
className: "spacer bottom-spacer"
}, null)
className = classSet(
"call-history" : true
"callhistory-narrow" : @props.narrowCallHistory
"fill-area-content" : true,
"flexbox-item-grow" : true
)
root = callGraph.root
if not @counter
@counter = 0
@collectedInvocations = callGraph.collectInvocations(
root
callGraph.getSize()
@props.searchFilter
)
boundForceUpdateFn = @forceUpdate.bind(@)
elements = @visiblePages.map((i) =>
return @collectedInvocations
.slice(invocationsPerPage * (i - 1), invocationsPerPage * i)
.map((invocation) =>
InvocationView(
invocation : invocation
forceUpdate : boundForceUpdateFn
setCurrentFunction : @props.setCurrentFunction
key : "invocation-" + invocation.id
)
)
)
R.div {className, onScroll: @onScroll},
spacer.top
elements
spacer.bottom
| 91339 | ### define
react : React
react-bootstrap : ReactBootstrap
with_react : withReact
./object_viewer : ObjectViewer
./invocation_view : InvocationView
###
R = withReact.R
classSet = React.addons.classSet
pageHeight = 1000
invocationHeight = 32
invocationsPerPage = pageHeight / invocationHeight
CallHistoryView = React.createClass
componentWillMount: ->
@visiblePages = [ 0 ]
componentDidMount: ->
@onScroll()
onScroll: (e) ->
container = @getDOMNode()
bellowFold = Math.ceil(container.scrollTop / pageHeight) or 1
aboveFold = Math.ceil((container.scrollTop + 100 + container.clientHeight) / pageHeight)
visiblePages = _.uniq([ bellowFold, aboveFold ])
if _.isEqual(visiblePages, @visiblePages)
return
@visiblePages = visiblePages
@forceUpdate()
render : ->
callGraph = @props.callGraph
lowest = _.max([ _.first(@visiblePages) - 1, 0 ])
highest = callGraph.getSize() / invocationsPerPage - _.last(@visiblePages)
spacer =
top :
R.div({
style: {height: lowest * pageHeight + "px"}
className: "spacer top-spacer"
}, null)
bottom :
R.div({
style: {height: highest * pageHeight + "px"}
className: "spacer bottom-spacer"
}, null)
className = classSet(
"call-history" : true
"callhistory-narrow" : @props.narrowCallHistory
"fill-area-content" : true,
"flexbox-item-grow" : true
)
root = callGraph.root
if not @counter
@counter = 0
@collectedInvocations = callGraph.collectInvocations(
root
callGraph.getSize()
@props.searchFilter
)
boundForceUpdateFn = @forceUpdate.bind(@)
elements = @visiblePages.map((i) =>
return @collectedInvocations
.slice(invocationsPerPage * (i - 1), invocationsPerPage * i)
.map((invocation) =>
InvocationView(
invocation : invocation
forceUpdate : boundForceUpdateFn
setCurrentFunction : @props.setCurrentFunction
key : "<KEY> + invocation.id
)
)
)
R.div {className, onScroll: @onScroll},
spacer.top
elements
spacer.bottom
| true | ### define
react : React
react-bootstrap : ReactBootstrap
with_react : withReact
./object_viewer : ObjectViewer
./invocation_view : InvocationView
###
R = withReact.R
classSet = React.addons.classSet
pageHeight = 1000
invocationHeight = 32
invocationsPerPage = pageHeight / invocationHeight
CallHistoryView = React.createClass
componentWillMount: ->
@visiblePages = [ 0 ]
componentDidMount: ->
@onScroll()
onScroll: (e) ->
container = @getDOMNode()
bellowFold = Math.ceil(container.scrollTop / pageHeight) or 1
aboveFold = Math.ceil((container.scrollTop + 100 + container.clientHeight) / pageHeight)
visiblePages = _.uniq([ bellowFold, aboveFold ])
if _.isEqual(visiblePages, @visiblePages)
return
@visiblePages = visiblePages
@forceUpdate()
render : ->
callGraph = @props.callGraph
lowest = _.max([ _.first(@visiblePages) - 1, 0 ])
highest = callGraph.getSize() / invocationsPerPage - _.last(@visiblePages)
spacer =
top :
R.div({
style: {height: lowest * pageHeight + "px"}
className: "spacer top-spacer"
}, null)
bottom :
R.div({
style: {height: highest * pageHeight + "px"}
className: "spacer bottom-spacer"
}, null)
className = classSet(
"call-history" : true
"callhistory-narrow" : @props.narrowCallHistory
"fill-area-content" : true,
"flexbox-item-grow" : true
)
root = callGraph.root
if not @counter
@counter = 0
@collectedInvocations = callGraph.collectInvocations(
root
callGraph.getSize()
@props.searchFilter
)
boundForceUpdateFn = @forceUpdate.bind(@)
elements = @visiblePages.map((i) =>
return @collectedInvocations
.slice(invocationsPerPage * (i - 1), invocationsPerPage * i)
.map((invocation) =>
InvocationView(
invocation : invocation
forceUpdate : boundForceUpdateFn
setCurrentFunction : @props.setCurrentFunction
key : "PI:KEY:<KEY>END_PI + invocation.id
)
)
)
R.div {className, onScroll: @onScroll},
spacer.top
elements
spacer.bottom
|
[
{
"context": "l this, db_command, options, callback\n\n\t\t\t\tkey = \"mongo-requests.#{collection}.#{type}\"\n\t\t\t\tif db_command.query?\n\t\t\t\t\tquery = Object.keys",
"end": 1030,
"score": 0.9443138837814331,
"start": 993,
"tag": "KEY",
"value": "mongo-requests.#{collection}.#{type}\""... | mongodb.coffee | j-licht/metrics-module | 0 | module.exports =
monitor: (mongodb_require_path, logger) ->
try
# for the v1 driver the methods to wrap are in the mongodb
# module in lib/mongodb/db.js
mongodb = require("#{mongodb_require_path}")
try
# for the v2 driver the relevant methods are in the mongodb-core
# module in lib/topologies/{server,replset,mongos}.js
v2_path = mongodb_require_path.replace(/\/mongodb$/, '/mongodb-core')
mongodbCore = require(v2_path)
Metrics = require("./metrics")
monitorMethod = (base, method, type) ->
return unless base?
return unless (_method = base[method])?
arglen = _method.length
mongo_driver_v1_wrapper = (db_command, options, callback) ->
if (typeof callback == 'undefined')
callback = options
options = {}
collection = db_command.collectionName
if collection.match(/\$cmd$/)
# Ignore noisy command methods like authenticating, ismaster and ping
return _method.call this, db_command, options, callback
key = "mongo-requests.#{collection}.#{type}"
if db_command.query?
query = Object.keys(db_command.query).sort().join("_")
key += "." + query
timer = new Metrics.Timer("mongo", {collection: collection, query:query})
start = new Date()
_method.call this, db_command, options, () ->
timer.done()
time = new Date() - start
logger.log
query: db_command.query
query_type: type
collection: collection
"response-time": new Date() - start
"mongo request"
callback.apply this, arguments
mongo_driver_v2_wrapper = (ns, ops, options, callback) ->
if (typeof callback == 'undefined')
callback = options
options = {}
if ns.match(/\$cmd$/)
# Ignore noisy command methods like authenticating, ismaster and ping
return _method.call this, ns, ops, options, callback
key = "mongo-requests.#{ns}.#{type}"
if ops[0].q? # ops[0].q
query = Object.keys(ops[0].q).sort().join("_")
key += "." + query
timer = new Metrics.Timer(key)
start = new Date()
_method.call this, ns, ops, options, () ->
timer.done()
time = new Date() - start
logger.log
query: ops[0].q
query_type: type
collection: ns
"response-time": new Date() - start
"mongo request"
callback.apply this, arguments
if arglen == 3
base[method] = mongo_driver_v1_wrapper
else if arglen == 4
base[method] = mongo_driver_v2_wrapper
monitorMethod(mongodb?.Db.prototype, "_executeQueryCommand", "query")
monitorMethod(mongodb?.Db.prototype, "_executeRemoveCommand", "remove")
monitorMethod(mongodb?.Db.prototype, "_executeInsertCommand", "insert")
monitorMethod(mongodb?.Db.prototype, "_executeUpdateCommand", "update")
monitorMethod(mongodbCore?.Server.prototype, "command", "command")
monitorMethod(mongodbCore?.Server.prototype, "remove", "remove")
monitorMethod(mongodbCore?.Server.prototype, "insert", "insert")
monitorMethod(mongodbCore?.Server.prototype, "update", "update")
monitorMethod(mongodbCore?.ReplSet.prototype, "command", "command")
monitorMethod(mongodbCore?.ReplSet.prototype, "remove", "remove")
monitorMethod(mongodbCore?.ReplSet.prototype, "insert", "insert")
monitorMethod(mongodbCore?.ReplSet.prototype, "update", "update")
monitorMethod(mongodbCore?.Mongos.prototype, "command", "command")
monitorMethod(mongodbCore?.Mongos.prototype, "remove", "remove")
monitorMethod(mongodbCore?.Mongos.prototype, "insert", "insert")
monitorMethod(mongodbCore?.Mongos.prototype, "update", "update")
| 86003 | module.exports =
monitor: (mongodb_require_path, logger) ->
try
# for the v1 driver the methods to wrap are in the mongodb
# module in lib/mongodb/db.js
mongodb = require("#{mongodb_require_path}")
try
# for the v2 driver the relevant methods are in the mongodb-core
# module in lib/topologies/{server,replset,mongos}.js
v2_path = mongodb_require_path.replace(/\/mongodb$/, '/mongodb-core')
mongodbCore = require(v2_path)
Metrics = require("./metrics")
monitorMethod = (base, method, type) ->
return unless base?
return unless (_method = base[method])?
arglen = _method.length
mongo_driver_v1_wrapper = (db_command, options, callback) ->
if (typeof callback == 'undefined')
callback = options
options = {}
collection = db_command.collectionName
if collection.match(/\$cmd$/)
# Ignore noisy command methods like authenticating, ismaster and ping
return _method.call this, db_command, options, callback
key = "<KEY>
if db_command.query?
query = Object.keys(db_command.query).sort().join("_")
key += "." + query
timer = new Metrics.Timer("mongo", {collection: collection, query:query})
start = new Date()
_method.call this, db_command, options, () ->
timer.done()
time = new Date() - start
logger.log
query: db_command.query
query_type: type
collection: collection
"response-time": new Date() - start
"mongo request"
callback.apply this, arguments
mongo_driver_v2_wrapper = (ns, ops, options, callback) ->
if (typeof callback == 'undefined')
callback = options
options = {}
if ns.match(/\$cmd$/)
# Ignore noisy command methods like authenticating, ismaster and ping
return _method.call this, ns, ops, options, callback
key = "<KEY>
if ops[0].q? # ops[0].q
query = Object.keys(ops[0].q).sort().join("_")
key += "." + query
timer = new Metrics.Timer(key)
start = new Date()
_method.call this, ns, ops, options, () ->
timer.done()
time = new Date() - start
logger.log
query: ops[0].q
query_type: type
collection: ns
"response-time": new Date() - start
"mongo request"
callback.apply this, arguments
if arglen == 3
base[method] = mongo_driver_v1_wrapper
else if arglen == 4
base[method] = mongo_driver_v2_wrapper
monitorMethod(mongodb?.Db.prototype, "_executeQueryCommand", "query")
monitorMethod(mongodb?.Db.prototype, "_executeRemoveCommand", "remove")
monitorMethod(mongodb?.Db.prototype, "_executeInsertCommand", "insert")
monitorMethod(mongodb?.Db.prototype, "_executeUpdateCommand", "update")
monitorMethod(mongodbCore?.Server.prototype, "command", "command")
monitorMethod(mongodbCore?.Server.prototype, "remove", "remove")
monitorMethod(mongodbCore?.Server.prototype, "insert", "insert")
monitorMethod(mongodbCore?.Server.prototype, "update", "update")
monitorMethod(mongodbCore?.ReplSet.prototype, "command", "command")
monitorMethod(mongodbCore?.ReplSet.prototype, "remove", "remove")
monitorMethod(mongodbCore?.ReplSet.prototype, "insert", "insert")
monitorMethod(mongodbCore?.ReplSet.prototype, "update", "update")
monitorMethod(mongodbCore?.Mongos.prototype, "command", "command")
monitorMethod(mongodbCore?.Mongos.prototype, "remove", "remove")
monitorMethod(mongodbCore?.Mongos.prototype, "insert", "insert")
monitorMethod(mongodbCore?.Mongos.prototype, "update", "update")
| true | module.exports =
monitor: (mongodb_require_path, logger) ->
try
# for the v1 driver the methods to wrap are in the mongodb
# module in lib/mongodb/db.js
mongodb = require("#{mongodb_require_path}")
try
# for the v2 driver the relevant methods are in the mongodb-core
# module in lib/topologies/{server,replset,mongos}.js
v2_path = mongodb_require_path.replace(/\/mongodb$/, '/mongodb-core')
mongodbCore = require(v2_path)
Metrics = require("./metrics")
monitorMethod = (base, method, type) ->
return unless base?
return unless (_method = base[method])?
arglen = _method.length
mongo_driver_v1_wrapper = (db_command, options, callback) ->
if (typeof callback == 'undefined')
callback = options
options = {}
collection = db_command.collectionName
if collection.match(/\$cmd$/)
# Ignore noisy command methods like authenticating, ismaster and ping
return _method.call this, db_command, options, callback
key = "PI:KEY:<KEY>END_PI
if db_command.query?
query = Object.keys(db_command.query).sort().join("_")
key += "." + query
timer = new Metrics.Timer("mongo", {collection: collection, query:query})
start = new Date()
_method.call this, db_command, options, () ->
timer.done()
time = new Date() - start
logger.log
query: db_command.query
query_type: type
collection: collection
"response-time": new Date() - start
"mongo request"
callback.apply this, arguments
mongo_driver_v2_wrapper = (ns, ops, options, callback) ->
if (typeof callback == 'undefined')
callback = options
options = {}
if ns.match(/\$cmd$/)
# Ignore noisy command methods like authenticating, ismaster and ping
return _method.call this, ns, ops, options, callback
key = "PI:KEY:<KEY>END_PI
if ops[0].q? # ops[0].q
query = Object.keys(ops[0].q).sort().join("_")
key += "." + query
timer = new Metrics.Timer(key)
start = new Date()
_method.call this, ns, ops, options, () ->
timer.done()
time = new Date() - start
logger.log
query: ops[0].q
query_type: type
collection: ns
"response-time": new Date() - start
"mongo request"
callback.apply this, arguments
if arglen == 3
base[method] = mongo_driver_v1_wrapper
else if arglen == 4
base[method] = mongo_driver_v2_wrapper
monitorMethod(mongodb?.Db.prototype, "_executeQueryCommand", "query")
monitorMethod(mongodb?.Db.prototype, "_executeRemoveCommand", "remove")
monitorMethod(mongodb?.Db.prototype, "_executeInsertCommand", "insert")
monitorMethod(mongodb?.Db.prototype, "_executeUpdateCommand", "update")
monitorMethod(mongodbCore?.Server.prototype, "command", "command")
monitorMethod(mongodbCore?.Server.prototype, "remove", "remove")
monitorMethod(mongodbCore?.Server.prototype, "insert", "insert")
monitorMethod(mongodbCore?.Server.prototype, "update", "update")
monitorMethod(mongodbCore?.ReplSet.prototype, "command", "command")
monitorMethod(mongodbCore?.ReplSet.prototype, "remove", "remove")
monitorMethod(mongodbCore?.ReplSet.prototype, "insert", "insert")
monitorMethod(mongodbCore?.ReplSet.prototype, "update", "update")
monitorMethod(mongodbCore?.Mongos.prototype, "command", "command")
monitorMethod(mongodbCore?.Mongos.prototype, "remove", "remove")
monitorMethod(mongodbCore?.Mongos.prototype, "insert", "insert")
monitorMethod(mongodbCore?.Mongos.prototype, "update", "update")
|
[
{
"context": "---------------------------------------------\n@[ \"oneliners\" ] = ( T, done ) ->\n ICQL = require",
"end": 1960,
"score": 0.9988803863525391,
"start": 1951,
"tag": "USERNAME",
"value": "oneliners"
},
{
"context": "µ44430', db.create_demo_table_middle\n ... | dev/icql/src/tests/basics.test.coffee | loveencounterflow/hengist | 0 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'ICQL/TESTS/MAIN'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
#...........................................................................................................
test = require '../../../../apps/guy-test'
jr = JSON.stringify
{ inspect, } = require 'util'
xrpr = ( x ) -> inspect x, { colors: yes, breakLength: Infinity, maxArrayLength: Infinity, depth: Infinity, }
xrpr2 = ( x ) -> inspect x, { colors: yes, breakLength: 20, maxArrayLength: Infinity, depth: Infinity, }
#...........................................................................................................
PATH = require 'path'
#-----------------------------------------------------------------------------------------------------------
get_icql_settings = ( remove_db = false ) ->
R = {}
R.connector = require 'better-sqlite3'
R.db_path = '/tmp/icql.db'
R.icql_path = PATH.resolve PATH.join __dirname, '../../../../assets/icql/test.icql'
if remove_db
try
( require 'fs' ).unlinkSync R.db_path
catch error
throw error unless ( error.code is 'ENOENT' )
return R
#-----------------------------------------------------------------------------------------------------------
@[ "oneliners" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
IC = require '../../../../apps/intercourse'
PATH = require 'path'
intercourse_path = require.resolve '../../../../apps/intercourse'
demo_path = PATH.join intercourse_path, '../../demos/sqlite-demo.icql'
debug '22999', demo_path
db = {}
ICQL.definitions_from_path_sync db, demo_path
debug '33442', db
return done()
throw new Error "sorry no tests as yet"
probes_and_matchers = [
# ["procedure foobar: some text\n illegal line",null,'illegal follow-up after one-liner']
["procedure foobar: some text",{"foobar":{"type":"procedure","null":{"text":"some text\n","location":{"line_nr":1},"kenning":"null","type":"procedure"}}},null]
["procedure foobar(): some text",{"foobar":{"type":"procedure","()":{"text":"some text\n","location":{"line_nr":1},"kenning":"()","type":"procedure","signature":[]}}},null]
["procedure foobar( first ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar(first): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar( first, ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar(first,): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar( first, second ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
["procedure foobar( first, second, ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
]
#.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
# # try
# result = await IC.read_definitions_from_text probe
# # catch error
# # return resolve error
# # debug '29929', xrpr2 result
# resolve result
done()
#-----------------------------------------------------------------------------------------------------------
@[ "parameters are expanded in procedures" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
db = ICQL.bind get_icql_settings()
# debug 'µ44433', db
db.create_demo_table()
#.........................................................................................................
db.$.function 'echo', { deterministic: false, varargs: true }, ( P... ) -> urge ( CND.grey 'DB' ), P...; null
db.$.function 'e', { deterministic: false, varargs: false }, ( x ) -> urge ( CND.grey 'DB' ), rpr x; x
#.........................................................................................................
debug db.$.all_rows db.read_demo_rows()
debug db.$.all_rows db.select_by_rowid { rowid: 2, }
try
db.update_by_rowid { rowid: 2, status: 'bar', }
catch error
debug 'µ33555', error.code
debug 'µ33555', error.name
debug 'µ33555', ( k for k of error )
debug 'µ33555', error.message
# TypeError
process.exit 1
debug db.$.all_rows db.select_by_rowid { rowid: 2, }
#.........................................................................................................
# statement = db.$.prepare "select rowid, * from demo where rowid = $rowid;"
# info 'µ00908', [ ( statement.iterate { rowid: 2, } )..., ]
# # statement = db.$.prepare "select 42; select rowid, * from demo where rowid = $rowid;"
# # statement = db.$.prepare "update demo set status = 'yes!' where rowid = $rowid;"
# # info 'µ00908', statement.run { rowid: 2, }
# info 'µ00908', db.$.run "update demo set status = 'yes!' where rowid = $rowid;", { rowid: 2, extra: true, }
# debug db.$.all_rows db.select_by_rowid { rowid: 2, }
# probes_and_matchers = [
# # ["procedure foobar: some text\n illegal line",null,'illegal follow-up after one-liner']
# ["procedure foobar: some text",{"foobar":{"type":"procedure","null":{"text":"some text\n","location":{"line_nr":1},"kenning":"null","type":"procedure"}}},null]
# ["procedure foobar(): some text",{"foobar":{"type":"procedure","()":{"text":"some text\n","location":{"line_nr":1},"kenning":"()","type":"procedure","signature":[]}}},null]
# ["procedure foobar( first ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar(first): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar( first, ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar(first,): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar( first, second ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
# ["procedure foobar( first, second, ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
# ]
#.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
# # try
# result = await IC.read_definitions_from_text probe
# # catch error
# # return resolve error
# # debug '29929', xrpr2 result
# resolve result
done()
#-----------------------------------------------------------------------------------------------------------
@[ "as_sql" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
PATH = require 'path'
db = ICQL.bind get_icql_settings()
probes_and_matchers = [
[true,'1',]
[false,'0',]
[42,'42',]
['text',"'text'",]
["text with 'quotes'","'text with ''quotes'''",]
[[1,2,3],"'[1,2,3]'",]
[[],"'[]'",]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
resolve db.$.as_sql probe
done()
#-----------------------------------------------------------------------------------------------------------
@[ "interpolate" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
PATH = require 'path'
db = ICQL.bind get_icql_settings()
probes_and_matchers = [
[["foo, $bar, baz",{bar:42,}],"foo, 42, baz"]
[["select * from t where d = $d;",{bar:42,}],null,"unable to express 'undefined' as SQL literal"]
[["select * from t where d = $d;",{d:true,}],"select * from t where d = 1;"]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
[ sql, Q, ] = probe
resolve db.$.interpolate sql, Q
done()
#-----------------------------------------------------------------------------------------------------------
@[ "fragments return interpolated source text" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
db = ICQL.bind get_icql_settings()
# debug 'µ44430', db
# debug 'µ44430', db.$.sql
# debug 'µ44430', db.create_demo_table_middle
key = 'somekey'
value = 'somevalue'
status = 'somestatus'
first = db.create_demo_table_first()
middle = db.create_demo_table_middle { key, value, status, }
last = db.create_demo_table_last()
T.eq first, "drop table if exists demo;\ncreate table demo (\n key text,\n value text,\n status text );\ninsert into demo values"
T.eq middle, "( 'somekey', 'somevalue', 'somestatus' )"
T.eq last, ";"
done()
# #-----------------------------------------------------------------------------------------------------------
# @[ "x" ] = ( T, done ) ->
# T.eq 42, 42
# T.eq 42, 43
# done()
# return null
#-----------------------------------------------------------------------------------------------------------
@[ "foreign keys" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
settings.echo = true
db = ICQL.bind settings
db.create_tables_with_foreign_key()
db.populate_tables_with_foreign_key()
rows = db.$.all_rows db.select_from_tables_with_foreign_key()
T.eq rows, [{"id":"id1","key":"foo"},{"id":"id2","key":"foo"},{"id":"id3","key":"other"},{"id":"id4","key":"bar"}]
db.drop_tables_with_foreign_key()
#---------------------------------------------------------------------------------------------------------
db = ICQL.bind settings
db.create_tables_with_foreign_key()
T.eq [], db.$.dependencies_of 't1'
T.eq [ 't1' ], db.$.dependencies_of 't2'
#---------------------------------------------------------------------------------------------------------
T.eq db.$.get_toposort(), [
{ name: 't2', type: 'table', sql: 'CREATE TABLE t2 (\n id text not null unique primary key,\n key text not null references t1 ( key ) )' },
{ name: 't1', type: 'table', sql: 'CREATE TABLE t1 (\n key text not null unique primary key )' },
{ name: 'sqlite_autoindex_t1_1', type: 'index', sql: null },
{ name: 'sqlite_autoindex_t2_1', type: 'index', sql: null } ]
#---------------------------------------------------------------------------------------------------------
db.populate_tables_with_foreign_key()
T.eq rows, [{"id":"id1","key":"foo"},{"id":"id2","key":"foo"},{"id":"id3","key":"other"},{"id":"id4","key":"bar"}]
db.$.clear()
T.eq db.$.get_toposort(), []
# db.drop_tables_with_foreign_key()
done()
#-----------------------------------------------------------------------------------------------------------
@[ "toposort with schema" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
settings.echo = true
db = ICQL.bind settings
schema = 'subdb'
db.$.attach ':memory:', schema
#.........................................................................................................
T.eq db.$.list_schemas(), [
{ seq: 0, name: 'main', file: '/tmp/icql.db' },
{ seq: 2, name: 'subdb', file: '' } ]
T.eq ( db.$.get_toposort schema ), []
#.........................................................................................................
template = db.create_tables_with_foreign_key_frg()
### TAINT use compile-time interpolation as soon as available ###
sql = template.replace /\{schema\}/g, db.$.as_identifier schema
db.$.execute sql
#.........................................................................................................
do =>
d = db.$.list_objects()
T.eq d, []
#.........................................................................................................
do =>
d = db.$.list_objects schema
d = ( e for e in d when e.type is 'table' )
for e in d
delete e.sql
T.eq d, [ { type: 'table', name: 'table_one' }, { type: 'table', name: 'table_two' } ]
#.........................................................................................................
T.eq ( db.$.get_toposort() ), []
T.eq ( db.$.get_toposort schema ), [
{ name: 'table_one', type: 'table', sql: 'CREATE TABLE table_one (\n key text not null unique primary key )' },
{ name: 'table_two', type: 'table', sql: 'CREATE TABLE table_two (\n id text not null unique primary key,\n key text not null references table_one ( key ) )' },
{ name: 'sqlite_autoindex_table_one_1', type: 'index', sql: null },
{ name: 'sqlite_autoindex_table_two_1', type: 'index', sql: null } ]
#.........................................................................................................
done()
#-----------------------------------------------------------------------------------------------------------
@[ "_error messages" ] = ( T, done ) ->
### demo to show that printout gets limited for long statements ###
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
db = ICQL.bind settings
db.create_demo_table()
sql = "select
1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018,
1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037,
1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056,
1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075,
1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094,
1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113,
1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132,
1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151,
1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170,
1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189,
1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208,
1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227,
1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246,
1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265,
1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284,
1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303,
1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322,
1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341,
1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360,
from demo;"
try
db.$.query sql
catch error
null
done()
############################################################################################################
unless module.parent?
test @
# test @[ "load_extension" ]
# test @[ "foreign keys" ]
# test @[ "toposort with schema" ]
# @[ "toposort with schema" ]()
| 225480 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'ICQL/TESTS/MAIN'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
#...........................................................................................................
test = require '../../../../apps/guy-test'
jr = JSON.stringify
{ inspect, } = require 'util'
xrpr = ( x ) -> inspect x, { colors: yes, breakLength: Infinity, maxArrayLength: Infinity, depth: Infinity, }
xrpr2 = ( x ) -> inspect x, { colors: yes, breakLength: 20, maxArrayLength: Infinity, depth: Infinity, }
#...........................................................................................................
PATH = require 'path'
#-----------------------------------------------------------------------------------------------------------
get_icql_settings = ( remove_db = false ) ->
R = {}
R.connector = require 'better-sqlite3'
R.db_path = '/tmp/icql.db'
R.icql_path = PATH.resolve PATH.join __dirname, '../../../../assets/icql/test.icql'
if remove_db
try
( require 'fs' ).unlinkSync R.db_path
catch error
throw error unless ( error.code is 'ENOENT' )
return R
#-----------------------------------------------------------------------------------------------------------
@[ "oneliners" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
IC = require '../../../../apps/intercourse'
PATH = require 'path'
intercourse_path = require.resolve '../../../../apps/intercourse'
demo_path = PATH.join intercourse_path, '../../demos/sqlite-demo.icql'
debug '22999', demo_path
db = {}
ICQL.definitions_from_path_sync db, demo_path
debug '33442', db
return done()
throw new Error "sorry no tests as yet"
probes_and_matchers = [
# ["procedure foobar: some text\n illegal line",null,'illegal follow-up after one-liner']
["procedure foobar: some text",{"foobar":{"type":"procedure","null":{"text":"some text\n","location":{"line_nr":1},"kenning":"null","type":"procedure"}}},null]
["procedure foobar(): some text",{"foobar":{"type":"procedure","()":{"text":"some text\n","location":{"line_nr":1},"kenning":"()","type":"procedure","signature":[]}}},null]
["procedure foobar( first ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar(first): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar( first, ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar(first,): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar( first, second ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
["procedure foobar( first, second, ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
]
#.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
# # try
# result = await IC.read_definitions_from_text probe
# # catch error
# # return resolve error
# # debug '29929', xrpr2 result
# resolve result
done()
#-----------------------------------------------------------------------------------------------------------
@[ "parameters are expanded in procedures" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
db = ICQL.bind get_icql_settings()
# debug 'µ44433', db
db.create_demo_table()
#.........................................................................................................
db.$.function 'echo', { deterministic: false, varargs: true }, ( P... ) -> urge ( CND.grey 'DB' ), P...; null
db.$.function 'e', { deterministic: false, varargs: false }, ( x ) -> urge ( CND.grey 'DB' ), rpr x; x
#.........................................................................................................
debug db.$.all_rows db.read_demo_rows()
debug db.$.all_rows db.select_by_rowid { rowid: 2, }
try
db.update_by_rowid { rowid: 2, status: 'bar', }
catch error
debug 'µ33555', error.code
debug 'µ33555', error.name
debug 'µ33555', ( k for k of error )
debug 'µ33555', error.message
# TypeError
process.exit 1
debug db.$.all_rows db.select_by_rowid { rowid: 2, }
#.........................................................................................................
# statement = db.$.prepare "select rowid, * from demo where rowid = $rowid;"
# info 'µ00908', [ ( statement.iterate { rowid: 2, } )..., ]
# # statement = db.$.prepare "select 42; select rowid, * from demo where rowid = $rowid;"
# # statement = db.$.prepare "update demo set status = 'yes!' where rowid = $rowid;"
# # info 'µ00908', statement.run { rowid: 2, }
# info 'µ00908', db.$.run "update demo set status = 'yes!' where rowid = $rowid;", { rowid: 2, extra: true, }
# debug db.$.all_rows db.select_by_rowid { rowid: 2, }
# probes_and_matchers = [
# # ["procedure foobar: some text\n illegal line",null,'illegal follow-up after one-liner']
# ["procedure foobar: some text",{"foobar":{"type":"procedure","null":{"text":"some text\n","location":{"line_nr":1},"kenning":"null","type":"procedure"}}},null]
# ["procedure foobar(): some text",{"foobar":{"type":"procedure","()":{"text":"some text\n","location":{"line_nr":1},"kenning":"()","type":"procedure","signature":[]}}},null]
# ["procedure foobar( first ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar(first): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar( first, ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar(first,): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar( first, second ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
# ["procedure foobar( first, second, ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
# ]
#.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
# # try
# result = await IC.read_definitions_from_text probe
# # catch error
# # return resolve error
# # debug '29929', xrpr2 result
# resolve result
done()
#-----------------------------------------------------------------------------------------------------------
@[ "as_sql" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
PATH = require 'path'
db = ICQL.bind get_icql_settings()
probes_and_matchers = [
[true,'1',]
[false,'0',]
[42,'42',]
['text',"'text'",]
["text with 'quotes'","'text with ''quotes'''",]
[[1,2,3],"'[1,2,3]'",]
[[],"'[]'",]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
resolve db.$.as_sql probe
done()
#-----------------------------------------------------------------------------------------------------------
@[ "interpolate" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
PATH = require 'path'
db = ICQL.bind get_icql_settings()
probes_and_matchers = [
[["foo, $bar, baz",{bar:42,}],"foo, 42, baz"]
[["select * from t where d = $d;",{bar:42,}],null,"unable to express 'undefined' as SQL literal"]
[["select * from t where d = $d;",{d:true,}],"select * from t where d = 1;"]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
[ sql, Q, ] = probe
resolve db.$.interpolate sql, Q
done()
#-----------------------------------------------------------------------------------------------------------
@[ "fragments return interpolated source text" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
db = ICQL.bind get_icql_settings()
# debug 'µ44430', db
# debug 'µ44430', db.$.sql
# debug 'µ44430', db.create_demo_table_middle
key = '<KEY>'
value = 'somevalue'
status = 'somestatus'
first = db.create_demo_table_first()
middle = db.create_demo_table_middle { key, value, status, }
last = db.create_demo_table_last()
T.eq first, "drop table if exists demo;\ncreate table demo (\n key text,\n value text,\n status text );\ninsert into demo values"
T.eq middle, "( 'somekey', 'somevalue', 'somestatus' )"
T.eq last, ";"
done()
# #-----------------------------------------------------------------------------------------------------------
# @[ "x" ] = ( T, done ) ->
# T.eq 42, 42
# T.eq 42, 43
# done()
# return null
#-----------------------------------------------------------------------------------------------------------
@[ "foreign keys" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
settings.echo = true
db = ICQL.bind settings
db.create_tables_with_foreign_key()
db.populate_tables_with_foreign_key()
rows = db.$.all_rows db.select_from_tables_with_foreign_key()
T.eq rows, [{"id":"id1","key":"foo"},{"id":"id2","key":"foo"},{"id":"id3","key":"other"},{"id":"id4","key":"bar"}]
db.drop_tables_with_foreign_key()
#---------------------------------------------------------------------------------------------------------
db = ICQL.bind settings
db.create_tables_with_foreign_key()
T.eq [], db.$.dependencies_of 't1'
T.eq [ 't1' ], db.$.dependencies_of 't2'
#---------------------------------------------------------------------------------------------------------
T.eq db.$.get_toposort(), [
{ name: 't2', type: 'table', sql: 'CREATE TABLE t2 (\n id text not null unique primary key,\n key text not null references t1 ( key ) )' },
{ name: 't1', type: 'table', sql: 'CREATE TABLE t1 (\n key text not null unique primary key )' },
{ name: 'sqlite_autoindex_t1_1', type: 'index', sql: null },
{ name: 'sqlite_autoindex_t2_1', type: 'index', sql: null } ]
#---------------------------------------------------------------------------------------------------------
db.populate_tables_with_foreign_key()
T.eq rows, [{"id":"id1","key":"foo"},{"id":"id2","key":"foo"},{"id":"id3","key":"other"},{"id":"id4","key":"bar"}]
db.$.clear()
T.eq db.$.get_toposort(), []
# db.drop_tables_with_foreign_key()
done()
#-----------------------------------------------------------------------------------------------------------
@[ "toposort with schema" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
settings.echo = true
db = ICQL.bind settings
schema = 'subdb'
db.$.attach ':memory:', schema
#.........................................................................................................
T.eq db.$.list_schemas(), [
{ seq: 0, name: 'main', file: '/tmp/icql.db' },
{ seq: 2, name: 'subdb', file: '' } ]
T.eq ( db.$.get_toposort schema ), []
#.........................................................................................................
template = db.create_tables_with_foreign_key_frg()
### TAINT use compile-time interpolation as soon as available ###
sql = template.replace /\{schema\}/g, db.$.as_identifier schema
db.$.execute sql
#.........................................................................................................
do =>
d = db.$.list_objects()
T.eq d, []
#.........................................................................................................
do =>
d = db.$.list_objects schema
d = ( e for e in d when e.type is 'table' )
for e in d
delete e.sql
T.eq d, [ { type: 'table', name: 'table_one' }, { type: 'table', name: 'table_two' } ]
#.........................................................................................................
T.eq ( db.$.get_toposort() ), []
T.eq ( db.$.get_toposort schema ), [
{ name: 'table_one', type: 'table', sql: 'CREATE TABLE table_one (\n key text not null unique primary key )' },
{ name: 'table_two', type: 'table', sql: 'CREATE TABLE table_two (\n id text not null unique primary key,\n key text not null references table_one ( key ) )' },
{ name: 'sqlite_autoindex_table_one_1', type: 'index', sql: null },
{ name: 'sqlite_autoindex_table_two_1', type: 'index', sql: null } ]
#.........................................................................................................
done()
#-----------------------------------------------------------------------------------------------------------
@[ "_error messages" ] = ( T, done ) ->
### demo to show that printout gets limited for long statements ###
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
db = ICQL.bind settings
db.create_demo_table()
sql = "select
1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018,
1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037,
1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056,
1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075,
1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094,
1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113,
1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132,
1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151,
1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170,
1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189,
1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208,
1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227,
1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246,
1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265,
1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284,
1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303,
1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322,
1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341,
1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360,
from demo;"
try
db.$.query sql
catch error
null
done()
############################################################################################################
unless module.parent?
test @
# test @[ "load_extension" ]
# test @[ "foreign keys" ]
# test @[ "toposort with schema" ]
# @[ "toposort with schema" ]()
| true |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'ICQL/TESTS/MAIN'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
#...........................................................................................................
test = require '../../../../apps/guy-test'
jr = JSON.stringify
{ inspect, } = require 'util'
xrpr = ( x ) -> inspect x, { colors: yes, breakLength: Infinity, maxArrayLength: Infinity, depth: Infinity, }
xrpr2 = ( x ) -> inspect x, { colors: yes, breakLength: 20, maxArrayLength: Infinity, depth: Infinity, }
#...........................................................................................................
PATH = require 'path'
#-----------------------------------------------------------------------------------------------------------
get_icql_settings = ( remove_db = false ) ->
R = {}
R.connector = require 'better-sqlite3'
R.db_path = '/tmp/icql.db'
R.icql_path = PATH.resolve PATH.join __dirname, '../../../../assets/icql/test.icql'
if remove_db
try
( require 'fs' ).unlinkSync R.db_path
catch error
throw error unless ( error.code is 'ENOENT' )
return R
#-----------------------------------------------------------------------------------------------------------
@[ "oneliners" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
IC = require '../../../../apps/intercourse'
PATH = require 'path'
intercourse_path = require.resolve '../../../../apps/intercourse'
demo_path = PATH.join intercourse_path, '../../demos/sqlite-demo.icql'
debug '22999', demo_path
db = {}
ICQL.definitions_from_path_sync db, demo_path
debug '33442', db
return done()
throw new Error "sorry no tests as yet"
probes_and_matchers = [
# ["procedure foobar: some text\n illegal line",null,'illegal follow-up after one-liner']
["procedure foobar: some text",{"foobar":{"type":"procedure","null":{"text":"some text\n","location":{"line_nr":1},"kenning":"null","type":"procedure"}}},null]
["procedure foobar(): some text",{"foobar":{"type":"procedure","()":{"text":"some text\n","location":{"line_nr":1},"kenning":"()","type":"procedure","signature":[]}}},null]
["procedure foobar( first ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar(first): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar( first, ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar(first,): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
["procedure foobar( first, second ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
["procedure foobar( first, second, ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
]
#.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
# # try
# result = await IC.read_definitions_from_text probe
# # catch error
# # return resolve error
# # debug '29929', xrpr2 result
# resolve result
done()
#-----------------------------------------------------------------------------------------------------------
@[ "parameters are expanded in procedures" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
db = ICQL.bind get_icql_settings()
# debug 'µ44433', db
db.create_demo_table()
#.........................................................................................................
db.$.function 'echo', { deterministic: false, varargs: true }, ( P... ) -> urge ( CND.grey 'DB' ), P...; null
db.$.function 'e', { deterministic: false, varargs: false }, ( x ) -> urge ( CND.grey 'DB' ), rpr x; x
#.........................................................................................................
debug db.$.all_rows db.read_demo_rows()
debug db.$.all_rows db.select_by_rowid { rowid: 2, }
try
db.update_by_rowid { rowid: 2, status: 'bar', }
catch error
debug 'µ33555', error.code
debug 'µ33555', error.name
debug 'µ33555', ( k for k of error )
debug 'µ33555', error.message
# TypeError
process.exit 1
debug db.$.all_rows db.select_by_rowid { rowid: 2, }
#.........................................................................................................
# statement = db.$.prepare "select rowid, * from demo where rowid = $rowid;"
# info 'µ00908', [ ( statement.iterate { rowid: 2, } )..., ]
# # statement = db.$.prepare "select 42; select rowid, * from demo where rowid = $rowid;"
# # statement = db.$.prepare "update demo set status = 'yes!' where rowid = $rowid;"
# # info 'µ00908', statement.run { rowid: 2, }
# info 'µ00908', db.$.run "update demo set status = 'yes!' where rowid = $rowid;", { rowid: 2, extra: true, }
# debug db.$.all_rows db.select_by_rowid { rowid: 2, }
# probes_and_matchers = [
# # ["procedure foobar: some text\n illegal line",null,'illegal follow-up after one-liner']
# ["procedure foobar: some text",{"foobar":{"type":"procedure","null":{"text":"some text\n","location":{"line_nr":1},"kenning":"null","type":"procedure"}}},null]
# ["procedure foobar(): some text",{"foobar":{"type":"procedure","()":{"text":"some text\n","location":{"line_nr":1},"kenning":"()","type":"procedure","signature":[]}}},null]
# ["procedure foobar( first ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar(first): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar( first, ): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar(first,): some text",{"foobar":{"type":"procedure","(first)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first)","type":"procedure","signature":["first"]}}},null]
# ["procedure foobar( first, second ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
# ["procedure foobar( first, second, ): some text",{"foobar":{"type":"procedure","(first,second)":{"text":"some text\n","location":{"line_nr":1},"kenning":"(first,second)","type":"procedure","signature":["first","second"]}}},null]
# ]
#.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
# # try
# result = await IC.read_definitions_from_text probe
# # catch error
# # return resolve error
# # debug '29929', xrpr2 result
# resolve result
done()
#-----------------------------------------------------------------------------------------------------------
@[ "as_sql" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
PATH = require 'path'
db = ICQL.bind get_icql_settings()
probes_and_matchers = [
[true,'1',]
[false,'0',]
[42,'42',]
['text',"'text'",]
["text with 'quotes'","'text with ''quotes'''",]
[[1,2,3],"'[1,2,3]'",]
[[],"'[]'",]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
resolve db.$.as_sql probe
done()
#-----------------------------------------------------------------------------------------------------------
@[ "interpolate" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
PATH = require 'path'
db = ICQL.bind get_icql_settings()
probes_and_matchers = [
[["foo, $bar, baz",{bar:42,}],"foo, 42, baz"]
[["select * from t where d = $d;",{bar:42,}],null,"unable to express 'undefined' as SQL literal"]
[["select * from t where d = $d;",{d:true,}],"select * from t where d = 1;"]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
[ sql, Q, ] = probe
resolve db.$.interpolate sql, Q
done()
#-----------------------------------------------------------------------------------------------------------
@[ "fragments return interpolated source text" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
db = ICQL.bind get_icql_settings()
# debug 'µ44430', db
# debug 'µ44430', db.$.sql
# debug 'µ44430', db.create_demo_table_middle
key = 'PI:KEY:<KEY>END_PI'
value = 'somevalue'
status = 'somestatus'
first = db.create_demo_table_first()
middle = db.create_demo_table_middle { key, value, status, }
last = db.create_demo_table_last()
T.eq first, "drop table if exists demo;\ncreate table demo (\n key text,\n value text,\n status text );\ninsert into demo values"
T.eq middle, "( 'somekey', 'somevalue', 'somestatus' )"
T.eq last, ";"
done()
# #-----------------------------------------------------------------------------------------------------------
# @[ "x" ] = ( T, done ) ->
# T.eq 42, 42
# T.eq 42, 43
# done()
# return null
#-----------------------------------------------------------------------------------------------------------
@[ "foreign keys" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
settings.echo = true
db = ICQL.bind settings
db.create_tables_with_foreign_key()
db.populate_tables_with_foreign_key()
rows = db.$.all_rows db.select_from_tables_with_foreign_key()
T.eq rows, [{"id":"id1","key":"foo"},{"id":"id2","key":"foo"},{"id":"id3","key":"other"},{"id":"id4","key":"bar"}]
db.drop_tables_with_foreign_key()
#---------------------------------------------------------------------------------------------------------
db = ICQL.bind settings
db.create_tables_with_foreign_key()
T.eq [], db.$.dependencies_of 't1'
T.eq [ 't1' ], db.$.dependencies_of 't2'
#---------------------------------------------------------------------------------------------------------
T.eq db.$.get_toposort(), [
{ name: 't2', type: 'table', sql: 'CREATE TABLE t2 (\n id text not null unique primary key,\n key text not null references t1 ( key ) )' },
{ name: 't1', type: 'table', sql: 'CREATE TABLE t1 (\n key text not null unique primary key )' },
{ name: 'sqlite_autoindex_t1_1', type: 'index', sql: null },
{ name: 'sqlite_autoindex_t2_1', type: 'index', sql: null } ]
#---------------------------------------------------------------------------------------------------------
db.populate_tables_with_foreign_key()
T.eq rows, [{"id":"id1","key":"foo"},{"id":"id2","key":"foo"},{"id":"id3","key":"other"},{"id":"id4","key":"bar"}]
db.$.clear()
T.eq db.$.get_toposort(), []
# db.drop_tables_with_foreign_key()
done()
#-----------------------------------------------------------------------------------------------------------
@[ "toposort with schema" ] = ( T, done ) ->
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
settings.echo = true
db = ICQL.bind settings
schema = 'subdb'
db.$.attach ':memory:', schema
#.........................................................................................................
T.eq db.$.list_schemas(), [
{ seq: 0, name: 'main', file: '/tmp/icql.db' },
{ seq: 2, name: 'subdb', file: '' } ]
T.eq ( db.$.get_toposort schema ), []
#.........................................................................................................
template = db.create_tables_with_foreign_key_frg()
### TAINT use compile-time interpolation as soon as available ###
sql = template.replace /\{schema\}/g, db.$.as_identifier schema
db.$.execute sql
#.........................................................................................................
do =>
d = db.$.list_objects()
T.eq d, []
#.........................................................................................................
do =>
d = db.$.list_objects schema
d = ( e for e in d when e.type is 'table' )
for e in d
delete e.sql
T.eq d, [ { type: 'table', name: 'table_one' }, { type: 'table', name: 'table_two' } ]
#.........................................................................................................
T.eq ( db.$.get_toposort() ), []
T.eq ( db.$.get_toposort schema ), [
{ name: 'table_one', type: 'table', sql: 'CREATE TABLE table_one (\n key text not null unique primary key )' },
{ name: 'table_two', type: 'table', sql: 'CREATE TABLE table_two (\n id text not null unique primary key,\n key text not null references table_one ( key ) )' },
{ name: 'sqlite_autoindex_table_one_1', type: 'index', sql: null },
{ name: 'sqlite_autoindex_table_two_1', type: 'index', sql: null } ]
#.........................................................................................................
done()
#-----------------------------------------------------------------------------------------------------------
@[ "_error messages" ] = ( T, done ) ->
### demo to show that printout gets limited for long statements ###
ICQL = require '../../../../apps/icql'
settings = get_icql_settings true
db = ICQL.bind settings
db.create_demo_table()
sql = "select
1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018,
1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037,
1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056,
1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075,
1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094,
1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113,
1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132,
1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151,
1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170,
1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189,
1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208,
1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227,
1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246,
1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265,
1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284,
1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303,
1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322,
1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341,
1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360,
from demo;"
try
db.$.query sql
catch error
null
done()
############################################################################################################
unless module.parent?
test @
# test @[ "load_extension" ]
# test @[ "foreign keys" ]
# test @[ "toposort with schema" ]
# @[ "toposort with schema" ]()
|
[
{
"context": " ->\n\n account = generateDummyAccount '123', 'foouser'\n\n @reactor.dispatch actions.LOAD_USER_SUCCE",
"end": 501,
"score": 0.7784577012062073,
"start": 494,
"tag": "USERNAME",
"value": "foouser"
},
{
"context": "->\n\n account1 = generateDummyAccount '1... | client/app/lib/flux/test/stores/usersstore.coffee | ezgikaysi/koding | 1 | actions = require '../../actions/actiontypes'
expect = require 'expect'
Reactor = require 'app/flux/base/reactor'
UsersStore = require '../../stores/usersstore'
generateDummyAccount = require 'app/util/generateDummyAccount'
describe 'UsersStore', ->
beforeEach ->
@reactor = new Reactor
@reactor.registerStores [UsersStore]
describe '#handleLoadSuccess', ->
it 'loads user', ->
account = generateDummyAccount '123', 'foouser'
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '123', account }
storeState = @reactor.evaluateToJS [UsersStore.getterPath]
expect(storeState['123']).toEqual account
describe '#handleLoadListSuccess', ->
it 'loads user list', ->
account1 = generateDummyAccount '123', 'qwertyuser'
account2 = generateDummyAccount '456', 'testuser'
users = [ account1, account2 ]
@reactor.dispatch actions.SEARCH_USERS_SUCCESS, { users }
storeState = @reactor.evaluateToJS [UsersStore.getterPath]
expect(storeState['123']).toEqual account1
expect(storeState['456']).toEqual account2
describe '#handleMarkUserAsTrollSuccess', ->
it 'marks user as troll', ->
account = generateDummyAccount '321', 'testaccount'
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '321', account }
@reactor.dispatch actions.MARK_USER_AS_TROLL_SUCCESS, account
storeState = @reactor.evaluate [UsersStore.getterPath]
console.log 'storeState ', storeState
expect(storeState.getIn ['321', 'isExempt']).toEqual yes
describe '#handleUnmarkUserAsTrollSuccess', ->
it 'deletes troll mark from user', ->
account = generateDummyAccount '321', 'testaccount'
account.isExempt = true
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '321', account }
@reactor.dispatch actions.UNMARK_USER_AS_TROLL_SUCCESS, account
storeState = @reactor.evaluate [UsersStore.getterPath]
console.log 'storeState ', storeState
expect(storeState.getIn ['321', 'isExempt']).toEqual no
| 154054 | actions = require '../../actions/actiontypes'
expect = require 'expect'
Reactor = require 'app/flux/base/reactor'
UsersStore = require '../../stores/usersstore'
generateDummyAccount = require 'app/util/generateDummyAccount'
describe 'UsersStore', ->
beforeEach ->
@reactor = new Reactor
@reactor.registerStores [UsersStore]
describe '#handleLoadSuccess', ->
it 'loads user', ->
account = generateDummyAccount '123', 'foouser'
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '123', account }
storeState = @reactor.evaluateToJS [UsersStore.getterPath]
expect(storeState['123']).toEqual account
describe '#handleLoadListSuccess', ->
it 'loads user list', ->
account1 = generateDummyAccount '123', '<PASSWORD>'
account2 = generateDummyAccount '456', 'testuser'
users = [ account1, account2 ]
@reactor.dispatch actions.SEARCH_USERS_SUCCESS, { users }
storeState = @reactor.evaluateToJS [UsersStore.getterPath]
expect(storeState['123']).toEqual account1
expect(storeState['456']).toEqual account2
describe '#handleMarkUserAsTrollSuccess', ->
it 'marks user as troll', ->
account = generateDummyAccount '321', 'testaccount'
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '321', account }
@reactor.dispatch actions.MARK_USER_AS_TROLL_SUCCESS, account
storeState = @reactor.evaluate [UsersStore.getterPath]
console.log 'storeState ', storeState
expect(storeState.getIn ['321', 'isExempt']).toEqual yes
describe '#handleUnmarkUserAsTrollSuccess', ->
it 'deletes troll mark from user', ->
account = generateDummyAccount '321', 'testaccount'
account.isExempt = true
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '321', account }
@reactor.dispatch actions.UNMARK_USER_AS_TROLL_SUCCESS, account
storeState = @reactor.evaluate [UsersStore.getterPath]
console.log 'storeState ', storeState
expect(storeState.getIn ['321', 'isExempt']).toEqual no
| true | actions = require '../../actions/actiontypes'
expect = require 'expect'
Reactor = require 'app/flux/base/reactor'
UsersStore = require '../../stores/usersstore'
generateDummyAccount = require 'app/util/generateDummyAccount'
describe 'UsersStore', ->
beforeEach ->
@reactor = new Reactor
@reactor.registerStores [UsersStore]
describe '#handleLoadSuccess', ->
it 'loads user', ->
account = generateDummyAccount '123', 'foouser'
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '123', account }
storeState = @reactor.evaluateToJS [UsersStore.getterPath]
expect(storeState['123']).toEqual account
describe '#handleLoadListSuccess', ->
it 'loads user list', ->
account1 = generateDummyAccount '123', 'PI:PASSWORD:<PASSWORD>END_PI'
account2 = generateDummyAccount '456', 'testuser'
users = [ account1, account2 ]
@reactor.dispatch actions.SEARCH_USERS_SUCCESS, { users }
storeState = @reactor.evaluateToJS [UsersStore.getterPath]
expect(storeState['123']).toEqual account1
expect(storeState['456']).toEqual account2
describe '#handleMarkUserAsTrollSuccess', ->
it 'marks user as troll', ->
account = generateDummyAccount '321', 'testaccount'
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '321', account }
@reactor.dispatch actions.MARK_USER_AS_TROLL_SUCCESS, account
storeState = @reactor.evaluate [UsersStore.getterPath]
console.log 'storeState ', storeState
expect(storeState.getIn ['321', 'isExempt']).toEqual yes
describe '#handleUnmarkUserAsTrollSuccess', ->
it 'deletes troll mark from user', ->
account = generateDummyAccount '321', 'testaccount'
account.isExempt = true
@reactor.dispatch actions.LOAD_USER_SUCCESS, { id: '321', account }
@reactor.dispatch actions.UNMARK_USER_AS_TROLL_SUCCESS, account
storeState = @reactor.evaluate [UsersStore.getterPath]
console.log 'storeState ', storeState
expect(storeState.getIn ['321', 'isExempt']).toEqual no
|
[
{
"context": " uuid: 'green-blue'\n token: 'blue-purple'\n toUuid: 'bright-green'\n f",
"end": 539,
"score": 0.751015841960907,
"start": 528,
"tag": "PASSWORD",
"value": "blue-purple"
},
{
"context": " uuid: 'green-blue'\n ... | test/check-whitelist-discover-as-spec.coffee | octoblu/meshblu-core-task-check-whitelist-discover-as | 0 | http = require 'http'
CheckWhitelistDiscoverAs = require '../'
describe 'CheckWhitelistDiscoverAs', ->
beforeEach ->
@whitelistManager =
checkDiscoverAs: sinon.stub()
@sut = new CheckWhitelistDiscoverAs
whitelistManager: @whitelistManager
describe '->do', ->
describe 'when called with a valid job', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'bright-green'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 204', ->
expect(@newJob.metadata.code).to.equal 204
it 'should get have the status of ', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a valid job without a from', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'bright-green'
responseId: 'yellow-green'
@sut.do job, (error, @newJob) => done error
it 'should call the whitelistmanager with the correct arguments', ->
expect(@whitelistManager.checkDiscoverAs).to.have.been.calledWith emitter: 'green-blue', subscriber: 'bright-green'
describe 'when called with a different valid job', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'dim-green'
token: 'blue-lime-green'
toUuid: 'hot-yellow'
fromUuid: 'ugly-yellow'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 204', ->
expect(@newJob.metadata.code).to.equal 204
it 'should get have the status of OK', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a job that with a device that has an invalid whitelist', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, false
job =
metadata:
auth:
uuid: 'puke-green'
token: 'blue-lime-green'
toUuid: 'super-purple'
fromUuid: 'not-so-super-purple'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 403', ->
expect(@newJob.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called and the checkDiscoverAs yields an error', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields new Error "black-n-black"
job =
metadata:
auth:
uuid: 'puke-green'
token: 'blue-lime-green'
toUuid: 'green-bomb'
fromUuid: 'green-safe'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 500', ->
expect(@newJob.metadata.code).to.equal 500
it 'should get have the status of Forbidden', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[500]
| 181163 | http = require 'http'
CheckWhitelistDiscoverAs = require '../'
describe 'CheckWhitelistDiscoverAs', ->
beforeEach ->
@whitelistManager =
checkDiscoverAs: sinon.stub()
@sut = new CheckWhitelistDiscoverAs
whitelistManager: @whitelistManager
describe '->do', ->
describe 'when called with a valid job', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: '<PASSWORD>'
toUuid: 'bright-green'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 204', ->
expect(@newJob.metadata.code).to.equal 204
it 'should get have the status of ', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a valid job without a from', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: '<PASSWORD>'
toUuid: 'bright-green'
responseId: 'yellow-green'
@sut.do job, (error, @newJob) => done error
it 'should call the whitelistmanager with the correct arguments', ->
expect(@whitelistManager.checkDiscoverAs).to.have.been.calledWith emitter: 'green-blue', subscriber: 'bright-green'
describe 'when called with a different valid job', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'dim-green'
token: '<PASSWORD>'
toUuid: 'hot-yellow'
fromUuid: 'ugly-yellow'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 204', ->
expect(@newJob.metadata.code).to.equal 204
it 'should get have the status of OK', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a job that with a device that has an invalid whitelist', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, false
job =
metadata:
auth:
uuid: 'puke-green'
token: '<PASSWORD>'
toUuid: 'super-purple'
fromUuid: 'not-so-super-purple'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 403', ->
expect(@newJob.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called and the checkDiscoverAs yields an error', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields new Error "black-n-black"
job =
metadata:
auth:
uuid: 'puke-green'
token: '<PASSWORD>'
toUuid: 'green-bomb'
fromUuid: 'green-safe'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 500', ->
expect(@newJob.metadata.code).to.equal 500
it 'should get have the status of Forbidden', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[500]
| true | http = require 'http'
CheckWhitelistDiscoverAs = require '../'
describe 'CheckWhitelistDiscoverAs', ->
beforeEach ->
@whitelistManager =
checkDiscoverAs: sinon.stub()
@sut = new CheckWhitelistDiscoverAs
whitelistManager: @whitelistManager
describe '->do', ->
describe 'when called with a valid job', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'bright-green'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 204', ->
expect(@newJob.metadata.code).to.equal 204
it 'should get have the status of ', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a valid job without a from', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'bright-green'
responseId: 'yellow-green'
@sut.do job, (error, @newJob) => done error
it 'should call the whitelistmanager with the correct arguments', ->
expect(@whitelistManager.checkDiscoverAs).to.have.been.calledWith emitter: 'green-blue', subscriber: 'bright-green'
describe 'when called with a different valid job', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, true
job =
metadata:
auth:
uuid: 'dim-green'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'hot-yellow'
fromUuid: 'ugly-yellow'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 204', ->
expect(@newJob.metadata.code).to.equal 204
it 'should get have the status of OK', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a job that with a device that has an invalid whitelist', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields null, false
job =
metadata:
auth:
uuid: 'puke-green'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'super-purple'
fromUuid: 'not-so-super-purple'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 403', ->
expect(@newJob.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called and the checkDiscoverAs yields an error', ->
beforeEach (done) ->
@whitelistManager.checkDiscoverAs.yields new Error "black-n-black"
job =
metadata:
auth:
uuid: 'puke-green'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'green-bomb'
fromUuid: 'green-safe'
responseId: 'purple-green'
@sut.do job, (error, @newJob) => done error
it 'should get have the responseId', ->
expect(@newJob.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 500', ->
expect(@newJob.metadata.code).to.equal 500
it 'should get have the status of Forbidden', ->
expect(@newJob.metadata.status).to.equal http.STATUS_CODES[500]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.